@fedify/fedify 2.4.0-dev.1599 → 2.4.0-dev.1618

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/{builder-BvCI7Xch.mjs → builder-C4a7TAvq.mjs} +24 -2
  2. package/dist/compat/mod.d.cts +1 -1
  3. package/dist/compat/mod.d.ts +1 -1
  4. package/dist/compat/transformers.test.mjs +1 -1
  5. package/dist/{context-C7Sbmci2.mjs → context-BJXxPElm.mjs} +2 -1
  6. package/dist/{context-GfQA-CqB.d.ts → context-Zii1f5xS.d.ts} +97 -1
  7. package/dist/{context-BLe0NPtZ.d.cts → context-lxX6I7as.d.cts} +97 -1
  8. package/dist/{deno-BCt09TJn.mjs → deno-DepnPEgI.mjs} +1 -1
  9. package/dist/{docloader-BrRjFwOp.mjs → docloader-C_IefWRb.mjs} +2 -2
  10. package/dist/federation/builder.test.mjs +11 -1
  11. package/dist/federation/handler.test.mjs +4 -4
  12. package/dist/federation/idempotency.test.mjs +2 -2
  13. package/dist/federation/metrics.test.mjs +1 -1
  14. package/dist/federation/middleware.test.mjs +456 -8
  15. package/dist/federation/mod.cjs +1 -1
  16. package/dist/federation/mod.d.cts +3 -3
  17. package/dist/federation/mod.d.ts +3 -3
  18. package/dist/federation/mod.js +1 -1
  19. package/dist/federation/send.test.mjs +3 -3
  20. package/dist/federation/tasks/enqueue.test.mjs +2 -2
  21. package/dist/federation/tasks/tasks.test.mjs +3 -3
  22. package/dist/federation/temporal.test.mjs +1 -1
  23. package/dist/federation/webfinger.test.mjs +2 -2
  24. package/dist/{http-yainOC9t.mjs → http-CT7tcVBN.mjs} +3 -3
  25. package/dist/{http-zJsVCnKu.cjs → http-D5ylizT7.cjs} +1 -1
  26. package/dist/{http--wLYmH1x.js → http-DD07Erm7.js} +1 -1
  27. package/dist/{key-DcLwG7x4.mjs → key-C3t-PS3M.mjs} +2 -2
  28. package/dist/{kv-cache-0TGAGm8S.js → kv-cache-Bvv7Wp8h.js} +1 -1
  29. package/dist/{kv-cache-SZL9uu3V.mjs → kv-cache-CK273Baz.mjs} +1 -1
  30. package/dist/{kv-cache-BPu_M3-N.cjs → kv-cache-DbFdquuM.cjs} +1 -1
  31. package/dist/{ld-B-jskR-q.mjs → ld-D8wAPjxC.mjs} +3 -3
  32. package/dist/{metrics-C-pKLuAU.mjs → metrics-D1NrDWq-.mjs} +1 -1
  33. package/dist/{middleware-DGEQ07xT.mjs → middleware-BRunoF2v.mjs} +232 -12
  34. package/dist/{middleware-HFQkD-r8.mjs → middleware-CaP0k3AD.mjs} +1 -1
  35. package/dist/{middleware-D1POKL1d.js → middleware-kQ-qwTDh.js} +245 -3
  36. package/dist/{middleware-DLzOFLD5.cjs → middleware-nmfhGFtV.cjs} +245 -3
  37. package/dist/{mod-Cmr39iWq.d.ts → mod-DLc2Ot6f.d.ts} +1 -1
  38. package/dist/{mod-B8Efb9qp.d.cts → mod-gOlPDuT8.d.cts} +1 -1
  39. package/dist/mod.cjs +4 -4
  40. package/dist/mod.d.cts +4 -4
  41. package/dist/mod.d.ts +4 -4
  42. package/dist/mod.js +4 -4
  43. package/dist/nodeinfo/handler.test.mjs +2 -2
  44. package/dist/{owner-CeJuB8wq.mjs → owner-BjdNNmKF.mjs} +2 -2
  45. package/dist/{proof-Bri1zUVM.js → proof--HiDnLAE.js} +14 -3
  46. package/dist/{proof-917XYw_e.mjs → proof-1Xy5Ur-T.mjs} +16 -4
  47. package/dist/{proof-BkQosXrd.cjs → proof-DcOiiLDF.cjs} +13 -2
  48. package/dist/{send-CDi3XQ0V.mjs → send-ClJ4UcZL.mjs} +3 -3
  49. package/dist/sig/http.test.mjs +2 -2
  50. package/dist/sig/key.test.mjs +1 -1
  51. package/dist/sig/ld.test.mjs +2 -2
  52. package/dist/sig/mod.cjs +2 -2
  53. package/dist/sig/mod.js +2 -2
  54. package/dist/sig/owner.test.mjs +1 -1
  55. package/dist/sig/proof.test.mjs +138 -1
  56. package/dist/{temporal-jusSJxbN.mjs → temporal-wA-b1IAz.mjs} +1 -1
  57. package/dist/testing/mod.d.mts +96 -0
  58. package/dist/testing/mod.mjs +2 -2
  59. package/dist/{testing-C3vgUK0b.mjs → testing-CO7ftO8A.mjs} +1 -1
  60. package/dist/utils/docloader.test.mjs +2 -2
  61. package/dist/utils/kv-cache.test.mjs +1 -1
  62. package/dist/utils/mod.cjs +1 -1
  63. package/dist/utils/mod.js +1 -1
  64. package/package.json +6 -6
@@ -2,10 +2,10 @@ import { Temporal } from "temporal-polyfill";
2
2
  import { URLPattern } from "urlpattern-polyfill";
3
3
  import { t as __exportAll } from "./chunk-D5IdezsZ.js";
4
4
  import { r as getDefaultActivityTransformers } from "./transformers-DXze6FUB.js";
5
- import { A as formatAcceptSignature, D as recordOutboxEnqueue, E as recordOutboxActivity, F as version, O as recordWebFingerHandle, P as name, S as recordCollectionTotalItems, T as recordInboxActivity, a as verifyRequestDetailed, b as recordCollectionPageItems, d as validateCryptoKey, f as getDurationMs, g as isAbortError, h as instrumentDocumentLoader, i as verifyRequest, k as registerQueueDepthGauge, m as getRemoteHost, n as parseRfc9421SignatureInput, o as exportJwk, p as getFederationMetrics, t as doubleKnock, u as importJwk, v as recordCircuitBreakerStateChange, w as recordFanoutRecipients, x as recordCollectionRequest, y as recordCollectionDispatchDuration } from "./http--wLYmH1x.js";
6
- import { _ as hasSignatureLike, b as signJsonLd, c as getKeyOwner, f as compactJsonLd, g as hasSignature, h as getNormalizationContextLoader, i as verifyObject, l as InvalidContextReferenceError, m as detachSignature, n as hasProofLike, o as normalizeOutgoingActivityJsonLd, r as signObject, s as doesActorOwnKey, u as assertSafeJsonLd, v as isClearlyMalformedContextReference, w as wrapContextLoaderForJsonLd, x as verifyCompactJsonLd, y as isInvalidUrlTypeError } from "./proof-Bri1zUVM.js";
5
+ import { A as formatAcceptSignature, D as recordOutboxEnqueue, E as recordOutboxActivity, F as version, O as recordWebFingerHandle, P as name, S as recordCollectionTotalItems, T as recordInboxActivity, a as verifyRequestDetailed, b as recordCollectionPageItems, d as validateCryptoKey, f as getDurationMs, g as isAbortError, h as instrumentDocumentLoader, i as verifyRequest, k as registerQueueDepthGauge, m as getRemoteHost, n as parseRfc9421SignatureInput, o as exportJwk, p as getFederationMetrics, t as doubleKnock, u as importJwk, v as recordCircuitBreakerStateChange, w as recordFanoutRecipients, x as recordCollectionRequest, y as recordCollectionDispatchDuration } from "./http-DD07Erm7.js";
6
+ import { _ as hasSignatureLike, b as signJsonLd, c as getKeyOwner, f as compactJsonLd, g as hasSignature, h as getNormalizationContextLoader, i as verifyObject, l as InvalidContextReferenceError, m as detachSignature, n as hasProofLike, o as normalizeOutgoingActivityJsonLd, r as signObject, s as doesActorOwnKey, u as assertSafeJsonLd, v as isClearlyMalformedContextReference, w as wrapContextLoaderForJsonLd, x as verifyCompactJsonLd, y as isInvalidUrlTypeError } from "./proof--HiDnLAE.js";
7
7
  import { n as getNodeInfo, t as nodeInfoToJson } from "./types-DC1pNgJA.js";
8
- import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-0TGAGm8S.js";
8
+ import { n as getAuthenticatedDocumentLoader, t as kvCache } from "./kv-cache-Bvv7Wp8h.js";
9
9
  import { getLogger, withContext } from "@logtape/logtape";
10
10
  import { Router, RouterError, assertPath } from "@fedify/uri-template";
11
11
  import { Activity, Collection, CollectionPage, CryptographicKey, Link, Multikey, Object as Object$1, OrderedCollection, OrderedCollectionPage, Tombstone, getTypeId, lookupObject, traverseCollection } from "@fedify/vocab";
@@ -102,6 +102,9 @@ var FederationBuilderImpl = class {
102
102
  inboxErrorHandler;
103
103
  outboxListenerErrorHandler;
104
104
  outboxAuthorizePredicate;
105
+ mediaUploaderPath;
106
+ mediaUploaderCallback;
107
+ mediaUploaderAuthorizePredicate;
105
108
  sharedInboxKeyDispatcher;
106
109
  unverifiedActivityHandler;
107
110
  outboxPermanentFailureHandler;
@@ -154,6 +157,9 @@ var FederationBuilderImpl = class {
154
157
  f.inboxErrorHandler = this.inboxErrorHandler;
155
158
  f.outboxListenerErrorHandler = this.outboxListenerErrorHandler;
156
159
  f.outboxAuthorizePredicate = this.outboxAuthorizePredicate;
160
+ f.mediaUploaderPath = this.mediaUploaderPath;
161
+ f.mediaUploaderCallback = this.mediaUploaderCallback;
162
+ f.mediaUploaderAuthorizePredicate = this.mediaUploaderAuthorizePredicate;
157
163
  f.sharedInboxKeyDispatcher = this.sharedInboxKeyDispatcher;
158
164
  f.unverifiedActivityHandler = this.unverifiedActivityHandler;
159
165
  f.outboxPermanentFailureHandler = this.outboxPermanentFailureHandler;
@@ -232,6 +238,10 @@ var FederationBuilderImpl = class {
232
238
  if (actor.publicKeyId == null) logger.warn("You configured a key pairs dispatcher, but the actor does not have a publicKey property. Set the property with Context.getActorKeyPairs(identifier).");
233
239
  if (actor.assertionMethodId == null) logger.warn("You configured a key pairs dispatcher, but the actor does not have an assertionMethod property. Set the property with Context.getActorKeyPairs(identifier).");
234
240
  }
241
+ if (this.mediaUploaderCallback != null) {
242
+ if (actor.endpoints == null || actor.endpoints.uploadMedia == null) logger.warn("You configured a media uploader, but the actor does not have a endpoints.uploadMedia property. Set the property with Context.getMediaUploaderUri(identifier).");
243
+ else if (actor.endpoints.uploadMedia.href != context.getMediaUploaderUri(identifier).href) logger.warn("You configured a media uploader, but the actor's endpoints.uploadMedia property does not match the media upload endpoint URI. Set the property with Context.getMediaUploaderUri(identifier).");
244
+ }
235
245
  return actor;
236
246
  } };
237
247
  this.actorCallbacks = callbacks;
@@ -444,6 +454,18 @@ var FederationBuilderImpl = class {
444
454
  };
445
455
  return setters;
446
456
  }
457
+ setMediaUploader(path, callback) {
458
+ if (this.mediaUploaderCallback != null) throw new RouterError("Media uploader already set.");
459
+ assertPath(path);
460
+ this.router.add(path, "mediaUploader", identifierSingular);
461
+ this.mediaUploaderPath = path;
462
+ this.mediaUploaderCallback = callback;
463
+ const setters = { authorize: (predicate) => {
464
+ this.mediaUploaderAuthorizePredicate = predicate;
465
+ return setters;
466
+ } };
467
+ return setters;
468
+ }
447
469
  setFollowingDispatcher(path, dispatcher) {
448
470
  if (this.router.has("following")) throw new RouterError("Following collection dispatcher already set.");
449
471
  assertPath(path);
@@ -2014,6 +2036,193 @@ async function handleOutbox(request, { identifier, context: ctx, outboxContextFa
2014
2036
  headers: { "Content-Type": "text/plain; charset=utf-8" }
2015
2037
  });
2016
2038
  }
2039
+ const plainTextHeaders = { "Content-Type": "text/plain; charset=utf-8" };
2040
+ /**
2041
+ * Handles a media upload request (the [ActivityPub Media Upload
2042
+ * extension](https://www.w3.org/wiki/SocialCG/ActivityPub/MediaUpload)).
2043
+ * @template TContextData The context data to pass to the context.
2044
+ * @param request The HTTP request.
2045
+ * @param parameters The parameters for handling the request.
2046
+ * @returns A promise that resolves to an HTTP response.
2047
+ * @since 2.4.0
2048
+ */
2049
+ async function handleMediaUpload(request, { identifier, context: ctx, mediaUploaderCallback, actorDispatcher, authorizePredicate, isRegisteredObjectUri, onUnauthorized, onNotFound }) {
2050
+ const logger = getLogger([
2051
+ "fedify",
2052
+ "federation",
2053
+ "mediaUploader"
2054
+ ]);
2055
+ if (request.bodyUsed) {
2056
+ logger.error("Request body has already been read.", { identifier });
2057
+ return new Response("Internal server error.", {
2058
+ status: 500,
2059
+ headers: plainTextHeaders
2060
+ });
2061
+ } else if (request.body?.locked) {
2062
+ logger.error("Request body is locked.", { identifier });
2063
+ return new Response("Internal server error.", {
2064
+ status: 500,
2065
+ headers: plainTextHeaders
2066
+ });
2067
+ }
2068
+ const contentType = request.headers.get("content-type");
2069
+ if (contentType == null || !contentType.toLowerCase().startsWith("multipart/form-data")) {
2070
+ logger.error("The media upload request is not multipart/form-data (got {contentType}).", {
2071
+ identifier,
2072
+ contentType
2073
+ });
2074
+ return new Response("Unsupported media type.", {
2075
+ status: 415,
2076
+ headers: plainTextHeaders
2077
+ });
2078
+ }
2079
+ if (actorDispatcher == null) {
2080
+ logger.error("Actor dispatcher is not set.", { identifier });
2081
+ return await onNotFound(request);
2082
+ }
2083
+ const actor = await actorDispatcher(ctx, identifier);
2084
+ if (actor == null || actor instanceof Tombstone) {
2085
+ logger.error("Actor {identifier} not found.", { identifier });
2086
+ return await onNotFound(request);
2087
+ }
2088
+ if (authorizePredicate != null) {
2089
+ let body;
2090
+ try {
2091
+ body = await request.arrayBuffer();
2092
+ } catch (error) {
2093
+ logger.error("Failed to read the multipart/form-data body:\n{error}", {
2094
+ identifier,
2095
+ error
2096
+ });
2097
+ return new Response("Invalid multipart/form-data body.", {
2098
+ status: 400,
2099
+ headers: plainTextHeaders
2100
+ });
2101
+ }
2102
+ const rebuild = () => new Request(request.url, {
2103
+ method: request.method,
2104
+ headers: request.headers,
2105
+ body: body.byteLength > 0 ? body : void 0
2106
+ });
2107
+ const authorizeContext = ctx.clone(ctx.data);
2108
+ authorizeContext.request = rebuild();
2109
+ if (!await authorizePredicate(authorizeContext, identifier)) return await onUnauthorized(rebuild());
2110
+ request = rebuild();
2111
+ }
2112
+ let form;
2113
+ try {
2114
+ form = await request.formData();
2115
+ } catch (error) {
2116
+ logger.error("Failed to parse the multipart/form-data body:\n{error}", {
2117
+ identifier,
2118
+ error
2119
+ });
2120
+ return new Response("Invalid multipart/form-data body.", {
2121
+ status: 400,
2122
+ headers: plainTextHeaders
2123
+ });
2124
+ }
2125
+ const file = form.get("file");
2126
+ if (!(file instanceof File)) {
2127
+ logger.error("The media upload request has no file field.", { identifier });
2128
+ return new Response("Missing file field.", {
2129
+ status: 400,
2130
+ headers: plainTextHeaders
2131
+ });
2132
+ }
2133
+ const objectField = form.get("object");
2134
+ if (objectField == null) {
2135
+ logger.error("The media upload request has no object field.", { identifier });
2136
+ return new Response("Missing object field.", {
2137
+ status: 400,
2138
+ headers: plainTextHeaders
2139
+ });
2140
+ }
2141
+ let object;
2142
+ try {
2143
+ const objectText = typeof objectField === "string" ? objectField : await objectField.text();
2144
+ object = await Object$1.fromJsonLd(JSON.parse(objectText), ctx);
2145
+ } catch (error) {
2146
+ logger.error("Failed to parse the object field:\n{error}", {
2147
+ identifier,
2148
+ error
2149
+ });
2150
+ return new Response("Invalid object field.", {
2151
+ status: 400,
2152
+ headers: plainTextHeaders
2153
+ });
2154
+ }
2155
+ let result;
2156
+ try {
2157
+ result = await mediaUploaderCallback(ctx, identifier, file, object);
2158
+ } catch (error) {
2159
+ logger.error("Failed to process the media upload:\n{error}", {
2160
+ identifier,
2161
+ error
2162
+ });
2163
+ return new Response("Internal server error.", {
2164
+ status: 500,
2165
+ headers: plainTextHeaders
2166
+ });
2167
+ }
2168
+ if (result == null) {
2169
+ logger.error("The media uploader callback for {identifier} returned null or undefined; it must return an object (201 Created) or a URL (202 Accepted).", { identifier });
2170
+ return new Response("Internal server error.", {
2171
+ status: 500,
2172
+ headers: plainTextHeaders
2173
+ });
2174
+ }
2175
+ const warnUnlessRegistered = (target) => {
2176
+ if (isRegisteredObjectUri(target)) return;
2177
+ logger.warn("The media uploader callback for {identifier} returned {target}, which does not point at a registered object dispatcher route; derive the returned id/URL from Context.getObjectUri(). The upload still succeeded.", {
2178
+ identifier,
2179
+ target: target.href
2180
+ });
2181
+ };
2182
+ if (result instanceof URL) {
2183
+ warnUnlessRegistered(result);
2184
+ logger.info("The media upload for {identifier} is still being processed; responding 202 Accepted.", {
2185
+ identifier,
2186
+ location: result.href
2187
+ });
2188
+ return new Response(null, {
2189
+ status: 202,
2190
+ headers: { Location: result.href }
2191
+ });
2192
+ }
2193
+ if (result.id == null) {
2194
+ logger.error("The media uploader callback for {identifier} returned an object without an id, so a 201 Created response cannot include the required Location header. Set the object's id with Context.getObjectUri(), or return the eventual URL to respond 202 Accepted instead.", { identifier });
2195
+ return new Response("Internal server error.", {
2196
+ status: 500,
2197
+ headers: plainTextHeaders
2198
+ });
2199
+ }
2200
+ warnUnlessRegistered(result.id);
2201
+ let jsonLd;
2202
+ try {
2203
+ jsonLd = await result.toJsonLd(ctx);
2204
+ } catch (error) {
2205
+ logger.error("Failed to serialize the uploaded object to JSON-LD:\n{error}", {
2206
+ identifier,
2207
+ error
2208
+ });
2209
+ return new Response("Internal server error.", {
2210
+ status: 500,
2211
+ headers: plainTextHeaders
2212
+ });
2213
+ }
2214
+ logger.info("The media upload for {identifier} is ready; responding 201 Created.", {
2215
+ identifier,
2216
+ location: result.id.href
2217
+ });
2218
+ return new Response(JSON.stringify(jsonLd), {
2219
+ status: 201,
2220
+ headers: {
2221
+ "Content-Type": "application/activity+json",
2222
+ Location: result.id.href
2223
+ }
2224
+ });
2225
+ }
2017
2226
  /**
2018
2227
  * Handles an inbox request for ActivityPub activities.
2019
2228
  * @template TContextData The context data to pass to the context.
@@ -4517,6 +4726,7 @@ var FederationImpl = class extends FederationBuilderImpl {
4517
4726
  benchmarkMode;
4518
4727
  benchmarkMetricReader;
4519
4728
  benchmarkTriggerOptions;
4729
+ #mediaUploaderNoAuthWarned = false;
4520
4730
  #queueDepthGaugeSourceId = `fedify-${(++nextQueueDepthGaugeSourceId).toString(36)}`;
4521
4731
  #queueDepthGaugeEntries = [];
4522
4732
  #queueDepthGaugeMeterProvider;
@@ -5832,6 +6042,32 @@ var FederationImpl = class extends FederationBuilderImpl {
5832
6042
  });
5833
6043
  case "benchmarkStats": return await handleBenchmarkStats(request, this.benchmarkMetricReader);
5834
6044
  case "benchmarkTrigger": return await handleBenchmarkTrigger(request, context, this.benchmarkTriggerOptions);
6045
+ case "mediaUploader":
6046
+ if (request.method !== "POST" || this.mediaUploaderCallback == null) return new Response("Method not allowed.", {
6047
+ status: 405,
6048
+ headers: {
6049
+ Allow: "POST",
6050
+ "Content-Type": "text/plain; charset=utf-8"
6051
+ }
6052
+ });
6053
+ if (this.mediaUploaderAuthorizePredicate == null && !this.#mediaUploaderNoAuthWarned) {
6054
+ this.#mediaUploaderNoAuthWarned = true;
6055
+ getLogger([
6056
+ "fedify",
6057
+ "federation",
6058
+ "mediaUploader"
6059
+ ]).warn("The media uploader is registered without an authorize() hook, so it accepts uploads from anyone who can reach the endpoint. Protect it with .authorize() unless a public upload endpoint is intended.");
6060
+ }
6061
+ return await handleMediaUpload(request, {
6062
+ identifier: route.values.identifier,
6063
+ context,
6064
+ mediaUploaderCallback: this.mediaUploaderCallback,
6065
+ actorDispatcher: this.actorCallbacks?.dispatcher,
6066
+ authorizePredicate: this.mediaUploaderAuthorizePredicate,
6067
+ isRegisteredObjectUri: (uri) => context.parseUri(uri)?.type === "object",
6068
+ onUnauthorized,
6069
+ onNotFound
6070
+ });
5835
6071
  }
5836
6072
  if (request.method !== "POST" && !acceptsJsonLd(request)) {
5837
6073
  metricState.endpoint = "not_acceptable";
@@ -6066,6 +6302,7 @@ function getEndpointCategory(routeName) {
6066
6302
  case "inbox": return "inbox";
6067
6303
  case "sharedInbox": return "shared_inbox";
6068
6304
  case "outbox": return "outbox";
6305
+ case "mediaUploader": return "media_upload";
6069
6306
  case "following": return "following";
6070
6307
  case "followers": return "followers";
6071
6308
  case "liked": return "liked";
@@ -6199,6 +6436,11 @@ var ContextImpl = class ContextImpl {
6199
6436
  if (path == null) throw new RouterError("No outbox dispatcher registered.");
6200
6437
  return new URL(path, this.canonicalOrigin);
6201
6438
  }
6439
+ getMediaUploaderUri(identifier) {
6440
+ const path = this.federation.router.build("mediaUploader", { identifier });
6441
+ if (path == null) throw new RouterError("No media uploader registered.");
6442
+ return new URL(path, this.canonicalOrigin);
6443
+ }
6202
6444
  getInboxUri(identifier) {
6203
6445
  if (identifier == null) {
6204
6446
  const path = this.federation.router.build("sharedInbox", {});
@@ -1,11 +1,11 @@
1
1
  const { URLPattern } = require("urlpattern-polyfill");
2
2
  const require_chunk = require("./chunk-Czpeue4M.cjs");
3
3
  const require_transformers = require("./transformers-DGwl-hD1.cjs");
4
- const require_http = require("./http-zJsVCnKu.cjs");
4
+ const require_http = require("./http-D5ylizT7.cjs");
5
5
  const require_temporal_polyfill = require("./temporal-polyfill-BCdTHexd.cjs");
6
- const require_proof = require("./proof-BkQosXrd.cjs");
6
+ const require_proof = require("./proof-DcOiiLDF.cjs");
7
7
  const require_types = require("./types-CPym83zc.cjs");
8
- const require_kv_cache = require("./kv-cache-BPu_M3-N.cjs");
8
+ const require_kv_cache = require("./kv-cache-DbFdquuM.cjs");
9
9
  let _logtape_logtape = require("@logtape/logtape");
10
10
  let _fedify_uri_template = require("@fedify/uri-template");
11
11
  let _fedify_vocab = require("@fedify/vocab");
@@ -103,6 +103,9 @@ var FederationBuilderImpl = class {
103
103
  inboxErrorHandler;
104
104
  outboxListenerErrorHandler;
105
105
  outboxAuthorizePredicate;
106
+ mediaUploaderPath;
107
+ mediaUploaderCallback;
108
+ mediaUploaderAuthorizePredicate;
106
109
  sharedInboxKeyDispatcher;
107
110
  unverifiedActivityHandler;
108
111
  outboxPermanentFailureHandler;
@@ -155,6 +158,9 @@ var FederationBuilderImpl = class {
155
158
  f.inboxErrorHandler = this.inboxErrorHandler;
156
159
  f.outboxListenerErrorHandler = this.outboxListenerErrorHandler;
157
160
  f.outboxAuthorizePredicate = this.outboxAuthorizePredicate;
161
+ f.mediaUploaderPath = this.mediaUploaderPath;
162
+ f.mediaUploaderCallback = this.mediaUploaderCallback;
163
+ f.mediaUploaderAuthorizePredicate = this.mediaUploaderAuthorizePredicate;
158
164
  f.sharedInboxKeyDispatcher = this.sharedInboxKeyDispatcher;
159
165
  f.unverifiedActivityHandler = this.unverifiedActivityHandler;
160
166
  f.outboxPermanentFailureHandler = this.outboxPermanentFailureHandler;
@@ -233,6 +239,10 @@ var FederationBuilderImpl = class {
233
239
  if (actor.publicKeyId == null) logger.warn("You configured a key pairs dispatcher, but the actor does not have a publicKey property. Set the property with Context.getActorKeyPairs(identifier).");
234
240
  if (actor.assertionMethodId == null) logger.warn("You configured a key pairs dispatcher, but the actor does not have an assertionMethod property. Set the property with Context.getActorKeyPairs(identifier).");
235
241
  }
242
+ if (this.mediaUploaderCallback != null) {
243
+ if (actor.endpoints == null || actor.endpoints.uploadMedia == null) logger.warn("You configured a media uploader, but the actor does not have a endpoints.uploadMedia property. Set the property with Context.getMediaUploaderUri(identifier).");
244
+ else if (actor.endpoints.uploadMedia.href != context.getMediaUploaderUri(identifier).href) logger.warn("You configured a media uploader, but the actor's endpoints.uploadMedia property does not match the media upload endpoint URI. Set the property with Context.getMediaUploaderUri(identifier).");
245
+ }
236
246
  return actor;
237
247
  } };
238
248
  this.actorCallbacks = callbacks;
@@ -445,6 +455,18 @@ var FederationBuilderImpl = class {
445
455
  };
446
456
  return setters;
447
457
  }
458
+ setMediaUploader(path, callback) {
459
+ if (this.mediaUploaderCallback != null) throw new _fedify_uri_template.RouterError("Media uploader already set.");
460
+ (0, _fedify_uri_template.assertPath)(path);
461
+ this.router.add(path, "mediaUploader", identifierSingular);
462
+ this.mediaUploaderPath = path;
463
+ this.mediaUploaderCallback = callback;
464
+ const setters = { authorize: (predicate) => {
465
+ this.mediaUploaderAuthorizePredicate = predicate;
466
+ return setters;
467
+ } };
468
+ return setters;
469
+ }
448
470
  setFollowingDispatcher(path, dispatcher) {
449
471
  if (this.router.has("following")) throw new _fedify_uri_template.RouterError("Following collection dispatcher already set.");
450
472
  (0, _fedify_uri_template.assertPath)(path);
@@ -2020,6 +2042,193 @@ async function handleOutbox(request, { identifier, context: ctx, outboxContextFa
2020
2042
  headers: { "Content-Type": "text/plain; charset=utf-8" }
2021
2043
  });
2022
2044
  }
2045
+ const plainTextHeaders = { "Content-Type": "text/plain; charset=utf-8" };
2046
+ /**
2047
+ * Handles a media upload request (the [ActivityPub Media Upload
2048
+ * extension](https://www.w3.org/wiki/SocialCG/ActivityPub/MediaUpload)).
2049
+ * @template TContextData The context data to pass to the context.
2050
+ * @param request The HTTP request.
2051
+ * @param parameters The parameters for handling the request.
2052
+ * @returns A promise that resolves to an HTTP response.
2053
+ * @since 2.4.0
2054
+ */
2055
+ async function handleMediaUpload(request, { identifier, context: ctx, mediaUploaderCallback, actorDispatcher, authorizePredicate, isRegisteredObjectUri, onUnauthorized, onNotFound }) {
2056
+ const logger = (0, _logtape_logtape.getLogger)([
2057
+ "fedify",
2058
+ "federation",
2059
+ "mediaUploader"
2060
+ ]);
2061
+ if (request.bodyUsed) {
2062
+ logger.error("Request body has already been read.", { identifier });
2063
+ return new Response("Internal server error.", {
2064
+ status: 500,
2065
+ headers: plainTextHeaders
2066
+ });
2067
+ } else if (request.body?.locked) {
2068
+ logger.error("Request body is locked.", { identifier });
2069
+ return new Response("Internal server error.", {
2070
+ status: 500,
2071
+ headers: plainTextHeaders
2072
+ });
2073
+ }
2074
+ const contentType = request.headers.get("content-type");
2075
+ if (contentType == null || !contentType.toLowerCase().startsWith("multipart/form-data")) {
2076
+ logger.error("The media upload request is not multipart/form-data (got {contentType}).", {
2077
+ identifier,
2078
+ contentType
2079
+ });
2080
+ return new Response("Unsupported media type.", {
2081
+ status: 415,
2082
+ headers: plainTextHeaders
2083
+ });
2084
+ }
2085
+ if (actorDispatcher == null) {
2086
+ logger.error("Actor dispatcher is not set.", { identifier });
2087
+ return await onNotFound(request);
2088
+ }
2089
+ const actor = await actorDispatcher(ctx, identifier);
2090
+ if (actor == null || actor instanceof _fedify_vocab.Tombstone) {
2091
+ logger.error("Actor {identifier} not found.", { identifier });
2092
+ return await onNotFound(request);
2093
+ }
2094
+ if (authorizePredicate != null) {
2095
+ let body;
2096
+ try {
2097
+ body = await request.arrayBuffer();
2098
+ } catch (error) {
2099
+ logger.error("Failed to read the multipart/form-data body:\n{error}", {
2100
+ identifier,
2101
+ error
2102
+ });
2103
+ return new Response("Invalid multipart/form-data body.", {
2104
+ status: 400,
2105
+ headers: plainTextHeaders
2106
+ });
2107
+ }
2108
+ const rebuild = () => new Request(request.url, {
2109
+ method: request.method,
2110
+ headers: request.headers,
2111
+ body: body.byteLength > 0 ? body : void 0
2112
+ });
2113
+ const authorizeContext = ctx.clone(ctx.data);
2114
+ authorizeContext.request = rebuild();
2115
+ if (!await authorizePredicate(authorizeContext, identifier)) return await onUnauthorized(rebuild());
2116
+ request = rebuild();
2117
+ }
2118
+ let form;
2119
+ try {
2120
+ form = await request.formData();
2121
+ } catch (error) {
2122
+ logger.error("Failed to parse the multipart/form-data body:\n{error}", {
2123
+ identifier,
2124
+ error
2125
+ });
2126
+ return new Response("Invalid multipart/form-data body.", {
2127
+ status: 400,
2128
+ headers: plainTextHeaders
2129
+ });
2130
+ }
2131
+ const file = form.get("file");
2132
+ if (!(file instanceof File)) {
2133
+ logger.error("The media upload request has no file field.", { identifier });
2134
+ return new Response("Missing file field.", {
2135
+ status: 400,
2136
+ headers: plainTextHeaders
2137
+ });
2138
+ }
2139
+ const objectField = form.get("object");
2140
+ if (objectField == null) {
2141
+ logger.error("The media upload request has no object field.", { identifier });
2142
+ return new Response("Missing object field.", {
2143
+ status: 400,
2144
+ headers: plainTextHeaders
2145
+ });
2146
+ }
2147
+ let object;
2148
+ try {
2149
+ const objectText = typeof objectField === "string" ? objectField : await objectField.text();
2150
+ object = await _fedify_vocab.Object.fromJsonLd(JSON.parse(objectText), ctx);
2151
+ } catch (error) {
2152
+ logger.error("Failed to parse the object field:\n{error}", {
2153
+ identifier,
2154
+ error
2155
+ });
2156
+ return new Response("Invalid object field.", {
2157
+ status: 400,
2158
+ headers: plainTextHeaders
2159
+ });
2160
+ }
2161
+ let result;
2162
+ try {
2163
+ result = await mediaUploaderCallback(ctx, identifier, file, object);
2164
+ } catch (error) {
2165
+ logger.error("Failed to process the media upload:\n{error}", {
2166
+ identifier,
2167
+ error
2168
+ });
2169
+ return new Response("Internal server error.", {
2170
+ status: 500,
2171
+ headers: plainTextHeaders
2172
+ });
2173
+ }
2174
+ if (result == null) {
2175
+ logger.error("The media uploader callback for {identifier} returned null or undefined; it must return an object (201 Created) or a URL (202 Accepted).", { identifier });
2176
+ return new Response("Internal server error.", {
2177
+ status: 500,
2178
+ headers: plainTextHeaders
2179
+ });
2180
+ }
2181
+ const warnUnlessRegistered = (target) => {
2182
+ if (isRegisteredObjectUri(target)) return;
2183
+ logger.warn("The media uploader callback for {identifier} returned {target}, which does not point at a registered object dispatcher route; derive the returned id/URL from Context.getObjectUri(). The upload still succeeded.", {
2184
+ identifier,
2185
+ target: target.href
2186
+ });
2187
+ };
2188
+ if (result instanceof URL) {
2189
+ warnUnlessRegistered(result);
2190
+ logger.info("The media upload for {identifier} is still being processed; responding 202 Accepted.", {
2191
+ identifier,
2192
+ location: result.href
2193
+ });
2194
+ return new Response(null, {
2195
+ status: 202,
2196
+ headers: { Location: result.href }
2197
+ });
2198
+ }
2199
+ if (result.id == null) {
2200
+ logger.error("The media uploader callback for {identifier} returned an object without an id, so a 201 Created response cannot include the required Location header. Set the object's id with Context.getObjectUri(), or return the eventual URL to respond 202 Accepted instead.", { identifier });
2201
+ return new Response("Internal server error.", {
2202
+ status: 500,
2203
+ headers: plainTextHeaders
2204
+ });
2205
+ }
2206
+ warnUnlessRegistered(result.id);
2207
+ let jsonLd;
2208
+ try {
2209
+ jsonLd = await result.toJsonLd(ctx);
2210
+ } catch (error) {
2211
+ logger.error("Failed to serialize the uploaded object to JSON-LD:\n{error}", {
2212
+ identifier,
2213
+ error
2214
+ });
2215
+ return new Response("Internal server error.", {
2216
+ status: 500,
2217
+ headers: plainTextHeaders
2218
+ });
2219
+ }
2220
+ logger.info("The media upload for {identifier} is ready; responding 201 Created.", {
2221
+ identifier,
2222
+ location: result.id.href
2223
+ });
2224
+ return new Response(JSON.stringify(jsonLd), {
2225
+ status: 201,
2226
+ headers: {
2227
+ "Content-Type": "application/activity+json",
2228
+ Location: result.id.href
2229
+ }
2230
+ });
2231
+ }
2023
2232
  /**
2024
2233
  * Handles an inbox request for ActivityPub activities.
2025
2234
  * @template TContextData The context data to pass to the context.
@@ -4527,6 +4736,7 @@ var FederationImpl = class extends FederationBuilderImpl {
4527
4736
  benchmarkMode;
4528
4737
  benchmarkMetricReader;
4529
4738
  benchmarkTriggerOptions;
4739
+ #mediaUploaderNoAuthWarned = false;
4530
4740
  #queueDepthGaugeSourceId = `fedify-${(++nextQueueDepthGaugeSourceId).toString(36)}`;
4531
4741
  #queueDepthGaugeEntries = [];
4532
4742
  #queueDepthGaugeMeterProvider;
@@ -5842,6 +6052,32 @@ var FederationImpl = class extends FederationBuilderImpl {
5842
6052
  });
5843
6053
  case "benchmarkStats": return await handleBenchmarkStats(request, this.benchmarkMetricReader);
5844
6054
  case "benchmarkTrigger": return await handleBenchmarkTrigger(request, context, this.benchmarkTriggerOptions);
6055
+ case "mediaUploader":
6056
+ if (request.method !== "POST" || this.mediaUploaderCallback == null) return new Response("Method not allowed.", {
6057
+ status: 405,
6058
+ headers: {
6059
+ Allow: "POST",
6060
+ "Content-Type": "text/plain; charset=utf-8"
6061
+ }
6062
+ });
6063
+ if (this.mediaUploaderAuthorizePredicate == null && !this.#mediaUploaderNoAuthWarned) {
6064
+ this.#mediaUploaderNoAuthWarned = true;
6065
+ (0, _logtape_logtape.getLogger)([
6066
+ "fedify",
6067
+ "federation",
6068
+ "mediaUploader"
6069
+ ]).warn("The media uploader is registered without an authorize() hook, so it accepts uploads from anyone who can reach the endpoint. Protect it with .authorize() unless a public upload endpoint is intended.");
6070
+ }
6071
+ return await handleMediaUpload(request, {
6072
+ identifier: route.values.identifier,
6073
+ context,
6074
+ mediaUploaderCallback: this.mediaUploaderCallback,
6075
+ actorDispatcher: this.actorCallbacks?.dispatcher,
6076
+ authorizePredicate: this.mediaUploaderAuthorizePredicate,
6077
+ isRegisteredObjectUri: (uri) => context.parseUri(uri)?.type === "object",
6078
+ onUnauthorized,
6079
+ onNotFound
6080
+ });
5845
6081
  }
5846
6082
  if (request.method !== "POST" && !acceptsJsonLd(request)) {
5847
6083
  metricState.endpoint = "not_acceptable";
@@ -6076,6 +6312,7 @@ function getEndpointCategory(routeName) {
6076
6312
  case "inbox": return "inbox";
6077
6313
  case "sharedInbox": return "shared_inbox";
6078
6314
  case "outbox": return "outbox";
6315
+ case "mediaUploader": return "media_upload";
6079
6316
  case "following": return "following";
6080
6317
  case "followers": return "followers";
6081
6318
  case "liked": return "liked";
@@ -6209,6 +6446,11 @@ var ContextImpl = class ContextImpl {
6209
6446
  if (path == null) throw new _fedify_uri_template.RouterError("No outbox dispatcher registered.");
6210
6447
  return new URL(path, this.canonicalOrigin);
6211
6448
  }
6449
+ getMediaUploaderUri(identifier) {
6450
+ const path = this.federation.router.build("mediaUploader", { identifier });
6451
+ if (path == null) throw new _fedify_uri_template.RouterError("No media uploader registered.");
6452
+ return new URL(path, this.canonicalOrigin);
6453
+ }
6212
6454
  getInboxUri(identifier) {
6213
6455
  if (identifier == null) {
6214
6456
  const path = this.federation.router.build("sharedInbox", {});
@@ -1,5 +1,5 @@
1
1
  /// <reference lib="esnext.temporal" />
2
- import { At as WebFingerLinksDispatcher, ct as ActorDispatcher, l as RequestContext, lt as ActorHandleMapper, st as ActorAliasMapper } from "./context-GfQA-CqB.js";
2
+ import { Mt as WebFingerLinksDispatcher, ct as ActorAliasMapper, l as RequestContext, lt as ActorDispatcher, ut as ActorHandleMapper } from "./context-Zii1f5xS.js";
3
3
  import { RouterError, RouterOptions, RouterRouteResult } from "@fedify/uri-template";
4
4
  import { MeterProvider, Span, Tracer } from "@opentelemetry/api";
5
5
 
@@ -1,5 +1,5 @@
1
1
  /// <reference lib="esnext.temporal" />
2
- import { At as WebFingerLinksDispatcher, ct as ActorDispatcher, l as RequestContext, lt as ActorHandleMapper, st as ActorAliasMapper } from "./context-BLe0NPtZ.cjs";
2
+ import { Mt as WebFingerLinksDispatcher, ct as ActorAliasMapper, l as RequestContext, lt as ActorDispatcher, ut as ActorHandleMapper } from "./context-lxX6I7as.cjs";
3
3
  import { MeterProvider, Span, Tracer } from "@opentelemetry/api";
4
4
  import { RouterError, RouterOptions, RouterRouteResult } from "@fedify/uri-template";
5
5
 
package/dist/mod.cjs CHANGED
@@ -3,11 +3,11 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  require("./chunk-Czpeue4M.cjs");
4
4
  const require_transformers = require("./transformers-DGwl-hD1.cjs");
5
5
  require("./compat/mod.cjs");
6
- const require_http = require("./http-zJsVCnKu.cjs");
7
- const require_middleware = require("./middleware-DLzOFLD5.cjs");
8
- const require_proof = require("./proof-BkQosXrd.cjs");
6
+ const require_http = require("./http-D5ylizT7.cjs");
7
+ const require_middleware = require("./middleware-nmfhGFtV.cjs");
8
+ const require_proof = require("./proof-DcOiiLDF.cjs");
9
9
  const require_types = require("./types-CPym83zc.cjs");
10
- const require_kv_cache = require("./kv-cache-BPu_M3-N.cjs");
10
+ const require_kv_cache = require("./kv-cache-DbFdquuM.cjs");
11
11
  const require_federation_mod = require("./federation/mod.cjs");
12
12
  require("./nodeinfo/mod.cjs");
13
13
  require("./runtime/mod.cjs");