@fedify/adonisjs 2.5.0-dev.2619 → 2.5.0-dev.2687
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.
- package/dist/configure.cjs.map +1 -1
- package/dist/configure.js.map +1 -1
- package/dist/package.cjs +1 -1
- package/dist/package.js +1 -1
- package/dist/providers/fedify_provider.cjs +5 -1
- package/dist/providers/fedify_provider.cjs.map +1 -1
- package/dist/providers/fedify_provider.js +5 -1
- package/dist/providers/fedify_provider.js.map +1 -1
- package/dist/src/builder.cjs.map +1 -1
- package/dist/src/builder.js.map +1 -1
- package/dist/src/define_config.cjs.map +1 -1
- package/dist/src/define_config.js.map +1 -1
- package/dist/src/fedify_middleware.cjs.map +1 -1
- package/dist/src/fedify_middleware.js.map +1 -1
- package/dist/src/http_context.cjs.map +1 -1
- package/dist/src/http_context.js.map +1 -1
- package/dist/src/logging.cjs.map +1 -1
- package/dist/src/logging.js.map +1 -1
- package/dist/src/unusable_authority.cjs.map +1 -1
- package/dist/src/unusable_authority.js.map +1 -1
- package/package.json +5 -5
package/dist/configure.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configure.cjs","names":["stubsRoot"],"sources":["../configure.ts"],"sourcesContent":["/**\n * The configure hook, run by `node ace configure @fedify/adonisjs`.\n *\n * It performs every wiring step the package needs, so that a freshly configured\n * application already federates: install the Fedify runtime packages, declare\n * the environment variables, publish the config file and the federation preload\n * files, register the service provider, and add the middleware to the server\n * stack.\n *\n * @module\n */\nimport type ConfigureCommand from \"@adonisjs/core/commands/configure\";\n\nimport packageJson from \"./package.json\" with { type: \"json\" };\nimport { stubsRoot } from \"./stubs/main.ts\";\n\n/**\n * The slice of `@adonisjs/assembler`'s `RcFileTransformer` this hook touches.\n *\n * Spelled out rather than inferred because the assembler is an *optional* peer\n * dependency: wherever it is absent — a type-check of a tree that did not\n * install it, for instance — the inferred parameter type of `updateRcFile`'s\n * callback degrades to `any`, and this file stops compiling under\n * `noImplicitAny`.\n */\ninterface RcFileEditor {\n addProvider(providerPath: string): unknown;\n addPreloadFile(modulePath: string): unknown;\n}\n\n/**\n * The range the Fedify runtime packages are installed with.\n *\n * Derived from this package's own version so a release cannot leave it behind:\n * every package in this monorepo shares one version, and the `@fedify/fedify`\n * peer dependency is declared as `workspace:^`, which publishes as this range.\n *\n * Installing unpinned would pull the next major once it is out, which the peer\n * range rejects: a peer warning, and two copies of the vocabulary, which the\n * `instanceof` comparisons noted below cannot survive.\n */\nconst FEDIFY_RANGE = `^${packageJson.version}`;\n\n/**\n * Wires `@fedify/adonisjs` into an application.\n *\n * Run by `node ace configure @fedify/adonisjs` (and therefore by\n * `node ace add @fedify/adonisjs`); see the module documentation for the\n * steps it performs.\n */\nexport async function configure(command: ConfigureCommand): Promise<void> {\n const codemods = await command.createCodemods();\n\n /**\n * Fedify itself is a peer dependency: the application, not this package,\n * decides which version it runs, and having exactly one copy in the tree\n * matters because Fedify's vocabulary classes are compared with `instanceof`.\n *\n * `@fedify/vocab` carries the ActivityStreams classes (`Person`, `Follow`,\n * `Note`, …) that dispatchers and inbox listeners are written against.\n */\n await codemods.installPackages([\n { name: `@fedify/fedify@${FEDIFY_RANGE}`, isDevDependency: false },\n { name: `@fedify/vocab@${FEDIFY_RANGE}`, isDevDependency: false },\n ]);\n\n /**\n * `PUBLIC_URL` is the canonical origin remote servers use to reach this\n * application. Fedify mints actor URIs and activity IDs from it, so it has to\n * be the public address rather than the listen address — behind a proxy or a\n * `fedify tunnel` those differ.\n *\n * `FEDERATION_HANDLE_HOST` is optional and only needed when fediverse handles\n * live on a different domain than the web origin, for example `@me@example.com`\n * served from `https://social.example.com`.\n */\n await codemods.defineEnvValidations({\n leadingComment: \"Variables for configuring Fedify\",\n variables: {\n PUBLIC_URL: `Env.schema.string({ format: 'url', tld: false })`,\n FEDERATION_HANDLE_HOST: `Env.schema.string.optional({ format: 'host' })`,\n },\n });\n\n await codemods.defineEnvVariables({ PUBLIC_URL: \"http://localhost:3333\" });\n\n /**\n * `config/fedify.ts` — the federation options.\n */\n await codemods.makeUsingStub(stubsRoot, \"config/fedify.stub\", {});\n\n /**\n * `start/federation.ts` — a preload file that imports the application's\n * dispatcher modules.\n *\n * A preload file rather than directory globbing: preload files are ordinary\n * application source, so `node ace build` compiles them and their relative\n * imports along with everything else, and AdonisJS imports them after every\n * provider has booted, which is what lets dispatchers use Lucid models.\n */\n await codemods.makeUsingStub(stubsRoot, \"start/federation.stub\", {});\n\n /**\n * `app/federation/main.ts` — a starting point for dispatchers.\n */\n await codemods.makeUsingStub(stubsRoot, \"federation/main.stub\", {});\n\n await codemods.updateRcFile((rcFile: RcFileEditor) => {\n rcFile.addProvider(\"@fedify/adonisjs/fedify_provider\");\n rcFile.addPreloadFile(\"#start/federation\");\n });\n\n /**\n * The middleware must live in the **server** stack.\n *\n * Fedify answers paths the AdonisJS router does not know about\n * (`/.well-known/webfinger`, `/.well-known/nodeinfo`, actor and inbox\n * endpoints), so it has to run before route matching. The server stack also\n * runs before `bodyparser_middleware` and before `@adonisjs/shield`, which\n * matters twice over: HTTP Signature verification needs the raw, unparsed\n * request body, and inbox `POST`s must not be rejected by CSRF protection.\n *\n * It also goes *first* in that stack, so that Fedify negotiates on the\n * client's real `Accept` header. The API starter kit's\n * `force_json_response_middleware`, for example, rewrites every `Accept` to\n * `application/json`, which would make Fedify serve the ActivityPub document\n * to a browser asking for HTML and skip the HTML fall-through.\n */\n await codemods.registerMiddleware(\"server\", [{\n
|
|
1
|
+
{"version":3,"file":"configure.cjs","names":["stubsRoot"],"sources":["../configure.ts"],"sourcesContent":["/**\n * The configure hook, run by `node ace configure @fedify/adonisjs`.\n *\n * It performs every wiring step the package needs, so that a freshly configured\n * application already federates: install the Fedify runtime packages, declare\n * the environment variables, publish the config file and the federation preload\n * files, register the service provider, and add the middleware to the server\n * stack.\n *\n * @module\n */\nimport type ConfigureCommand from \"@adonisjs/core/commands/configure\";\n\nimport packageJson from \"./package.json\" with { type: \"json\" };\nimport { stubsRoot } from \"./stubs/main.ts\";\n\n/**\n * The slice of `@adonisjs/assembler`'s `RcFileTransformer` this hook touches.\n *\n * Spelled out rather than inferred because the assembler is an *optional* peer\n * dependency: wherever it is absent — a type-check of a tree that did not\n * install it, for instance — the inferred parameter type of `updateRcFile`'s\n * callback degrades to `any`, and this file stops compiling under\n * `noImplicitAny`.\n */\ninterface RcFileEditor {\n addProvider(providerPath: string): unknown;\n addPreloadFile(modulePath: string): unknown;\n}\n\n/**\n * The range the Fedify runtime packages are installed with.\n *\n * Derived from this package's own version so a release cannot leave it behind:\n * every package in this monorepo shares one version, and the `@fedify/fedify`\n * peer dependency is declared as `workspace:^`, which publishes as this range.\n *\n * Installing unpinned would pull the next major once it is out, which the peer\n * range rejects: a peer warning, and two copies of the vocabulary, which the\n * `instanceof` comparisons noted below cannot survive.\n */\nconst FEDIFY_RANGE = `^${packageJson.version}`;\n\n/**\n * Wires `@fedify/adonisjs` into an application.\n *\n * Run by `node ace configure @fedify/adonisjs` (and therefore by\n * `node ace add @fedify/adonisjs`); see the module documentation for the\n * steps it performs.\n */\nexport async function configure(command: ConfigureCommand): Promise<void> {\n const codemods = await command.createCodemods();\n\n /**\n * Fedify itself is a peer dependency: the application, not this package,\n * decides which version it runs, and having exactly one copy in the tree\n * matters because Fedify's vocabulary classes are compared with `instanceof`.\n *\n * `@fedify/vocab` carries the ActivityStreams classes (`Person`, `Follow`,\n * `Note`, …) that dispatchers and inbox listeners are written against.\n */\n await codemods.installPackages([\n { name: `@fedify/fedify@${FEDIFY_RANGE}`, isDevDependency: false },\n { name: `@fedify/vocab@${FEDIFY_RANGE}`, isDevDependency: false },\n ]);\n\n /**\n * `PUBLIC_URL` is the canonical origin remote servers use to reach this\n * application. Fedify mints actor URIs and activity IDs from it, so it has to\n * be the public address rather than the listen address — behind a proxy or a\n * `fedify tunnel` those differ.\n *\n * `FEDERATION_HANDLE_HOST` is optional and only needed when fediverse handles\n * live on a different domain than the web origin, for example `@me@example.com`\n * served from `https://social.example.com`.\n */\n await codemods.defineEnvValidations({\n leadingComment: \"Variables for configuring Fedify\",\n variables: {\n PUBLIC_URL: `Env.schema.string({ format: 'url', tld: false })`,\n FEDERATION_HANDLE_HOST: `Env.schema.string.optional({ format: 'host' })`,\n },\n });\n\n await codemods.defineEnvVariables({ PUBLIC_URL: \"http://localhost:3333\" });\n\n /**\n * `config/fedify.ts` — the federation options.\n */\n await codemods.makeUsingStub(stubsRoot, \"config/fedify.stub\", {});\n\n /**\n * `start/federation.ts` — a preload file that imports the application's\n * dispatcher modules.\n *\n * A preload file rather than directory globbing: preload files are ordinary\n * application source, so `node ace build` compiles them and their relative\n * imports along with everything else, and AdonisJS imports them after every\n * provider has booted, which is what lets dispatchers use Lucid models.\n */\n await codemods.makeUsingStub(stubsRoot, \"start/federation.stub\", {});\n\n /**\n * `app/federation/main.ts` — a starting point for dispatchers.\n */\n await codemods.makeUsingStub(stubsRoot, \"federation/main.stub\", {});\n\n await codemods.updateRcFile((rcFile: RcFileEditor) => {\n rcFile.addProvider(\"@fedify/adonisjs/fedify_provider\");\n rcFile.addPreloadFile(\"#start/federation\");\n });\n\n /**\n * The middleware must live in the **server** stack.\n *\n * Fedify answers paths the AdonisJS router does not know about\n * (`/.well-known/webfinger`, `/.well-known/nodeinfo`, actor and inbox\n * endpoints), so it has to run before route matching. The server stack also\n * runs before `bodyparser_middleware` and before `@adonisjs/shield`, which\n * matters twice over: HTTP Signature verification needs the raw, unparsed\n * request body, and inbox `POST`s must not be rejected by CSRF protection.\n *\n * It also goes *first* in that stack, so that Fedify negotiates on the\n * client's real `Accept` header. The API starter kit's\n * `force_json_response_middleware`, for example, rewrites every `Accept` to\n * `application/json`, which would make Fedify serve the ActivityPub document\n * to a browser asking for HTML and skip the HTML fall-through.\n */\n await codemods.registerMiddleware(\"server\", [\n {\n path: \"@fedify/adonisjs/fedify_middleware\",\n position: \"before\",\n },\n ]);\n\n command.logger.success(\"Configured @fedify/adonisjs\");\n command.logger.info(\n 'Register dispatchers in app/federation/main.ts, then run \"node ace serve\"',\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyCA,MAAM,eAAe;;;;;;;;AASrB,eAAsB,UAAU,SAA0C;CACxE,MAAM,WAAW,MAAM,QAAQ,eAAe;;;;;;;;;CAU9C,MAAM,SAAS,gBAAgB,CAC7B;EAAE,MAAM,kBAAkB;EAAgB,iBAAiB;CAAM,GACjE;EAAE,MAAM,iBAAiB;EAAgB,iBAAiB;CAAM,CAClE,CAAC;;;;;;;;;;;CAYD,MAAM,SAAS,qBAAqB;EAClC,gBAAgB;EAChB,WAAW;GACT,YAAY;GACZ,wBAAwB;EAC1B;CACF,CAAC;CAED,MAAM,SAAS,mBAAmB,EAAE,YAAY,wBAAwB,CAAC;;;;CAKzE,MAAM,SAAS,cAAcA,8BAAW,sBAAsB,CAAC,CAAC;;;;;;;;;;CAWhE,MAAM,SAAS,cAAcA,8BAAW,yBAAyB,CAAC,CAAC;;;;CAKnE,MAAM,SAAS,cAAcA,8BAAW,wBAAwB,CAAC,CAAC;CAElE,MAAM,SAAS,cAAc,WAAyB;EACpD,OAAO,YAAY,kCAAkC;EACrD,OAAO,eAAe,mBAAmB;CAC3C,CAAC;;;;;;;;;;;;;;;;;CAkBD,MAAM,SAAS,mBAAmB,UAAU,CAC1C;EACE,MAAM;EACN,UAAU;CACZ,CACF,CAAC;CAED,QAAQ,OAAO,QAAQ,6BAA6B;CACpD,QAAQ,OAAO,KACb,6EACF;AACF"}
|
package/dist/configure.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"configure.js","names":["packageJson.version"],"sources":["../configure.ts"],"sourcesContent":["/**\n * The configure hook, run by `node ace configure @fedify/adonisjs`.\n *\n * It performs every wiring step the package needs, so that a freshly configured\n * application already federates: install the Fedify runtime packages, declare\n * the environment variables, publish the config file and the federation preload\n * files, register the service provider, and add the middleware to the server\n * stack.\n *\n * @module\n */\nimport type ConfigureCommand from \"@adonisjs/core/commands/configure\";\n\nimport packageJson from \"./package.json\" with { type: \"json\" };\nimport { stubsRoot } from \"./stubs/main.ts\";\n\n/**\n * The slice of `@adonisjs/assembler`'s `RcFileTransformer` this hook touches.\n *\n * Spelled out rather than inferred because the assembler is an *optional* peer\n * dependency: wherever it is absent — a type-check of a tree that did not\n * install it, for instance — the inferred parameter type of `updateRcFile`'s\n * callback degrades to `any`, and this file stops compiling under\n * `noImplicitAny`.\n */\ninterface RcFileEditor {\n addProvider(providerPath: string): unknown;\n addPreloadFile(modulePath: string): unknown;\n}\n\n/**\n * The range the Fedify runtime packages are installed with.\n *\n * Derived from this package's own version so a release cannot leave it behind:\n * every package in this monorepo shares one version, and the `@fedify/fedify`\n * peer dependency is declared as `workspace:^`, which publishes as this range.\n *\n * Installing unpinned would pull the next major once it is out, which the peer\n * range rejects: a peer warning, and two copies of the vocabulary, which the\n * `instanceof` comparisons noted below cannot survive.\n */\nconst FEDIFY_RANGE = `^${packageJson.version}`;\n\n/**\n * Wires `@fedify/adonisjs` into an application.\n *\n * Run by `node ace configure @fedify/adonisjs` (and therefore by\n * `node ace add @fedify/adonisjs`); see the module documentation for the\n * steps it performs.\n */\nexport async function configure(command: ConfigureCommand): Promise<void> {\n const codemods = await command.createCodemods();\n\n /**\n * Fedify itself is a peer dependency: the application, not this package,\n * decides which version it runs, and having exactly one copy in the tree\n * matters because Fedify's vocabulary classes are compared with `instanceof`.\n *\n * `@fedify/vocab` carries the ActivityStreams classes (`Person`, `Follow`,\n * `Note`, …) that dispatchers and inbox listeners are written against.\n */\n await codemods.installPackages([\n { name: `@fedify/fedify@${FEDIFY_RANGE}`, isDevDependency: false },\n { name: `@fedify/vocab@${FEDIFY_RANGE}`, isDevDependency: false },\n ]);\n\n /**\n * `PUBLIC_URL` is the canonical origin remote servers use to reach this\n * application. Fedify mints actor URIs and activity IDs from it, so it has to\n * be the public address rather than the listen address — behind a proxy or a\n * `fedify tunnel` those differ.\n *\n * `FEDERATION_HANDLE_HOST` is optional and only needed when fediverse handles\n * live on a different domain than the web origin, for example `@me@example.com`\n * served from `https://social.example.com`.\n */\n await codemods.defineEnvValidations({\n leadingComment: \"Variables for configuring Fedify\",\n variables: {\n PUBLIC_URL: `Env.schema.string({ format: 'url', tld: false })`,\n FEDERATION_HANDLE_HOST: `Env.schema.string.optional({ format: 'host' })`,\n },\n });\n\n await codemods.defineEnvVariables({ PUBLIC_URL: \"http://localhost:3333\" });\n\n /**\n * `config/fedify.ts` — the federation options.\n */\n await codemods.makeUsingStub(stubsRoot, \"config/fedify.stub\", {});\n\n /**\n * `start/federation.ts` — a preload file that imports the application's\n * dispatcher modules.\n *\n * A preload file rather than directory globbing: preload files are ordinary\n * application source, so `node ace build` compiles them and their relative\n * imports along with everything else, and AdonisJS imports them after every\n * provider has booted, which is what lets dispatchers use Lucid models.\n */\n await codemods.makeUsingStub(stubsRoot, \"start/federation.stub\", {});\n\n /**\n * `app/federation/main.ts` — a starting point for dispatchers.\n */\n await codemods.makeUsingStub(stubsRoot, \"federation/main.stub\", {});\n\n await codemods.updateRcFile((rcFile: RcFileEditor) => {\n rcFile.addProvider(\"@fedify/adonisjs/fedify_provider\");\n rcFile.addPreloadFile(\"#start/federation\");\n });\n\n /**\n * The middleware must live in the **server** stack.\n *\n * Fedify answers paths the AdonisJS router does not know about\n * (`/.well-known/webfinger`, `/.well-known/nodeinfo`, actor and inbox\n * endpoints), so it has to run before route matching. The server stack also\n * runs before `bodyparser_middleware` and before `@adonisjs/shield`, which\n * matters twice over: HTTP Signature verification needs the raw, unparsed\n * request body, and inbox `POST`s must not be rejected by CSRF protection.\n *\n * It also goes *first* in that stack, so that Fedify negotiates on the\n * client's real `Accept` header. The API starter kit's\n * `force_json_response_middleware`, for example, rewrites every `Accept` to\n * `application/json`, which would make Fedify serve the ActivityPub document\n * to a browser asking for HTML and skip the HTML fall-through.\n */\n await codemods.registerMiddleware(\"server\", [{\n
|
|
1
|
+
{"version":3,"file":"configure.js","names":["packageJson.version"],"sources":["../configure.ts"],"sourcesContent":["/**\n * The configure hook, run by `node ace configure @fedify/adonisjs`.\n *\n * It performs every wiring step the package needs, so that a freshly configured\n * application already federates: install the Fedify runtime packages, declare\n * the environment variables, publish the config file and the federation preload\n * files, register the service provider, and add the middleware to the server\n * stack.\n *\n * @module\n */\nimport type ConfigureCommand from \"@adonisjs/core/commands/configure\";\n\nimport packageJson from \"./package.json\" with { type: \"json\" };\nimport { stubsRoot } from \"./stubs/main.ts\";\n\n/**\n * The slice of `@adonisjs/assembler`'s `RcFileTransformer` this hook touches.\n *\n * Spelled out rather than inferred because the assembler is an *optional* peer\n * dependency: wherever it is absent — a type-check of a tree that did not\n * install it, for instance — the inferred parameter type of `updateRcFile`'s\n * callback degrades to `any`, and this file stops compiling under\n * `noImplicitAny`.\n */\ninterface RcFileEditor {\n addProvider(providerPath: string): unknown;\n addPreloadFile(modulePath: string): unknown;\n}\n\n/**\n * The range the Fedify runtime packages are installed with.\n *\n * Derived from this package's own version so a release cannot leave it behind:\n * every package in this monorepo shares one version, and the `@fedify/fedify`\n * peer dependency is declared as `workspace:^`, which publishes as this range.\n *\n * Installing unpinned would pull the next major once it is out, which the peer\n * range rejects: a peer warning, and two copies of the vocabulary, which the\n * `instanceof` comparisons noted below cannot survive.\n */\nconst FEDIFY_RANGE = `^${packageJson.version}`;\n\n/**\n * Wires `@fedify/adonisjs` into an application.\n *\n * Run by `node ace configure @fedify/adonisjs` (and therefore by\n * `node ace add @fedify/adonisjs`); see the module documentation for the\n * steps it performs.\n */\nexport async function configure(command: ConfigureCommand): Promise<void> {\n const codemods = await command.createCodemods();\n\n /**\n * Fedify itself is a peer dependency: the application, not this package,\n * decides which version it runs, and having exactly one copy in the tree\n * matters because Fedify's vocabulary classes are compared with `instanceof`.\n *\n * `@fedify/vocab` carries the ActivityStreams classes (`Person`, `Follow`,\n * `Note`, …) that dispatchers and inbox listeners are written against.\n */\n await codemods.installPackages([\n { name: `@fedify/fedify@${FEDIFY_RANGE}`, isDevDependency: false },\n { name: `@fedify/vocab@${FEDIFY_RANGE}`, isDevDependency: false },\n ]);\n\n /**\n * `PUBLIC_URL` is the canonical origin remote servers use to reach this\n * application. Fedify mints actor URIs and activity IDs from it, so it has to\n * be the public address rather than the listen address — behind a proxy or a\n * `fedify tunnel` those differ.\n *\n * `FEDERATION_HANDLE_HOST` is optional and only needed when fediverse handles\n * live on a different domain than the web origin, for example `@me@example.com`\n * served from `https://social.example.com`.\n */\n await codemods.defineEnvValidations({\n leadingComment: \"Variables for configuring Fedify\",\n variables: {\n PUBLIC_URL: `Env.schema.string({ format: 'url', tld: false })`,\n FEDERATION_HANDLE_HOST: `Env.schema.string.optional({ format: 'host' })`,\n },\n });\n\n await codemods.defineEnvVariables({ PUBLIC_URL: \"http://localhost:3333\" });\n\n /**\n * `config/fedify.ts` — the federation options.\n */\n await codemods.makeUsingStub(stubsRoot, \"config/fedify.stub\", {});\n\n /**\n * `start/federation.ts` — a preload file that imports the application's\n * dispatcher modules.\n *\n * A preload file rather than directory globbing: preload files are ordinary\n * application source, so `node ace build` compiles them and their relative\n * imports along with everything else, and AdonisJS imports them after every\n * provider has booted, which is what lets dispatchers use Lucid models.\n */\n await codemods.makeUsingStub(stubsRoot, \"start/federation.stub\", {});\n\n /**\n * `app/federation/main.ts` — a starting point for dispatchers.\n */\n await codemods.makeUsingStub(stubsRoot, \"federation/main.stub\", {});\n\n await codemods.updateRcFile((rcFile: RcFileEditor) => {\n rcFile.addProvider(\"@fedify/adonisjs/fedify_provider\");\n rcFile.addPreloadFile(\"#start/federation\");\n });\n\n /**\n * The middleware must live in the **server** stack.\n *\n * Fedify answers paths the AdonisJS router does not know about\n * (`/.well-known/webfinger`, `/.well-known/nodeinfo`, actor and inbox\n * endpoints), so it has to run before route matching. The server stack also\n * runs before `bodyparser_middleware` and before `@adonisjs/shield`, which\n * matters twice over: HTTP Signature verification needs the raw, unparsed\n * request body, and inbox `POST`s must not be rejected by CSRF protection.\n *\n * It also goes *first* in that stack, so that Fedify negotiates on the\n * client's real `Accept` header. The API starter kit's\n * `force_json_response_middleware`, for example, rewrites every `Accept` to\n * `application/json`, which would make Fedify serve the ActivityPub document\n * to a browser asking for HTML and skip the HTML fall-through.\n */\n await codemods.registerMiddleware(\"server\", [\n {\n path: \"@fedify/adonisjs/fedify_middleware\",\n position: \"before\",\n },\n ]);\n\n command.logger.success(\"Configured @fedify/adonisjs\");\n command.logger.info(\n 'Register dispatchers in app/federation/main.ts, then run \"node ace serve\"',\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAyCA,MAAM,eAAe,IAAIA;;;;;;;;AASzB,eAAsB,UAAU,SAA0C;CACxE,MAAM,WAAW,MAAM,QAAQ,eAAe;;;;;;;;;CAU9C,MAAM,SAAS,gBAAgB,CAC7B;EAAE,MAAM,kBAAkB;EAAgB,iBAAiB;CAAM,GACjE;EAAE,MAAM,iBAAiB;EAAgB,iBAAiB;CAAM,CAClE,CAAC;;;;;;;;;;;CAYD,MAAM,SAAS,qBAAqB;EAClC,gBAAgB;EAChB,WAAW;GACT,YAAY;GACZ,wBAAwB;EAC1B;CACF,CAAC;CAED,MAAM,SAAS,mBAAmB,EAAE,YAAY,wBAAwB,CAAC;;;;CAKzE,MAAM,SAAS,cAAc,WAAW,sBAAsB,CAAC,CAAC;;;;;;;;;;CAWhE,MAAM,SAAS,cAAc,WAAW,yBAAyB,CAAC,CAAC;;;;CAKnE,MAAM,SAAS,cAAc,WAAW,wBAAwB,CAAC,CAAC;CAElE,MAAM,SAAS,cAAc,WAAyB;EACpD,OAAO,YAAY,kCAAkC;EACrD,OAAO,eAAe,mBAAmB;CAC3C,CAAC;;;;;;;;;;;;;;;;;CAkBD,MAAM,SAAS,mBAAmB,UAAU,CAC1C;EACE,MAAM;EACN,UAAU;CACZ,CACF,CAAC;CAED,QAAQ,OAAO,QAAQ,6BAA6B;CACpD,QAAQ,OAAO,KACb,6EACF;AACF"}
|
package/dist/package.cjs
CHANGED
package/dist/package.js
CHANGED
|
@@ -244,7 +244,11 @@ var FedifyProvider = class {
|
|
|
244
244
|
const stopped = this.#queue ?? Promise.resolve();
|
|
245
245
|
if (!this.#loggingConfigured) return stopped;
|
|
246
246
|
this.#loggingConfigured = false;
|
|
247
|
-
return stopped.then(
|
|
247
|
+
return stopped.then(async () => {
|
|
248
|
+
try {
|
|
249
|
+
await (0, _logtape_logtape.reset)();
|
|
250
|
+
} catch {}
|
|
251
|
+
});
|
|
248
252
|
}
|
|
249
253
|
/**
|
|
250
254
|
* Called when the HTTP server starts listening and requests can arrive.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fedify_provider.cjs","names":["#ready","builder","configProvider","E_INVALID_FEDIFY_CONFIG","#buildable","E_FEDERATION_NOT_READY","#middleware","#listening","FedifyMiddleware","#loggingConfigured","configureFedifyLogging","#serverStarted","#settle","#queueController","#queue","#readyTimer"],"sources":["../../providers/fedify_provider.ts"],"sourcesContent":["/**\n * The `@fedify/adonisjs` service provider; see {@link FedifyProvider}.\n *\n * @module\n */\nimport { configProvider } from \"@adonisjs/core\";\nimport type { Logger } from \"@adonisjs/core/logger\";\nimport type { ApplicationService, ConfigProvider } from \"@adonisjs/core/types\";\nimport type { Federation } from \"@fedify/fedify\";\nimport { reset as resetLogging } from \"@logtape/logtape\";\n\nimport { builder } from \"../src/builder.ts\";\nimport {\n E_FEDERATION_NOT_READY,\n E_INVALID_FEDIFY_CONFIG,\n} from \"../src/errors.ts\";\nimport FedifyMiddleware from \"../src/fedify_middleware.ts\";\nimport { installFederationGetter } from \"../src/http_context.ts\";\nimport { configureFedifyLogging } from \"../src/logging.ts\";\nimport type { ContextData, ResolvedFedifyConfig } from \"../src/types.ts\";\n\n/**\n * How long a request that arrives before `ready()` waits for the federation.\n *\n * Generous, since it only needs to outlast earlier providers' `ready()` hooks.\n * It turns a `ready()` that never comes (an earlier provider waiting on this\n * server) into an error instead of a request that never completes.\n */\nconst READY_TIMEOUT_MS = 30_000;\n\n/**\n * A memoised factory: the value, plus a way to drop what was cached.\n */\ntype Memoized<T> = (() => Promise<T>) & { forget(): void };\n\n/**\n * Memoises an asynchronous factory, caching successes only.\n *\n * Used for the container bindings instead of `container.singleton()`, which\n * also caches *rejections*: one early, swallowed `make('fedify')` would pin\n * `E_FEDERATION_NOT_READY` for the life of the process. A failed attempt is\n * forgotten instead, so the next caller runs the factory again. `forget()`\n * drops a cached success once the caller knows it is stale.\n */\nfunction memoizeSuccess<T>(factory: () => Promise<T>): Memoized<T> {\n let cached: Promise<T> | undefined;\n\n const memo = (): Promise<T> => {\n cached ??= factory().catch((error: unknown) => {\n cached = undefined;\n throw error;\n });\n\n return cached;\n };\n\n return Object.assign(memo, {\n forget: (): void => {\n cached = undefined;\n },\n });\n}\n\n/**\n * The service provider registered from `adonisrc.ts` as\n * `@fedify/adonisjs/fedify_provider`.\n *\n * Binds `fedify.builder`, `fedify.config`, `fedify` and\n * {@link FedifyMiddleware}, installs `ctx.federation`, bridges Fedify's logs\n * into the AdonisJS logger, builds the federation after the preload files\n * have run, and drains the task queue in the web process.\n */\nexport default class FedifyProvider {\n /**\n * Aborts the queue worker on shutdown.\n */\n #queueController = new AbortController();\n\n /**\n * The `startQueue()` promise, settled once every listener has stopped.\n * `shutdown()` returns it so AdonisJS waits for the workers. Undefined when\n * this process does not drain the queue.\n */\n #queue?: Promise<void>;\n\n /**\n * Whether this provider configured LogTape and must undo it on shutdown.\n *\n * LogTape's configuration is process-global and its sink closes over *this*\n * application's `Logger`. Left in place, a second application in the same\n * process (the test runner, a dev-server restart) would find LogTape already\n * configured and keep logging into the terminated application's logger.\n */\n #loggingConfigured = false;\n\n /**\n * Whether the builder may be sealed into a `Federation` object.\n *\n * Dispatchers are registered in preload files, which AdonisJS imports *after*\n * every provider's `boot()` and `start()`. Building earlier would yield a\n * federation with no routes and 404s as the only symptom, so an early build\n * fails with an explanatory error instead.\n */\n #buildable = false;\n\n /**\n * Whether the HTTP server has started accepting connections.\n *\n * AdonisJS listens inside `start()` and runs `ready()` hooks afterwards, so a\n * request (a health probe, `fedify tunnel`) can arrive before this provider\n * is ready. Such a request is the one caller allowed to *wait* for the\n * federation, since `ready()` is on its way; any other caller (a `start()`\n * hook, a preload file, an Ace command) fails fast because nothing would\n * make it ready while they wait.\n */\n #listening = false;\n\n /**\n * Settles once `ready()` has built the federation: resolved on success,\n * rejected with the configuration error, or with `E_FEDERATION_NOT_READY`\n * when the application shuts down first or {@link READY_TIMEOUT_MS} passes.\n */\n #ready = Promise.withResolvers<void>();\n #readyTimer?: ReturnType<typeof setTimeout>;\n\n /**\n * The memoised middleware binding, kept here so that a failed `ready()` can\n * forget it.\n *\n * A request that arrives while `ready()` is running builds its middleware\n * from a federation that is buildable at that moment. Should `ready()` fail\n * afterwards, that middleware would otherwise stay cached and keep serving\n * federation traffic in an application whose `make('fedify')` fails fast and\n * whose queue never started.\n */\n #middleware?: Memoized<FedifyMiddleware<ContextData>>;\n\n protected app: ApplicationService;\n\n /**\n * Longhand rather than a parameter property, which Node's type stripping\n * does not support; the tests run these sources through it.\n */\n constructor(app: ApplicationService) {\n this.app = app;\n\n // Only requests waiting on `ready()` observe the rejection; without this\n // handler Node would report it as unhandled when nobody was.\n this.#ready.promise.catch(() => {});\n }\n\n /**\n * Registers the container bindings.\n */\n register(): void {\n /**\n * Bound as a value: the builder is a module-level singleton that\n * application code also imports directly, and both routes must reach the\n * same object.\n */\n this.app.container.bindValue(\"fedify.builder\", builder);\n\n this.app.container.bind(\n \"fedify.config\",\n memoizeSuccess(async () => {\n const provider = this.app.config.get<\n ConfigProvider<ResolvedFedifyConfig>\n >(\"fedify\");\n const config = await configProvider.resolve<ResolvedFedifyConfig>(\n this.app,\n provider,\n );\n\n if (!config) {\n throw new E_INVALID_FEDIFY_CONFIG();\n }\n\n return config;\n }),\n );\n\n const buildFederation = memoizeSuccess(async () => {\n const config = await this.app.container.make(\"fedify.config\");\n const federationBuilder = await this.app.container.make(\"fedify.builder\");\n\n return federationBuilder.build(config);\n });\n\n this.app.container.bind(\"fedify\", () => {\n if (!this.#buildable) {\n throw new E_FEDERATION_NOT_READY();\n }\n\n return buildFederation();\n });\n\n /**\n * The middleware, built with the federation and configuration in scope, as\n * `@adonisjs/cors` and `@adonisjs/session` do. `server.use()` resolves\n * the class through the container on every request, which lands here.\n *\n * A plain `bind()` plus {@link memoizeSuccess} rather than `singleton()`\n * (see the helper), so every request shares one instance.\n *\n * A request that arrives after the server listens but before `ready()` has\n * built the federation waits for it (see {@link #listening}); any other\n * caller gets `E_FEDERATION_NOT_READY` at once.\n */\n this.#middleware = memoizeSuccess(async () => {\n if (!this.#buildable) {\n if (!this.#listening) throw new E_FEDERATION_NOT_READY();\n await this.#ready.promise;\n }\n\n const federation = await this.app.container.make(\"fedify\");\n const config = await this.app.container.make(\"fedify.config\");\n\n return new FedifyMiddleware<ContextData>(\n federation,\n config.contextDataFactory,\n { ignoreRoutePrefixes: config.ignoreRoutePrefixes },\n );\n });\n\n this.app.container.bind(FedifyMiddleware, this.#middleware);\n }\n\n /**\n * Installs `ctx.federation`, bridges Fedify's logs into the AdonisJS logger,\n * and subscribes to the HTTP server's ready event.\n */\n async boot(): Promise<void> {\n // `ctx.federation` as a Macroable getter on the `HttpContext` prototype.\n // The middleware also installs it on each context's class (covering\n // another `@adonisjs/core` copy); this covers requests the middleware\n // never saw, which then get `E_FEDIFY_CONTEXT_UNAVAILABLE` rather than\n // `undefined`.\n installFederationGetter();\n\n const config = await this.app.container.make(\"fedify.config\");\n\n if (config.logging !== false) {\n const logger = await this.app.container.make(\"logger\");\n this.#loggingConfigured = await configureFedifyLogging({\n logger,\n categories: config.logging === true\n ? undefined\n : config.logging.categories,\n });\n }\n\n // The core `app_provider` binds the emitter; a bare application in a test\n // may lack it, and then has no HTTP server to hear from either.\n if (this.app.container.hasBinding(\"emitter\")) {\n const emitter = await this.app.container.make(\"emitter\");\n emitter.on(\"http:server_ready\", () => this.#serverStarted());\n }\n }\n\n /**\n * Runs after the preload files have registered every dispatcher.\n */\n async ready(): Promise<void> {\n this.#buildable = true;\n\n // Build eagerly so a broken federation surfaces at startup rather than on\n // the first federation request. Requests waiting in the middleware\n // binding get the same outcome.\n let federation: Federation<ContextData>;\n let worker: { contextData: ContextData; logger: Logger } | undefined;\n try {\n federation = await this.app.container.make(\"fedify\");\n const config = await this.app.container.make(\"fedify.config\");\n\n // Only the web process drains the queue: Ace commands, the REPL and the\n // test runner also reach `ready()`, where a worker would outlive the\n // command and compete for the queue. The context data is built before\n // the waiting requests are released, so a throwing callback fails\n // startup like a broken federation instead of rejecting `ready()` with\n // requests already being served.\n if (\n typeof config.queueContextData === \"function\" &&\n this.app.getEnvironment() === \"web\"\n ) {\n worker = {\n contextData: await config.queueContextData(),\n logger: await this.app.container.make(\"logger\"),\n };\n }\n } catch (error: unknown) {\n // Back to failing fast: a surviving process (an Ace command, the REPL)\n // must not have later `make('fedify')` calls re-run the configuration,\n // nor keep the middleware a request built while this hook was still\n // running (see {@link #middleware}).\n this.#buildable = false;\n this.#middleware?.forget();\n this.#settle(error);\n throw error;\n }\n this.#settle();\n\n if (worker === undefined) return;\n\n // `shutdown()` can have run while this hook was awaiting above: it settles\n // and aborts, but finds no queue promise to wait for. Starting a worker on\n // the aborted signal now would leave one running that nothing awaits.\n if (this.#queueController.signal.aborted) return;\n\n // `startQueue` settles only when the queue stops, so it must not be\n // awaited here. The promise is kept for `shutdown()`, `catch` included,\n // so awaiting it there never rejects.\n const { contextData, logger } = worker;\n this.#queue = federation\n .startQueue(contextData, { signal: this.#queueController.signal })\n .catch((error: unknown) => {\n if (this.#queueController.signal.aborted) return;\n logger.error(\n { err: error },\n \"The Fedify task queue stopped unexpectedly\",\n );\n });\n }\n\n /**\n * Stops the queue worker and waits for it, releases any request still\n * waiting on `ready()`, and takes the LogTape configuration down.\n *\n * Aborting only *asks* the listeners to stop; `startQueue()` settles once\n * they have, possibly one in-flight delivery later. Returning that promise\n * keeps the rest of the shutdown sequence (closing the database, most\n * importantly) behind it.\n *\n * LogTape is reset after the queue stops, so an outgoing delivery can still\n * log, and only if this provider configured it (see\n * {@link #loggingConfigured}); resetting the application's own\n * configuration would silence its logs.\n *\n * The return type stays a promise even with no queue to wait for: AdonisJS\n * warns when a provider hook returns a non-thenable.\n */\n shutdown(): Promise<void> {\n this.#settle(new E_FEDERATION_NOT_READY());\n this.#queueController.abort();\n\n const stopped = this.#queue ?? Promise.resolve();\n if (!this.#loggingConfigured) return stopped;\n\n this.#loggingConfigured = false;\n // A failing reset must not fail the shutdown queued behind it. The queue\n // promise never rejects, so only the reset is guarded.\n return stopped.then(() => resetLogging().catch(() => {}));\n }\n\n /**\n * Called when the HTTP server starts listening and requests can arrive.\n */\n #serverStarted(): void {\n this.#listening = true;\n if (this.#buildable) return;\n\n this.#readyTimer = setTimeout(\n () => this.#settle(new E_FEDERATION_NOT_READY()),\n READY_TIMEOUT_MS,\n );\n // A pending timer must not keep the process alive.\n this.#readyTimer.unref();\n }\n\n /**\n * Settles the `ready()` promise once; later calls are no-ops.\n */\n #settle(error?: unknown): void {\n clearTimeout(this.#readyTimer);\n if (error === undefined) this.#ready.resolve();\n else this.#ready.reject(error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAM,mBAAmB;;;;;;;;;;AAgBzB,SAAS,eAAkB,SAAwC;CACjE,IAAI;CAEJ,MAAM,aAAyB;EAC7B,WAAW,QAAQ,CAAC,CAAC,OAAO,UAAmB;GAC7C,SAAS;GACT,MAAM;EACR,CAAC;EAED,OAAO;CACT;CAEA,OAAO,OAAO,OAAO,MAAM,EACzB,cAAoB;EAClB,SAAS;CACX,EACF,CAAC;AACH;;;;;;;;;;AAWA,IAAqB,iBAArB,MAAoC;;;;CAIlC,mBAAmB,IAAI,gBAAgB;;;;;;CAOvC;;;;;;;;;CAUA,qBAAqB;;;;;;;;;CAUrB,aAAa;;;;;;;;;;;CAYb,aAAa;;;;;;CAOb,SAAS,QAAQ,cAAoB;CACrC;;;;;;;;;;;CAYA;CAEA,AAAU;;;;;CAMV,Y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,iBAAiB,MAAM;EAE5B,MAAM,UAAU,KAAKC,UAAU,QAAQ,QAAQ;EAC/C,IAAI,CAAC,KAAKL,oBAAoB,OAAO;EAErC,KAAKA,qBAAqB;EAG1B,OAAO,QAAQ,uCAAwB,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC;CAC1D;;;;CAKA,iBAAuB;EACrB,KAAKF,aAAa;EAClB,IAAI,KAAKH,YAAY;EAErB,KAAKW,cAAc,iBACX,KAAKH,QAAQ,IAAIP,0CAAuB,CAAC,GAC/C,gBACF;EAEA,KAAKU,YAAY,MAAM;CACzB;;;;CAKA,QAAQ,OAAuB;EAC7B,aAAa,KAAKA,WAAW;EAC7B,IAAI,UAAU,WAAW,KAAKf,OAAO,QAAQ;OACxC,KAAKA,OAAO,OAAO,KAAK;CAC/B;AACF"}
|
|
1
|
+
{"version":3,"file":"fedify_provider.cjs","names":["#ready","builder","configProvider","E_INVALID_FEDIFY_CONFIG","#buildable","E_FEDERATION_NOT_READY","#middleware","#listening","FedifyMiddleware","#loggingConfigured","configureFedifyLogging","#serverStarted","#settle","#queueController","#queue","#readyTimer"],"sources":["../../providers/fedify_provider.ts"],"sourcesContent":["/**\n * The `@fedify/adonisjs` service provider; see {@link FedifyProvider}.\n *\n * @module\n */\nimport { configProvider } from \"@adonisjs/core\";\nimport type { Logger } from \"@adonisjs/core/logger\";\nimport type { ApplicationService, ConfigProvider } from \"@adonisjs/core/types\";\nimport type { Federation } from \"@fedify/fedify\";\nimport { reset as resetLogging } from \"@logtape/logtape\";\n\nimport { builder } from \"../src/builder.ts\";\nimport {\n E_FEDERATION_NOT_READY,\n E_INVALID_FEDIFY_CONFIG,\n} from \"../src/errors.ts\";\nimport FedifyMiddleware from \"../src/fedify_middleware.ts\";\nimport { installFederationGetter } from \"../src/http_context.ts\";\nimport { configureFedifyLogging } from \"../src/logging.ts\";\nimport type { ContextData, ResolvedFedifyConfig } from \"../src/types.ts\";\n\n/**\n * How long a request that arrives before `ready()` waits for the federation.\n *\n * Generous, since it only needs to outlast earlier providers' `ready()` hooks.\n * It turns a `ready()` that never comes (an earlier provider waiting on this\n * server) into an error instead of a request that never completes.\n */\nconst READY_TIMEOUT_MS = 30_000;\n\n/**\n * A memoised factory: the value, plus a way to drop what was cached.\n */\ntype Memoized<T> = (() => Promise<T>) & { forget(): void };\n\n/**\n * Memoises an asynchronous factory, caching successes only.\n *\n * Used for the container bindings instead of `container.singleton()`, which\n * also caches *rejections*: one early, swallowed `make('fedify')` would pin\n * `E_FEDERATION_NOT_READY` for the life of the process. A failed attempt is\n * forgotten instead, so the next caller runs the factory again. `forget()`\n * drops a cached success once the caller knows it is stale.\n */\nfunction memoizeSuccess<T>(factory: () => Promise<T>): Memoized<T> {\n let cached: Promise<T> | undefined;\n\n const memo = (): Promise<T> => {\n cached ??= factory().catch((error: unknown) => {\n cached = undefined;\n throw error;\n });\n\n return cached;\n };\n\n return Object.assign(memo, {\n forget: (): void => {\n cached = undefined;\n },\n });\n}\n\n/**\n * The service provider registered from `adonisrc.ts` as\n * `@fedify/adonisjs/fedify_provider`.\n *\n * Binds `fedify.builder`, `fedify.config`, `fedify` and\n * {@link FedifyMiddleware}, installs `ctx.federation`, bridges Fedify's logs\n * into the AdonisJS logger, builds the federation after the preload files\n * have run, and drains the task queue in the web process.\n */\nexport default class FedifyProvider {\n /**\n * Aborts the queue worker on shutdown.\n */\n #queueController = new AbortController();\n\n /**\n * The `startQueue()` promise, settled once every listener has stopped.\n * `shutdown()` returns it so AdonisJS waits for the workers. Undefined when\n * this process does not drain the queue.\n */\n #queue?: Promise<void>;\n\n /**\n * Whether this provider configured LogTape and must undo it on shutdown.\n *\n * LogTape's configuration is process-global and its sink closes over *this*\n * application's `Logger`. Left in place, a second application in the same\n * process (the test runner, a dev-server restart) would find LogTape already\n * configured and keep logging into the terminated application's logger.\n */\n #loggingConfigured = false;\n\n /**\n * Whether the builder may be sealed into a `Federation` object.\n *\n * Dispatchers are registered in preload files, which AdonisJS imports *after*\n * every provider's `boot()` and `start()`. Building earlier would yield a\n * federation with no routes and 404s as the only symptom, so an early build\n * fails with an explanatory error instead.\n */\n #buildable = false;\n\n /**\n * Whether the HTTP server has started accepting connections.\n *\n * AdonisJS listens inside `start()` and runs `ready()` hooks afterwards, so a\n * request (a health probe, `fedify tunnel`) can arrive before this provider\n * is ready. Such a request is the one caller allowed to *wait* for the\n * federation, since `ready()` is on its way; any other caller (a `start()`\n * hook, a preload file, an Ace command) fails fast because nothing would\n * make it ready while they wait.\n */\n #listening = false;\n\n /**\n * Settles once `ready()` has built the federation: resolved on success,\n * rejected with the configuration error, or with `E_FEDERATION_NOT_READY`\n * when the application shuts down first or {@link READY_TIMEOUT_MS} passes.\n */\n #ready = Promise.withResolvers<void>();\n #readyTimer?: ReturnType<typeof setTimeout>;\n\n /**\n * The memoised middleware binding, kept here so that a failed `ready()` can\n * forget it.\n *\n * A request that arrives while `ready()` is running builds its middleware\n * from a federation that is buildable at that moment. Should `ready()` fail\n * afterwards, that middleware would otherwise stay cached and keep serving\n * federation traffic in an application whose `make('fedify')` fails fast and\n * whose queue never started.\n */\n #middleware?: Memoized<FedifyMiddleware<ContextData>>;\n\n protected app: ApplicationService;\n\n /**\n * Longhand rather than a parameter property, which Node's type stripping\n * does not support; the tests run these sources through it.\n */\n constructor(app: ApplicationService) {\n this.app = app;\n\n // Only requests waiting on `ready()` observe the rejection; without this\n // handler Node would report it as unhandled when nobody was.\n this.#ready.promise.catch(() => {});\n }\n\n /**\n * Registers the container bindings.\n */\n register(): void {\n /**\n * Bound as a value: the builder is a module-level singleton that\n * application code also imports directly, and both routes must reach the\n * same object.\n */\n this.app.container.bindValue(\"fedify.builder\", builder);\n\n this.app.container.bind(\n \"fedify.config\",\n memoizeSuccess(async () => {\n const provider =\n this.app.config.get<ConfigProvider<ResolvedFedifyConfig>>(\"fedify\");\n const config = await configProvider.resolve<ResolvedFedifyConfig>(\n this.app,\n provider,\n );\n\n if (!config) {\n throw new E_INVALID_FEDIFY_CONFIG();\n }\n\n return config;\n }),\n );\n\n const buildFederation = memoizeSuccess(async () => {\n const config = await this.app.container.make(\"fedify.config\");\n const federationBuilder = await this.app.container.make(\"fedify.builder\");\n\n return federationBuilder.build(config);\n });\n\n this.app.container.bind(\"fedify\", () => {\n if (!this.#buildable) {\n throw new E_FEDERATION_NOT_READY();\n }\n\n return buildFederation();\n });\n\n /**\n * The middleware, built with the federation and configuration in scope, as\n * `@adonisjs/cors` and `@adonisjs/session` do. `server.use()` resolves\n * the class through the container on every request, which lands here.\n *\n * A plain `bind()` plus {@link memoizeSuccess} rather than `singleton()`\n * (see the helper), so every request shares one instance.\n *\n * A request that arrives after the server listens but before `ready()` has\n * built the federation waits for it (see {@link #listening}); any other\n * caller gets `E_FEDERATION_NOT_READY` at once.\n */\n this.#middleware = memoizeSuccess(async () => {\n if (!this.#buildable) {\n if (!this.#listening) throw new E_FEDERATION_NOT_READY();\n await this.#ready.promise;\n }\n\n const federation = await this.app.container.make(\"fedify\");\n const config = await this.app.container.make(\"fedify.config\");\n\n return new FedifyMiddleware<ContextData>(\n federation,\n config.contextDataFactory,\n { ignoreRoutePrefixes: config.ignoreRoutePrefixes },\n );\n });\n\n this.app.container.bind(FedifyMiddleware, this.#middleware);\n }\n\n /**\n * Installs `ctx.federation`, bridges Fedify's logs into the AdonisJS logger,\n * and subscribes to the HTTP server's ready event.\n */\n async boot(): Promise<void> {\n // `ctx.federation` as a Macroable getter on the `HttpContext` prototype.\n // The middleware also installs it on each context's class (covering\n // another `@adonisjs/core` copy); this covers requests the middleware\n // never saw, which then get `E_FEDIFY_CONTEXT_UNAVAILABLE` rather than\n // `undefined`.\n installFederationGetter();\n\n const config = await this.app.container.make(\"fedify.config\");\n\n if (config.logging !== false) {\n const logger = await this.app.container.make(\"logger\");\n this.#loggingConfigured = await configureFedifyLogging({\n logger,\n categories:\n config.logging === true ? undefined : config.logging.categories,\n });\n }\n\n // The core `app_provider` binds the emitter; a bare application in a test\n // may lack it, and then has no HTTP server to hear from either.\n if (this.app.container.hasBinding(\"emitter\")) {\n const emitter = await this.app.container.make(\"emitter\");\n emitter.on(\"http:server_ready\", () => this.#serverStarted());\n }\n }\n\n /**\n * Runs after the preload files have registered every dispatcher.\n */\n async ready(): Promise<void> {\n this.#buildable = true;\n\n // Build eagerly so a broken federation surfaces at startup rather than on\n // the first federation request. Requests waiting in the middleware\n // binding get the same outcome.\n let federation: Federation<ContextData>;\n let worker: { contextData: ContextData; logger: Logger } | undefined;\n try {\n federation = await this.app.container.make(\"fedify\");\n const config = await this.app.container.make(\"fedify.config\");\n\n // Only the web process drains the queue: Ace commands, the REPL and the\n // test runner also reach `ready()`, where a worker would outlive the\n // command and compete for the queue. The context data is built before\n // the waiting requests are released, so a throwing callback fails\n // startup like a broken federation instead of rejecting `ready()` with\n // requests already being served.\n if (\n typeof config.queueContextData === \"function\" &&\n this.app.getEnvironment() === \"web\"\n ) {\n worker = {\n contextData: await config.queueContextData(),\n logger: await this.app.container.make(\"logger\"),\n };\n }\n } catch (error: unknown) {\n // Back to failing fast: a surviving process (an Ace command, the REPL)\n // must not have later `make('fedify')` calls re-run the configuration,\n // nor keep the middleware a request built while this hook was still\n // running (see {@link #middleware}).\n this.#buildable = false;\n this.#middleware?.forget();\n this.#settle(error);\n throw error;\n }\n this.#settle();\n\n if (worker === undefined) return;\n\n // `shutdown()` can have run while this hook was awaiting above: it settles\n // and aborts, but finds no queue promise to wait for. Starting a worker on\n // the aborted signal now would leave one running that nothing awaits.\n if (this.#queueController.signal.aborted) return;\n\n // `startQueue` settles only when the queue stops, so it must not be\n // awaited here. The promise is kept for `shutdown()`, `catch` included,\n // so awaiting it there never rejects.\n const { contextData, logger } = worker;\n this.#queue = federation\n .startQueue(contextData, { signal: this.#queueController.signal })\n .catch((error: unknown) => {\n if (this.#queueController.signal.aborted) return;\n logger.error(\n { err: error },\n \"The Fedify task queue stopped unexpectedly\",\n );\n });\n }\n\n /**\n * Stops the queue worker and waits for it, releases any request still\n * waiting on `ready()`, and takes the LogTape configuration down.\n *\n * Aborting only *asks* the listeners to stop; `startQueue()` settles once\n * they have, possibly one in-flight delivery later. Returning that promise\n * keeps the rest of the shutdown sequence (closing the database, most\n * importantly) behind it.\n *\n * LogTape is reset after the queue stops, so an outgoing delivery can still\n * log, and only if this provider configured it (see\n * {@link #loggingConfigured}); resetting the application's own\n * configuration would silence its logs.\n *\n * The return type stays a promise even with no queue to wait for: AdonisJS\n * warns when a provider hook returns a non-thenable.\n */\n shutdown(): Promise<void> {\n this.#settle(new E_FEDERATION_NOT_READY());\n this.#queueController.abort();\n\n const stopped = this.#queue ?? Promise.resolve();\n if (!this.#loggingConfigured) return stopped;\n\n this.#loggingConfigured = false;\n // A failing reset must not fail the shutdown queued behind it. The queue\n // promise never rejects, so only the reset is guarded.\n return stopped.then(async () => {\n try {\n await resetLogging();\n } catch {\n // Reset failures must not fail the shutdown queued behind them.\n }\n });\n }\n\n /**\n * Called when the HTTP server starts listening and requests can arrive.\n */\n #serverStarted(): void {\n this.#listening = true;\n if (this.#buildable) return;\n\n this.#readyTimer = setTimeout(\n () => this.#settle(new E_FEDERATION_NOT_READY()),\n READY_TIMEOUT_MS,\n );\n // A pending timer must not keep the process alive.\n this.#readyTimer.unref();\n }\n\n /**\n * Settles the `ready()` promise once; later calls are no-ops.\n */\n #settle(error?: unknown): void {\n clearTimeout(this.#readyTimer);\n if (error === undefined) this.#ready.resolve();\n else this.#ready.reject(error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4BA,MAAM,mBAAmB;;;;;;;;;;AAgBzB,SAAS,eAAkB,SAAwC;CACjE,IAAI;CAEJ,MAAM,aAAyB;EAC7B,WAAW,QAAQ,CAAC,CAAC,OAAO,UAAmB;GAC7C,SAAS;GACT,MAAM;EACR,CAAC;EAED,OAAO;CACT;CAEA,OAAO,OAAO,OAAO,MAAM,EACzB,cAAoB;EAClB,SAAS;CACX,EACF,CAAC;AACH;;;;;;;;;;AAWA,IAAqB,iBAArB,MAAoC;;;;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B;GACzB,IAAI,KAAKA,iBAAiB,OAAO,SAAS;GAC1C,OAAO,MACL,EAAE,KAAK,MAAM,GACb,4CACF;EACF,CAAC;CACL;;;;;;;;;;;;;;;;;;CAmBA,WAA0B;EACxB,KAAKD,QAAQ,IAAIP,0CAAuB,CAAC;EACzC,KAAKQ,iBAAiB,MAAM;EAE5B,MAAM,UAAU,KAAKC,UAAU,QAAQ,QAAQ;EAC/C,IAAI,CAAC,KAAKL,oBAAoB,OAAO;EAErC,KAAKA,qBAAqB;EAG1B,OAAO,QAAQ,KAAK,YAAY;GAC9B,IAAI;IACF,kCAAmB;GACrB,QAAQ,CAER;EACF,CAAC;CACH;;;;CAKA,iBAAuB;EACrB,KAAKF,aAAa;EAClB,IAAI,KAAKH,YAAY;EAErB,KAAKW,cAAc,iBACX,KAAKH,QAAQ,IAAIP,0CAAuB,CAAC,GAC/C,gBACF;EAEA,KAAKU,YAAY,MAAM;CACzB;;;;CAKA,QAAQ,OAAuB;EAC7B,aAAa,KAAKA,WAAW;EAC7B,IAAI,UAAU,WAAW,KAAKf,OAAO,QAAQ;OACxC,KAAKA,OAAO,OAAO,KAAK;CAC/B;AACF"}
|
|
@@ -243,7 +243,11 @@ var FedifyProvider = class {
|
|
|
243
243
|
const stopped = this.#queue ?? Promise.resolve();
|
|
244
244
|
if (!this.#loggingConfigured) return stopped;
|
|
245
245
|
this.#loggingConfigured = false;
|
|
246
|
-
return stopped.then(
|
|
246
|
+
return stopped.then(async () => {
|
|
247
|
+
try {
|
|
248
|
+
await reset();
|
|
249
|
+
} catch {}
|
|
250
|
+
});
|
|
247
251
|
}
|
|
248
252
|
/**
|
|
249
253
|
* Called when the HTTP server starts listening and requests can arrive.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fedify_provider.js","names":["#ready","#buildable","#middleware","#listening","#loggingConfigured","#serverStarted","#settle","#queueController","#queue","resetLogging","#readyTimer"],"sources":["../../providers/fedify_provider.ts"],"sourcesContent":["/**\n * The `@fedify/adonisjs` service provider; see {@link FedifyProvider}.\n *\n * @module\n */\nimport { configProvider } from \"@adonisjs/core\";\nimport type { Logger } from \"@adonisjs/core/logger\";\nimport type { ApplicationService, ConfigProvider } from \"@adonisjs/core/types\";\nimport type { Federation } from \"@fedify/fedify\";\nimport { reset as resetLogging } from \"@logtape/logtape\";\n\nimport { builder } from \"../src/builder.ts\";\nimport {\n E_FEDERATION_NOT_READY,\n E_INVALID_FEDIFY_CONFIG,\n} from \"../src/errors.ts\";\nimport FedifyMiddleware from \"../src/fedify_middleware.ts\";\nimport { installFederationGetter } from \"../src/http_context.ts\";\nimport { configureFedifyLogging } from \"../src/logging.ts\";\nimport type { ContextData, ResolvedFedifyConfig } from \"../src/types.ts\";\n\n/**\n * How long a request that arrives before `ready()` waits for the federation.\n *\n * Generous, since it only needs to outlast earlier providers' `ready()` hooks.\n * It turns a `ready()` that never comes (an earlier provider waiting on this\n * server) into an error instead of a request that never completes.\n */\nconst READY_TIMEOUT_MS = 30_000;\n\n/**\n * A memoised factory: the value, plus a way to drop what was cached.\n */\ntype Memoized<T> = (() => Promise<T>) & { forget(): void };\n\n/**\n * Memoises an asynchronous factory, caching successes only.\n *\n * Used for the container bindings instead of `container.singleton()`, which\n * also caches *rejections*: one early, swallowed `make('fedify')` would pin\n * `E_FEDERATION_NOT_READY` for the life of the process. A failed attempt is\n * forgotten instead, so the next caller runs the factory again. `forget()`\n * drops a cached success once the caller knows it is stale.\n */\nfunction memoizeSuccess<T>(factory: () => Promise<T>): Memoized<T> {\n let cached: Promise<T> | undefined;\n\n const memo = (): Promise<T> => {\n cached ??= factory().catch((error: unknown) => {\n cached = undefined;\n throw error;\n });\n\n return cached;\n };\n\n return Object.assign(memo, {\n forget: (): void => {\n cached = undefined;\n },\n });\n}\n\n/**\n * The service provider registered from `adonisrc.ts` as\n * `@fedify/adonisjs/fedify_provider`.\n *\n * Binds `fedify.builder`, `fedify.config`, `fedify` and\n * {@link FedifyMiddleware}, installs `ctx.federation`, bridges Fedify's logs\n * into the AdonisJS logger, builds the federation after the preload files\n * have run, and drains the task queue in the web process.\n */\nexport default class FedifyProvider {\n /**\n * Aborts the queue worker on shutdown.\n */\n #queueController = new AbortController();\n\n /**\n * The `startQueue()` promise, settled once every listener has stopped.\n * `shutdown()` returns it so AdonisJS waits for the workers. Undefined when\n * this process does not drain the queue.\n */\n #queue?: Promise<void>;\n\n /**\n * Whether this provider configured LogTape and must undo it on shutdown.\n *\n * LogTape's configuration is process-global and its sink closes over *this*\n * application's `Logger`. Left in place, a second application in the same\n * process (the test runner, a dev-server restart) would find LogTape already\n * configured and keep logging into the terminated application's logger.\n */\n #loggingConfigured = false;\n\n /**\n * Whether the builder may be sealed into a `Federation` object.\n *\n * Dispatchers are registered in preload files, which AdonisJS imports *after*\n * every provider's `boot()` and `start()`. Building earlier would yield a\n * federation with no routes and 404s as the only symptom, so an early build\n * fails with an explanatory error instead.\n */\n #buildable = false;\n\n /**\n * Whether the HTTP server has started accepting connections.\n *\n * AdonisJS listens inside `start()` and runs `ready()` hooks afterwards, so a\n * request (a health probe, `fedify tunnel`) can arrive before this provider\n * is ready. Such a request is the one caller allowed to *wait* for the\n * federation, since `ready()` is on its way; any other caller (a `start()`\n * hook, a preload file, an Ace command) fails fast because nothing would\n * make it ready while they wait.\n */\n #listening = false;\n\n /**\n * Settles once `ready()` has built the federation: resolved on success,\n * rejected with the configuration error, or with `E_FEDERATION_NOT_READY`\n * when the application shuts down first or {@link READY_TIMEOUT_MS} passes.\n */\n #ready = Promise.withResolvers<void>();\n #readyTimer?: ReturnType<typeof setTimeout>;\n\n /**\n * The memoised middleware binding, kept here so that a failed `ready()` can\n * forget it.\n *\n * A request that arrives while `ready()` is running builds its middleware\n * from a federation that is buildable at that moment. Should `ready()` fail\n * afterwards, that middleware would otherwise stay cached and keep serving\n * federation traffic in an application whose `make('fedify')` fails fast and\n * whose queue never started.\n */\n #middleware?: Memoized<FedifyMiddleware<ContextData>>;\n\n protected app: ApplicationService;\n\n /**\n * Longhand rather than a parameter property, which Node's type stripping\n * does not support; the tests run these sources through it.\n */\n constructor(app: ApplicationService) {\n this.app = app;\n\n // Only requests waiting on `ready()` observe the rejection; without this\n // handler Node would report it as unhandled when nobody was.\n this.#ready.promise.catch(() => {});\n }\n\n /**\n * Registers the container bindings.\n */\n register(): void {\n /**\n * Bound as a value: the builder is a module-level singleton that\n * application code also imports directly, and both routes must reach the\n * same object.\n */\n this.app.container.bindValue(\"fedify.builder\", builder);\n\n this.app.container.bind(\n \"fedify.config\",\n memoizeSuccess(async () => {\n const provider = this.app.config.get<\n ConfigProvider<ResolvedFedifyConfig>\n >(\"fedify\");\n const config = await configProvider.resolve<ResolvedFedifyConfig>(\n this.app,\n provider,\n );\n\n if (!config) {\n throw new E_INVALID_FEDIFY_CONFIG();\n }\n\n return config;\n }),\n );\n\n const buildFederation = memoizeSuccess(async () => {\n const config = await this.app.container.make(\"fedify.config\");\n const federationBuilder = await this.app.container.make(\"fedify.builder\");\n\n return federationBuilder.build(config);\n });\n\n this.app.container.bind(\"fedify\", () => {\n if (!this.#buildable) {\n throw new E_FEDERATION_NOT_READY();\n }\n\n return buildFederation();\n });\n\n /**\n * The middleware, built with the federation and configuration in scope, as\n * `@adonisjs/cors` and `@adonisjs/session` do. `server.use()` resolves\n * the class through the container on every request, which lands here.\n *\n * A plain `bind()` plus {@link memoizeSuccess} rather than `singleton()`\n * (see the helper), so every request shares one instance.\n *\n * A request that arrives after the server listens but before `ready()` has\n * built the federation waits for it (see {@link #listening}); any other\n * caller gets `E_FEDERATION_NOT_READY` at once.\n */\n this.#middleware = memoizeSuccess(async () => {\n if (!this.#buildable) {\n if (!this.#listening) throw new E_FEDERATION_NOT_READY();\n await this.#ready.promise;\n }\n\n const federation = await this.app.container.make(\"fedify\");\n const config = await this.app.container.make(\"fedify.config\");\n\n return new FedifyMiddleware<ContextData>(\n federation,\n config.contextDataFactory,\n { ignoreRoutePrefixes: config.ignoreRoutePrefixes },\n );\n });\n\n this.app.container.bind(FedifyMiddleware, this.#middleware);\n }\n\n /**\n * Installs `ctx.federation`, bridges Fedify's logs into the AdonisJS logger,\n * and subscribes to the HTTP server's ready event.\n */\n async boot(): Promise<void> {\n // `ctx.federation` as a Macroable getter on the `HttpContext` prototype.\n // The middleware also installs it on each context's class (covering\n // another `@adonisjs/core` copy); this covers requests the middleware\n // never saw, which then get `E_FEDIFY_CONTEXT_UNAVAILABLE` rather than\n // `undefined`.\n installFederationGetter();\n\n const config = await this.app.container.make(\"fedify.config\");\n\n if (config.logging !== false) {\n const logger = await this.app.container.make(\"logger\");\n this.#loggingConfigured = await configureFedifyLogging({\n logger,\n categories: config.logging === true\n ? undefined\n : config.logging.categories,\n });\n }\n\n // The core `app_provider` binds the emitter; a bare application in a test\n // may lack it, and then has no HTTP server to hear from either.\n if (this.app.container.hasBinding(\"emitter\")) {\n const emitter = await this.app.container.make(\"emitter\");\n emitter.on(\"http:server_ready\", () => this.#serverStarted());\n }\n }\n\n /**\n * Runs after the preload files have registered every dispatcher.\n */\n async ready(): Promise<void> {\n this.#buildable = true;\n\n // Build eagerly so a broken federation surfaces at startup rather than on\n // the first federation request. Requests waiting in the middleware\n // binding get the same outcome.\n let federation: Federation<ContextData>;\n let worker: { contextData: ContextData; logger: Logger } | undefined;\n try {\n federation = await this.app.container.make(\"fedify\");\n const config = await this.app.container.make(\"fedify.config\");\n\n // Only the web process drains the queue: Ace commands, the REPL and the\n // test runner also reach `ready()`, where a worker would outlive the\n // command and compete for the queue. The context data is built before\n // the waiting requests are released, so a throwing callback fails\n // startup like a broken federation instead of rejecting `ready()` with\n // requests already being served.\n if (\n typeof config.queueContextData === \"function\" &&\n this.app.getEnvironment() === \"web\"\n ) {\n worker = {\n contextData: await config.queueContextData(),\n logger: await this.app.container.make(\"logger\"),\n };\n }\n } catch (error: unknown) {\n // Back to failing fast: a surviving process (an Ace command, the REPL)\n // must not have later `make('fedify')` calls re-run the configuration,\n // nor keep the middleware a request built while this hook was still\n // running (see {@link #middleware}).\n this.#buildable = false;\n this.#middleware?.forget();\n this.#settle(error);\n throw error;\n }\n this.#settle();\n\n if (worker === undefined) return;\n\n // `shutdown()` can have run while this hook was awaiting above: it settles\n // and aborts, but finds no queue promise to wait for. Starting a worker on\n // the aborted signal now would leave one running that nothing awaits.\n if (this.#queueController.signal.aborted) return;\n\n // `startQueue` settles only when the queue stops, so it must not be\n // awaited here. The promise is kept for `shutdown()`, `catch` included,\n // so awaiting it there never rejects.\n const { contextData, logger } = worker;\n this.#queue = federation\n .startQueue(contextData, { signal: this.#queueController.signal })\n .catch((error: unknown) => {\n if (this.#queueController.signal.aborted) return;\n logger.error(\n { err: error },\n \"The Fedify task queue stopped unexpectedly\",\n );\n });\n }\n\n /**\n * Stops the queue worker and waits for it, releases any request still\n * waiting on `ready()`, and takes the LogTape configuration down.\n *\n * Aborting only *asks* the listeners to stop; `startQueue()` settles once\n * they have, possibly one in-flight delivery later. Returning that promise\n * keeps the rest of the shutdown sequence (closing the database, most\n * importantly) behind it.\n *\n * LogTape is reset after the queue stops, so an outgoing delivery can still\n * log, and only if this provider configured it (see\n * {@link #loggingConfigured}); resetting the application's own\n * configuration would silence its logs.\n *\n * The return type stays a promise even with no queue to wait for: AdonisJS\n * warns when a provider hook returns a non-thenable.\n */\n shutdown(): Promise<void> {\n this.#settle(new E_FEDERATION_NOT_READY());\n this.#queueController.abort();\n\n const stopped = this.#queue ?? Promise.resolve();\n if (!this.#loggingConfigured) return stopped;\n\n this.#loggingConfigured = false;\n // A failing reset must not fail the shutdown queued behind it. The queue\n // promise never rejects, so only the reset is guarded.\n return stopped.then(() => resetLogging().catch(() => {}));\n }\n\n /**\n * Called when the HTTP server starts listening and requests can arrive.\n */\n #serverStarted(): void {\n this.#listening = true;\n if (this.#buildable) return;\n\n this.#readyTimer = setTimeout(\n () => this.#settle(new E_FEDERATION_NOT_READY()),\n READY_TIMEOUT_MS,\n );\n // A pending timer must not keep the process alive.\n this.#readyTimer.unref();\n }\n\n /**\n * Settles the `ready()` promise once; later calls are no-ops.\n */\n #settle(error?: unknown): void {\n clearTimeout(this.#readyTimer);\n if (error === undefined) this.#ready.resolve();\n else this.#ready.reject(error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4BA,MAAM,mBAAmB;;;;;;;;;;AAgBzB,SAAS,eAAkB,SAAwC;CACjE,IAAI;CAEJ,MAAM,aAAyB;EAC7B,WAAW,QAAQ,CAAC,CAAC,OAAO,UAAmB;GAC7C,SAAS;GACT,MAAM;EACR,CAAC;EAED,OAAO;CACT;CAEA,OAAO,OAAO,OAAO,MAAM,EACzB,cAAoB;EAClB,SAAS;CACX,EACF,CAAC;AACH;;;;;;;;;;AAWA,IAAqB,iBAArB,MAAoC;;;;CAIlC,mBAAmB,IAAI,gBAAgB;;;;;;CAOvC;;;;;;;;;CAUA,qBAAqB;;;;;;;;;CAUrB,aAAa;;;;;;;;;;;CAYb,aAAa;;;;;;CAOb,SAAS,QAAQ,cAAoB;CACrC;;;;;;;;;;;CAYA;CAEA,AAAU;;;;;CAMV,YAAY,KAAyB;EACnC,KAAK,MAAM;EAIX,KAAKA,OAAO,QAAQ,YAAY,CAAC,CAAC;CACpC;;;;CAKA,WAAiB;;;;;;EAMf,KAAK,IAAI,UAAU,UAAU,kBAAkB,OAAO;EAEtD,KAAK,IAAI,UAAU,KACjB,iBACA,eAAe,YAAY;GACzB,MAAM,WAAW,KAAK,IAAI,OAAO,IAE/B,QAAQ;GACV,MAAM,SAAS,MAAM,eAAe,QAClC,KAAK,KACL,QACF;GAEA,IAAI,CAAC,QAAQ;IACX,MAAM,IAAI,wBAAwB;GACpC;GAEA,OAAO;EACT,CAAC,CACH;EAEA,MAAM,kBAAkB,eAAe,YAAY;GACjD,MAAM,SAAS,MAAM,KAAK,IAAI,UAAU,KAAK,eAAe;GAC5D,MAAM,oBAAoB,MAAM,KAAK,IAAI,UAAU,KAAK,gBAAgB;GAExE,OAAO,kBAAkB,MAAM,MAAM;EACvC,CAAC;EAED,KAA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","#queueController","#queue","resetLogging","#readyTimer"],"sources":["../../providers/fedify_provider.ts"],"sourcesContent":["/**\n * The `@fedify/adonisjs` service provider; see {@link FedifyProvider}.\n *\n * @module\n */\nimport { configProvider } from \"@adonisjs/core\";\nimport type { Logger } from \"@adonisjs/core/logger\";\nimport type { ApplicationService, ConfigProvider } from \"@adonisjs/core/types\";\nimport type { Federation } from \"@fedify/fedify\";\nimport { reset as resetLogging } from \"@logtape/logtape\";\n\nimport { builder } from \"../src/builder.ts\";\nimport {\n E_FEDERATION_NOT_READY,\n E_INVALID_FEDIFY_CONFIG,\n} from \"../src/errors.ts\";\nimport FedifyMiddleware from \"../src/fedify_middleware.ts\";\nimport { installFederationGetter } from \"../src/http_context.ts\";\nimport { configureFedifyLogging } from \"../src/logging.ts\";\nimport type { ContextData, ResolvedFedifyConfig } from \"../src/types.ts\";\n\n/**\n * How long a request that arrives before `ready()` waits for the federation.\n *\n * Generous, since it only needs to outlast earlier providers' `ready()` hooks.\n * It turns a `ready()` that never comes (an earlier provider waiting on this\n * server) into an error instead of a request that never completes.\n */\nconst READY_TIMEOUT_MS = 30_000;\n\n/**\n * A memoised factory: the value, plus a way to drop what was cached.\n */\ntype Memoized<T> = (() => Promise<T>) & { forget(): void };\n\n/**\n * Memoises an asynchronous factory, caching successes only.\n *\n * Used for the container bindings instead of `container.singleton()`, which\n * also caches *rejections*: one early, swallowed `make('fedify')` would pin\n * `E_FEDERATION_NOT_READY` for the life of the process. A failed attempt is\n * forgotten instead, so the next caller runs the factory again. `forget()`\n * drops a cached success once the caller knows it is stale.\n */\nfunction memoizeSuccess<T>(factory: () => Promise<T>): Memoized<T> {\n let cached: Promise<T> | undefined;\n\n const memo = (): Promise<T> => {\n cached ??= factory().catch((error: unknown) => {\n cached = undefined;\n throw error;\n });\n\n return cached;\n };\n\n return Object.assign(memo, {\n forget: (): void => {\n cached = undefined;\n },\n });\n}\n\n/**\n * The service provider registered from `adonisrc.ts` as\n * `@fedify/adonisjs/fedify_provider`.\n *\n * Binds `fedify.builder`, `fedify.config`, `fedify` and\n * {@link FedifyMiddleware}, installs `ctx.federation`, bridges Fedify's logs\n * into the AdonisJS logger, builds the federation after the preload files\n * have run, and drains the task queue in the web process.\n */\nexport default class FedifyProvider {\n /**\n * Aborts the queue worker on shutdown.\n */\n #queueController = new AbortController();\n\n /**\n * The `startQueue()` promise, settled once every listener has stopped.\n * `shutdown()` returns it so AdonisJS waits for the workers. Undefined when\n * this process does not drain the queue.\n */\n #queue?: Promise<void>;\n\n /**\n * Whether this provider configured LogTape and must undo it on shutdown.\n *\n * LogTape's configuration is process-global and its sink closes over *this*\n * application's `Logger`. Left in place, a second application in the same\n * process (the test runner, a dev-server restart) would find LogTape already\n * configured and keep logging into the terminated application's logger.\n */\n #loggingConfigured = false;\n\n /**\n * Whether the builder may be sealed into a `Federation` object.\n *\n * Dispatchers are registered in preload files, which AdonisJS imports *after*\n * every provider's `boot()` and `start()`. Building earlier would yield a\n * federation with no routes and 404s as the only symptom, so an early build\n * fails with an explanatory error instead.\n */\n #buildable = false;\n\n /**\n * Whether the HTTP server has started accepting connections.\n *\n * AdonisJS listens inside `start()` and runs `ready()` hooks afterwards, so a\n * request (a health probe, `fedify tunnel`) can arrive before this provider\n * is ready. Such a request is the one caller allowed to *wait* for the\n * federation, since `ready()` is on its way; any other caller (a `start()`\n * hook, a preload file, an Ace command) fails fast because nothing would\n * make it ready while they wait.\n */\n #listening = false;\n\n /**\n * Settles once `ready()` has built the federation: resolved on success,\n * rejected with the configuration error, or with `E_FEDERATION_NOT_READY`\n * when the application shuts down first or {@link READY_TIMEOUT_MS} passes.\n */\n #ready = Promise.withResolvers<void>();\n #readyTimer?: ReturnType<typeof setTimeout>;\n\n /**\n * The memoised middleware binding, kept here so that a failed `ready()` can\n * forget it.\n *\n * A request that arrives while `ready()` is running builds its middleware\n * from a federation that is buildable at that moment. Should `ready()` fail\n * afterwards, that middleware would otherwise stay cached and keep serving\n * federation traffic in an application whose `make('fedify')` fails fast and\n * whose queue never started.\n */\n #middleware?: Memoized<FedifyMiddleware<ContextData>>;\n\n protected app: ApplicationService;\n\n /**\n * Longhand rather than a parameter property, which Node's type stripping\n * does not support; the tests run these sources through it.\n */\n constructor(app: ApplicationService) {\n this.app = app;\n\n // Only requests waiting on `ready()` observe the rejection; without this\n // handler Node would report it as unhandled when nobody was.\n this.#ready.promise.catch(() => {});\n }\n\n /**\n * Registers the container bindings.\n */\n register(): void {\n /**\n * Bound as a value: the builder is a module-level singleton that\n * application code also imports directly, and both routes must reach the\n * same object.\n */\n this.app.container.bindValue(\"fedify.builder\", builder);\n\n this.app.container.bind(\n \"fedify.config\",\n memoizeSuccess(async () => {\n const provider =\n this.app.config.get<ConfigProvider<ResolvedFedifyConfig>>(\"fedify\");\n const config = await configProvider.resolve<ResolvedFedifyConfig>(\n this.app,\n provider,\n );\n\n if (!config) {\n throw new E_INVALID_FEDIFY_CONFIG();\n }\n\n return config;\n }),\n );\n\n const buildFederation = memoizeSuccess(async () => {\n const config = await this.app.container.make(\"fedify.config\");\n const federationBuilder = await this.app.container.make(\"fedify.builder\");\n\n return federationBuilder.build(config);\n });\n\n this.app.container.bind(\"fedify\", () => {\n if (!this.#buildable) {\n throw new E_FEDERATION_NOT_READY();\n }\n\n return buildFederation();\n });\n\n /**\n * The middleware, built with the federation and configuration in scope, as\n * `@adonisjs/cors` and `@adonisjs/session` do. `server.use()` resolves\n * the class through the container on every request, which lands here.\n *\n * A plain `bind()` plus {@link memoizeSuccess} rather than `singleton()`\n * (see the helper), so every request shares one instance.\n *\n * A request that arrives after the server listens but before `ready()` has\n * built the federation waits for it (see {@link #listening}); any other\n * caller gets `E_FEDERATION_NOT_READY` at once.\n */\n this.#middleware = memoizeSuccess(async () => {\n if (!this.#buildable) {\n if (!this.#listening) throw new E_FEDERATION_NOT_READY();\n await this.#ready.promise;\n }\n\n const federation = await this.app.container.make(\"fedify\");\n const config = await this.app.container.make(\"fedify.config\");\n\n return new FedifyMiddleware<ContextData>(\n federation,\n config.contextDataFactory,\n { ignoreRoutePrefixes: config.ignoreRoutePrefixes },\n );\n });\n\n this.app.container.bind(FedifyMiddleware, this.#middleware);\n }\n\n /**\n * Installs `ctx.federation`, bridges Fedify's logs into the AdonisJS logger,\n * and subscribes to the HTTP server's ready event.\n */\n async boot(): Promise<void> {\n // `ctx.federation` as a Macroable getter on the `HttpContext` prototype.\n // The middleware also installs it on each context's class (covering\n // another `@adonisjs/core` copy); this covers requests the middleware\n // never saw, which then get `E_FEDIFY_CONTEXT_UNAVAILABLE` rather than\n // `undefined`.\n installFederationGetter();\n\n const config = await this.app.container.make(\"fedify.config\");\n\n if (config.logging !== false) {\n const logger = await this.app.container.make(\"logger\");\n this.#loggingConfigured = await configureFedifyLogging({\n logger,\n categories:\n config.logging === true ? undefined : config.logging.categories,\n });\n }\n\n // The core `app_provider` binds the emitter; a bare application in a test\n // may lack it, and then has no HTTP server to hear from either.\n if (this.app.container.hasBinding(\"emitter\")) {\n const emitter = await this.app.container.make(\"emitter\");\n emitter.on(\"http:server_ready\", () => this.#serverStarted());\n }\n }\n\n /**\n * Runs after the preload files have registered every dispatcher.\n */\n async ready(): Promise<void> {\n this.#buildable = true;\n\n // Build eagerly so a broken federation surfaces at startup rather than on\n // the first federation request. Requests waiting in the middleware\n // binding get the same outcome.\n let federation: Federation<ContextData>;\n let worker: { contextData: ContextData; logger: Logger } | undefined;\n try {\n federation = await this.app.container.make(\"fedify\");\n const config = await this.app.container.make(\"fedify.config\");\n\n // Only the web process drains the queue: Ace commands, the REPL and the\n // test runner also reach `ready()`, where a worker would outlive the\n // command and compete for the queue. The context data is built before\n // the waiting requests are released, so a throwing callback fails\n // startup like a broken federation instead of rejecting `ready()` with\n // requests already being served.\n if (\n typeof config.queueContextData === \"function\" &&\n this.app.getEnvironment() === \"web\"\n ) {\n worker = {\n contextData: await config.queueContextData(),\n logger: await this.app.container.make(\"logger\"),\n };\n }\n } catch (error: unknown) {\n // Back to failing fast: a surviving process (an Ace command, the REPL)\n // must not have later `make('fedify')` calls re-run the configuration,\n // nor keep the middleware a request built while this hook was still\n // running (see {@link #middleware}).\n this.#buildable = false;\n this.#middleware?.forget();\n this.#settle(error);\n throw error;\n }\n this.#settle();\n\n if (worker === undefined) return;\n\n // `shutdown()` can have run while this hook was awaiting above: it settles\n // and aborts, but finds no queue promise to wait for. Starting a worker on\n // the aborted signal now would leave one running that nothing awaits.\n if (this.#queueController.signal.aborted) return;\n\n // `startQueue` settles only when the queue stops, so it must not be\n // awaited here. The promise is kept for `shutdown()`, `catch` included,\n // so awaiting it there never rejects.\n const { contextData, logger } = worker;\n this.#queue = federation\n .startQueue(contextData, { signal: this.#queueController.signal })\n .catch((error: unknown) => {\n if (this.#queueController.signal.aborted) return;\n logger.error(\n { err: error },\n \"The Fedify task queue stopped unexpectedly\",\n );\n });\n }\n\n /**\n * Stops the queue worker and waits for it, releases any request still\n * waiting on `ready()`, and takes the LogTape configuration down.\n *\n * Aborting only *asks* the listeners to stop; `startQueue()` settles once\n * they have, possibly one in-flight delivery later. Returning that promise\n * keeps the rest of the shutdown sequence (closing the database, most\n * importantly) behind it.\n *\n * LogTape is reset after the queue stops, so an outgoing delivery can still\n * log, and only if this provider configured it (see\n * {@link #loggingConfigured}); resetting the application's own\n * configuration would silence its logs.\n *\n * The return type stays a promise even with no queue to wait for: AdonisJS\n * warns when a provider hook returns a non-thenable.\n */\n shutdown(): Promise<void> {\n this.#settle(new E_FEDERATION_NOT_READY());\n this.#queueController.abort();\n\n const stopped = this.#queue ?? Promise.resolve();\n if (!this.#loggingConfigured) return stopped;\n\n this.#loggingConfigured = false;\n // A failing reset must not fail the shutdown queued behind it. The queue\n // promise never rejects, so only the reset is guarded.\n return stopped.then(async () => {\n try {\n await resetLogging();\n } catch {\n // Reset failures must not fail the shutdown queued behind them.\n }\n });\n }\n\n /**\n * Called when the HTTP server starts listening and requests can arrive.\n */\n #serverStarted(): void {\n this.#listening = true;\n if (this.#buildable) return;\n\n this.#readyTimer = setTimeout(\n () => this.#settle(new E_FEDERATION_NOT_READY()),\n READY_TIMEOUT_MS,\n );\n // A pending timer must not keep the process alive.\n this.#readyTimer.unref();\n }\n\n /**\n * Settles the `ready()` promise once; later calls are no-ops.\n */\n #settle(error?: unknown): void {\n clearTimeout(this.#readyTimer);\n if (error === undefined) this.#ready.resolve();\n else this.#ready.reject(error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA4BA,MAAM,mBAAmB;;;;;;;;;;AAgBzB,SAAS,eAAkB,SAAwC;CACjE,IAAI;CAEJ,MAAM,aAAyB;EAC7B,WAAW,QAAQ,CAAC,CAAC,OAAO,UAAmB;GAC7C,SAAS;GACT,MAAM;EACR,CAAC;EAED,OAAO;CACT;CAEA,OAAO,OAAO,OAAO,MAAM,EACzB,cAAoB;EAClB,SAAS;CACX,EACF,CAAC;AACH;;;;;;;;;;AAWA,IAAqB,iBAArB,MAAoC;;;;CAIlC,mBAAmB,IAAI,gBAAgB;;;;;;CAOvC;;;;;;;;;CAUA,qBAAqB;;;;;;;;;CAUrB,aAAa;;;;;;;;;;;CAYb,aAAa;;;;;;CAOb,SAAS,QAAQ,cAAoB;CACrC;;;;;;;;;;;CAYA;CAEA,AAAU;;;;;CAMV,YAAY,KAAyB;EACnC,KAAK,MAAM;EAIX,KAAKA,OAAO,QAAQ,YAAY,CAAC,CAAC;CACpC;;;;CAKA,WAAiB;;;;;;EAMf,KAAK,IAAI,UAAU,UAAU,kBAAkB,OAAO;EAEtD,KAAK,IAAI,UAAU,KACjB,iBACA,eAAe,YAAY;GACzB,MAAM,WACJ,KAAK,IAAI,OAAO,IAA0C,QAAQ;GACpE,MAAM,SAAS,MAAM,eAAe,QAClC,KAAK,KACL,QACF;GAEA,IAAI,CAAC,QAAQ;IACX,MAAM,IAAI,wBAAwB;GACpC;GAEA,OAAO;EACT,CAAC,CACH;EAEA,MAAM,kBAAkB,eAAe,YAAY;GACjD,MAAM,SAAS,MAAM,KAAK,IAAI,UAAU,KAAK,eAAe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AQ;OACxC,KAAKA,OAAO,OAAO,KAAK;CAC/B;AACF"}
|
package/dist/src/builder.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builder.cjs","names":[],"sources":["../../src/builder.ts"],"sourcesContent":["/**\n * The application-wide {@link FederationBuilder}.\n *\n * Fedify's builder pattern separates *registering* dispatchers from *building*\n * the `Federation` object. That separation is what makes an AdonisJS\n * integration possible at all: dispatcher registration happens while the\n * application boots (in preload files, which may import Lucid models and other\n * container services), while the `Federation` itself can only be built once\n * every registration is in — and once `config/fedify.ts` has been resolved.\n *\n * The builder is a process-wide singleton for the same reason AdonisJS's own\n * `router` and `server` service modules are: application code has to be able to\n * reach it from a plain `import` at module scope, without an `await`.\n *\n * Note that this module deliberately imports nothing from AdonisJS. The\n * original prototype of this package bound the builder into the IoC container\n * as an import side effect, which meant the container binding existed only if\n * some other module happened to import this one first. Binding is the service\n * provider's job instead; see `providers/fedify_provider.ts`.\n *\n * On the dual build: this is the one module with state, so the classic\n * dual-package hazard applies — a process that loaded both the ESM and the\n * CommonJS copy would otherwise hold two builders, and dispatchers registered\n * on one would be silently missing from the `Federation` built from the other.\n * The singleton therefore lives in a `globalThis` slot under a registered\n * symbol, which every copy of this module resolves to the same object.\n *\n * @module\n */\nimport {\n createFederationBuilder,\n type FederationBuilder,\n} from \"@fedify/fedify\";\n\nimport type { ContextData } from \"./types.ts\";\n\n/**\n * The slot the singleton lives in, keyed by major version.\n *\n * Every copy of *this* package resolves the same key, which is the point — the\n * ESM and CommonJS builds have to agree. A different major version of\n * `@fedify/adonisjs` hoisted into the same process gets a slot of its own\n * rather than inheriting dispatchers registered against another major's\n * `FederationBuilder`.\n */\nconst SLOT: unique symbol = Symbol.for(\"@fedify/adonisjs@2/builder\");\n\nconst registry = globalThis as { [SLOT]?: FederationBuilder<ContextData> };\n\n/**\n * The builder that dispatchers and inbox listeners are registered on.\n *\n * Prefer importing it through the `@fedify/adonisjs/services/builder` service\n * module, which is the path the generated stubs and the documentation use.\n */\nexport const builder: FederationBuilder<ContextData> = registry[SLOT] ??=\n createFederationBuilder<ContextData>();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,OAAsB,OAAO,IAAI,4BAA4B;AAEnE,MAAM,WAAW;;;;;;;AAQjB,MAAa,
|
|
1
|
+
{"version":3,"file":"builder.cjs","names":[],"sources":["../../src/builder.ts"],"sourcesContent":["/**\n * The application-wide {@link FederationBuilder}.\n *\n * Fedify's builder pattern separates *registering* dispatchers from *building*\n * the `Federation` object. That separation is what makes an AdonisJS\n * integration possible at all: dispatcher registration happens while the\n * application boots (in preload files, which may import Lucid models and other\n * container services), while the `Federation` itself can only be built once\n * every registration is in — and once `config/fedify.ts` has been resolved.\n *\n * The builder is a process-wide singleton for the same reason AdonisJS's own\n * `router` and `server` service modules are: application code has to be able to\n * reach it from a plain `import` at module scope, without an `await`.\n *\n * Note that this module deliberately imports nothing from AdonisJS. The\n * original prototype of this package bound the builder into the IoC container\n * as an import side effect, which meant the container binding existed only if\n * some other module happened to import this one first. Binding is the service\n * provider's job instead; see `providers/fedify_provider.ts`.\n *\n * On the dual build: this is the one module with state, so the classic\n * dual-package hazard applies — a process that loaded both the ESM and the\n * CommonJS copy would otherwise hold two builders, and dispatchers registered\n * on one would be silently missing from the `Federation` built from the other.\n * The singleton therefore lives in a `globalThis` slot under a registered\n * symbol, which every copy of this module resolves to the same object.\n *\n * @module\n */\nimport {\n createFederationBuilder,\n type FederationBuilder,\n} from \"@fedify/fedify\";\n\nimport type { ContextData } from \"./types.ts\";\n\n/**\n * The slot the singleton lives in, keyed by major version.\n *\n * Every copy of *this* package resolves the same key, which is the point — the\n * ESM and CommonJS builds have to agree. A different major version of\n * `@fedify/adonisjs` hoisted into the same process gets a slot of its own\n * rather than inheriting dispatchers registered against another major's\n * `FederationBuilder`.\n */\nconst SLOT: unique symbol = Symbol.for(\"@fedify/adonisjs@2/builder\");\n\nconst registry = globalThis as { [SLOT]?: FederationBuilder<ContextData> };\n\n/**\n * The builder that dispatchers and inbox listeners are registered on.\n *\n * Prefer importing it through the `@fedify/adonisjs/services/builder` service\n * module, which is the path the generated stubs and the documentation use.\n */\nexport const builder: FederationBuilder<ContextData> = (registry[SLOT] ??=\n createFederationBuilder<ContextData>());\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,OAAsB,OAAO,IAAI,4BAA4B;AAEnE,MAAM,WAAW;;;;;;;AAQjB,MAAa,UAA2C,SAAS,sDAC1B"}
|
package/dist/src/builder.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builder.js","names":[],"sources":["../../src/builder.ts"],"sourcesContent":["/**\n * The application-wide {@link FederationBuilder}.\n *\n * Fedify's builder pattern separates *registering* dispatchers from *building*\n * the `Federation` object. That separation is what makes an AdonisJS\n * integration possible at all: dispatcher registration happens while the\n * application boots (in preload files, which may import Lucid models and other\n * container services), while the `Federation` itself can only be built once\n * every registration is in — and once `config/fedify.ts` has been resolved.\n *\n * The builder is a process-wide singleton for the same reason AdonisJS's own\n * `router` and `server` service modules are: application code has to be able to\n * reach it from a plain `import` at module scope, without an `await`.\n *\n * Note that this module deliberately imports nothing from AdonisJS. The\n * original prototype of this package bound the builder into the IoC container\n * as an import side effect, which meant the container binding existed only if\n * some other module happened to import this one first. Binding is the service\n * provider's job instead; see `providers/fedify_provider.ts`.\n *\n * On the dual build: this is the one module with state, so the classic\n * dual-package hazard applies — a process that loaded both the ESM and the\n * CommonJS copy would otherwise hold two builders, and dispatchers registered\n * on one would be silently missing from the `Federation` built from the other.\n * The singleton therefore lives in a `globalThis` slot under a registered\n * symbol, which every copy of this module resolves to the same object.\n *\n * @module\n */\nimport {\n createFederationBuilder,\n type FederationBuilder,\n} from \"@fedify/fedify\";\n\nimport type { ContextData } from \"./types.ts\";\n\n/**\n * The slot the singleton lives in, keyed by major version.\n *\n * Every copy of *this* package resolves the same key, which is the point — the\n * ESM and CommonJS builds have to agree. A different major version of\n * `@fedify/adonisjs` hoisted into the same process gets a slot of its own\n * rather than inheriting dispatchers registered against another major's\n * `FederationBuilder`.\n */\nconst SLOT: unique symbol = Symbol.for(\"@fedify/adonisjs@2/builder\");\n\nconst registry = globalThis as { [SLOT]?: FederationBuilder<ContextData> };\n\n/**\n * The builder that dispatchers and inbox listeners are registered on.\n *\n * Prefer importing it through the `@fedify/adonisjs/services/builder` service\n * module, which is the path the generated stubs and the documentation use.\n */\nexport const builder: FederationBuilder<ContextData> = registry[SLOT] ??=\n createFederationBuilder<ContextData>();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,OAAsB,OAAO,IAAI,4BAA4B;AAEnE,MAAM,WAAW;;;;;;;AAQjB,MAAa,
|
|
1
|
+
{"version":3,"file":"builder.js","names":[],"sources":["../../src/builder.ts"],"sourcesContent":["/**\n * The application-wide {@link FederationBuilder}.\n *\n * Fedify's builder pattern separates *registering* dispatchers from *building*\n * the `Federation` object. That separation is what makes an AdonisJS\n * integration possible at all: dispatcher registration happens while the\n * application boots (in preload files, which may import Lucid models and other\n * container services), while the `Federation` itself can only be built once\n * every registration is in — and once `config/fedify.ts` has been resolved.\n *\n * The builder is a process-wide singleton for the same reason AdonisJS's own\n * `router` and `server` service modules are: application code has to be able to\n * reach it from a plain `import` at module scope, without an `await`.\n *\n * Note that this module deliberately imports nothing from AdonisJS. The\n * original prototype of this package bound the builder into the IoC container\n * as an import side effect, which meant the container binding existed only if\n * some other module happened to import this one first. Binding is the service\n * provider's job instead; see `providers/fedify_provider.ts`.\n *\n * On the dual build: this is the one module with state, so the classic\n * dual-package hazard applies — a process that loaded both the ESM and the\n * CommonJS copy would otherwise hold two builders, and dispatchers registered\n * on one would be silently missing from the `Federation` built from the other.\n * The singleton therefore lives in a `globalThis` slot under a registered\n * symbol, which every copy of this module resolves to the same object.\n *\n * @module\n */\nimport {\n createFederationBuilder,\n type FederationBuilder,\n} from \"@fedify/fedify\";\n\nimport type { ContextData } from \"./types.ts\";\n\n/**\n * The slot the singleton lives in, keyed by major version.\n *\n * Every copy of *this* package resolves the same key, which is the point — the\n * ESM and CommonJS builds have to agree. A different major version of\n * `@fedify/adonisjs` hoisted into the same process gets a slot of its own\n * rather than inheriting dispatchers registered against another major's\n * `FederationBuilder`.\n */\nconst SLOT: unique symbol = Symbol.for(\"@fedify/adonisjs@2/builder\");\n\nconst registry = globalThis as { [SLOT]?: FederationBuilder<ContextData> };\n\n/**\n * The builder that dispatchers and inbox listeners are registered on.\n *\n * Prefer importing it through the `@fedify/adonisjs/services/builder` service\n * module, which is the path the generated stubs and the documentation use.\n */\nexport const builder: FederationBuilder<ContextData> = (registry[SLOT] ??=\n createFederationBuilder<ContextData>());\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,OAAsB,OAAO,IAAI,4BAA4B;AAEnE,MAAM,WAAW;;;;;;;AAQjB,MAAa,UAA2C,SAAS,UAC/D,wBAAqC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define_config.cjs","names":["configProvider","InvalidArgumentsException"],"sources":["../../src/define_config.ts"],"sourcesContent":["/**\n * The `defineConfig` helper used by `config/fedify.ts`.\n *\n * @module\n */\nimport { configProvider } from \"@adonisjs/core\";\nimport { InvalidArgumentsException } from \"@adonisjs/core/exceptions\";\nimport type { ConfigProvider } from \"@adonisjs/core/types\";\nimport type { FederationOptions } from \"@fedify/fedify\";\n\nimport type {\n ContextData,\n FedifyConfig,\n ResolvedFedifyConfig,\n} from \"./types.ts\";\n\n/**\n * Whether the `queue` option carries a queue at all.\n *\n * `FederationOptions.queue` takes either one `MessageQueue` for every role or\n * an object of per-role queues, and Fedify reads an object whose members are\n * all `undefined` as no queue. Testing the option's presence would therefore\n * misfire in both directions: `queue: { outbox: app.inProduction ? q :\n * undefined }` looks configured in development, and `queue: {}` looks like a\n * queue that needs draining.\n */\nfunction hasQueue(queue: FederationOptions<unknown>[\"queue\"]): boolean {\n if (queue == null) return false;\n if (\"enqueue\" in queue && \"listen\" in queue) return true;\n return Object.values(queue).some((role) => role != null);\n}\n\n/**\n * Defines the Fedify configuration of an AdonisJS application.\n *\n * The return value is an AdonisJS *config provider* rather than a plain object,\n * which lets the resolution step reach the application instance — needed to\n * detect production mode and to log through the application's logger — while\n * `config/fedify.ts` itself stays a simple, synchronous, statically analysable\n * module.\n *\n * @example\n * ```ts\n * // config/fedify.ts\n * import { defineConfig } from '@fedify/adonisjs'\n * import { SqliteKvStore } from '@fedify/sqlite'\n * import env from '#start/env'\n *\n * export default defineConfig({\n * origin: env.get('PUBLIC_URL'),\n * kv: new SqliteKvStore(database),\n * })\n * ```\n */\nexport function defineConfig(\n config: FedifyConfig,\n): ConfigProvider<ResolvedFedifyConfig> {\n return configProvider.create<ResolvedFedifyConfig>(async (app) => {\n if (!config.origin) {\n throw new InvalidArgumentsException(\n 'Missing \"origin\" in config/fedify.ts. It must be the canonical public URL of this server, ' +\n \"usually read from the PUBLIC_URL environment variable\",\n );\n }\n\n let kv = config.kv;\n if (kv === undefined) {\n const { MemoryKvStore } = await import(\"@fedify/fedify\");\n kv = new MemoryKvStore();\n\n if (app.inProduction) {\n // Not fatal — an application may genuinely run a single process and\n // accept the trade-off — but silently losing inbox idempotency and the\n // document cache on every restart is worth shouting about.\n const logger = await app.container.make(\"logger\");\n logger.warn(\n \"Fedify is using an in-memory key-value store in production. Inbox idempotency, \" +\n \"the document cache and outbox state will be lost on restart and cannot be shared \" +\n 'between processes. Configure \"kv\" in config/fedify.ts with a persistent store such ' +\n \"as @fedify/sqlite, @fedify/postgres or @fedify/redis\",\n );\n }\n }\n\n const {\n contextDataFactory,\n ignoreRoutePrefixes,\n logging,\n queueContextData,\n ...federationOptions\n } = config;\n\n /**\n * A configured queue forces the \"who drains it\" decision to be explicit.\n *\n * Fedify's own default starts the queue lazily on the first enqueued task,\n * capturing that request's context data and reusing it for every background\n * job thereafter. For this integration the captured value would be a single\n * stale `HttpContext`, whose request has long since finished. Rather than\n * pick a wrong default, refuse to guess.\n */\n if (hasQueue(federationOptions.queue) && queueContextData === undefined) {\n throw new InvalidArgumentsException(\n 'config/fedify.ts configures a \"queue\" but not \"queueContextData\". Set ' +\n '\"queueContextData\" to a callback to have this process drain the queue, or to ' +\n '\"false\" when a separate worker process owns it',\n );\n }\n\n /**\n * The mirror image: a drainer for a queue that does not exist. Nothing\n * fails on its own — `startQueue()` resolves over no queues and\n * `sendActivity()` delivers inline without retry, so failed deliveries are\n * silently lost.\n *\n * Only a warning, because a task registered with\n * `defineTask(name, { queue })` from a preload file brings its own queue,\n * which this configuration cannot see. Refusing would break a valid\n * application, and dropping the callback would hand that queue back to\n * Fedify's lazy start. Only a *callback* is reported: `false` stays valid\n * without a queue, so `queue: app.inProduction ? … : undefined` still\n * boots in development and test.\n */\n if (\n !hasQueue(federationOptions.queue) &&\n typeof queueContextData === \"function\"\n ) {\n const logger = await app.container.make(\"logger\");\n logger.warn(\n 'config/fedify.ts sets \"queueContextData\" but no \"queue\". Unless a task registers its own ' +\n \"queue through defineTask(), there is nothing to drain and activity delivery stays \" +\n 'inline, with failed deliveries never retried. Configure \"queue\" with a message queue ' +\n \"such as @fedify/sqlite, @fedify/postgres, @fedify/redis or @fedify/amqp, or remove \" +\n '\"queueContextData\"',\n );\n }\n\n return {\n ...federationOptions,\n kv,\n\n // The queue is always started deliberately — by this package's service\n // provider, or by a separate worker — never lazily by Fedify.\n manuallyStartQueue
|
|
1
|
+
{"version":3,"file":"define_config.cjs","names":["configProvider","InvalidArgumentsException"],"sources":["../../src/define_config.ts"],"sourcesContent":["/**\n * The `defineConfig` helper used by `config/fedify.ts`.\n *\n * @module\n */\nimport { configProvider } from \"@adonisjs/core\";\nimport { InvalidArgumentsException } from \"@adonisjs/core/exceptions\";\nimport type { ConfigProvider } from \"@adonisjs/core/types\";\nimport type { FederationOptions } from \"@fedify/fedify\";\n\nimport type {\n ContextData,\n FedifyConfig,\n ResolvedFedifyConfig,\n} from \"./types.ts\";\n\n/**\n * Whether the `queue` option carries a queue at all.\n *\n * `FederationOptions.queue` takes either one `MessageQueue` for every role or\n * an object of per-role queues, and Fedify reads an object whose members are\n * all `undefined` as no queue. Testing the option's presence would therefore\n * misfire in both directions: `queue: { outbox: app.inProduction ? q :\n * undefined }` looks configured in development, and `queue: {}` looks like a\n * queue that needs draining.\n */\nfunction hasQueue(queue: FederationOptions<unknown>[\"queue\"]): boolean {\n if (queue == null) return false;\n if (\"enqueue\" in queue && \"listen\" in queue) return true;\n return Object.values(queue).some((role) => role != null);\n}\n\n/**\n * Defines the Fedify configuration of an AdonisJS application.\n *\n * The return value is an AdonisJS *config provider* rather than a plain object,\n * which lets the resolution step reach the application instance — needed to\n * detect production mode and to log through the application's logger — while\n * `config/fedify.ts` itself stays a simple, synchronous, statically analysable\n * module.\n *\n * @example\n * ```ts\n * // config/fedify.ts\n * import { defineConfig } from '@fedify/adonisjs'\n * import { SqliteKvStore } from '@fedify/sqlite'\n * import env from '#start/env'\n *\n * export default defineConfig({\n * origin: env.get('PUBLIC_URL'),\n * kv: new SqliteKvStore(database),\n * })\n * ```\n */\nexport function defineConfig(\n config: FedifyConfig,\n): ConfigProvider<ResolvedFedifyConfig> {\n return configProvider.create<ResolvedFedifyConfig>(async (app) => {\n if (!config.origin) {\n throw new InvalidArgumentsException(\n 'Missing \"origin\" in config/fedify.ts. It must be the canonical public URL of this server, ' +\n \"usually read from the PUBLIC_URL environment variable\",\n );\n }\n\n let kv = config.kv;\n if (kv === undefined) {\n const { MemoryKvStore } = await import(\"@fedify/fedify\");\n kv = new MemoryKvStore();\n\n if (app.inProduction) {\n // Not fatal — an application may genuinely run a single process and\n // accept the trade-off — but silently losing inbox idempotency and the\n // document cache on every restart is worth shouting about.\n const logger = await app.container.make(\"logger\");\n logger.warn(\n \"Fedify is using an in-memory key-value store in production. Inbox idempotency, \" +\n \"the document cache and outbox state will be lost on restart and cannot be shared \" +\n 'between processes. Configure \"kv\" in config/fedify.ts with a persistent store such ' +\n \"as @fedify/sqlite, @fedify/postgres or @fedify/redis\",\n );\n }\n }\n\n const {\n contextDataFactory,\n ignoreRoutePrefixes,\n logging,\n queueContextData,\n ...federationOptions\n } = config;\n\n /**\n * A configured queue forces the \"who drains it\" decision to be explicit.\n *\n * Fedify's own default starts the queue lazily on the first enqueued task,\n * capturing that request's context data and reusing it for every background\n * job thereafter. For this integration the captured value would be a single\n * stale `HttpContext`, whose request has long since finished. Rather than\n * pick a wrong default, refuse to guess.\n */\n if (hasQueue(federationOptions.queue) && queueContextData === undefined) {\n throw new InvalidArgumentsException(\n 'config/fedify.ts configures a \"queue\" but not \"queueContextData\". Set ' +\n '\"queueContextData\" to a callback to have this process drain the queue, or to ' +\n '\"false\" when a separate worker process owns it',\n );\n }\n\n /**\n * The mirror image: a drainer for a queue that does not exist. Nothing\n * fails on its own — `startQueue()` resolves over no queues and\n * `sendActivity()` delivers inline without retry, so failed deliveries are\n * silently lost.\n *\n * Only a warning, because a task registered with\n * `defineTask(name, { queue })` from a preload file brings its own queue,\n * which this configuration cannot see. Refusing would break a valid\n * application, and dropping the callback would hand that queue back to\n * Fedify's lazy start. Only a *callback* is reported: `false` stays valid\n * without a queue, so `queue: app.inProduction ? … : undefined` still\n * boots in development and test.\n */\n if (\n !hasQueue(federationOptions.queue) &&\n typeof queueContextData === \"function\"\n ) {\n const logger = await app.container.make(\"logger\");\n logger.warn(\n 'config/fedify.ts sets \"queueContextData\" but no \"queue\". Unless a task registers its own ' +\n \"queue through defineTask(), there is nothing to drain and activity delivery stays \" +\n 'inline, with failed deliveries never retried. Configure \"queue\" with a message queue ' +\n \"such as @fedify/sqlite, @fedify/postgres, @fedify/redis or @fedify/amqp, or remove \" +\n '\"queueContextData\"',\n );\n }\n\n return {\n ...federationOptions,\n kv,\n\n // The queue is always started deliberately — by this package's service\n // provider, or by a separate worker — never lazily by Fedify.\n manuallyStartQueue:\n queueContextData !== undefined ? true : config.manuallyStartQueue,\n\n /**\n * The cast is sound because `ContextDataFactoryOption` makes\n * `contextDataFactory` a *required* key the moment an application\n * augments `FedifyTypes`. This branch is therefore only reachable while\n * `ContextData` still includes `HttpContext`, which is exactly what it\n * returns.\n */\n contextDataFactory: contextDataFactory ?? ((ctx) => ctx as ContextData),\n ignoreRoutePrefixes: ignoreRoutePrefixes ?? [],\n logging: logging ?? true,\n queueContextData,\n };\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA0BA,SAAS,SAAS,OAAqD;CACrE,IAAI,SAAS,MAAM,OAAO;CAC1B,IAAI,aAAa,SAAS,YAAY,OAAO,OAAO;CACpD,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,SAAS,QAAQ,IAAI;AACzD;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,aACd,QACsC;CACtC,OAAOA,8BAAe,OAA6B,OAAO,QAAQ;EAChE,IAAI,CAAC,OAAO,QAAQ;GAClB,MAAM,IAAIC,oDACR,iGACE,uDACJ;EACF;EAEA,IAAI,KAAK,OAAO;EAChB,IAAI,OAAO,WAAW;GACpB,MAAM,EAAE,kBAAkB,MAAM,OAAO;GACvC,KAAK,IAAI,cAAc;GAEvB,IAAI,IAAI,cAAc;IAIpB,MAAM,SAAS,MAAM,IAAI,UAAU,KAAK,QAAQ;IAChD,OAAO,KACL,oFACE,sFACA,0FACA,sDACJ;GACF;EACF;EAEA,MAAM,EACJ,oBACA,qBACA,SACA,kBACA,GAAG,sBACD;;;;;;;;;;EAWJ,IAAI,SAAS,kBAAkB,KAAK,KAAK,qBAAqB,WAAW;GACvE,MAAM,IAAIA,oDACR,+EACE,oFACA,kDACJ;EACF;;;;;;;;;;;;;;;EAgBA,IACE,CAAC,SAAS,kBAAkB,KAAK,KACjC,OAAO,qBAAqB,YAC5B;GACA,MAAM,SAAS,MAAM,IAAI,UAAU,KAAK,QAAQ;GAChD,OAAO,KACL,kGACE,uFACA,4FACA,wFACA,sBACJ;EACF;EAEA,OAAO;GACL,GAAG;GACH;GAIA,oBACE,qBAAqB,YAAY,OAAO,OAAO;;;;;;;;GASjD,oBAAoB,wBAAwB,QAAQ;GACpD,qBAAqB,uBAAuB,CAAC;GAC7C,SAAS,WAAW;GACpB;EACF;CACF,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"define_config.js","names":[],"sources":["../../src/define_config.ts"],"sourcesContent":["/**\n * The `defineConfig` helper used by `config/fedify.ts`.\n *\n * @module\n */\nimport { configProvider } from \"@adonisjs/core\";\nimport { InvalidArgumentsException } from \"@adonisjs/core/exceptions\";\nimport type { ConfigProvider } from \"@adonisjs/core/types\";\nimport type { FederationOptions } from \"@fedify/fedify\";\n\nimport type {\n ContextData,\n FedifyConfig,\n ResolvedFedifyConfig,\n} from \"./types.ts\";\n\n/**\n * Whether the `queue` option carries a queue at all.\n *\n * `FederationOptions.queue` takes either one `MessageQueue` for every role or\n * an object of per-role queues, and Fedify reads an object whose members are\n * all `undefined` as no queue. Testing the option's presence would therefore\n * misfire in both directions: `queue: { outbox: app.inProduction ? q :\n * undefined }` looks configured in development, and `queue: {}` looks like a\n * queue that needs draining.\n */\nfunction hasQueue(queue: FederationOptions<unknown>[\"queue\"]): boolean {\n if (queue == null) return false;\n if (\"enqueue\" in queue && \"listen\" in queue) return true;\n return Object.values(queue).some((role) => role != null);\n}\n\n/**\n * Defines the Fedify configuration of an AdonisJS application.\n *\n * The return value is an AdonisJS *config provider* rather than a plain object,\n * which lets the resolution step reach the application instance — needed to\n * detect production mode and to log through the application's logger — while\n * `config/fedify.ts` itself stays a simple, synchronous, statically analysable\n * module.\n *\n * @example\n * ```ts\n * // config/fedify.ts\n * import { defineConfig } from '@fedify/adonisjs'\n * import { SqliteKvStore } from '@fedify/sqlite'\n * import env from '#start/env'\n *\n * export default defineConfig({\n * origin: env.get('PUBLIC_URL'),\n * kv: new SqliteKvStore(database),\n * })\n * ```\n */\nexport function defineConfig(\n config: FedifyConfig,\n): ConfigProvider<ResolvedFedifyConfig> {\n return configProvider.create<ResolvedFedifyConfig>(async (app) => {\n if (!config.origin) {\n throw new InvalidArgumentsException(\n 'Missing \"origin\" in config/fedify.ts. It must be the canonical public URL of this server, ' +\n \"usually read from the PUBLIC_URL environment variable\",\n );\n }\n\n let kv = config.kv;\n if (kv === undefined) {\n const { MemoryKvStore } = await import(\"@fedify/fedify\");\n kv = new MemoryKvStore();\n\n if (app.inProduction) {\n // Not fatal — an application may genuinely run a single process and\n // accept the trade-off — but silently losing inbox idempotency and the\n // document cache on every restart is worth shouting about.\n const logger = await app.container.make(\"logger\");\n logger.warn(\n \"Fedify is using an in-memory key-value store in production. Inbox idempotency, \" +\n \"the document cache and outbox state will be lost on restart and cannot be shared \" +\n 'between processes. Configure \"kv\" in config/fedify.ts with a persistent store such ' +\n \"as @fedify/sqlite, @fedify/postgres or @fedify/redis\",\n );\n }\n }\n\n const {\n contextDataFactory,\n ignoreRoutePrefixes,\n logging,\n queueContextData,\n ...federationOptions\n } = config;\n\n /**\n * A configured queue forces the \"who drains it\" decision to be explicit.\n *\n * Fedify's own default starts the queue lazily on the first enqueued task,\n * capturing that request's context data and reusing it for every background\n * job thereafter. For this integration the captured value would be a single\n * stale `HttpContext`, whose request has long since finished. Rather than\n * pick a wrong default, refuse to guess.\n */\n if (hasQueue(federationOptions.queue) && queueContextData === undefined) {\n throw new InvalidArgumentsException(\n 'config/fedify.ts configures a \"queue\" but not \"queueContextData\". Set ' +\n '\"queueContextData\" to a callback to have this process drain the queue, or to ' +\n '\"false\" when a separate worker process owns it',\n );\n }\n\n /**\n * The mirror image: a drainer for a queue that does not exist. Nothing\n * fails on its own — `startQueue()` resolves over no queues and\n * `sendActivity()` delivers inline without retry, so failed deliveries are\n * silently lost.\n *\n * Only a warning, because a task registered with\n * `defineTask(name, { queue })` from a preload file brings its own queue,\n * which this configuration cannot see. Refusing would break a valid\n * application, and dropping the callback would hand that queue back to\n * Fedify's lazy start. Only a *callback* is reported: `false` stays valid\n * without a queue, so `queue: app.inProduction ? … : undefined` still\n * boots in development and test.\n */\n if (\n !hasQueue(federationOptions.queue) &&\n typeof queueContextData === \"function\"\n ) {\n const logger = await app.container.make(\"logger\");\n logger.warn(\n 'config/fedify.ts sets \"queueContextData\" but no \"queue\". Unless a task registers its own ' +\n \"queue through defineTask(), there is nothing to drain and activity delivery stays \" +\n 'inline, with failed deliveries never retried. Configure \"queue\" with a message queue ' +\n \"such as @fedify/sqlite, @fedify/postgres, @fedify/redis or @fedify/amqp, or remove \" +\n '\"queueContextData\"',\n );\n }\n\n return {\n ...federationOptions,\n kv,\n\n // The queue is always started deliberately — by this package's service\n // provider, or by a separate worker — never lazily by Fedify.\n manuallyStartQueue
|
|
1
|
+
{"version":3,"file":"define_config.js","names":[],"sources":["../../src/define_config.ts"],"sourcesContent":["/**\n * The `defineConfig` helper used by `config/fedify.ts`.\n *\n * @module\n */\nimport { configProvider } from \"@adonisjs/core\";\nimport { InvalidArgumentsException } from \"@adonisjs/core/exceptions\";\nimport type { ConfigProvider } from \"@adonisjs/core/types\";\nimport type { FederationOptions } from \"@fedify/fedify\";\n\nimport type {\n ContextData,\n FedifyConfig,\n ResolvedFedifyConfig,\n} from \"./types.ts\";\n\n/**\n * Whether the `queue` option carries a queue at all.\n *\n * `FederationOptions.queue` takes either one `MessageQueue` for every role or\n * an object of per-role queues, and Fedify reads an object whose members are\n * all `undefined` as no queue. Testing the option's presence would therefore\n * misfire in both directions: `queue: { outbox: app.inProduction ? q :\n * undefined }` looks configured in development, and `queue: {}` looks like a\n * queue that needs draining.\n */\nfunction hasQueue(queue: FederationOptions<unknown>[\"queue\"]): boolean {\n if (queue == null) return false;\n if (\"enqueue\" in queue && \"listen\" in queue) return true;\n return Object.values(queue).some((role) => role != null);\n}\n\n/**\n * Defines the Fedify configuration of an AdonisJS application.\n *\n * The return value is an AdonisJS *config provider* rather than a plain object,\n * which lets the resolution step reach the application instance — needed to\n * detect production mode and to log through the application's logger — while\n * `config/fedify.ts` itself stays a simple, synchronous, statically analysable\n * module.\n *\n * @example\n * ```ts\n * // config/fedify.ts\n * import { defineConfig } from '@fedify/adonisjs'\n * import { SqliteKvStore } from '@fedify/sqlite'\n * import env from '#start/env'\n *\n * export default defineConfig({\n * origin: env.get('PUBLIC_URL'),\n * kv: new SqliteKvStore(database),\n * })\n * ```\n */\nexport function defineConfig(\n config: FedifyConfig,\n): ConfigProvider<ResolvedFedifyConfig> {\n return configProvider.create<ResolvedFedifyConfig>(async (app) => {\n if (!config.origin) {\n throw new InvalidArgumentsException(\n 'Missing \"origin\" in config/fedify.ts. It must be the canonical public URL of this server, ' +\n \"usually read from the PUBLIC_URL environment variable\",\n );\n }\n\n let kv = config.kv;\n if (kv === undefined) {\n const { MemoryKvStore } = await import(\"@fedify/fedify\");\n kv = new MemoryKvStore();\n\n if (app.inProduction) {\n // Not fatal — an application may genuinely run a single process and\n // accept the trade-off — but silently losing inbox idempotency and the\n // document cache on every restart is worth shouting about.\n const logger = await app.container.make(\"logger\");\n logger.warn(\n \"Fedify is using an in-memory key-value store in production. Inbox idempotency, \" +\n \"the document cache and outbox state will be lost on restart and cannot be shared \" +\n 'between processes. Configure \"kv\" in config/fedify.ts with a persistent store such ' +\n \"as @fedify/sqlite, @fedify/postgres or @fedify/redis\",\n );\n }\n }\n\n const {\n contextDataFactory,\n ignoreRoutePrefixes,\n logging,\n queueContextData,\n ...federationOptions\n } = config;\n\n /**\n * A configured queue forces the \"who drains it\" decision to be explicit.\n *\n * Fedify's own default starts the queue lazily on the first enqueued task,\n * capturing that request's context data and reusing it for every background\n * job thereafter. For this integration the captured value would be a single\n * stale `HttpContext`, whose request has long since finished. Rather than\n * pick a wrong default, refuse to guess.\n */\n if (hasQueue(federationOptions.queue) && queueContextData === undefined) {\n throw new InvalidArgumentsException(\n 'config/fedify.ts configures a \"queue\" but not \"queueContextData\". Set ' +\n '\"queueContextData\" to a callback to have this process drain the queue, or to ' +\n '\"false\" when a separate worker process owns it',\n );\n }\n\n /**\n * The mirror image: a drainer for a queue that does not exist. Nothing\n * fails on its own — `startQueue()` resolves over no queues and\n * `sendActivity()` delivers inline without retry, so failed deliveries are\n * silently lost.\n *\n * Only a warning, because a task registered with\n * `defineTask(name, { queue })` from a preload file brings its own queue,\n * which this configuration cannot see. Refusing would break a valid\n * application, and dropping the callback would hand that queue back to\n * Fedify's lazy start. Only a *callback* is reported: `false` stays valid\n * without a queue, so `queue: app.inProduction ? … : undefined` still\n * boots in development and test.\n */\n if (\n !hasQueue(federationOptions.queue) &&\n typeof queueContextData === \"function\"\n ) {\n const logger = await app.container.make(\"logger\");\n logger.warn(\n 'config/fedify.ts sets \"queueContextData\" but no \"queue\". Unless a task registers its own ' +\n \"queue through defineTask(), there is nothing to drain and activity delivery stays \" +\n 'inline, with failed deliveries never retried. Configure \"queue\" with a message queue ' +\n \"such as @fedify/sqlite, @fedify/postgres, @fedify/redis or @fedify/amqp, or remove \" +\n '\"queueContextData\"',\n );\n }\n\n return {\n ...federationOptions,\n kv,\n\n // The queue is always started deliberately — by this package's service\n // provider, or by a separate worker — never lazily by Fedify.\n manuallyStartQueue:\n queueContextData !== undefined ? true : config.manuallyStartQueue,\n\n /**\n * The cast is sound because `ContextDataFactoryOption` makes\n * `contextDataFactory` a *required* key the moment an application\n * augments `FedifyTypes`. This branch is therefore only reachable while\n * `ContextData` still includes `HttpContext`, which is exactly what it\n * returns.\n */\n contextDataFactory: contextDataFactory ?? ((ctx) => ctx as ContextData),\n ignoreRoutePrefixes: ignoreRoutePrefixes ?? [],\n logging: logging ?? true,\n queueContextData,\n };\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA0BA,SAAS,SAAS,OAAqD;CACrE,IAAI,SAAS,MAAM,OAAO;CAC1B,IAAI,aAAa,SAAS,YAAY,OAAO,OAAO;CACpD,OAAO,OAAO,OAAO,KAAK,CAAC,CAAC,MAAM,SAAS,QAAQ,IAAI;AACzD;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,aACd,QACsC;CACtC,OAAO,eAAe,OAA6B,OAAO,QAAQ;EAChE,IAAI,CAAC,OAAO,QAAQ;GAClB,MAAM,IAAI,0BACR,iGACE,uDACJ;EACF;EAEA,IAAI,KAAK,OAAO;EAChB,IAAI,OAAO,WAAW;GACpB,MAAM,EAAE,kBAAkB,MAAM,OAAO;GACvC,KAAK,IAAI,cAAc;GAEvB,IAAI,IAAI,cAAc;IAIpB,MAAM,SAAS,MAAM,IAAI,UAAU,KAAK,QAAQ;IAChD,OAAO,KACL,oFACE,sFACA,0FACA,sDACJ;GACF;EACF;EAEA,MAAM,EACJ,oBACA,qBACA,SACA,kBACA,GAAG,sBACD;;;;;;;;;;EAWJ,IAAI,SAAS,kBAAkB,KAAK,KAAK,qBAAqB,WAAW;GACvE,MAAM,IAAI,0BACR,+EACE,oFACA,kDACJ;EACF;;;;;;;;;;;;;;;EAgBA,IACE,CAAC,SAAS,kBAAkB,KAAK,KACjC,OAAO,qBAAqB,YAC5B;GACA,MAAM,SAAS,MAAM,IAAI,UAAU,KAAK,QAAQ;GAChD,OAAO,KACL,kGACE,uFACA,4FACA,wFACA,sBACJ;EACF;EAEA,OAAO;GACL,GAAG;GACH;GAIA,oBACE,qBAAqB,YAAY,OAAO,OAAO;;;;;;;;GASjD,oBAAoB,wBAAwB,QAAQ;GACpD,qBAAqB,uBAAuB,CAAC;GAC7C,SAAS,WAAW;GACpB;EACF;CACF,CAAC;AACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fedify_middleware.cjs","names":["Readable","PLACEHOLDER_HOST","E_MISSING_FEDERATION","#federation","#contextDataFactory","#ignoreRoutePrefixes","ensureFederationGetter","E_FEDIFY_CONTEXT_UNAVAILABLE"],"sources":["../../src/fedify_middleware.ts"],"sourcesContent":["/**\n * The AdonisJS server middleware that mounts Fedify.\n *\n * The service provider binds {@link FedifyMiddleware} with the `Federation`\n * and `config/fedify.ts`; applications that build their own `Federation` use\n * {@link fedifyMiddleware} instead. Nothing here depends on the container.\n *\n * @module\n */\nimport { Readable } from \"node:stream\";\n\nimport type { HttpContext } from \"@adonisjs/core/http\";\nimport type { NextFn } from \"@adonisjs/core/types/http\";\nimport type { Federation } from \"@fedify/fedify\";\n\nimport {\n E_FEDIFY_CONTEXT_UNAVAILABLE,\n E_MISSING_FEDERATION,\n} from \"./errors.ts\";\nimport {\n ensureFederationGetter,\n type HttpContextClass,\n setFederationContextFactory,\n} from \"./http_context.ts\";\nimport type { ContextData, ContextDataFactory } from \"./types.ts\";\nimport {\n PLACEHOLDER_HOST,\n warnUnusableAuthority,\n} from \"./unusable_authority.ts\";\n\n/**\n * Options accepted by {@link FedifyMiddleware} and {@link fedifyMiddleware}.\n */\nexport interface FedifyMiddlewareOptions {\n /**\n * URL path prefixes to bypass entirely. See\n * {@link import('./types.js').FedifyConfig.ignoreRoutePrefixes}.\n *\n * @default `[]`\n */\n ignoreRoutePrefixes?: string[];\n}\n\n/**\n * The instance shape of the middleware.\n */\nexport interface FedifyMiddlewareHandler {\n handle(ctx: HttpContext, next: NextFn): Promise<void>;\n}\n\n/**\n * What {@link fedifyMiddleware} returns: a middleware **class**, since\n * `server.use()` constructs entries through the container.\n */\nexport type FedifyMiddlewareClass = new () => FedifyMiddlewareHandler;\n\n/**\n * The arguments after `federation`. The factory defaults to producing\n * `undefined`, so it may only be omitted when `TContextData` admits it;\n * otherwise omitting it is a compile error. The tuple wrapper keeps the\n * conditional from distributing over a union.\n */\nexport type FedifyMiddlewareArgs<TContextData> = [undefined] extends\n [TContextData] ? [\n contextDataFactory?: ContextDataFactory<TContextData>,\n options?: FedifyMiddlewareOptions,\n ]\n : [\n contextDataFactory: ContextDataFactory<TContextData>,\n options?: FedifyMiddlewareOptions,\n ];\n\n/**\n * Context classes whose conflicting `federation` member was already reported.\n */\nconst conflicting = new WeakSet<object>();\n\n/**\n * Methods `new Request()` refuses; in practice only `TRACE` arrives here.\n */\nconst FORBIDDEN_METHODS = new Set([\"CONNECT\", \"TRACE\", \"TRACK\"]);\n\n/**\n * Wraps the raw `IncomingMessage` in a `ReadableStream` that stays inert until\n * first read. The `Request` is built before Fedify decides whether it handles\n * the request; an eager `Readable.toWeb()` would start draining the socket and\n * hang the AdonisJS body parser on every declined `POST`.\n */\nfunction lazyRequestBody(\n message: HttpContext[\"request\"][\"request\"],\n): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n reader ??= (Readable.toWeb(message) as ReadableStream<Uint8Array>)\n .getReader();\n\n const { done, value } = await reader.read();\n if (done) controller.close();\n else controller.enqueue(value);\n },\n cancel(reason) {\n return reader?.cancel(reason);\n },\n },\n { highWaterMark: 0 },\n );\n}\n\n/**\n * What an authority may not contain: `Host` admits only `uri-host [\":\" port]`,\n * so anything that could carry a path, query, fragment or userinfo makes the\n * value something other than an authority.\n */\nconst NON_AUTHORITY = /[/?#\\\\@\\s]/;\n\n/**\n * Keeps the first entry of a comma-separated authority (`X-Forwarded-Host`\n * behind two proxies), which `new URL()` would reject.\n *\n * Under `trustProxy`, `authority()` returns `X-Forwarded-Host` verbatim, so a\n * client could send `example.com/x` and shift the path Fedify sees to\n * `/x/users/alice` while AdonisJS still routes the real path — bypassing\n * `ignoreRoutePrefixes`. Anything that could carry a path, query, fragment or\n * userinfo (`good.example@evil.com` parses to the host `evil.com`) is\n * therefore refused outright, which leaves the {@link PLACEHOLDER_HOST}\n * fallback to keep the path intact.\n */\nfunction normalizeAuthority(host: string): string {\n const comma = host.indexOf(\",\");\n const authority = (comma < 0 ? host : host.slice(0, comma)).trim();\n return NON_AUTHORITY.test(authority) ? \"\" : authority;\n}\n\n/**\n * Reduces a request target to origin form, or `undefined` when it carries no\n * path. An absolute target (`GET http://example.com/users/alice HTTP/1.1`)\n * reaches `req.url` verbatim; only its path and query survive, so the request\n * line cannot pick the host Fedify sees and let an inbox `POST` signed for\n * another server verify here.\n */\nfunction toOriginForm(target: string): string | undefined {\n // Origin form already. It is interpolated, not resolved, so `//users/alice`\n // keeps its path instead of reading `users` as a host.\n if (target.startsWith(\"/\")) return target;\n\n // Textually rather than through `new URL()`, which would hand back the\n // *normalised* path or, for a target it refuses, nothing at all --\n // collapsing the request to `/` and hiding the real path from\n // `ignoreRoutePrefixes` and `ctx.federation`.\n const prefix = /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\/[^/?#]*/.exec(target);\n // Asterisk form (`OPTIONS *`) or malformed. Authority form reaches only\n // `CONNECT`, which {@link FORBIDDEN_METHODS} refuses.\n if (prefix === null) return undefined;\n\n const rest = target.slice(prefix[0].length);\n return rest.startsWith(\"/\") ? rest : `/${rest}`;\n}\n\n/**\n * Builds the URL for one authority, or `undefined` if it cannot carry one.\n * The target is interpolated, never resolved, so the authority stays the one\n * {@link normalizeAuthority} passed; an empty one is refused because\n * `new URL(\"http:///users/alice\")` silently takes `users` as the host.\n */\nfunction buildRequestUrl(\n protocol: string,\n authority: string,\n target: string,\n): URL | undefined {\n if (authority === \"\") return undefined;\n\n try {\n return new URL(`${protocol}://${authority}${target}`);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Builds the URL Fedify sees from the raw request target, keeping the\n * percent-encoding Fedify's URI templates expect and the bytes a peer signed.\n * Only the target's path and query are read (see {@link toOriginForm}); the\n * authority comes from {@link normalizeAuthority}, via `authority()` so\n * HTTP/2's `:authority` is covered. Every input is attacker-controlled, so\n * the result only has to exist: the scheme is reduced to `http`/`https`, and\n * an unusable authority falls back to {@link PLACEHOLDER_HOST} rather than a\n * 500. Since that breaks signature verification, the discarded value is\n * returned for the caller to log once it knows Fedify will see the request.\n *\n * The accepted authority is returned verbatim as well, for the `Host` header\n * {@link toFetchRequest} synthesises on HTTP/2: `URL` normalises what it\n * parses (case, default port, punycode) while a signature covers the bytes as\n * sent. It is absent exactly when the placeholder stood in.\n */\nfunction toRequestUrl(\n request: HttpContext[\"request\"],\n): { url: URL; authority?: string; unusableAuthority?: string } {\n // `protocol()` hands back the first `X-Forwarded-Proto` token as it\n // arrived; an upper-case `HTTPS` must not be read as plain `http`.\n const protocol = request.protocol().toLowerCase() === \"https\"\n ? \"https\"\n : \"http\";\n const host = request.authority();\n const authority = host == null ? \"\" : normalizeAuthority(host);\n // A target with no origin form is routed as `/`, which matches no\n // federation route, so AdonisJS answers.\n const target = toOriginForm(request.request.url ?? \"/\") ?? \"/\";\n\n const parsed = buildRequestUrl(protocol, authority, target);\n let url = parsed;\n let unusableAuthority: string | undefined;\n if (url === undefined) {\n // Only the authority can be at fault: the target starts with `/`, and a\n // URL parser in path state takes any bytes after it.\n url = new URL(`${protocol}://${PLACEHOLDER_HOST}${target}`);\n if (host != null) unusableAuthority = host;\n }\n\n return {\n url,\n authority: parsed === undefined ? undefined : authority,\n unusableAuthority,\n };\n}\n\n/**\n * Converts an AdonisJS request into a WHATWG `Request` for Fedify.\n *\n * `intended()`, not `method()`, so `_method` spoofing cannot turn an inbox\n * `POST` into a `GET`. Headers are forwarded as they arrived; HTTP/2\n * pseudo-headers are skipped, and since that leaves no `Host` (which\n * signatures may cover), one is synthesised only then, from the authority the\n * URL was built from.\n */\nfunction toFetchRequest(\n ctx: HttpContext,\n url: URL,\n authority: string | undefined,\n): Request {\n const request = ctx.request;\n const method = request.intended().toUpperCase();\n\n const headers = new Headers();\n const rawHeaders = request.headers();\n // `Object.keys()`, not `for...in`: a polluted prototype must not be forwarded.\n for (const key of Object.keys(rawHeaders)) {\n if (key.startsWith(\":\")) continue;\n const value = rawHeaders[key];\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else if (typeof value === \"string\") {\n headers.append(key, value);\n }\n }\n\n // Only when absent: an HTTP/1.1 `Host` is what the peer signed and what the\n // verifier reads, so it is never touched (a proxy rewriting `Host` has to\n // preserve it; see the README). On HTTP/2 the authority travels in\n // `:authority`, which the pseudo-header skip dropped, so it is put back\n // here -- verbatim, not `url.host`, since `URL` case-folds, drops a default\n // port and punycodes while a signature covers the bytes as sent. An\n // unusable authority gets the placeholder in the URL only, never a header.\n if (authority !== undefined && !headers.has(\"host\")) {\n headers.set(\"host\", authority);\n }\n\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n return new Request(url, {\n method,\n headers,\n body: hasBody ? lazyRequestBody(request.request) : undefined,\n // Not in the DOM lib's `RequestInit`, but Node requires it for streams.\n ...{ duplex: \"half\" },\n });\n}\n\n/**\n * Copies a WHATWG `Response` produced by Fedify onto the AdonisJS response.\n * `Set-Cookie` goes through `getSetCookie()` because iterating `Headers`\n * folds it; `Vary` is merged rather than copied, so a `Vary: Origin` an\n * upstream middleware set survives Fedify's own `Vary: Accept`; bodyless\n * responses (`204`, `304`, `HEAD`) are not streamed.\n */\nfunction writeFedifyResponse(response: Response, ctx: HttpContext): void {\n ctx.response.status(response.status);\n\n for (const [key, value] of response.headers) {\n const name = key.toLowerCase();\n if (name === \"set-cookie\") continue;\n if (name === \"vary\") {\n mergeIntoVary(ctx, value);\n continue;\n }\n ctx.response.header(key, value);\n }\n\n for (const cookie of response.headers.getSetCookie()) {\n ctx.response.append(\"set-cookie\", cookie);\n }\n\n const bodyless = response.body === null ||\n response.status === 204 ||\n response.status === 304 ||\n // `intended()`: a spoofed `_method=HEAD` must not suppress the body.\n ctx.request.intended().toUpperCase() === \"HEAD\";\n\n if (bodyless) {\n // Do not leave a body Fedify produced anyway (usually for HEAD) dangling;\n // a failed cleanup must not become an unhandled rejection.\n response.body?.cancel().catch(() => {});\n return;\n }\n\n ctx.response.stream(response.body!, (error) => {\n ctx.logger.error({ err: error }, \"Failed to stream the Fedify response\");\n return [\"Internal server error\", 500];\n });\n}\n\n/**\n * Splits a `Vary` value into its entries.\n */\nfunction parseVary(value: string): string[] {\n return value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry !== \"\");\n}\n\n/**\n * Merges a raw `Vary` value into the response's `Vary`.\n *\n * `ctx.response.header()` replaces rather than appends, so writing `Vary`\n * directly would drop what an upstream middleware or a route already put\n * there (CORS's `Origin`, say) and let a shared cache mix representations.\n *\n * Both of AdonisJS's header layers are read: `header()` buffers a value that\n * is copied onto the Node response when the reply is written, while\n * `ctx.response.vary()` writes to the Node response directly, and\n * `getHeader()` prefers the buffered value. Once `Accept` is buffered before\n * `next()`, a `vary(\"Origin\")` a route calls is therefore invisible through\n * `getHeader()` alone and would be overwritten at write time. The union goes\n * back to the buffered layer, since that is what goes out. `Vary: *` on any\n * side wins.\n */\nfunction mergeIntoVary(ctx: HttpContext, rawValue: string): void {\n const vary: string[] = [];\n const layers = [\n String(ctx.response.getHeader(\"Vary\") ?? \"\"),\n String(ctx.response.response.getHeader(\"vary\") ?? \"\"),\n rawValue,\n ];\n\n for (const layer of layers) {\n for (const value of parseVary(layer)) {\n if (value === \"*\") {\n ctx.response.header(\"Vary\", \"*\");\n return;\n }\n if (!vary.some((v) => v.toLowerCase() === value.toLowerCase())) {\n vary.push(value);\n }\n }\n }\n\n if (vary.length > 0) ctx.response.header(\"Vary\", vary.join(\", \"));\n}\n\n/**\n * Headers of a discarded response that must not describe the one written over\n * it: cache and validator metadata, which decides how long a shared cache\n * keeps the substitute, and metadata about a body nobody will see. The\n * targeted cache-control family (`CDN-Cache-Control`, `Surrogate-Control`, …)\n * is included because a CDN honours it over `Cache-Control` and largely\n * ignores `Vary`, so a leftover lifetime would keep the 406 cached for\n * ActivityPub clients too. Enumerated rather than matched on a `content-`\n * prefix, which would also take `Content-Security-Policy`.\n */\nconst DISCARDED_ENTITY_HEADERS: ReadonlySet<string> = new Set([\n \"age\",\n \"cache-control\",\n \"cdn-cache-control\",\n \"cloudflare-cdn-cache-control\",\n \"content-digest\",\n \"content-disposition\",\n \"content-encoding\",\n \"content-language\",\n \"content-length\",\n \"content-location\",\n \"content-range\",\n \"content-type\",\n \"digest\",\n \"etag\",\n \"expires\",\n \"last-modified\",\n \"pragma\",\n \"repr-digest\",\n \"surrogate-control\",\n \"surrogate-key\",\n]);\n\n/**\n * Removes a response header around a quirk of AdonisJS's `removeHeader()`,\n * which drops the buffered entry only when the current value is truthy, so one\n * set to `\"\"` would survive. It also forwards to Node unconditionally, which\n * throws once the head is flushed, so this is only safe while\n * `ctx.response.headersSent` is false.\n */\nfunction removeResponseHeader(ctx: HttpContext, key: string): void {\n // A non-empty placeholder, so the buffered entry is truthy and deleted.\n ctx.response.header(key, \"-\");\n ctx.response.removeHeader(key);\n}\n\n/**\n * Drops the body a discarded response left buffered, so the one written over\n * it is the one that goes out.\n *\n * `response.send()` assigns `lazyBody.content` alone, and `finish()` reads the\n * other entries after it: a path passed to `download()` would still be\n * streamed in place of the new body, and a readable passed to `stream()`\n * would be forgotten — one leaked file descriptor per request. Resetting\n * `lazyBody` drops both.\n */\nfunction discardPendingBody(ctx: HttpContext): void {\n const stream = ctx.response.outgoingStream;\n ctx.response.lazyBody = {};\n if (stream == null) return;\n\n // `ResponseStream` is either a Node `Readable` or a WHATWG `ReadableStream`.\n if (\"destroy\" in stream) {\n // Nothing else listens, since AdonisJS never attached to the stream, and\n // an unlistened `error` event is an uncaught exception.\n stream.on(\"error\", () => {});\n if (!stream.destroyed) stream.destroy();\n } else if (!stream.locked) {\n // Likewise, a rejected `cancel()` must not become an unhandled rejection.\n stream.cancel().catch(() => {});\n }\n}\n\n/**\n * Undoes what a discarded response did to the headers, before another is\n * written over it.\n *\n * `next()` mixes two populations: a header a *later middleware* set\n * (`@adonisjs/cors`'s `Access-Control-Allow-Origin`, say) answers this\n * request and has to survive, while one the *discarded page* set describes a\n * body nobody will see. They are told apart by name: only\n * {@link DISCARDED_ENTITY_HEADERS} are touched, and each is put back exactly\n * as the snapshot had it — removed when the snapshot had none. Restoring\n * every snapshot entry instead would undo the request's own answer, since\n * `response.header()` replaces rather than merges.\n *\n * `Vary` is reconciled by {@link mergeIntoVary} around `next()` instead,\n * since only the union of the snapshot and the current value is right.\n */\nfunction rollBackDiscardedResponse(\n ctx: HttpContext,\n headersBefore: ReturnType<HttpContext[\"response\"][\"getHeaders\"]>,\n): void {\n const headersAfter = ctx.response.getHeaders();\n\n for (const key of DISCARDED_ENTITY_HEADERS) {\n // `hasOwn()`, not `in`: `constructor` is a legal header name.\n const before = Object.hasOwn(headersBefore, key)\n ? headersBefore[key]\n : undefined;\n\n // Written back whether or not `next()` changed it: `header()` is\n // idempotent, and takes an array, so a repeated header goes back whole.\n if (before !== undefined) ctx.response.header(key, before);\n else if (Object.hasOwn(headersAfter, key)) removeResponseHeader(ctx, key);\n }\n}\n\n/**\n * The response handed back to Fedify after AdonisJS answered a delegated\n * request. Nothing is written from it, but Fedify logs and meters its\n * status, so it reports what AdonisJS answered. `Response` only accepts\n * 200-599, so anything else (a 1xx) is reported as 200.\n */\nfunction delegatedResponse(status: number): Response {\n return new Response(null, {\n status: status >= 200 && status <= 599 ? status : 200,\n });\n}\n\n/**\n * Mounts a `Federation` instance inside an AdonisJS application; the\n * counterpart of `integrateFederation()` in `@fedify/express`.\n *\n * Register it in the **server** stack: Fedify serves paths the router does\n * not know, and the body stream is still intact there for signature\n * verification. An instance holds configuration only, so one serves every\n * request.\n */\nexport default class FedifyMiddleware<TContextData = ContextData>\n implements FedifyMiddlewareHandler {\n #federation: Federation<TContextData>;\n #contextDataFactory: ContextDataFactory<TContextData>;\n #ignoreRoutePrefixes: string[];\n\n /**\n * @param federation The federation instance to mount.\n * @param args The context-data factory and the options; see\n * {@link FedifyMiddlewareArgs}. The factory sees a pre-routing\n * `HttpContext`; see {@link import('./types.js').ContextDataFactory}.\n */\n constructor(\n federation: Federation<TContextData>,\n ...args: FedifyMiddlewareArgs<TContextData>\n ) {\n // The container zero-arg-constructs this class when the object the kernel\n // resolved is not the one the provider bound (a duplicated package copy,\n // or the ESM and CJS builds mixed); fail here rather than on every request.\n if (federation == null) throw new E_MISSING_FEDERATION();\n\n // The conditional tuple is unresolved here; read it through its common shape.\n const [contextDataFactory, options] = args as [\n ContextDataFactory<TContextData>?,\n FedifyMiddlewareOptions?,\n ];\n\n this.#federation = federation;\n this.#contextDataFactory = contextDataFactory ??\n (() => undefined as TContextData);\n this.#ignoreRoutePrefixes = options?.ignoreRoutePrefixes ?? [];\n }\n\n async handle(ctx: HttpContext, next: NextFn): Promise<void> {\n const federation = this.#federation;\n\n // Install the `ctx.federation` getter on this context's class: it covers a\n // duplicated `@adonisjs/core` and the container-free path, which has no\n // provider. A conflicting `federation` member is reported once; the\n // federation endpoints do not need the accessor.\n const contextClass = ctx.constructor as unknown as HttpContextClass;\n if (\n !ensureFederationGetter(contextClass) && !conflicting.has(contextClass)\n ) {\n conflicting.add(contextClass);\n ctx.logger.error(\n 'Something other than @fedify/adonisjs defines \"federation\" on this ' +\n 'application\\'s HttpContext, so \"ctx.federation\" is not the Fedify ' +\n \"request context. Federation endpoints are unaffected; rename the \" +\n \"conflicting macro or getter to use it from controllers\",\n );\n }\n\n // The ignore check and Fedify must see the same URL, so build it once.\n const { url, authority, unusableAuthority } = toRequestUrl(ctx.request);\n const path = url.pathname;\n\n if (\n this.#ignoreRoutePrefixes.some((prefix) => path.startsWith(prefix)) ||\n FORBIDDEN_METHODS.has(ctx.request.intended().toUpperCase())\n ) {\n // Opted out, or impossible to represent as a `Request`.\n setFederationContextFactory(ctx, () => {\n throw new E_FEDIFY_CONTEXT_UNAVAILABLE(path);\n });\n return next();\n }\n\n // Only past the bypass: on an opted-out path Fedify never sees the URL,\n // so the placeholder is harmless.\n if (unusableAuthority !== undefined) {\n warnUnusableAuthority(ctx.logger, unusableAuthority);\n }\n\n const request = toFetchRequest(ctx, url, authority);\n\n // `federation.fetch()` takes `contextData` by value, so the factory runs\n // before the router.\n const contextData = await this.#contextDataFactory(ctx);\n\n // Also for requests Fedify declines: a controller serving the HTML half of\n // a shared URL needs it. The getter creates the context lazily.\n setFederationContextFactory(\n ctx,\n () => federation.createContext(request, contextData),\n );\n\n /**\n * What happened while Fedify was deciding: whether a fall-through callback\n * handed the request to AdonisJS, and whether AdonisJS produced nothing of\n * its own so the 406 below is the answer. \"Nothing\" means no route\n * matched (`ctx.route` is set only on a match) *and* the framework's own\n * 404: a later server middleware (`@adonisjs/cors` on a preflight) or a\n * downstream failure can answer without the router running, and must not\n * be overwritten. A downstream middleware *deliberately* answering 404 on\n * a Fedify-owned path is indistinguishable from that default and is also\n * replaced by the 406.\n *\n * `router.match()` could say before `next()` whether a route exists and\n * spare the rollback, but is deliberately not asked:\n *\n * 1. Every integration follows the deferred-406 contract the manual\n * documents: delegate, and answer 406 only when the framework answered\n * 404 (Hono reads `ctx.res.status` after `next()`, Express `req.route`).\n * Deciding from the route table would give AdonisJS a narrower one.\n *\n * 2. Server middleware answers without a route by design (`@adonisjs/cors`\n * on a preflight, `@adonisjs/static`, a maintenance page), and Fedify\n * calls `onNotAcceptable` for a wildcard `Accept` too -- what curl and\n * a preflight send -- so skipping `next()` would cut those off on every\n * path Fedify owns.\n *\n * 3. `ctx.route` is the framework's own verdict. A lookup here would\n * duplicate `routeFinder`'s preamble and drift silently as the router\n * changes.\n *\n * The price is undoing a response AdonisJS was allowed to start: the\n * headers in {@link DISCARDED_ENTITY_HEADERS} are put back by name, a\n * pending body is dropped, and nothing is touched once the head has been\n * flushed.\n *\n * An object rather than two `let`s so TypeScript does not narrow them.\n */\n const outcome: { delegated: boolean; answer406: boolean } = {\n delegated: false,\n answer406: false,\n };\n\n const response = await federation.fetch(request, {\n contextData,\n\n /**\n * Fedify has no route for this path: hand the request to AdonisJS.\n * `await next()` resolves even on no match, since `E_ROUTE_NOT_FOUND`\n * goes through the exception handler and renders a 404.\n */\n onNotFound: async () => {\n outcome.delegated = true;\n await next();\n return delegatedResponse(ctx.response.getStatus());\n },\n\n /**\n * Fedify has a route but cannot satisfy `Accept` (a browser at an actor\n * URL). AdonisJS gets a chance to serve its own representation first;\n * 406 is only the answer if it has nothing either. `Accept` is merged\n * into `Vary` rather than written over it, and the snapshot's value is\n * merged back after `next()`, because a route may have replaced the\n * header meanwhile.\n */\n onNotAcceptable: async () => {\n outcome.delegated = true;\n mergeIntoVary(ctx, \"Accept\");\n // A value snapshot, not a live view: `getHeaders()` builds a fresh\n // object on every call.\n const headersBefore = ctx.response.getHeaders();\n await next();\n\n // Put back what `Vary` carried before `next()`, `Accept` included. A\n // superset only costs cache hits; a missing entry lets a cache mix the\n // two representations up.\n mergeIntoVary(ctx, String(headersBefore.vary ?? \"\"));\n\n const status = ctx.response.getStatus();\n // Not once the head is flushed: the 406 could not be written over it,\n // and `removeHeader()` would raise `ERR_HTTP_HEADERS_SENT`.\n outcome.answer406 = ctx.route === undefined && status === 404 &&\n !ctx.response.headersSent;\n\n if (outcome.answer406) rollBackDiscardedResponse(ctx, headersBefore);\n\n // The 406 itself is produced below; this only feeds Fedify's log.\n return delegatedResponse(outcome.answer406 ? 406 : status);\n },\n });\n\n // Fedify owns the path, cannot satisfy `Accept`, and AdonisJS had nothing\n // either. `Vary` already carries `Accept`.\n if (outcome.answer406) {\n // Before `send()`, which only sets the buffered *content*: a 404 page\n // rendered with `download()` or `stream()` would otherwise still go out,\n // or leak its readable.\n discardPendingBody(ctx);\n ctx.response\n .status(406)\n .type(\"text/plain\")\n .send(\"Not acceptable\");\n return;\n }\n\n if (outcome.delegated) {\n // AdonisJS produced the response (a matched route or its own 404 page).\n return;\n }\n\n writeFedifyResponse(response, ctx);\n }\n}\n\n/**\n * Creates a middleware class around a `Federation` the application built\n * itself, with no container or `config/fedify.ts` involved. This is the\n * package's default export; most applications use the provider instead.\n *\n * @example\n * ```ts\n * // start/kernel.ts\n * import fedifyMiddleware from '@fedify/adonisjs'\n * // A module of the application's own that default-exports its `Federation`.\n * import federation from '../app/federation.js'\n *\n * server.use([\n * async () => ({ default: fedifyMiddleware(federation, (ctx) => ctx) }),\n * ])\n * ```\n *\n * With the default `ContextData` of `HttpContext | null`, pass `(ctx) => ctx`\n * to match the provider; see {@link FedifyMiddlewareArgs}.\n *\n * @returns A {@link FedifyMiddleware} subclass whose constructor takes no\n * arguments, which is what `server.use()` constructs.\n * @param federation The federation instance to mount.\n * @param args The context-data factory and the options.\n */\nexport function fedifyMiddleware<TContextData>(\n federation: Federation<TContextData>,\n ...args: FedifyMiddlewareArgs<TContextData>\n): FedifyMiddlewareClass {\n // Here rather than in the constructor guard, which fires only on the first\n // request and blames the provider or a duplicated package copy; a factory\n // caller's likely mistake is a module that default-exports nothing.\n if (federation == null) {\n throw new E_MISSING_FEDERATION(\n \"fedifyMiddleware() was called without a Federation instance. Check \" +\n \"that the module its first argument comes from actually \" +\n \"default-exports the Federation it builds\",\n );\n }\n\n // Named so container errors and tracing show something readable.\n return class ConfiguredFedifyMiddleware\n extends FedifyMiddleware<TContextData> {\n constructor() {\n super(federation, ...args);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA2EA,MAAM,cAAc,IAAI,QAAgB;;;;AAKxC,MAAM,oBAAoB,IAAI,IAAI;CAAC;CAAW;CAAS;AAAO,CAAC;;;;;;;AAQ/D,SAAS,gBACP,SAC4B;CAC5B,IAAI;CAEJ,OAAO,IAAI,eACT;EACE,MAAM,KAAK,YAAY;GACrB,WAAYA,qBAAS,MAAM,OAAO,CAAC,CAChC,UAAU;GAEb,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;GAC1C,IAAI,MAAM,WAAW,MAAM;QACtB,WAAW,QAAQ,KAAK;EAC/B;EACA,OAAO,QAAQ;GACb,OAAO,QAAQ,OAAO,MAAM;EAC9B;CACF,GACA,EAAE,eAAe,EAAE,CACrB;AACF;;;;;;AAOA,MAAM,gBAAgB;;;;;;;;;;;;;AActB,SAAS,mBAAmB,MAAsB;CAChD,MAAM,QAAQ,KAAK,QAAQ,GAAG;CAC9B,MAAM,aAAa,QAAQ,IAAI,OAAO,KAAK,MAAM,GAAG,KAAK,EAAC,CAAE,KAAK;CACjE,OAAO,cAAc,KAAK,SAAS,IAAI,KAAK;AAC9C;;;;;;;;AASA,SAAS,aAAa,QAAoC;CAGxD,IAAI,OAAO,WAAW,GAAG,GAAG,OAAO;CAMnC,MAAM,SAAS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
|
|
1
|
+
{"version":3,"file":"fedify_middleware.cjs","names":["Readable","PLACEHOLDER_HOST","E_MISSING_FEDERATION","#federation","#contextDataFactory","#ignoreRoutePrefixes","ensureFederationGetter","E_FEDIFY_CONTEXT_UNAVAILABLE"],"sources":["../../src/fedify_middleware.ts"],"sourcesContent":["/**\n * The AdonisJS server middleware that mounts Fedify.\n *\n * The service provider binds {@link FedifyMiddleware} with the `Federation`\n * and `config/fedify.ts`; applications that build their own `Federation` use\n * {@link fedifyMiddleware} instead. Nothing here depends on the container.\n *\n * @module\n */\nimport { Readable } from \"node:stream\";\n\nimport type { HttpContext } from \"@adonisjs/core/http\";\nimport type { NextFn } from \"@adonisjs/core/types/http\";\nimport type { Federation } from \"@fedify/fedify\";\n\nimport {\n E_FEDIFY_CONTEXT_UNAVAILABLE,\n E_MISSING_FEDERATION,\n} from \"./errors.ts\";\nimport {\n ensureFederationGetter,\n type HttpContextClass,\n setFederationContextFactory,\n} from \"./http_context.ts\";\nimport type { ContextData, ContextDataFactory } from \"./types.ts\";\nimport {\n PLACEHOLDER_HOST,\n warnUnusableAuthority,\n} from \"./unusable_authority.ts\";\n\n/**\n * Options accepted by {@link FedifyMiddleware} and {@link fedifyMiddleware}.\n */\nexport interface FedifyMiddlewareOptions {\n /**\n * URL path prefixes to bypass entirely. See\n * {@link import('./types.js').FedifyConfig.ignoreRoutePrefixes}.\n *\n * @default `[]`\n */\n ignoreRoutePrefixes?: string[];\n}\n\n/**\n * The instance shape of the middleware.\n */\nexport interface FedifyMiddlewareHandler {\n handle(ctx: HttpContext, next: NextFn): Promise<void>;\n}\n\n/**\n * What {@link fedifyMiddleware} returns: a middleware **class**, since\n * `server.use()` constructs entries through the container.\n */\nexport type FedifyMiddlewareClass = new () => FedifyMiddlewareHandler;\n\n/**\n * The arguments after `federation`. The factory defaults to producing\n * `undefined`, so it may only be omitted when `TContextData` admits it;\n * otherwise omitting it is a compile error. The tuple wrapper keeps the\n * conditional from distributing over a union.\n */\nexport type FedifyMiddlewareArgs<TContextData> = [undefined] extends [\n TContextData,\n]\n ? [\n contextDataFactory?: ContextDataFactory<TContextData>,\n options?: FedifyMiddlewareOptions,\n ]\n : [\n contextDataFactory: ContextDataFactory<TContextData>,\n options?: FedifyMiddlewareOptions,\n ];\n\n/**\n * Context classes whose conflicting `federation` member was already reported.\n */\nconst conflicting = new WeakSet<object>();\n\n/**\n * Methods `new Request()` refuses; in practice only `TRACE` arrives here.\n */\nconst FORBIDDEN_METHODS = new Set([\"CONNECT\", \"TRACE\", \"TRACK\"]);\n\n/**\n * Wraps the raw `IncomingMessage` in a `ReadableStream` that stays inert until\n * first read. The `Request` is built before Fedify decides whether it handles\n * the request; an eager `Readable.toWeb()` would start draining the socket and\n * hang the AdonisJS body parser on every declined `POST`.\n */\nfunction lazyRequestBody(\n message: HttpContext[\"request\"][\"request\"],\n): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n reader ??= (\n Readable.toWeb(message) as ReadableStream<Uint8Array>\n ).getReader();\n\n const { done, value } = await reader.read();\n if (done) controller.close();\n else controller.enqueue(value);\n },\n cancel(reason) {\n return reader?.cancel(reason);\n },\n },\n { highWaterMark: 0 },\n );\n}\n\n/**\n * What an authority may not contain: `Host` admits only `uri-host [\":\" port]`,\n * so anything that could carry a path, query, fragment or userinfo makes the\n * value something other than an authority.\n */\nconst NON_AUTHORITY = /[/?#\\\\@\\s]/;\n\n/**\n * Keeps the first entry of a comma-separated authority (`X-Forwarded-Host`\n * behind two proxies), which `new URL()` would reject.\n *\n * Under `trustProxy`, `authority()` returns `X-Forwarded-Host` verbatim, so a\n * client could send `example.com/x` and shift the path Fedify sees to\n * `/x/users/alice` while AdonisJS still routes the real path — bypassing\n * `ignoreRoutePrefixes`. Anything that could carry a path, query, fragment or\n * userinfo (`good.example@evil.com` parses to the host `evil.com`) is\n * therefore refused outright, which leaves the {@link PLACEHOLDER_HOST}\n * fallback to keep the path intact.\n */\nfunction normalizeAuthority(host: string): string {\n const comma = host.indexOf(\",\");\n const authority = (comma < 0 ? host : host.slice(0, comma)).trim();\n return NON_AUTHORITY.test(authority) ? \"\" : authority;\n}\n\n/**\n * Reduces a request target to origin form, or `undefined` when it carries no\n * path. An absolute target (`GET http://example.com/users/alice HTTP/1.1`)\n * reaches `req.url` verbatim; only its path and query survive, so the request\n * line cannot pick the host Fedify sees and let an inbox `POST` signed for\n * another server verify here.\n */\nfunction toOriginForm(target: string): string | undefined {\n // Origin form already. It is interpolated, not resolved, so `//users/alice`\n // keeps its path instead of reading `users` as a host.\n if (target.startsWith(\"/\")) return target;\n\n // Textually rather than through `new URL()`, which would hand back the\n // *normalised* path or, for a target it refuses, nothing at all --\n // collapsing the request to `/` and hiding the real path from\n // `ignoreRoutePrefixes` and `ctx.federation`.\n const prefix = /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\/[^/?#]*/.exec(target);\n // Asterisk form (`OPTIONS *`) or malformed. Authority form reaches only\n // `CONNECT`, which {@link FORBIDDEN_METHODS} refuses.\n if (prefix === null) return undefined;\n\n const rest = target.slice(prefix[0].length);\n return rest.startsWith(\"/\") ? rest : `/${rest}`;\n}\n\n/**\n * Builds the URL for one authority, or `undefined` if it cannot carry one.\n * The target is interpolated, never resolved, so the authority stays the one\n * {@link normalizeAuthority} passed; an empty one is refused because\n * `new URL(\"http:///users/alice\")` silently takes `users` as the host.\n */\nfunction buildRequestUrl(\n protocol: string,\n authority: string,\n target: string,\n): URL | undefined {\n if (authority === \"\") return undefined;\n\n try {\n return new URL(`${protocol}://${authority}${target}`);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Builds the URL Fedify sees from the raw request target, keeping the\n * percent-encoding Fedify's URI templates expect and the bytes a peer signed.\n * Only the target's path and query are read (see {@link toOriginForm}); the\n * authority comes from {@link normalizeAuthority}, via `authority()` so\n * HTTP/2's `:authority` is covered. Every input is attacker-controlled, so\n * the result only has to exist: the scheme is reduced to `http`/`https`, and\n * an unusable authority falls back to {@link PLACEHOLDER_HOST} rather than a\n * 500. Since that breaks signature verification, the discarded value is\n * returned for the caller to log once it knows Fedify will see the request.\n *\n * The accepted authority is returned verbatim as well, for the `Host` header\n * {@link toFetchRequest} synthesises on HTTP/2: `URL` normalises what it\n * parses (case, default port, punycode) while a signature covers the bytes as\n * sent. It is absent exactly when the placeholder stood in.\n */\nfunction toRequestUrl(request: HttpContext[\"request\"]): {\n url: URL;\n authority?: string;\n unusableAuthority?: string;\n} {\n // `protocol()` hands back the first `X-Forwarded-Proto` token as it\n // arrived; an upper-case `HTTPS` must not be read as plain `http`.\n const protocol =\n request.protocol().toLowerCase() === \"https\" ? \"https\" : \"http\";\n const host = request.authority();\n const authority = host == null ? \"\" : normalizeAuthority(host);\n // A target with no origin form is routed as `/`, which matches no\n // federation route, so AdonisJS answers.\n const target = toOriginForm(request.request.url ?? \"/\") ?? \"/\";\n\n const parsed = buildRequestUrl(protocol, authority, target);\n let url = parsed;\n let unusableAuthority: string | undefined;\n if (url === undefined) {\n // Only the authority can be at fault: the target starts with `/`, and a\n // URL parser in path state takes any bytes after it.\n url = new URL(`${protocol}://${PLACEHOLDER_HOST}${target}`);\n if (host != null) unusableAuthority = host;\n }\n\n return {\n url,\n authority: parsed === undefined ? undefined : authority,\n unusableAuthority,\n };\n}\n\n/**\n * Converts an AdonisJS request into a WHATWG `Request` for Fedify.\n *\n * `intended()`, not `method()`, so `_method` spoofing cannot turn an inbox\n * `POST` into a `GET`. Headers are forwarded as they arrived; HTTP/2\n * pseudo-headers are skipped, and since that leaves no `Host` (which\n * signatures may cover), one is synthesised only then, from the authority the\n * URL was built from.\n */\nfunction toFetchRequest(\n ctx: HttpContext,\n url: URL,\n authority: string | undefined,\n): Request {\n const request = ctx.request;\n const method = request.intended().toUpperCase();\n\n const headers = new Headers();\n const rawHeaders = request.headers();\n // `Object.keys()`, not `for...in`: a polluted prototype must not be forwarded.\n for (const key of Object.keys(rawHeaders)) {\n if (key.startsWith(\":\")) continue;\n const value = rawHeaders[key];\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else if (typeof value === \"string\") {\n headers.append(key, value);\n }\n }\n\n // Only when absent: an HTTP/1.1 `Host` is what the peer signed and what the\n // verifier reads, so it is never touched (a proxy rewriting `Host` has to\n // preserve it; see the README). On HTTP/2 the authority travels in\n // `:authority`, which the pseudo-header skip dropped, so it is put back\n // here -- verbatim, not `url.host`, since `URL` case-folds, drops a default\n // port and punycodes while a signature covers the bytes as sent. An\n // unusable authority gets the placeholder in the URL only, never a header.\n if (authority !== undefined && !headers.has(\"host\")) {\n headers.set(\"host\", authority);\n }\n\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n return new Request(url, {\n method,\n headers,\n body: hasBody ? lazyRequestBody(request.request) : undefined,\n // Not in the DOM lib's `RequestInit`, but Node requires it for streams.\n ...{ duplex: \"half\" },\n });\n}\n\n/**\n * Copies a WHATWG `Response` produced by Fedify onto the AdonisJS response.\n * `Set-Cookie` goes through `getSetCookie()` because iterating `Headers`\n * folds it; `Vary` is merged rather than copied, so a `Vary: Origin` an\n * upstream middleware set survives Fedify's own `Vary: Accept`; bodyless\n * responses (`204`, `304`, `HEAD`) are not streamed.\n */\nfunction writeFedifyResponse(response: Response, ctx: HttpContext): void {\n ctx.response.status(response.status);\n\n for (const [key, value] of response.headers) {\n const name = key.toLowerCase();\n if (name === \"set-cookie\") continue;\n if (name === \"vary\") {\n mergeIntoVary(ctx, value);\n continue;\n }\n ctx.response.header(key, value);\n }\n\n for (const cookie of response.headers.getSetCookie()) {\n ctx.response.append(\"set-cookie\", cookie);\n }\n\n const bodyless =\n response.body === null ||\n response.status === 204 ||\n response.status === 304 ||\n // `intended()`: a spoofed `_method=HEAD` must not suppress the body.\n ctx.request.intended().toUpperCase() === \"HEAD\";\n\n if (bodyless) {\n // Do not leave a body Fedify produced anyway (usually for HEAD) dangling;\n // a failed cleanup must not become an unhandled rejection.\n response.body?.cancel().catch(() => {});\n return;\n }\n\n ctx.response.stream(response.body!, (error) => {\n ctx.logger.error({ err: error }, \"Failed to stream the Fedify response\");\n return [\"Internal server error\", 500];\n });\n}\n\n/**\n * Splits a `Vary` value into its entries.\n */\nfunction parseVary(value: string): string[] {\n return value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry !== \"\");\n}\n\n/**\n * Merges a raw `Vary` value into the response's `Vary`.\n *\n * `ctx.response.header()` replaces rather than appends, so writing `Vary`\n * directly would drop what an upstream middleware or a route already put\n * there (CORS's `Origin`, say) and let a shared cache mix representations.\n *\n * Both of AdonisJS's header layers are read: `header()` buffers a value that\n * is copied onto the Node response when the reply is written, while\n * `ctx.response.vary()` writes to the Node response directly, and\n * `getHeader()` prefers the buffered value. Once `Accept` is buffered before\n * `next()`, a `vary(\"Origin\")` a route calls is therefore invisible through\n * `getHeader()` alone and would be overwritten at write time. The union goes\n * back to the buffered layer, since that is what goes out. `Vary: *` on any\n * side wins.\n */\nfunction mergeIntoVary(ctx: HttpContext, rawValue: string): void {\n const vary: string[] = [];\n const layers = [\n String(ctx.response.getHeader(\"Vary\") ?? \"\"),\n String(ctx.response.response.getHeader(\"vary\") ?? \"\"),\n rawValue,\n ];\n\n for (const layer of layers) {\n for (const value of parseVary(layer)) {\n if (value === \"*\") {\n ctx.response.header(\"Vary\", \"*\");\n return;\n }\n if (!vary.some((v) => v.toLowerCase() === value.toLowerCase())) {\n vary.push(value);\n }\n }\n }\n\n if (vary.length > 0) ctx.response.header(\"Vary\", vary.join(\", \"));\n}\n\n/**\n * Headers of a discarded response that must not describe the one written over\n * it: cache and validator metadata, which decides how long a shared cache\n * keeps the substitute, and metadata about a body nobody will see. The\n * targeted cache-control family (`CDN-Cache-Control`, `Surrogate-Control`, …)\n * is included because a CDN honours it over `Cache-Control` and largely\n * ignores `Vary`, so a leftover lifetime would keep the 406 cached for\n * ActivityPub clients too. Enumerated rather than matched on a `content-`\n * prefix, which would also take `Content-Security-Policy`.\n */\nconst DISCARDED_ENTITY_HEADERS: ReadonlySet<string> = new Set([\n \"age\",\n \"cache-control\",\n \"cdn-cache-control\",\n \"cloudflare-cdn-cache-control\",\n \"content-digest\",\n \"content-disposition\",\n \"content-encoding\",\n \"content-language\",\n \"content-length\",\n \"content-location\",\n \"content-range\",\n \"content-type\",\n \"digest\",\n \"etag\",\n \"expires\",\n \"last-modified\",\n \"pragma\",\n \"repr-digest\",\n \"surrogate-control\",\n \"surrogate-key\",\n]);\n\n/**\n * Removes a response header around a quirk of AdonisJS's `removeHeader()`,\n * which drops the buffered entry only when the current value is truthy, so one\n * set to `\"\"` would survive. It also forwards to Node unconditionally, which\n * throws once the head is flushed, so this is only safe while\n * `ctx.response.headersSent` is false.\n */\nfunction removeResponseHeader(ctx: HttpContext, key: string): void {\n // A non-empty placeholder, so the buffered entry is truthy and deleted.\n ctx.response.header(key, \"-\");\n ctx.response.removeHeader(key);\n}\n\n/**\n * Drops the body a discarded response left buffered, so the one written over\n * it is the one that goes out.\n *\n * `response.send()` assigns `lazyBody.content` alone, and `finish()` reads the\n * other entries after it: a path passed to `download()` would still be\n * streamed in place of the new body, and a readable passed to `stream()`\n * would be forgotten — one leaked file descriptor per request. Resetting\n * `lazyBody` drops both.\n */\nfunction discardPendingBody(ctx: HttpContext): void {\n const stream = ctx.response.outgoingStream;\n ctx.response.lazyBody = {};\n if (stream == null) return;\n\n // `ResponseStream` is either a Node `Readable` or a WHATWG `ReadableStream`.\n if (\"destroy\" in stream) {\n // Nothing else listens, since AdonisJS never attached to the stream, and\n // an unlistened `error` event is an uncaught exception.\n stream.on(\"error\", () => {});\n if (!stream.destroyed) stream.destroy();\n } else if (!stream.locked) {\n // Likewise, a rejected `cancel()` must not become an unhandled rejection.\n stream.cancel().catch(() => {});\n }\n}\n\n/**\n * Undoes what a discarded response did to the headers, before another is\n * written over it.\n *\n * `next()` mixes two populations: a header a *later middleware* set\n * (`@adonisjs/cors`'s `Access-Control-Allow-Origin`, say) answers this\n * request and has to survive, while one the *discarded page* set describes a\n * body nobody will see. They are told apart by name: only\n * {@link DISCARDED_ENTITY_HEADERS} are touched, and each is put back exactly\n * as the snapshot had it — removed when the snapshot had none. Restoring\n * every snapshot entry instead would undo the request's own answer, since\n * `response.header()` replaces rather than merges.\n *\n * `Vary` is reconciled by {@link mergeIntoVary} around `next()` instead,\n * since only the union of the snapshot and the current value is right.\n */\nfunction rollBackDiscardedResponse(\n ctx: HttpContext,\n headersBefore: ReturnType<HttpContext[\"response\"][\"getHeaders\"]>,\n): void {\n const headersAfter = ctx.response.getHeaders();\n\n for (const key of DISCARDED_ENTITY_HEADERS) {\n // `hasOwn()`, not `in`: `constructor` is a legal header name.\n const before = Object.hasOwn(headersBefore, key)\n ? headersBefore[key]\n : undefined;\n\n // Written back whether or not `next()` changed it: `header()` is\n // idempotent, and takes an array, so a repeated header goes back whole.\n if (before !== undefined) ctx.response.header(key, before);\n else if (Object.hasOwn(headersAfter, key)) removeResponseHeader(ctx, key);\n }\n}\n\n/**\n * The response handed back to Fedify after AdonisJS answered a delegated\n * request. Nothing is written from it, but Fedify logs and meters its\n * status, so it reports what AdonisJS answered. `Response` only accepts\n * 200-599, so anything else (a 1xx) is reported as 200.\n */\nfunction delegatedResponse(status: number): Response {\n return new Response(null, {\n status: status >= 200 && status <= 599 ? status : 200,\n });\n}\n\n/**\n * Mounts a `Federation` instance inside an AdonisJS application; the\n * counterpart of `integrateFederation()` in `@fedify/express`.\n *\n * Register it in the **server** stack: Fedify serves paths the router does\n * not know, and the body stream is still intact there for signature\n * verification. An instance holds configuration only, so one serves every\n * request.\n */\nexport default class FedifyMiddleware<\n TContextData = ContextData,\n> implements FedifyMiddlewareHandler {\n #federation: Federation<TContextData>;\n #contextDataFactory: ContextDataFactory<TContextData>;\n #ignoreRoutePrefixes: string[];\n\n /**\n * @param federation The federation instance to mount.\n * @param args The context-data factory and the options; see\n * {@link FedifyMiddlewareArgs}. The factory sees a pre-routing\n * `HttpContext`; see {@link import('./types.js').ContextDataFactory}.\n */\n constructor(\n federation: Federation<TContextData>,\n ...args: FedifyMiddlewareArgs<TContextData>\n ) {\n // The container zero-arg-constructs this class when the object the kernel\n // resolved is not the one the provider bound (a duplicated package copy,\n // or the ESM and CJS builds mixed); fail here rather than on every request.\n if (federation == null) throw new E_MISSING_FEDERATION();\n\n // The conditional tuple is unresolved here; read it through its common shape.\n const [contextDataFactory, options] = args as [\n ContextDataFactory<TContextData>?,\n FedifyMiddlewareOptions?,\n ];\n\n this.#federation = federation;\n this.#contextDataFactory =\n contextDataFactory ?? (() => undefined as TContextData);\n this.#ignoreRoutePrefixes = options?.ignoreRoutePrefixes ?? [];\n }\n\n async handle(ctx: HttpContext, next: NextFn): Promise<void> {\n const federation = this.#federation;\n\n // Install the `ctx.federation` getter on this context's class: it covers a\n // duplicated `@adonisjs/core` and the container-free path, which has no\n // provider. A conflicting `federation` member is reported once; the\n // federation endpoints do not need the accessor.\n const contextClass = ctx.constructor as unknown as HttpContextClass;\n if (\n !ensureFederationGetter(contextClass) &&\n !conflicting.has(contextClass)\n ) {\n conflicting.add(contextClass);\n ctx.logger.error(\n 'Something other than @fedify/adonisjs defines \"federation\" on this ' +\n 'application\\'s HttpContext, so \"ctx.federation\" is not the Fedify ' +\n \"request context. Federation endpoints are unaffected; rename the \" +\n \"conflicting macro or getter to use it from controllers\",\n );\n }\n\n // The ignore check and Fedify must see the same URL, so build it once.\n const { url, authority, unusableAuthority } = toRequestUrl(ctx.request);\n const path = url.pathname;\n\n if (\n this.#ignoreRoutePrefixes.some((prefix) => path.startsWith(prefix)) ||\n FORBIDDEN_METHODS.has(ctx.request.intended().toUpperCase())\n ) {\n // Opted out, or impossible to represent as a `Request`.\n setFederationContextFactory(ctx, () => {\n throw new E_FEDIFY_CONTEXT_UNAVAILABLE(path);\n });\n return next();\n }\n\n // Only past the bypass: on an opted-out path Fedify never sees the URL,\n // so the placeholder is harmless.\n if (unusableAuthority !== undefined) {\n warnUnusableAuthority(ctx.logger, unusableAuthority);\n }\n\n const request = toFetchRequest(ctx, url, authority);\n\n // `federation.fetch()` takes `contextData` by value, so the factory runs\n // before the router.\n const contextData = await this.#contextDataFactory(ctx);\n\n // Also for requests Fedify declines: a controller serving the HTML half of\n // a shared URL needs it. The getter creates the context lazily.\n setFederationContextFactory(ctx, () =>\n federation.createContext(request, contextData),\n );\n\n /**\n * What happened while Fedify was deciding: whether a fall-through callback\n * handed the request to AdonisJS, and whether AdonisJS produced nothing of\n * its own so the 406 below is the answer. \"Nothing\" means no route\n * matched (`ctx.route` is set only on a match) *and* the framework's own\n * 404: a later server middleware (`@adonisjs/cors` on a preflight) or a\n * downstream failure can answer without the router running, and must not\n * be overwritten. A downstream middleware *deliberately* answering 404 on\n * a Fedify-owned path is indistinguishable from that default and is also\n * replaced by the 406.\n *\n * `router.match()` could say before `next()` whether a route exists and\n * spare the rollback, but is deliberately not asked:\n *\n * 1. Every integration follows the deferred-406 contract the manual\n * documents: delegate, and answer 406 only when the framework answered\n * 404 (Hono reads `ctx.res.status` after `next()`, Express `req.route`).\n * Deciding from the route table would give AdonisJS a narrower one.\n *\n * 2. Server middleware answers without a route by design (`@adonisjs/cors`\n * on a preflight, `@adonisjs/static`, a maintenance page), and Fedify\n * calls `onNotAcceptable` for a wildcard `Accept` too -- what curl and\n * a preflight send -- so skipping `next()` would cut those off on every\n * path Fedify owns.\n *\n * 3. `ctx.route` is the framework's own verdict. A lookup here would\n * duplicate `routeFinder`'s preamble and drift silently as the router\n * changes.\n *\n * The price is undoing a response AdonisJS was allowed to start: the\n * headers in {@link DISCARDED_ENTITY_HEADERS} are put back by name, a\n * pending body is dropped, and nothing is touched once the head has been\n * flushed.\n *\n * An object rather than two `let`s so TypeScript does not narrow them.\n */\n const outcome: { delegated: boolean; answer406: boolean } = {\n delegated: false,\n answer406: false,\n };\n\n const response = await federation.fetch(request, {\n contextData,\n\n /**\n * Fedify has no route for this path: hand the request to AdonisJS.\n * `await next()` resolves even on no match, since `E_ROUTE_NOT_FOUND`\n * goes through the exception handler and renders a 404.\n */\n onNotFound: async () => {\n outcome.delegated = true;\n await next();\n return delegatedResponse(ctx.response.getStatus());\n },\n\n /**\n * Fedify has a route but cannot satisfy `Accept` (a browser at an actor\n * URL). AdonisJS gets a chance to serve its own representation first;\n * 406 is only the answer if it has nothing either. `Accept` is merged\n * into `Vary` rather than written over it, and the snapshot's value is\n * merged back after `next()`, because a route may have replaced the\n * header meanwhile.\n */\n onNotAcceptable: async () => {\n outcome.delegated = true;\n mergeIntoVary(ctx, \"Accept\");\n // A value snapshot, not a live view: `getHeaders()` builds a fresh\n // object on every call.\n const headersBefore = ctx.response.getHeaders();\n await next();\n\n // Put back what `Vary` carried before `next()`, `Accept` included. A\n // superset only costs cache hits; a missing entry lets a cache mix the\n // two representations up.\n mergeIntoVary(ctx, String(headersBefore.vary ?? \"\"));\n\n const status = ctx.response.getStatus();\n // Not once the head is flushed: the 406 could not be written over it,\n // and `removeHeader()` would raise `ERR_HTTP_HEADERS_SENT`.\n outcome.answer406 =\n ctx.route === undefined &&\n status === 404 &&\n !ctx.response.headersSent;\n\n if (outcome.answer406) rollBackDiscardedResponse(ctx, headersBefore);\n\n // The 406 itself is produced below; this only feeds Fedify's log.\n return delegatedResponse(outcome.answer406 ? 406 : status);\n },\n });\n\n // Fedify owns the path, cannot satisfy `Accept`, and AdonisJS had nothing\n // either. `Vary` already carries `Accept`.\n if (outcome.answer406) {\n // Before `send()`, which only sets the buffered *content*: a 404 page\n // rendered with `download()` or `stream()` would otherwise still go out,\n // or leak its readable.\n discardPendingBody(ctx);\n ctx.response.status(406).type(\"text/plain\").send(\"Not acceptable\");\n return;\n }\n\n if (outcome.delegated) {\n // AdonisJS produced the response (a matched route or its own 404 page).\n return;\n }\n\n writeFedifyResponse(response, ctx);\n }\n}\n\n/**\n * Creates a middleware class around a `Federation` the application built\n * itself, with no container or `config/fedify.ts` involved. This is the\n * package's default export; most applications use the provider instead.\n *\n * @example\n * ```ts\n * // start/kernel.ts\n * import fedifyMiddleware from '@fedify/adonisjs'\n * // A module of the application's own that default-exports its `Federation`.\n * import federation from '../app/federation.js'\n *\n * server.use([\n * async () => ({ default: fedifyMiddleware(federation, (ctx) => ctx) }),\n * ])\n * ```\n *\n * With the default `ContextData` of `HttpContext | null`, pass `(ctx) => ctx`\n * to match the provider; see {@link FedifyMiddlewareArgs}.\n *\n * @returns A {@link FedifyMiddleware} subclass whose constructor takes no\n * arguments, which is what `server.use()` constructs.\n * @param federation The federation instance to mount.\n * @param args The context-data factory and the options.\n */\nexport function fedifyMiddleware<TContextData>(\n federation: Federation<TContextData>,\n ...args: FedifyMiddlewareArgs<TContextData>\n): FedifyMiddlewareClass {\n // Here rather than in the constructor guard, which fires only on the first\n // request and blames the provider or a duplicated package copy; a factory\n // caller's likely mistake is a module that default-exports nothing.\n if (federation == null) {\n throw new E_MISSING_FEDERATION(\n \"fedifyMiddleware() was called without a Federation instance. Check \" +\n \"that the module its first argument comes from actually \" +\n \"default-exports the Federation it builds\",\n );\n }\n\n // Named so container errors and tracing show something readable.\n return class ConfiguredFedifyMiddleware extends FedifyMiddleware<TContextData> {\n constructor() {\n super(federation, ...args);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6EA,MAAM,cAAc,IAAI,QAAgB;;;;AAKxC,MAAM,oBAAoB,IAAI,IAAI;CAAC;CAAW;CAAS;AAAO,CAAC;;;;;;;AAQ/D,SAAS,gBACP,SAC4B;CAC5B,IAAI;CAEJ,OAAO,IAAI,eACT;EACE,MAAM,KAAK,YAAY;GACrB,WACEA,qBAAS,MAAM,OAAO,CAAC,CACvB,UAAU;GAEZ,MAAM,EAAE,MAAM,UAAU,MAAM,OAAO,KAAK;GAC1C,IAAI,MAAM,WAAW,MAAM;QACtB,WAAW,QAAQ,KAAK;EAC/B;EACA,OAAO,QAAQ;GACb,OAAO,QAAQ,OAAO,MAAM;EAC9B;CACF,GACA,EAAE,eAAe,EAAE,CACrB;AACF;;;;;;AAOA,MAAM,gBAAgB;;;;;;;;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EA,IAAI,QAAQ,WAAW;GAErB;EACF;EAEA,oBAAoB,UAAU,GAAG;CACnC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,iBACd,YACA,GAAG,MACoB;CAIvB,IAAI,cAAc,MAAM;EACtB,MAAM,IAAIF,wCACR,wEACE,4DACA,0CACJ;CACF;CAGA,OAAO,MAAM,mCAAmC,iBAA+B;EAC7E,cAAc;GACZ,MAAM,YAAY,GAAG,IAAI;EAC3B;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fedify_middleware.js","names":["#federation","#contextDataFactory","#ignoreRoutePrefixes"],"sources":["../../src/fedify_middleware.ts"],"sourcesContent":["/**\n * The AdonisJS server middleware that mounts Fedify.\n *\n * The service provider binds {@link FedifyMiddleware} with the `Federation`\n * and `config/fedify.ts`; applications that build their own `Federation` use\n * {@link fedifyMiddleware} instead. Nothing here depends on the container.\n *\n * @module\n */\nimport { Readable } from \"node:stream\";\n\nimport type { HttpContext } from \"@adonisjs/core/http\";\nimport type { NextFn } from \"@adonisjs/core/types/http\";\nimport type { Federation } from \"@fedify/fedify\";\n\nimport {\n E_FEDIFY_CONTEXT_UNAVAILABLE,\n E_MISSING_FEDERATION,\n} from \"./errors.ts\";\nimport {\n ensureFederationGetter,\n type HttpContextClass,\n setFederationContextFactory,\n} from \"./http_context.ts\";\nimport type { ContextData, ContextDataFactory } from \"./types.ts\";\nimport {\n PLACEHOLDER_HOST,\n warnUnusableAuthority,\n} from \"./unusable_authority.ts\";\n\n/**\n * Options accepted by {@link FedifyMiddleware} and {@link fedifyMiddleware}.\n */\nexport interface FedifyMiddlewareOptions {\n /**\n * URL path prefixes to bypass entirely. See\n * {@link import('./types.js').FedifyConfig.ignoreRoutePrefixes}.\n *\n * @default `[]`\n */\n ignoreRoutePrefixes?: string[];\n}\n\n/**\n * The instance shape of the middleware.\n */\nexport interface FedifyMiddlewareHandler {\n handle(ctx: HttpContext, next: NextFn): Promise<void>;\n}\n\n/**\n * What {@link fedifyMiddleware} returns: a middleware **class**, since\n * `server.use()` constructs entries through the container.\n */\nexport type FedifyMiddlewareClass = new () => FedifyMiddlewareHandler;\n\n/**\n * The arguments after `federation`. The factory defaults to producing\n * `undefined`, so it may only be omitted when `TContextData` admits it;\n * otherwise omitting it is a compile error. The tuple wrapper keeps the\n * conditional from distributing over a union.\n */\nexport type FedifyMiddlewareArgs<TContextData> = [undefined] extends\n [TContextData] ? [\n contextDataFactory?: ContextDataFactory<TContextData>,\n options?: FedifyMiddlewareOptions,\n ]\n : [\n contextDataFactory: ContextDataFactory<TContextData>,\n options?: FedifyMiddlewareOptions,\n ];\n\n/**\n * Context classes whose conflicting `federation` member was already reported.\n */\nconst conflicting = new WeakSet<object>();\n\n/**\n * Methods `new Request()` refuses; in practice only `TRACE` arrives here.\n */\nconst FORBIDDEN_METHODS = new Set([\"CONNECT\", \"TRACE\", \"TRACK\"]);\n\n/**\n * Wraps the raw `IncomingMessage` in a `ReadableStream` that stays inert until\n * first read. The `Request` is built before Fedify decides whether it handles\n * the request; an eager `Readable.toWeb()` would start draining the socket and\n * hang the AdonisJS body parser on every declined `POST`.\n */\nfunction lazyRequestBody(\n message: HttpContext[\"request\"][\"request\"],\n): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n reader ??= (Readable.toWeb(message) as ReadableStream<Uint8Array>)\n .getReader();\n\n const { done, value } = await reader.read();\n if (done) controller.close();\n else controller.enqueue(value);\n },\n cancel(reason) {\n return reader?.cancel(reason);\n },\n },\n { highWaterMark: 0 },\n );\n}\n\n/**\n * What an authority may not contain: `Host` admits only `uri-host [\":\" port]`,\n * so anything that could carry a path, query, fragment or userinfo makes the\n * value something other than an authority.\n */\nconst NON_AUTHORITY = /[/?#\\\\@\\s]/;\n\n/**\n * Keeps the first entry of a comma-separated authority (`X-Forwarded-Host`\n * behind two proxies), which `new URL()` would reject.\n *\n * Under `trustProxy`, `authority()` returns `X-Forwarded-Host` verbatim, so a\n * client could send `example.com/x` and shift the path Fedify sees to\n * `/x/users/alice` while AdonisJS still routes the real path — bypassing\n * `ignoreRoutePrefixes`. Anything that could carry a path, query, fragment or\n * userinfo (`good.example@evil.com` parses to the host `evil.com`) is\n * therefore refused outright, which leaves the {@link PLACEHOLDER_HOST}\n * fallback to keep the path intact.\n */\nfunction normalizeAuthority(host: string): string {\n const comma = host.indexOf(\",\");\n const authority = (comma < 0 ? host : host.slice(0, comma)).trim();\n return NON_AUTHORITY.test(authority) ? \"\" : authority;\n}\n\n/**\n * Reduces a request target to origin form, or `undefined` when it carries no\n * path. An absolute target (`GET http://example.com/users/alice HTTP/1.1`)\n * reaches `req.url` verbatim; only its path and query survive, so the request\n * line cannot pick the host Fedify sees and let an inbox `POST` signed for\n * another server verify here.\n */\nfunction toOriginForm(target: string): string | undefined {\n // Origin form already. It is interpolated, not resolved, so `//users/alice`\n // keeps its path instead of reading `users` as a host.\n if (target.startsWith(\"/\")) return target;\n\n // Textually rather than through `new URL()`, which would hand back the\n // *normalised* path or, for a target it refuses, nothing at all --\n // collapsing the request to `/` and hiding the real path from\n // `ignoreRoutePrefixes` and `ctx.federation`.\n const prefix = /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\/[^/?#]*/.exec(target);\n // Asterisk form (`OPTIONS *`) or malformed. Authority form reaches only\n // `CONNECT`, which {@link FORBIDDEN_METHODS} refuses.\n if (prefix === null) return undefined;\n\n const rest = target.slice(prefix[0].length);\n return rest.startsWith(\"/\") ? rest : `/${rest}`;\n}\n\n/**\n * Builds the URL for one authority, or `undefined` if it cannot carry one.\n * The target is interpolated, never resolved, so the authority stays the one\n * {@link normalizeAuthority} passed; an empty one is refused because\n * `new URL(\"http:///users/alice\")` silently takes `users` as the host.\n */\nfunction buildRequestUrl(\n protocol: string,\n authority: string,\n target: string,\n): URL | undefined {\n if (authority === \"\") return undefined;\n\n try {\n return new URL(`${protocol}://${authority}${target}`);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Builds the URL Fedify sees from the raw request target, keeping the\n * percent-encoding Fedify's URI templates expect and the bytes a peer signed.\n * Only the target's path and query are read (see {@link toOriginForm}); the\n * authority comes from {@link normalizeAuthority}, via `authority()` so\n * HTTP/2's `:authority` is covered. Every input is attacker-controlled, so\n * the result only has to exist: the scheme is reduced to `http`/`https`, and\n * an unusable authority falls back to {@link PLACEHOLDER_HOST} rather than a\n * 500. Since that breaks signature verification, the discarded value is\n * returned for the caller to log once it knows Fedify will see the request.\n *\n * The accepted authority is returned verbatim as well, for the `Host` header\n * {@link toFetchRequest} synthesises on HTTP/2: `URL` normalises what it\n * parses (case, default port, punycode) while a signature covers the bytes as\n * sent. It is absent exactly when the placeholder stood in.\n */\nfunction toRequestUrl(\n request: HttpContext[\"request\"],\n): { url: URL; authority?: string; unusableAuthority?: string } {\n // `protocol()` hands back the first `X-Forwarded-Proto` token as it\n // arrived; an upper-case `HTTPS` must not be read as plain `http`.\n const protocol = request.protocol().toLowerCase() === \"https\"\n ? \"https\"\n : \"http\";\n const host = request.authority();\n const authority = host == null ? \"\" : normalizeAuthority(host);\n // A target with no origin form is routed as `/`, which matches no\n // federation route, so AdonisJS answers.\n const target = toOriginForm(request.request.url ?? \"/\") ?? \"/\";\n\n const parsed = buildRequestUrl(protocol, authority, target);\n let url = parsed;\n let unusableAuthority: string | undefined;\n if (url === undefined) {\n // Only the authority can be at fault: the target starts with `/`, and a\n // URL parser in path state takes any bytes after it.\n url = new URL(`${protocol}://${PLACEHOLDER_HOST}${target}`);\n if (host != null) unusableAuthority = host;\n }\n\n return {\n url,\n authority: parsed === undefined ? undefined : authority,\n unusableAuthority,\n };\n}\n\n/**\n * Converts an AdonisJS request into a WHATWG `Request` for Fedify.\n *\n * `intended()`, not `method()`, so `_method` spoofing cannot turn an inbox\n * `POST` into a `GET`. Headers are forwarded as they arrived; HTTP/2\n * pseudo-headers are skipped, and since that leaves no `Host` (which\n * signatures may cover), one is synthesised only then, from the authority the\n * URL was built from.\n */\nfunction toFetchRequest(\n ctx: HttpContext,\n url: URL,\n authority: string | undefined,\n): Request {\n const request = ctx.request;\n const method = request.intended().toUpperCase();\n\n const headers = new Headers();\n const rawHeaders = request.headers();\n // `Object.keys()`, not `for...in`: a polluted prototype must not be forwarded.\n for (const key of Object.keys(rawHeaders)) {\n if (key.startsWith(\":\")) continue;\n const value = rawHeaders[key];\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else if (typeof value === \"string\") {\n headers.append(key, value);\n }\n }\n\n // Only when absent: an HTTP/1.1 `Host` is what the peer signed and what the\n // verifier reads, so it is never touched (a proxy rewriting `Host` has to\n // preserve it; see the README). On HTTP/2 the authority travels in\n // `:authority`, which the pseudo-header skip dropped, so it is put back\n // here -- verbatim, not `url.host`, since `URL` case-folds, drops a default\n // port and punycodes while a signature covers the bytes as sent. An\n // unusable authority gets the placeholder in the URL only, never a header.\n if (authority !== undefined && !headers.has(\"host\")) {\n headers.set(\"host\", authority);\n }\n\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n return new Request(url, {\n method,\n headers,\n body: hasBody ? lazyRequestBody(request.request) : undefined,\n // Not in the DOM lib's `RequestInit`, but Node requires it for streams.\n ...{ duplex: \"half\" },\n });\n}\n\n/**\n * Copies a WHATWG `Response` produced by Fedify onto the AdonisJS response.\n * `Set-Cookie` goes through `getSetCookie()` because iterating `Headers`\n * folds it; `Vary` is merged rather than copied, so a `Vary: Origin` an\n * upstream middleware set survives Fedify's own `Vary: Accept`; bodyless\n * responses (`204`, `304`, `HEAD`) are not streamed.\n */\nfunction writeFedifyResponse(response: Response, ctx: HttpContext): void {\n ctx.response.status(response.status);\n\n for (const [key, value] of response.headers) {\n const name = key.toLowerCase();\n if (name === \"set-cookie\") continue;\n if (name === \"vary\") {\n mergeIntoVary(ctx, value);\n continue;\n }\n ctx.response.header(key, value);\n }\n\n for (const cookie of response.headers.getSetCookie()) {\n ctx.response.append(\"set-cookie\", cookie);\n }\n\n const bodyless = response.body === null ||\n response.status === 204 ||\n response.status === 304 ||\n // `intended()`: a spoofed `_method=HEAD` must not suppress the body.\n ctx.request.intended().toUpperCase() === \"HEAD\";\n\n if (bodyless) {\n // Do not leave a body Fedify produced anyway (usually for HEAD) dangling;\n // a failed cleanup must not become an unhandled rejection.\n response.body?.cancel().catch(() => {});\n return;\n }\n\n ctx.response.stream(response.body!, (error) => {\n ctx.logger.error({ err: error }, \"Failed to stream the Fedify response\");\n return [\"Internal server error\", 500];\n });\n}\n\n/**\n * Splits a `Vary` value into its entries.\n */\nfunction parseVary(value: string): string[] {\n return value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry !== \"\");\n}\n\n/**\n * Merges a raw `Vary` value into the response's `Vary`.\n *\n * `ctx.response.header()` replaces rather than appends, so writing `Vary`\n * directly would drop what an upstream middleware or a route already put\n * there (CORS's `Origin`, say) and let a shared cache mix representations.\n *\n * Both of AdonisJS's header layers are read: `header()` buffers a value that\n * is copied onto the Node response when the reply is written, while\n * `ctx.response.vary()` writes to the Node response directly, and\n * `getHeader()` prefers the buffered value. Once `Accept` is buffered before\n * `next()`, a `vary(\"Origin\")` a route calls is therefore invisible through\n * `getHeader()` alone and would be overwritten at write time. The union goes\n * back to the buffered layer, since that is what goes out. `Vary: *` on any\n * side wins.\n */\nfunction mergeIntoVary(ctx: HttpContext, rawValue: string): void {\n const vary: string[] = [];\n const layers = [\n String(ctx.response.getHeader(\"Vary\") ?? \"\"),\n String(ctx.response.response.getHeader(\"vary\") ?? \"\"),\n rawValue,\n ];\n\n for (const layer of layers) {\n for (const value of parseVary(layer)) {\n if (value === \"*\") {\n ctx.response.header(\"Vary\", \"*\");\n return;\n }\n if (!vary.some((v) => v.toLowerCase() === value.toLowerCase())) {\n vary.push(value);\n }\n }\n }\n\n if (vary.length > 0) ctx.response.header(\"Vary\", vary.join(\", \"));\n}\n\n/**\n * Headers of a discarded response that must not describe the one written over\n * it: cache and validator metadata, which decides how long a shared cache\n * keeps the substitute, and metadata about a body nobody will see. The\n * targeted cache-control family (`CDN-Cache-Control`, `Surrogate-Control`, …)\n * is included because a CDN honours it over `Cache-Control` and largely\n * ignores `Vary`, so a leftover lifetime would keep the 406 cached for\n * ActivityPub clients too. Enumerated rather than matched on a `content-`\n * prefix, which would also take `Content-Security-Policy`.\n */\nconst DISCARDED_ENTITY_HEADERS: ReadonlySet<string> = new Set([\n \"age\",\n \"cache-control\",\n \"cdn-cache-control\",\n \"cloudflare-cdn-cache-control\",\n \"content-digest\",\n \"content-disposition\",\n \"content-encoding\",\n \"content-language\",\n \"content-length\",\n \"content-location\",\n \"content-range\",\n \"content-type\",\n \"digest\",\n \"etag\",\n \"expires\",\n \"last-modified\",\n \"pragma\",\n \"repr-digest\",\n \"surrogate-control\",\n \"surrogate-key\",\n]);\n\n/**\n * Removes a response header around a quirk of AdonisJS's `removeHeader()`,\n * which drops the buffered entry only when the current value is truthy, so one\n * set to `\"\"` would survive. It also forwards to Node unconditionally, which\n * throws once the head is flushed, so this is only safe while\n * `ctx.response.headersSent` is false.\n */\nfunction removeResponseHeader(ctx: HttpContext, key: string): void {\n // A non-empty placeholder, so the buffered entry is truthy and deleted.\n ctx.response.header(key, \"-\");\n ctx.response.removeHeader(key);\n}\n\n/**\n * Drops the body a discarded response left buffered, so the one written over\n * it is the one that goes out.\n *\n * `response.send()` assigns `lazyBody.content` alone, and `finish()` reads the\n * other entries after it: a path passed to `download()` would still be\n * streamed in place of the new body, and a readable passed to `stream()`\n * would be forgotten — one leaked file descriptor per request. Resetting\n * `lazyBody` drops both.\n */\nfunction discardPendingBody(ctx: HttpContext): void {\n const stream = ctx.response.outgoingStream;\n ctx.response.lazyBody = {};\n if (stream == null) return;\n\n // `ResponseStream` is either a Node `Readable` or a WHATWG `ReadableStream`.\n if (\"destroy\" in stream) {\n // Nothing else listens, since AdonisJS never attached to the stream, and\n // an unlistened `error` event is an uncaught exception.\n stream.on(\"error\", () => {});\n if (!stream.destroyed) stream.destroy();\n } else if (!stream.locked) {\n // Likewise, a rejected `cancel()` must not become an unhandled rejection.\n stream.cancel().catch(() => {});\n }\n}\n\n/**\n * Undoes what a discarded response did to the headers, before another is\n * written over it.\n *\n * `next()` mixes two populations: a header a *later middleware* set\n * (`@adonisjs/cors`'s `Access-Control-Allow-Origin`, say) answers this\n * request and has to survive, while one the *discarded page* set describes a\n * body nobody will see. They are told apart by name: only\n * {@link DISCARDED_ENTITY_HEADERS} are touched, and each is put back exactly\n * as the snapshot had it — removed when the snapshot had none. Restoring\n * every snapshot entry instead would undo the request's own answer, since\n * `response.header()` replaces rather than merges.\n *\n * `Vary` is reconciled by {@link mergeIntoVary} around `next()` instead,\n * since only the union of the snapshot and the current value is right.\n */\nfunction rollBackDiscardedResponse(\n ctx: HttpContext,\n headersBefore: ReturnType<HttpContext[\"response\"][\"getHeaders\"]>,\n): void {\n const headersAfter = ctx.response.getHeaders();\n\n for (const key of DISCARDED_ENTITY_HEADERS) {\n // `hasOwn()`, not `in`: `constructor` is a legal header name.\n const before = Object.hasOwn(headersBefore, key)\n ? headersBefore[key]\n : undefined;\n\n // Written back whether or not `next()` changed it: `header()` is\n // idempotent, and takes an array, so a repeated header goes back whole.\n if (before !== undefined) ctx.response.header(key, before);\n else if (Object.hasOwn(headersAfter, key)) removeResponseHeader(ctx, key);\n }\n}\n\n/**\n * The response handed back to Fedify after AdonisJS answered a delegated\n * request. Nothing is written from it, but Fedify logs and meters its\n * status, so it reports what AdonisJS answered. `Response` only accepts\n * 200-599, so anything else (a 1xx) is reported as 200.\n */\nfunction delegatedResponse(status: number): Response {\n return new Response(null, {\n status: status >= 200 && status <= 599 ? status : 200,\n });\n}\n\n/**\n * Mounts a `Federation` instance inside an AdonisJS application; the\n * counterpart of `integrateFederation()` in `@fedify/express`.\n *\n * Register it in the **server** stack: Fedify serves paths the router does\n * not know, and the body stream is still intact there for signature\n * verification. An instance holds configuration only, so one serves every\n * request.\n */\nexport default class FedifyMiddleware<TContextData = ContextData>\n implements FedifyMiddlewareHandler {\n #federation: Federation<TContextData>;\n #contextDataFactory: ContextDataFactory<TContextData>;\n #ignoreRoutePrefixes: string[];\n\n /**\n * @param federation The federation instance to mount.\n * @param args The context-data factory and the options; see\n * {@link FedifyMiddlewareArgs}. The factory sees a pre-routing\n * `HttpContext`; see {@link import('./types.js').ContextDataFactory}.\n */\n constructor(\n federation: Federation<TContextData>,\n ...args: FedifyMiddlewareArgs<TContextData>\n ) {\n // The container zero-arg-constructs this class when the object the kernel\n // resolved is not the one the provider bound (a duplicated package copy,\n // or the ESM and CJS builds mixed); fail here rather than on every request.\n if (federation == null) throw new E_MISSING_FEDERATION();\n\n // The conditional tuple is unresolved here; read it through its common shape.\n const [contextDataFactory, options] = args as [\n ContextDataFactory<TContextData>?,\n FedifyMiddlewareOptions?,\n ];\n\n this.#federation = federation;\n this.#contextDataFactory = contextDataFactory ??\n (() => undefined as TContextData);\n this.#ignoreRoutePrefixes = options?.ignoreRoutePrefixes ?? [];\n }\n\n async handle(ctx: HttpContext, next: NextFn): Promise<void> {\n const federation = this.#federation;\n\n // Install the `ctx.federation` getter on this context's class: it covers a\n // duplicated `@adonisjs/core` and the container-free path, which has no\n // provider. A conflicting `federation` member is reported once; the\n // federation endpoints do not need the accessor.\n const contextClass = ctx.constructor as unknown as HttpContextClass;\n if (\n !ensureFederationGetter(contextClass) && !conflicting.has(contextClass)\n ) {\n conflicting.add(contextClass);\n ctx.logger.error(\n 'Something other than @fedify/adonisjs defines \"federation\" on this ' +\n 'application\\'s HttpContext, so \"ctx.federation\" is not the Fedify ' +\n \"request context. Federation endpoints are unaffected; rename the \" +\n \"conflicting macro or getter to use it from controllers\",\n );\n }\n\n // The ignore check and Fedify must see the same URL, so build it once.\n const { url, authority, unusableAuthority } = toRequestUrl(ctx.request);\n const path = url.pathname;\n\n if (\n this.#ignoreRoutePrefixes.some((prefix) => path.startsWith(prefix)) ||\n FORBIDDEN_METHODS.has(ctx.request.intended().toUpperCase())\n ) {\n // Opted out, or impossible to represent as a `Request`.\n setFederationContextFactory(ctx, () => {\n throw new E_FEDIFY_CONTEXT_UNAVAILABLE(path);\n });\n return next();\n }\n\n // Only past the bypass: on an opted-out path Fedify never sees the URL,\n // so the placeholder is harmless.\n if (unusableAuthority !== undefined) {\n warnUnusableAuthority(ctx.logger, unusableAuthority);\n }\n\n const request = toFetchRequest(ctx, url, authority);\n\n // `federation.fetch()` takes `contextData` by value, so the factory runs\n // before the router.\n const contextData = await this.#contextDataFactory(ctx);\n\n // Also for requests Fedify declines: a controller serving the HTML half of\n // a shared URL needs it. The getter creates the context lazily.\n setFederationContextFactory(\n ctx,\n () => federation.createContext(request, contextData),\n );\n\n /**\n * What happened while Fedify was deciding: whether a fall-through callback\n * handed the request to AdonisJS, and whether AdonisJS produced nothing of\n * its own so the 406 below is the answer. \"Nothing\" means no route\n * matched (`ctx.route` is set only on a match) *and* the framework's own\n * 404: a later server middleware (`@adonisjs/cors` on a preflight) or a\n * downstream failure can answer without the router running, and must not\n * be overwritten. A downstream middleware *deliberately* answering 404 on\n * a Fedify-owned path is indistinguishable from that default and is also\n * replaced by the 406.\n *\n * `router.match()` could say before `next()` whether a route exists and\n * spare the rollback, but is deliberately not asked:\n *\n * 1. Every integration follows the deferred-406 contract the manual\n * documents: delegate, and answer 406 only when the framework answered\n * 404 (Hono reads `ctx.res.status` after `next()`, Express `req.route`).\n * Deciding from the route table would give AdonisJS a narrower one.\n *\n * 2. Server middleware answers without a route by design (`@adonisjs/cors`\n * on a preflight, `@adonisjs/static`, a maintenance page), and Fedify\n * calls `onNotAcceptable` for a wildcard `Accept` too -- what curl and\n * a preflight send -- so skipping `next()` would cut those off on every\n * path Fedify owns.\n *\n * 3. `ctx.route` is the framework's own verdict. A lookup here would\n * duplicate `routeFinder`'s preamble and drift silently as the router\n * changes.\n *\n * The price is undoing a response AdonisJS was allowed to start: the\n * headers in {@link DISCARDED_ENTITY_HEADERS} are put back by name, a\n * pending body is dropped, and nothing is touched once the head has been\n * flushed.\n *\n * An object rather than two `let`s so TypeScript does not narrow them.\n */\n const outcome: { delegated: boolean; answer406: boolean } = {\n delegated: false,\n answer406: false,\n };\n\n const response = await federation.fetch(request, {\n contextData,\n\n /**\n * Fedify has no route for this path: hand the request to AdonisJS.\n * `await next()` resolves even on no match, since `E_ROUTE_NOT_FOUND`\n * goes through the exception handler and renders a 404.\n */\n onNotFound: async () => {\n outcome.delegated = true;\n await next();\n return delegatedResponse(ctx.response.getStatus());\n },\n\n /**\n * Fedify has a route but cannot satisfy `Accept` (a browser at an actor\n * URL). AdonisJS gets a chance to serve its own representation first;\n * 406 is only the answer if it has nothing either. `Accept` is merged\n * into `Vary` rather than written over it, and the snapshot's value is\n * merged back after `next()`, because a route may have replaced the\n * header meanwhile.\n */\n onNotAcceptable: async () => {\n outcome.delegated = true;\n mergeIntoVary(ctx, \"Accept\");\n // A value snapshot, not a live view: `getHeaders()` builds a fresh\n // object on every call.\n const headersBefore = ctx.response.getHeaders();\n await next();\n\n // Put back what `Vary` carried before `next()`, `Accept` included. A\n // superset only costs cache hits; a missing entry lets a cache mix the\n // two representations up.\n mergeIntoVary(ctx, String(headersBefore.vary ?? \"\"));\n\n const status = ctx.response.getStatus();\n // Not once the head is flushed: the 406 could not be written over it,\n // and `removeHeader()` would raise `ERR_HTTP_HEADERS_SENT`.\n outcome.answer406 = ctx.route === undefined && status === 404 &&\n !ctx.response.headersSent;\n\n if (outcome.answer406) rollBackDiscardedResponse(ctx, headersBefore);\n\n // The 406 itself is produced below; this only feeds Fedify's log.\n return delegatedResponse(outcome.answer406 ? 406 : status);\n },\n });\n\n // Fedify owns the path, cannot satisfy `Accept`, and AdonisJS had nothing\n // either. `Vary` already carries `Accept`.\n if (outcome.answer406) {\n // Before `send()`, which only sets the buffered *content*: a 404 page\n // rendered with `download()` or `stream()` would otherwise still go out,\n // or leak its readable.\n discardPendingBody(ctx);\n ctx.response\n .status(406)\n .type(\"text/plain\")\n .send(\"Not acceptable\");\n return;\n }\n\n if (outcome.delegated) {\n // AdonisJS produced the response (a matched route or its own 404 page).\n return;\n }\n\n writeFedifyResponse(response, ctx);\n }\n}\n\n/**\n * Creates a middleware class around a `Federation` the application built\n * itself, with no container or `config/fedify.ts` involved. This is the\n * package's default export; most applications use the provider instead.\n *\n * @example\n * ```ts\n * // start/kernel.ts\n * import fedifyMiddleware from '@fedify/adonisjs'\n * // A module of the application's own that default-exports its `Federation`.\n * import federation from '../app/federation.js'\n *\n * server.use([\n * async () => ({ default: fedifyMiddleware(federation, (ctx) => ctx) }),\n * ])\n * ```\n *\n * With the default `ContextData` of `HttpContext | null`, pass `(ctx) => ctx`\n * to match the provider; see {@link FedifyMiddlewareArgs}.\n *\n * @returns A {@link FedifyMiddleware} subclass whose constructor takes no\n * arguments, which is what `server.use()` constructs.\n * @param federation The federation instance to mount.\n * @param args The context-data factory and the options.\n */\nexport function fedifyMiddleware<TContextData>(\n federation: Federation<TContextData>,\n ...args: FedifyMiddlewareArgs<TContextData>\n): FedifyMiddlewareClass {\n // Here rather than in the constructor guard, which fires only on the first\n // request and blames the provider or a duplicated package copy; a factory\n // caller's likely mistake is a module that default-exports nothing.\n if (federation == null) {\n throw new E_MISSING_FEDERATION(\n \"fedifyMiddleware() was called without a Federation instance. Check \" +\n \"that the module its first argument comes from actually \" +\n \"default-exports the Federation it builds\",\n );\n }\n\n // Named so container errors and tracing show something readable.\n return class ConfiguredFedifyMiddleware\n extends FedifyMiddleware<TContextData> {\n constructor() {\n super(federation, ...args);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2EA,MAAM,cAAc,IAAI,QAAgB;;;;AAKxC,MAAM,oBAAoB,IAAI,IAAI;CAAC;CAAW;CAAS;AAAO,CAAC;;;;;;;AAQ/D,SAAS,gBACP,SAC4B;CAC5B,IAAI;CAEJ,OAAO,IAAI,eACT;EACE,MAAM,KAAK,YAAY;GACrB,WAAY,SAAS,MAAM,OAAO,CAAC,CAChC,UAAU;GAEb,MAAM,E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AAK,aAAa;IAGnE,OAAO,kBAAkB,QAAQ,YAAY,MAAM,MAAM;GAC3D;EACF,CAAC;EAID,IAAI,QAAQ,WAAW;GAIrB,mBAAmB,GAAG;GACtB,IAAI,SACD,OAAO,GAAG,CAAC,CACX,KAAK,YAAY,CAAC,CAClB,KAAK,gBAAgB;GACxB;EACF;EAEA,IAAI,QAAQ,WAAW;GAErB;EACF;EAEA,oBAAoB,UAAU,GAAG;CACnC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,iBACd,YACA,GAAG,MACoB;CAIvB,IAAI,cAAc,MAAM;EACtB,MAAM,IAAI,qBACR,wEACE,4DACA,0CACJ;CACF;CAGA,OAAO,MAAM,mCACH,iBAA+B;EACvC,cAAc;GACZ,MAAM,YAAY,GAAG,IAAI;EAC3B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"fedify_middleware.js","names":["#federation","#contextDataFactory","#ignoreRoutePrefixes"],"sources":["../../src/fedify_middleware.ts"],"sourcesContent":["/**\n * The AdonisJS server middleware that mounts Fedify.\n *\n * The service provider binds {@link FedifyMiddleware} with the `Federation`\n * and `config/fedify.ts`; applications that build their own `Federation` use\n * {@link fedifyMiddleware} instead. Nothing here depends on the container.\n *\n * @module\n */\nimport { Readable } from \"node:stream\";\n\nimport type { HttpContext } from \"@adonisjs/core/http\";\nimport type { NextFn } from \"@adonisjs/core/types/http\";\nimport type { Federation } from \"@fedify/fedify\";\n\nimport {\n E_FEDIFY_CONTEXT_UNAVAILABLE,\n E_MISSING_FEDERATION,\n} from \"./errors.ts\";\nimport {\n ensureFederationGetter,\n type HttpContextClass,\n setFederationContextFactory,\n} from \"./http_context.ts\";\nimport type { ContextData, ContextDataFactory } from \"./types.ts\";\nimport {\n PLACEHOLDER_HOST,\n warnUnusableAuthority,\n} from \"./unusable_authority.ts\";\n\n/**\n * Options accepted by {@link FedifyMiddleware} and {@link fedifyMiddleware}.\n */\nexport interface FedifyMiddlewareOptions {\n /**\n * URL path prefixes to bypass entirely. See\n * {@link import('./types.js').FedifyConfig.ignoreRoutePrefixes}.\n *\n * @default `[]`\n */\n ignoreRoutePrefixes?: string[];\n}\n\n/**\n * The instance shape of the middleware.\n */\nexport interface FedifyMiddlewareHandler {\n handle(ctx: HttpContext, next: NextFn): Promise<void>;\n}\n\n/**\n * What {@link fedifyMiddleware} returns: a middleware **class**, since\n * `server.use()` constructs entries through the container.\n */\nexport type FedifyMiddlewareClass = new () => FedifyMiddlewareHandler;\n\n/**\n * The arguments after `federation`. The factory defaults to producing\n * `undefined`, so it may only be omitted when `TContextData` admits it;\n * otherwise omitting it is a compile error. The tuple wrapper keeps the\n * conditional from distributing over a union.\n */\nexport type FedifyMiddlewareArgs<TContextData> = [undefined] extends [\n TContextData,\n]\n ? [\n contextDataFactory?: ContextDataFactory<TContextData>,\n options?: FedifyMiddlewareOptions,\n ]\n : [\n contextDataFactory: ContextDataFactory<TContextData>,\n options?: FedifyMiddlewareOptions,\n ];\n\n/**\n * Context classes whose conflicting `federation` member was already reported.\n */\nconst conflicting = new WeakSet<object>();\n\n/**\n * Methods `new Request()` refuses; in practice only `TRACE` arrives here.\n */\nconst FORBIDDEN_METHODS = new Set([\"CONNECT\", \"TRACE\", \"TRACK\"]);\n\n/**\n * Wraps the raw `IncomingMessage` in a `ReadableStream` that stays inert until\n * first read. The `Request` is built before Fedify decides whether it handles\n * the request; an eager `Readable.toWeb()` would start draining the socket and\n * hang the AdonisJS body parser on every declined `POST`.\n */\nfunction lazyRequestBody(\n message: HttpContext[\"request\"][\"request\"],\n): ReadableStream<Uint8Array> {\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n\n return new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n reader ??= (\n Readable.toWeb(message) as ReadableStream<Uint8Array>\n ).getReader();\n\n const { done, value } = await reader.read();\n if (done) controller.close();\n else controller.enqueue(value);\n },\n cancel(reason) {\n return reader?.cancel(reason);\n },\n },\n { highWaterMark: 0 },\n );\n}\n\n/**\n * What an authority may not contain: `Host` admits only `uri-host [\":\" port]`,\n * so anything that could carry a path, query, fragment or userinfo makes the\n * value something other than an authority.\n */\nconst NON_AUTHORITY = /[/?#\\\\@\\s]/;\n\n/**\n * Keeps the first entry of a comma-separated authority (`X-Forwarded-Host`\n * behind two proxies), which `new URL()` would reject.\n *\n * Under `trustProxy`, `authority()` returns `X-Forwarded-Host` verbatim, so a\n * client could send `example.com/x` and shift the path Fedify sees to\n * `/x/users/alice` while AdonisJS still routes the real path — bypassing\n * `ignoreRoutePrefixes`. Anything that could carry a path, query, fragment or\n * userinfo (`good.example@evil.com` parses to the host `evil.com`) is\n * therefore refused outright, which leaves the {@link PLACEHOLDER_HOST}\n * fallback to keep the path intact.\n */\nfunction normalizeAuthority(host: string): string {\n const comma = host.indexOf(\",\");\n const authority = (comma < 0 ? host : host.slice(0, comma)).trim();\n return NON_AUTHORITY.test(authority) ? \"\" : authority;\n}\n\n/**\n * Reduces a request target to origin form, or `undefined` when it carries no\n * path. An absolute target (`GET http://example.com/users/alice HTTP/1.1`)\n * reaches `req.url` verbatim; only its path and query survive, so the request\n * line cannot pick the host Fedify sees and let an inbox `POST` signed for\n * another server verify here.\n */\nfunction toOriginForm(target: string): string | undefined {\n // Origin form already. It is interpolated, not resolved, so `//users/alice`\n // keeps its path instead of reading `users` as a host.\n if (target.startsWith(\"/\")) return target;\n\n // Textually rather than through `new URL()`, which would hand back the\n // *normalised* path or, for a target it refuses, nothing at all --\n // collapsing the request to `/` and hiding the real path from\n // `ignoreRoutePrefixes` and `ctx.federation`.\n const prefix = /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\/[^/?#]*/.exec(target);\n // Asterisk form (`OPTIONS *`) or malformed. Authority form reaches only\n // `CONNECT`, which {@link FORBIDDEN_METHODS} refuses.\n if (prefix === null) return undefined;\n\n const rest = target.slice(prefix[0].length);\n return rest.startsWith(\"/\") ? rest : `/${rest}`;\n}\n\n/**\n * Builds the URL for one authority, or `undefined` if it cannot carry one.\n * The target is interpolated, never resolved, so the authority stays the one\n * {@link normalizeAuthority} passed; an empty one is refused because\n * `new URL(\"http:///users/alice\")` silently takes `users` as the host.\n */\nfunction buildRequestUrl(\n protocol: string,\n authority: string,\n target: string,\n): URL | undefined {\n if (authority === \"\") return undefined;\n\n try {\n return new URL(`${protocol}://${authority}${target}`);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Builds the URL Fedify sees from the raw request target, keeping the\n * percent-encoding Fedify's URI templates expect and the bytes a peer signed.\n * Only the target's path and query are read (see {@link toOriginForm}); the\n * authority comes from {@link normalizeAuthority}, via `authority()` so\n * HTTP/2's `:authority` is covered. Every input is attacker-controlled, so\n * the result only has to exist: the scheme is reduced to `http`/`https`, and\n * an unusable authority falls back to {@link PLACEHOLDER_HOST} rather than a\n * 500. Since that breaks signature verification, the discarded value is\n * returned for the caller to log once it knows Fedify will see the request.\n *\n * The accepted authority is returned verbatim as well, for the `Host` header\n * {@link toFetchRequest} synthesises on HTTP/2: `URL` normalises what it\n * parses (case, default port, punycode) while a signature covers the bytes as\n * sent. It is absent exactly when the placeholder stood in.\n */\nfunction toRequestUrl(request: HttpContext[\"request\"]): {\n url: URL;\n authority?: string;\n unusableAuthority?: string;\n} {\n // `protocol()` hands back the first `X-Forwarded-Proto` token as it\n // arrived; an upper-case `HTTPS` must not be read as plain `http`.\n const protocol =\n request.protocol().toLowerCase() === \"https\" ? \"https\" : \"http\";\n const host = request.authority();\n const authority = host == null ? \"\" : normalizeAuthority(host);\n // A target with no origin form is routed as `/`, which matches no\n // federation route, so AdonisJS answers.\n const target = toOriginForm(request.request.url ?? \"/\") ?? \"/\";\n\n const parsed = buildRequestUrl(protocol, authority, target);\n let url = parsed;\n let unusableAuthority: string | undefined;\n if (url === undefined) {\n // Only the authority can be at fault: the target starts with `/`, and a\n // URL parser in path state takes any bytes after it.\n url = new URL(`${protocol}://${PLACEHOLDER_HOST}${target}`);\n if (host != null) unusableAuthority = host;\n }\n\n return {\n url,\n authority: parsed === undefined ? undefined : authority,\n unusableAuthority,\n };\n}\n\n/**\n * Converts an AdonisJS request into a WHATWG `Request` for Fedify.\n *\n * `intended()`, not `method()`, so `_method` spoofing cannot turn an inbox\n * `POST` into a `GET`. Headers are forwarded as they arrived; HTTP/2\n * pseudo-headers are skipped, and since that leaves no `Host` (which\n * signatures may cover), one is synthesised only then, from the authority the\n * URL was built from.\n */\nfunction toFetchRequest(\n ctx: HttpContext,\n url: URL,\n authority: string | undefined,\n): Request {\n const request = ctx.request;\n const method = request.intended().toUpperCase();\n\n const headers = new Headers();\n const rawHeaders = request.headers();\n // `Object.keys()`, not `for...in`: a polluted prototype must not be forwarded.\n for (const key of Object.keys(rawHeaders)) {\n if (key.startsWith(\":\")) continue;\n const value = rawHeaders[key];\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else if (typeof value === \"string\") {\n headers.append(key, value);\n }\n }\n\n // Only when absent: an HTTP/1.1 `Host` is what the peer signed and what the\n // verifier reads, so it is never touched (a proxy rewriting `Host` has to\n // preserve it; see the README). On HTTP/2 the authority travels in\n // `:authority`, which the pseudo-header skip dropped, so it is put back\n // here -- verbatim, not `url.host`, since `URL` case-folds, drops a default\n // port and punycodes while a signature covers the bytes as sent. An\n // unusable authority gets the placeholder in the URL only, never a header.\n if (authority !== undefined && !headers.has(\"host\")) {\n headers.set(\"host\", authority);\n }\n\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n\n return new Request(url, {\n method,\n headers,\n body: hasBody ? lazyRequestBody(request.request) : undefined,\n // Not in the DOM lib's `RequestInit`, but Node requires it for streams.\n ...{ duplex: \"half\" },\n });\n}\n\n/**\n * Copies a WHATWG `Response` produced by Fedify onto the AdonisJS response.\n * `Set-Cookie` goes through `getSetCookie()` because iterating `Headers`\n * folds it; `Vary` is merged rather than copied, so a `Vary: Origin` an\n * upstream middleware set survives Fedify's own `Vary: Accept`; bodyless\n * responses (`204`, `304`, `HEAD`) are not streamed.\n */\nfunction writeFedifyResponse(response: Response, ctx: HttpContext): void {\n ctx.response.status(response.status);\n\n for (const [key, value] of response.headers) {\n const name = key.toLowerCase();\n if (name === \"set-cookie\") continue;\n if (name === \"vary\") {\n mergeIntoVary(ctx, value);\n continue;\n }\n ctx.response.header(key, value);\n }\n\n for (const cookie of response.headers.getSetCookie()) {\n ctx.response.append(\"set-cookie\", cookie);\n }\n\n const bodyless =\n response.body === null ||\n response.status === 204 ||\n response.status === 304 ||\n // `intended()`: a spoofed `_method=HEAD` must not suppress the body.\n ctx.request.intended().toUpperCase() === \"HEAD\";\n\n if (bodyless) {\n // Do not leave a body Fedify produced anyway (usually for HEAD) dangling;\n // a failed cleanup must not become an unhandled rejection.\n response.body?.cancel().catch(() => {});\n return;\n }\n\n ctx.response.stream(response.body!, (error) => {\n ctx.logger.error({ err: error }, \"Failed to stream the Fedify response\");\n return [\"Internal server error\", 500];\n });\n}\n\n/**\n * Splits a `Vary` value into its entries.\n */\nfunction parseVary(value: string): string[] {\n return value\n .split(\",\")\n .map((entry) => entry.trim())\n .filter((entry) => entry !== \"\");\n}\n\n/**\n * Merges a raw `Vary` value into the response's `Vary`.\n *\n * `ctx.response.header()` replaces rather than appends, so writing `Vary`\n * directly would drop what an upstream middleware or a route already put\n * there (CORS's `Origin`, say) and let a shared cache mix representations.\n *\n * Both of AdonisJS's header layers are read: `header()` buffers a value that\n * is copied onto the Node response when the reply is written, while\n * `ctx.response.vary()` writes to the Node response directly, and\n * `getHeader()` prefers the buffered value. Once `Accept` is buffered before\n * `next()`, a `vary(\"Origin\")` a route calls is therefore invisible through\n * `getHeader()` alone and would be overwritten at write time. The union goes\n * back to the buffered layer, since that is what goes out. `Vary: *` on any\n * side wins.\n */\nfunction mergeIntoVary(ctx: HttpContext, rawValue: string): void {\n const vary: string[] = [];\n const layers = [\n String(ctx.response.getHeader(\"Vary\") ?? \"\"),\n String(ctx.response.response.getHeader(\"vary\") ?? \"\"),\n rawValue,\n ];\n\n for (const layer of layers) {\n for (const value of parseVary(layer)) {\n if (value === \"*\") {\n ctx.response.header(\"Vary\", \"*\");\n return;\n }\n if (!vary.some((v) => v.toLowerCase() === value.toLowerCase())) {\n vary.push(value);\n }\n }\n }\n\n if (vary.length > 0) ctx.response.header(\"Vary\", vary.join(\", \"));\n}\n\n/**\n * Headers of a discarded response that must not describe the one written over\n * it: cache and validator metadata, which decides how long a shared cache\n * keeps the substitute, and metadata about a body nobody will see. The\n * targeted cache-control family (`CDN-Cache-Control`, `Surrogate-Control`, …)\n * is included because a CDN honours it over `Cache-Control` and largely\n * ignores `Vary`, so a leftover lifetime would keep the 406 cached for\n * ActivityPub clients too. Enumerated rather than matched on a `content-`\n * prefix, which would also take `Content-Security-Policy`.\n */\nconst DISCARDED_ENTITY_HEADERS: ReadonlySet<string> = new Set([\n \"age\",\n \"cache-control\",\n \"cdn-cache-control\",\n \"cloudflare-cdn-cache-control\",\n \"content-digest\",\n \"content-disposition\",\n \"content-encoding\",\n \"content-language\",\n \"content-length\",\n \"content-location\",\n \"content-range\",\n \"content-type\",\n \"digest\",\n \"etag\",\n \"expires\",\n \"last-modified\",\n \"pragma\",\n \"repr-digest\",\n \"surrogate-control\",\n \"surrogate-key\",\n]);\n\n/**\n * Removes a response header around a quirk of AdonisJS's `removeHeader()`,\n * which drops the buffered entry only when the current value is truthy, so one\n * set to `\"\"` would survive. It also forwards to Node unconditionally, which\n * throws once the head is flushed, so this is only safe while\n * `ctx.response.headersSent` is false.\n */\nfunction removeResponseHeader(ctx: HttpContext, key: string): void {\n // A non-empty placeholder, so the buffered entry is truthy and deleted.\n ctx.response.header(key, \"-\");\n ctx.response.removeHeader(key);\n}\n\n/**\n * Drops the body a discarded response left buffered, so the one written over\n * it is the one that goes out.\n *\n * `response.send()` assigns `lazyBody.content` alone, and `finish()` reads the\n * other entries after it: a path passed to `download()` would still be\n * streamed in place of the new body, and a readable passed to `stream()`\n * would be forgotten — one leaked file descriptor per request. Resetting\n * `lazyBody` drops both.\n */\nfunction discardPendingBody(ctx: HttpContext): void {\n const stream = ctx.response.outgoingStream;\n ctx.response.lazyBody = {};\n if (stream == null) return;\n\n // `ResponseStream` is either a Node `Readable` or a WHATWG `ReadableStream`.\n if (\"destroy\" in stream) {\n // Nothing else listens, since AdonisJS never attached to the stream, and\n // an unlistened `error` event is an uncaught exception.\n stream.on(\"error\", () => {});\n if (!stream.destroyed) stream.destroy();\n } else if (!stream.locked) {\n // Likewise, a rejected `cancel()` must not become an unhandled rejection.\n stream.cancel().catch(() => {});\n }\n}\n\n/**\n * Undoes what a discarded response did to the headers, before another is\n * written over it.\n *\n * `next()` mixes two populations: a header a *later middleware* set\n * (`@adonisjs/cors`'s `Access-Control-Allow-Origin`, say) answers this\n * request and has to survive, while one the *discarded page* set describes a\n * body nobody will see. They are told apart by name: only\n * {@link DISCARDED_ENTITY_HEADERS} are touched, and each is put back exactly\n * as the snapshot had it — removed when the snapshot had none. Restoring\n * every snapshot entry instead would undo the request's own answer, since\n * `response.header()` replaces rather than merges.\n *\n * `Vary` is reconciled by {@link mergeIntoVary} around `next()` instead,\n * since only the union of the snapshot and the current value is right.\n */\nfunction rollBackDiscardedResponse(\n ctx: HttpContext,\n headersBefore: ReturnType<HttpContext[\"response\"][\"getHeaders\"]>,\n): void {\n const headersAfter = ctx.response.getHeaders();\n\n for (const key of DISCARDED_ENTITY_HEADERS) {\n // `hasOwn()`, not `in`: `constructor` is a legal header name.\n const before = Object.hasOwn(headersBefore, key)\n ? headersBefore[key]\n : undefined;\n\n // Written back whether or not `next()` changed it: `header()` is\n // idempotent, and takes an array, so a repeated header goes back whole.\n if (before !== undefined) ctx.response.header(key, before);\n else if (Object.hasOwn(headersAfter, key)) removeResponseHeader(ctx, key);\n }\n}\n\n/**\n * The response handed back to Fedify after AdonisJS answered a delegated\n * request. Nothing is written from it, but Fedify logs and meters its\n * status, so it reports what AdonisJS answered. `Response` only accepts\n * 200-599, so anything else (a 1xx) is reported as 200.\n */\nfunction delegatedResponse(status: number): Response {\n return new Response(null, {\n status: status >= 200 && status <= 599 ? status : 200,\n });\n}\n\n/**\n * Mounts a `Federation` instance inside an AdonisJS application; the\n * counterpart of `integrateFederation()` in `@fedify/express`.\n *\n * Register it in the **server** stack: Fedify serves paths the router does\n * not know, and the body stream is still intact there for signature\n * verification. An instance holds configuration only, so one serves every\n * request.\n */\nexport default class FedifyMiddleware<\n TContextData = ContextData,\n> implements FedifyMiddlewareHandler {\n #federation: Federation<TContextData>;\n #contextDataFactory: ContextDataFactory<TContextData>;\n #ignoreRoutePrefixes: string[];\n\n /**\n * @param federation The federation instance to mount.\n * @param args The context-data factory and the options; see\n * {@link FedifyMiddlewareArgs}. The factory sees a pre-routing\n * `HttpContext`; see {@link import('./types.js').ContextDataFactory}.\n */\n constructor(\n federation: Federation<TContextData>,\n ...args: FedifyMiddlewareArgs<TContextData>\n ) {\n // The container zero-arg-constructs this class when the object the kernel\n // resolved is not the one the provider bound (a duplicated package copy,\n // or the ESM and CJS builds mixed); fail here rather than on every request.\n if (federation == null) throw new E_MISSING_FEDERATION();\n\n // The conditional tuple is unresolved here; read it through its common shape.\n const [contextDataFactory, options] = args as [\n ContextDataFactory<TContextData>?,\n FedifyMiddlewareOptions?,\n ];\n\n this.#federation = federation;\n this.#contextDataFactory =\n contextDataFactory ?? (() => undefined as TContextData);\n this.#ignoreRoutePrefixes = options?.ignoreRoutePrefixes ?? [];\n }\n\n async handle(ctx: HttpContext, next: NextFn): Promise<void> {\n const federation = this.#federation;\n\n // Install the `ctx.federation` getter on this context's class: it covers a\n // duplicated `@adonisjs/core` and the container-free path, which has no\n // provider. A conflicting `federation` member is reported once; the\n // federation endpoints do not need the accessor.\n const contextClass = ctx.constructor as unknown as HttpContextClass;\n if (\n !ensureFederationGetter(contextClass) &&\n !conflicting.has(contextClass)\n ) {\n conflicting.add(contextClass);\n ctx.logger.error(\n 'Something other than @fedify/adonisjs defines \"federation\" on this ' +\n 'application\\'s HttpContext, so \"ctx.federation\" is not the Fedify ' +\n \"request context. Federation endpoints are unaffected; rename the \" +\n \"conflicting macro or getter to use it from controllers\",\n );\n }\n\n // The ignore check and Fedify must see the same URL, so build it once.\n const { url, authority, unusableAuthority } = toRequestUrl(ctx.request);\n const path = url.pathname;\n\n if (\n this.#ignoreRoutePrefixes.some((prefix) => path.startsWith(prefix)) ||\n FORBIDDEN_METHODS.has(ctx.request.intended().toUpperCase())\n ) {\n // Opted out, or impossible to represent as a `Request`.\n setFederationContextFactory(ctx, () => {\n throw new E_FEDIFY_CONTEXT_UNAVAILABLE(path);\n });\n return next();\n }\n\n // Only past the bypass: on an opted-out path Fedify never sees the URL,\n // so the placeholder is harmless.\n if (unusableAuthority !== undefined) {\n warnUnusableAuthority(ctx.logger, unusableAuthority);\n }\n\n const request = toFetchRequest(ctx, url, authority);\n\n // `federation.fetch()` takes `contextData` by value, so the factory runs\n // before the router.\n const contextData = await this.#contextDataFactory(ctx);\n\n // Also for requests Fedify declines: a controller serving the HTML half of\n // a shared URL needs it. The getter creates the context lazily.\n setFederationContextFactory(ctx, () =>\n federation.createContext(request, contextData),\n );\n\n /**\n * What happened while Fedify was deciding: whether a fall-through callback\n * handed the request to AdonisJS, and whether AdonisJS produced nothing of\n * its own so the 406 below is the answer. \"Nothing\" means no route\n * matched (`ctx.route` is set only on a match) *and* the framework's own\n * 404: a later server middleware (`@adonisjs/cors` on a preflight) or a\n * downstream failure can answer without the router running, and must not\n * be overwritten. A downstream middleware *deliberately* answering 404 on\n * a Fedify-owned path is indistinguishable from that default and is also\n * replaced by the 406.\n *\n * `router.match()` could say before `next()` whether a route exists and\n * spare the rollback, but is deliberately not asked:\n *\n * 1. Every integration follows the deferred-406 contract the manual\n * documents: delegate, and answer 406 only when the framework answered\n * 404 (Hono reads `ctx.res.status` after `next()`, Express `req.route`).\n * Deciding from the route table would give AdonisJS a narrower one.\n *\n * 2. Server middleware answers without a route by design (`@adonisjs/cors`\n * on a preflight, `@adonisjs/static`, a maintenance page), and Fedify\n * calls `onNotAcceptable` for a wildcard `Accept` too -- what curl and\n * a preflight send -- so skipping `next()` would cut those off on every\n * path Fedify owns.\n *\n * 3. `ctx.route` is the framework's own verdict. A lookup here would\n * duplicate `routeFinder`'s preamble and drift silently as the router\n * changes.\n *\n * The price is undoing a response AdonisJS was allowed to start: the\n * headers in {@link DISCARDED_ENTITY_HEADERS} are put back by name, a\n * pending body is dropped, and nothing is touched once the head has been\n * flushed.\n *\n * An object rather than two `let`s so TypeScript does not narrow them.\n */\n const outcome: { delegated: boolean; answer406: boolean } = {\n delegated: false,\n answer406: false,\n };\n\n const response = await federation.fetch(request, {\n contextData,\n\n /**\n * Fedify has no route for this path: hand the request to AdonisJS.\n * `await next()` resolves even on no match, since `E_ROUTE_NOT_FOUND`\n * goes through the exception handler and renders a 404.\n */\n onNotFound: async () => {\n outcome.delegated = true;\n await next();\n return delegatedResponse(ctx.response.getStatus());\n },\n\n /**\n * Fedify has a route but cannot satisfy `Accept` (a browser at an actor\n * URL). AdonisJS gets a chance to serve its own representation first;\n * 406 is only the answer if it has nothing either. `Accept` is merged\n * into `Vary` rather than written over it, and the snapshot's value is\n * merged back after `next()`, because a route may have replaced the\n * header meanwhile.\n */\n onNotAcceptable: async () => {\n outcome.delegated = true;\n mergeIntoVary(ctx, \"Accept\");\n // A value snapshot, not a live view: `getHeaders()` builds a fresh\n // object on every call.\n const headersBefore = ctx.response.getHeaders();\n await next();\n\n // Put back what `Vary` carried before `next()`, `Accept` included. A\n // superset only costs cache hits; a missing entry lets a cache mix the\n // two representations up.\n mergeIntoVary(ctx, String(headersBefore.vary ?? \"\"));\n\n const status = ctx.response.getStatus();\n // Not once the head is flushed: the 406 could not be written over it,\n // and `removeHeader()` would raise `ERR_HTTP_HEADERS_SENT`.\n outcome.answer406 =\n ctx.route === undefined &&\n status === 404 &&\n !ctx.response.headersSent;\n\n if (outcome.answer406) rollBackDiscardedResponse(ctx, headersBefore);\n\n // The 406 itself is produced below; this only feeds Fedify's log.\n return delegatedResponse(outcome.answer406 ? 406 : status);\n },\n });\n\n // Fedify owns the path, cannot satisfy `Accept`, and AdonisJS had nothing\n // either. `Vary` already carries `Accept`.\n if (outcome.answer406) {\n // Before `send()`, which only sets the buffered *content*: a 404 page\n // rendered with `download()` or `stream()` would otherwise still go out,\n // or leak its readable.\n discardPendingBody(ctx);\n ctx.response.status(406).type(\"text/plain\").send(\"Not acceptable\");\n return;\n }\n\n if (outcome.delegated) {\n // AdonisJS produced the response (a matched route or its own 404 page).\n return;\n }\n\n writeFedifyResponse(response, ctx);\n }\n}\n\n/**\n * Creates a middleware class around a `Federation` the application built\n * itself, with no container or `config/fedify.ts` involved. This is the\n * package's default export; most applications use the provider instead.\n *\n * @example\n * ```ts\n * // start/kernel.ts\n * import fedifyMiddleware from '@fedify/adonisjs'\n * // A module of the application's own that default-exports its `Federation`.\n * import federation from '../app/federation.js'\n *\n * server.use([\n * async () => ({ default: fedifyMiddleware(federation, (ctx) => ctx) }),\n * ])\n * ```\n *\n * With the default `ContextData` of `HttpContext | null`, pass `(ctx) => ctx`\n * to match the provider; see {@link FedifyMiddlewareArgs}.\n *\n * @returns A {@link FedifyMiddleware} subclass whose constructor takes no\n * arguments, which is what `server.use()` constructs.\n * @param federation The federation instance to mount.\n * @param args The context-data factory and the options.\n */\nexport function fedifyMiddleware<TContextData>(\n federation: Federation<TContextData>,\n ...args: FedifyMiddlewareArgs<TContextData>\n): FedifyMiddlewareClass {\n // Here rather than in the constructor guard, which fires only on the first\n // request and blames the provider or a duplicated package copy; a factory\n // caller's likely mistake is a module that default-exports nothing.\n if (federation == null) {\n throw new E_MISSING_FEDERATION(\n \"fedifyMiddleware() was called without a Federation instance. Check \" +\n \"that the module its first argument comes from actually \" +\n \"default-exports the Federation it builds\",\n );\n }\n\n // Named so container errors and tracing show something readable.\n return class ConfiguredFedifyMiddleware extends FedifyMiddleware<TContextData> {\n constructor() {\n super(federation, ...args);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6EA,MAAM,cAAc,IAAI,QAAgB;;;;AAKxC,MAAM,oBAA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AW;IAC9C,MAAM,KAAK;IAKX,cAAc,KAAK,OAAO,cAAc,QAAQ,EAAE,CAAC;IAEnD,MAAM,SAAS,IAAI,SAAS,UAAU;IAGtC,QAAQ,YACN,IAAI,UAAU,aACd,WAAW,OACX,CAAC,IAAI,SAAS;IAEhB,IAAI,QAAQ,WAAW,0BAA0B,KAAK,aAAa;IAGnE,OAAO,kBAAkB,QAAQ,YAAY,MAAM,MAAM;GAC3D;EACF,CAAC;EAID,IAAI,QAAQ,WAAW;GAIrB,mBAAmB,GAAG;GACtB,IAAI,SAAS,OAAO,GAAG,CAAC,CAAC,KAAK,YAAY,CAAC,CAAC,KAAK,gBAAgB;GACjE;EACF;EAEA,IAAI,QAAQ,WAAW;GAErB;EACF;EAEA,oBAAoB,UAAU,GAAG;CACnC;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,iBACd,YACA,GAAG,MACoB;CAIvB,IAAI,cAAc,MAAM;EACtB,MAAM,IAAI,qBACR,wEACE,4DACA,0CACJ;CACF;CAGA,OAAO,MAAM,mCAAmC,iBAA+B;EAC7E,cAAc;GACZ,MAAM,YAAY,GAAG,IAAI;EAC3B;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http_context.cjs","names":["HttpContext","E_FEDIFY_CONTEXT_UNAVAILABLE"],"sources":["../../src/http_context.ts"],"sourcesContent":["/**\n * The `ctx.federation` accessor: a Macroable getter on `HttpContext` (like\n * `ctx.view`) that reads a per-request factory the middleware stores on the\n * instance, and memoises the result.\n *\n * @module\n */\nimport { HttpContext } from \"@adonisjs/core/http\";\nimport type { RequestContext } from \"@fedify/fedify\";\n\nimport { E_FEDIFY_CONTEXT_UNAVAILABLE } from \"./errors.ts\";\n\n/**\n * The per-request slot holding the factory for `ctx.federation`. A\n * registered symbol so the ESM and CommonJS builds share it, keyed by major\n * version so another major in the same process gets its own.\n */\nconst FACTORY: unique symbol = Symbol.for(\n \"@fedify/adonisjs@2/federation-factory\",\n);\n\n/**\n * The accessors this module has installed, so a `federation` member defined\n * by somebody else can be told apart from ours. `Macroable.getter()` wraps\n * the function it is given, hence a registry rather than a marker; it lives on\n * `globalThis` for the same reasons as {@link FACTORY}.\n */\nconst INSTALLED: unique symbol = Symbol.for(\n \"@fedify/adonisjs@2/federation-getters\",\n);\n\nconst registry = globalThis as { [INSTALLED]?: WeakSet<object> };\n\nconst installedGetters: WeakSet<object> = registry[INSTALLED]
|
|
1
|
+
{"version":3,"file":"http_context.cjs","names":["HttpContext","E_FEDIFY_CONTEXT_UNAVAILABLE"],"sources":["../../src/http_context.ts"],"sourcesContent":["/**\n * The `ctx.federation` accessor: a Macroable getter on `HttpContext` (like\n * `ctx.view`) that reads a per-request factory the middleware stores on the\n * instance, and memoises the result.\n *\n * @module\n */\nimport { HttpContext } from \"@adonisjs/core/http\";\nimport type { RequestContext } from \"@fedify/fedify\";\n\nimport { E_FEDIFY_CONTEXT_UNAVAILABLE } from \"./errors.ts\";\n\n/**\n * The per-request slot holding the factory for `ctx.federation`. A\n * registered symbol so the ESM and CommonJS builds share it, keyed by major\n * version so another major in the same process gets its own.\n */\nconst FACTORY: unique symbol = Symbol.for(\n \"@fedify/adonisjs@2/federation-factory\",\n);\n\n/**\n * The accessors this module has installed, so a `federation` member defined\n * by somebody else can be told apart from ours. `Macroable.getter()` wraps\n * the function it is given, hence a registry rather than a marker; it lives on\n * `globalThis` for the same reasons as {@link FACTORY}.\n */\nconst INSTALLED: unique symbol = Symbol.for(\n \"@fedify/adonisjs@2/federation-getters\",\n);\n\nconst registry = globalThis as { [INSTALLED]?: WeakSet<object> };\n\nconst installedGetters: WeakSet<object> = (registry[INSTALLED] ??=\n new WeakSet());\n\n/**\n * The shape of a context that carries the {@link FACTORY} slot.\n */\ntype FactoryCarrier = {\n [FACTORY]?: () => RequestContext<unknown>;\n};\n\n/**\n * A context class the getter can be installed on.\n */\nexport type HttpContextClass = typeof HttpContext;\n\n/**\n * Records how to create the `RequestContext` for `ctx`; the getter runs\n * `create` on first access.\n */\nexport function setFederationContextFactory<TContextData>(\n ctx: HttpContext,\n create: () => RequestContext<TContextData>,\n): void {\n Object.defineProperty(ctx, FACTORY, {\n value: create,\n configurable: true,\n enumerable: false,\n writable: true,\n });\n}\n\n/**\n * Installs the `federation` getter on a context class, once per class. The\n * middleware also calls this on `ctx.constructor`, which covers an\n * application with its own copy of `@adonisjs/core`. Macroable's\n * `singleton` flag memoises the value on the instance.\n *\n * @returns `false` when a `federation` member somebody else defined is in the\n * way; nothing is changed then, and the caller decides how to report it.\n */\nexport function ensureFederationGetter(\n target: HttpContextClass = HttpContext,\n): boolean {\n const existing = Object.getOwnPropertyDescriptor(\n target.prototype,\n \"federation\",\n );\n if (existing !== undefined) return isOwnGetter(existing.get);\n\n target.getter(\n \"federation\",\n function (this: HttpContext) {\n const create = (this as HttpContext & FactoryCarrier)[FACTORY];\n if (create === undefined) {\n throw new E_FEDIFY_CONTEXT_UNAVAILABLE(this.request.url());\n }\n return create() as HttpContext[\"federation\"];\n },\n true,\n );\n\n // Record the wrapper Macroable actually installed.\n const installed = Object.getOwnPropertyDescriptor(\n target.prototype,\n \"federation\",\n )?.get;\n if (installed !== undefined) installedGetters.add(installed);\n\n return true;\n}\n\n/**\n * {@link ensureFederationGetter}, but a conflict throws. Called from the\n * provider's `boot()`.\n */\nexport function installFederationGetter(\n target: HttpContextClass = HttpContext,\n): void {\n if (ensureFederationGetter(target)) return;\n\n throw new Error(\n 'Cannot install \"ctx.federation\": the HttpContext class already has a ' +\n '\"federation\" member that @fedify/adonisjs did not define. Remove the ' +\n \"conflicting macro or getter, or rename it\",\n );\n}\n\nfunction isOwnGetter(fn: unknown): boolean {\n return typeof fn === \"function\" && installedGetters.has(fn);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAM,UAAyB,OAAO,IACpC,uCACF;;;;;;;AAQA,MAAM,YAA2B,OAAO,IACtC,uCACF;AAEA,MAAM,WAAW;AAEjB,MAAM,mBAAqC,SAAS,eAClD,IAAI,QAAQ;;;;;AAkBd,SAAgB,4BACd,KACA,QACM;CACN,OAAO,eAAe,KAAK,SAAS;EAClC,OAAO;EACP,cAAc;EACd,YAAY;EACZ,UAAU;CACZ,CAAC;AACH;;;;;;;;;;AAWA,SAAgB,uBACd,SAA2BA,iCAClB;CACT,MAAM,WAAW,OAAO,yBACtB,OAAO,WACP,YACF;CACA,IAAI,aAAa,WAAW,OAAO,YAAY,SAAS,GAAG;CAE3D,OAAO,OACL,cACA,WAA6B;EAC3B,MAAM,SAAU,KAAsC;EACtD,IAAI,WAAW,WAAW;GACxB,MAAM,IAAIC,gDAA6B,KAAK,QAAQ,IAAI,CAAC;EAC3D;EACA,OAAO,OAAO;CAChB,GACA,IACF;CAGA,MAAM,YAAY,OAAO,yBACvB,OAAO,WACP,YACF,CAAC,EAAE;CACH,IAAI,cAAc,WAAW,iBAAiB,IAAI,SAAS;CAE3D,OAAO;AACT;;;;;AAMA,SAAgB,wBACd,SAA2BD,iCACrB;CACN,IAAI,uBAAuB,MAAM,GAAG;CAEpC,MAAM,IAAI,MACR,4EACE,4EACA,2CACJ;AACF;AAEA,SAAS,YAAY,IAAsB;CACzC,OAAO,OAAO,OAAO,cAAc,iBAAiB,IAAI,EAAE;AAC5D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http_context.js","names":[],"sources":["../../src/http_context.ts"],"sourcesContent":["/**\n * The `ctx.federation` accessor: a Macroable getter on `HttpContext` (like\n * `ctx.view`) that reads a per-request factory the middleware stores on the\n * instance, and memoises the result.\n *\n * @module\n */\nimport { HttpContext } from \"@adonisjs/core/http\";\nimport type { RequestContext } from \"@fedify/fedify\";\n\nimport { E_FEDIFY_CONTEXT_UNAVAILABLE } from \"./errors.ts\";\n\n/**\n * The per-request slot holding the factory for `ctx.federation`. A\n * registered symbol so the ESM and CommonJS builds share it, keyed by major\n * version so another major in the same process gets its own.\n */\nconst FACTORY: unique symbol = Symbol.for(\n \"@fedify/adonisjs@2/federation-factory\",\n);\n\n/**\n * The accessors this module has installed, so a `federation` member defined\n * by somebody else can be told apart from ours. `Macroable.getter()` wraps\n * the function it is given, hence a registry rather than a marker; it lives on\n * `globalThis` for the same reasons as {@link FACTORY}.\n */\nconst INSTALLED: unique symbol = Symbol.for(\n \"@fedify/adonisjs@2/federation-getters\",\n);\n\nconst registry = globalThis as { [INSTALLED]?: WeakSet<object> };\n\nconst installedGetters: WeakSet<object> = registry[INSTALLED]
|
|
1
|
+
{"version":3,"file":"http_context.js","names":[],"sources":["../../src/http_context.ts"],"sourcesContent":["/**\n * The `ctx.federation` accessor: a Macroable getter on `HttpContext` (like\n * `ctx.view`) that reads a per-request factory the middleware stores on the\n * instance, and memoises the result.\n *\n * @module\n */\nimport { HttpContext } from \"@adonisjs/core/http\";\nimport type { RequestContext } from \"@fedify/fedify\";\n\nimport { E_FEDIFY_CONTEXT_UNAVAILABLE } from \"./errors.ts\";\n\n/**\n * The per-request slot holding the factory for `ctx.federation`. A\n * registered symbol so the ESM and CommonJS builds share it, keyed by major\n * version so another major in the same process gets its own.\n */\nconst FACTORY: unique symbol = Symbol.for(\n \"@fedify/adonisjs@2/federation-factory\",\n);\n\n/**\n * The accessors this module has installed, so a `federation` member defined\n * by somebody else can be told apart from ours. `Macroable.getter()` wraps\n * the function it is given, hence a registry rather than a marker; it lives on\n * `globalThis` for the same reasons as {@link FACTORY}.\n */\nconst INSTALLED: unique symbol = Symbol.for(\n \"@fedify/adonisjs@2/federation-getters\",\n);\n\nconst registry = globalThis as { [INSTALLED]?: WeakSet<object> };\n\nconst installedGetters: WeakSet<object> = (registry[INSTALLED] ??=\n new WeakSet());\n\n/**\n * The shape of a context that carries the {@link FACTORY} slot.\n */\ntype FactoryCarrier = {\n [FACTORY]?: () => RequestContext<unknown>;\n};\n\n/**\n * A context class the getter can be installed on.\n */\nexport type HttpContextClass = typeof HttpContext;\n\n/**\n * Records how to create the `RequestContext` for `ctx`; the getter runs\n * `create` on first access.\n */\nexport function setFederationContextFactory<TContextData>(\n ctx: HttpContext,\n create: () => RequestContext<TContextData>,\n): void {\n Object.defineProperty(ctx, FACTORY, {\n value: create,\n configurable: true,\n enumerable: false,\n writable: true,\n });\n}\n\n/**\n * Installs the `federation` getter on a context class, once per class. The\n * middleware also calls this on `ctx.constructor`, which covers an\n * application with its own copy of `@adonisjs/core`. Macroable's\n * `singleton` flag memoises the value on the instance.\n *\n * @returns `false` when a `federation` member somebody else defined is in the\n * way; nothing is changed then, and the caller decides how to report it.\n */\nexport function ensureFederationGetter(\n target: HttpContextClass = HttpContext,\n): boolean {\n const existing = Object.getOwnPropertyDescriptor(\n target.prototype,\n \"federation\",\n );\n if (existing !== undefined) return isOwnGetter(existing.get);\n\n target.getter(\n \"federation\",\n function (this: HttpContext) {\n const create = (this as HttpContext & FactoryCarrier)[FACTORY];\n if (create === undefined) {\n throw new E_FEDIFY_CONTEXT_UNAVAILABLE(this.request.url());\n }\n return create() as HttpContext[\"federation\"];\n },\n true,\n );\n\n // Record the wrapper Macroable actually installed.\n const installed = Object.getOwnPropertyDescriptor(\n target.prototype,\n \"federation\",\n )?.get;\n if (installed !== undefined) installedGetters.add(installed);\n\n return true;\n}\n\n/**\n * {@link ensureFederationGetter}, but a conflict throws. Called from the\n * provider's `boot()`.\n */\nexport function installFederationGetter(\n target: HttpContextClass = HttpContext,\n): void {\n if (ensureFederationGetter(target)) return;\n\n throw new Error(\n 'Cannot install \"ctx.federation\": the HttpContext class already has a ' +\n '\"federation\" member that @fedify/adonisjs did not define. Remove the ' +\n \"conflicting macro or getter, or rename it\",\n );\n}\n\nfunction isOwnGetter(fn: unknown): boolean {\n return typeof fn === \"function\" && installedGetters.has(fn);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,MAAM,UAAyB,OAAO,IACpC,uCACF;;;;;;;AAQA,MAAM,YAA2B,OAAO,IACtC,uCACF;AAEA,MAAM,WAAW;AAEjB,MAAM,mBAAqC,SAAS,eAClD,IAAI,QAAQ;;;;;AAkBd,SAAgB,4BACd,KACA,QACM;CACN,OAAO,eAAe,KAAK,SAAS;EAClC,OAAO;EACP,cAAc;EACd,YAAY;EACZ,UAAU;CACZ,CAAC;AACH;;;;;;;;;;AAWA,SAAgB,uBACd,SAA2B,aAClB;CACT,MAAM,WAAW,OAAO,yBACtB,OAAO,WACP,YACF;CACA,IAAI,aAAa,WAAW,OAAO,YAAY,SAAS,GAAG;CAE3D,OAAO,OACL,cACA,WAA6B;EAC3B,MAAM,SAAU,KAAsC;EACtD,IAAI,WAAW,WAAW;GACxB,MAAM,IAAI,6BAA6B,KAAK,QAAQ,IAAI,CAAC;EAC3D;EACA,OAAO,OAAO;CAChB,GACA,IACF;CAGA,MAAM,YAAY,OAAO,yBACvB,OAAO,WACP,YACF,CAAC,EAAE;CACH,IAAI,cAAc,WAAW,iBAAiB,IAAI,SAAS;CAE3D,OAAO;AACT;;;;;AAMA,SAAgB,wBACd,SAA2B,aACrB;CACN,IAAI,uBAAuB,MAAM,GAAG;CAEpC,MAAM,IAAI,MACR,4EACE,4EACA,2CACJ;AACF;AAEA,SAAS,YAAY,IAAsB;CACzC,OAAO,OAAO,OAAO,cAAc,iBAAiB,IAAI,EAAE;AAC5D"}
|
package/dist/src/logging.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logging.cjs","names":["AsyncLocalStorage"],"sources":["../../src/logging.ts"],"sourcesContent":["/**\n * Bridges Fedify's [LogTape] logs into the AdonisJS logger.\n *\n * Fedify reports signature verification, delivery attempts, WebFinger lookups,\n * and document loading through LogTape, but none of it is visible unless\n * LogTape is configured. This module routes those records into the\n * application's Pino logger so they share its formatting and level filtering.\n *\n * [LogTape]: https://logtape.org/\n *\n * @module\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { Logger } from \"@adonisjs/core/logger\";\nimport {\n configure,\n getConfig,\n getTextFormatter,\n type LogLevel,\n type LogRecord,\n type TextFormatter,\n} from \"@logtape/logtape\";\n\n/**\n * Options for {@link configureFedifyLogging}.\n */\nexport interface FedifyLoggingOptions {\n /**\n * The AdonisJS logger to forward records to.\n */\n logger: Logger;\n\n /**\n * The LogTape categories to route into the AdonisJS logger. The default\n * covers Fedify's logs and LogTape's meta category, where LogTape reports\n * its own misconfiguration.\n *\n * @default `[['logtape', 'meta'], ['fedify']]`\n */\n categories?: (string | string[])[];\n}\n\n/**\n * A Pino log method in its `(mergingObject, message)` form.\n */\ntype LogMethod = (
|
|
1
|
+
{"version":3,"file":"logging.cjs","names":["AsyncLocalStorage"],"sources":["../../src/logging.ts"],"sourcesContent":["/**\n * Bridges Fedify's [LogTape] logs into the AdonisJS logger.\n *\n * Fedify reports signature verification, delivery attempts, WebFinger lookups,\n * and document loading through LogTape, but none of it is visible unless\n * LogTape is configured. This module routes those records into the\n * application's Pino logger so they share its formatting and level filtering.\n *\n * [LogTape]: https://logtape.org/\n *\n * @module\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { Logger } from \"@adonisjs/core/logger\";\nimport {\n configure,\n getConfig,\n getTextFormatter,\n type LogLevel,\n type LogRecord,\n type TextFormatter,\n} from \"@logtape/logtape\";\n\n/**\n * Options for {@link configureFedifyLogging}.\n */\nexport interface FedifyLoggingOptions {\n /**\n * The AdonisJS logger to forward records to.\n */\n logger: Logger;\n\n /**\n * The LogTape categories to route into the AdonisJS logger. The default\n * covers Fedify's logs and LogTape's meta category, where LogTape reports\n * its own misconfiguration.\n *\n * @default `[['logtape', 'meta'], ['fedify']]`\n */\n categories?: (string | string[])[];\n}\n\n/**\n * A Pino log method in its `(mergingObject, message)` form.\n */\ntype LogMethod = (properties: Record<string, unknown>, message: string) => void;\n\n/**\n * Maps a LogTape level onto the matching Pino method (`warning` becomes\n * `warn`). The methods are wrapped rather than bound because `bind()` would\n * pick the `(message, ...values)` overload instead of the merging-object one.\n */\nfunction logWith(logger: Logger, level: LogLevel): LogMethod | undefined {\n switch (level) {\n case \"trace\":\n return (properties, message) => logger.trace(properties, message);\n case \"debug\":\n return (properties, message) => logger.debug(properties, message);\n case \"info\":\n return (properties, message) => logger.info(properties, message);\n case \"warning\":\n return (properties, message) => logger.warn(properties, message);\n case \"error\":\n return (properties, message) => logger.error(properties, message);\n case \"fatal\":\n return (properties, message) => logger.fatal(properties, message);\n default:\n return undefined;\n }\n}\n\n/**\n * Turns a record's LogTape properties into Pino's merging object, so that\n * `redact` paths, serializers, and log aggregators see them as fields rather\n * than as text flattened into the message.\n *\n * An `error` property holding an `Error` is moved to `err`, the key Pino\n * serialises errors under. It is moved rather than copied because the\n * rendered message already carries the inspected value.\n */\nfunction toLogFields(\n properties: Record<string, unknown>,\n): Record<string, unknown> {\n const fields: Record<string, unknown> = { ...properties };\n\n if (fields.error instanceof Error && fields.err === undefined) {\n fields.err = fields.error;\n delete fields.error;\n }\n\n return fields;\n}\n\n/**\n * Configures LogTape so that Fedify's logs flow into the AdonisJS logger.\n * The service provider calls this during `boot()` unless `config/fedify.ts`\n * sets `logging: false`, the escape hatch for applications that configure\n * LogTape themselves.\n *\n * LogTape is a process-global singleton and `configure()` throws when called\n * twice. The usual causes (an application configuring LogTape itself without\n * `logging: false`, or a test process booting several applications) should\n * keep the existing configuration, so this function logs a debug message and\n * returns instead of throwing.\n *\n * Timestamps and levels are stripped from the rendered message because the\n * AdonisJS logger adds its own. Properties are also passed as Pino fields;\n * see {@link toLogFields}.\n *\n * @returns Whether this call configured LogTape and should therefore undo it.\n * The provider resets it in `shutdown()` so that a process booting a second\n * application (the test runner, an in-process dev-server restart) does not\n * keep logging into the old application's logger.\n */\nexport async function configureFedifyLogging(\n options: FedifyLoggingOptions,\n): Promise<boolean> {\n const { logger } = options;\n const categories = options.categories ?? [[\"logtape\", \"meta\"], [\"fedify\"]];\n\n if (getConfig() != null) {\n logger.debug(\n \"LogTape is already configured, so the Fedify logging bridge was left \" +\n 'alone. Set \"logging\" to false in config/fedify.ts to make that ' +\n \"explicit.\",\n );\n return false;\n }\n\n const formatter: TextFormatter = getTextFormatter({\n timestamp: \"disabled\",\n level: () => \"\",\n });\n\n await configure({\n sinks: {\n adonisjs: (record: LogRecord) => {\n // The formatter still emits an empty `[]` where the level would go.\n const message = formatter(record)\n .replace(/^\\[\\]\\s+/, \"\")\n .trimEnd();\n const fields = toLogFields(record.properties);\n\n const write = logWith(logger, record.level);\n /* c8 ignore next 3 -- LogTape may add levels in a future release */\n if (write === undefined) {\n logger.info(fields, message);\n return;\n }\n write(fields, message);\n },\n },\n filters: {},\n loggers: categories.map((category) => ({ category, sinks: [\"adonisjs\"] })),\n contextLocalStorage: new AsyncLocalStorage(),\n });\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqDA,SAAS,QAAQ,QAAgB,OAAwC;CACvE,QAAQ,OAAR;EACE,KAAK,SACH,QAAQ,YAAY,YAAY,OAAO,MAAM,YAAY,OAAO;EAClE,KAAK,SACH,QAAQ,YAAY,YAAY,OAAO,MAAM,YAAY,OAAO;EAClE,KAAK,QACH,QAAQ,YAAY,YAAY,OAAO,KAAK,YAAY,OAAO;EACjE,KAAK,WACH,QAAQ,YAAY,YAAY,OAAO,KAAK,YAAY,OAAO;EACjE,KAAK,SACH,QAAQ,YAAY,YAAY,OAAO,MAAM,YAAY,OAAO;EAClE,KAAK,SACH,QAAQ,YAAY,YAAY,OAAO,MAAM,YAAY,OAAO;EAClE,SACE,OAAO;CACX;AACF;;;;;;;;;;AAWA,SAAS,YACP,YACyB;CACzB,MAAM,SAAkC,EAAE,GAAG,WAAW;CAExD,IAAI,OAAO,iBAAiB,SAAS,OAAO,QAAQ,WAAW;EAC7D,OAAO,MAAM,OAAO;EACpB,OAAO,OAAO;CAChB;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;AAuBA,eAAsB,uBACpB,SACkB;CAClB,MAAM,EAAE,WAAW;CACnB,MAAM,aAAa,QAAQ,cAAc,CAAC,CAAC,WAAW,MAAM,GAAG,CAAC,QAAQ,CAAC;CAEzE,oCAAc,KAAK,MAAM;EACvB,OAAO,MACL,0EACE,sEACA,WACJ;EACA,OAAO;CACT;CAEA,MAAM,mDAA4C;EAChD,WAAW;EACX,aAAa;CACf,CAAC;CAED,sCAAgB;EACd,OAAO,EACL,WAAW,WAAsB;GAE/B,MAAM,UAAU,UAAU,MAAM,CAAC,CAC9B,QAAQ,YAAY,EAAE,CAAC,CACvB,QAAQ;GACX,MAAM,SAAS,YAAY,OAAO,UAAU;GAE5C,MAAM,QAAQ,QAAQ,QAAQ,OAAO,KAAK;;GAE1C,IAAI,UAAU,WAAW;IACvB,OAAO,KAAK,QAAQ,OAAO;IAC3B;GACF;GACA,MAAM,QAAQ,OAAO;EACvB,EACF;EACA,SAAS,CAAC;EACV,SAAS,WAAW,KAAK,cAAc;GAAE;GAAU,OAAO,CAAC,UAAU;EAAE,EAAE;EACzE,qBAAqB,IAAIA,mCAAkB;CAC7C,CAAC;CAED,OAAO;AACT"}
|
package/dist/src/logging.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logging.js","names":[],"sources":["../../src/logging.ts"],"sourcesContent":["/**\n * Bridges Fedify's [LogTape] logs into the AdonisJS logger.\n *\n * Fedify reports signature verification, delivery attempts, WebFinger lookups,\n * and document loading through LogTape, but none of it is visible unless\n * LogTape is configured. This module routes those records into the\n * application's Pino logger so they share its formatting and level filtering.\n *\n * [LogTape]: https://logtape.org/\n *\n * @module\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { Logger } from \"@adonisjs/core/logger\";\nimport {\n configure,\n getConfig,\n getTextFormatter,\n type LogLevel,\n type LogRecord,\n type TextFormatter,\n} from \"@logtape/logtape\";\n\n/**\n * Options for {@link configureFedifyLogging}.\n */\nexport interface FedifyLoggingOptions {\n /**\n * The AdonisJS logger to forward records to.\n */\n logger: Logger;\n\n /**\n * The LogTape categories to route into the AdonisJS logger. The default\n * covers Fedify's logs and LogTape's meta category, where LogTape reports\n * its own misconfiguration.\n *\n * @default `[['logtape', 'meta'], ['fedify']]`\n */\n categories?: (string | string[])[];\n}\n\n/**\n * A Pino log method in its `(mergingObject, message)` form.\n */\ntype LogMethod = (
|
|
1
|
+
{"version":3,"file":"logging.js","names":[],"sources":["../../src/logging.ts"],"sourcesContent":["/**\n * Bridges Fedify's [LogTape] logs into the AdonisJS logger.\n *\n * Fedify reports signature verification, delivery attempts, WebFinger lookups,\n * and document loading through LogTape, but none of it is visible unless\n * LogTape is configured. This module routes those records into the\n * application's Pino logger so they share its formatting and level filtering.\n *\n * [LogTape]: https://logtape.org/\n *\n * @module\n */\nimport { AsyncLocalStorage } from \"node:async_hooks\";\n\nimport type { Logger } from \"@adonisjs/core/logger\";\nimport {\n configure,\n getConfig,\n getTextFormatter,\n type LogLevel,\n type LogRecord,\n type TextFormatter,\n} from \"@logtape/logtape\";\n\n/**\n * Options for {@link configureFedifyLogging}.\n */\nexport interface FedifyLoggingOptions {\n /**\n * The AdonisJS logger to forward records to.\n */\n logger: Logger;\n\n /**\n * The LogTape categories to route into the AdonisJS logger. The default\n * covers Fedify's logs and LogTape's meta category, where LogTape reports\n * its own misconfiguration.\n *\n * @default `[['logtape', 'meta'], ['fedify']]`\n */\n categories?: (string | string[])[];\n}\n\n/**\n * A Pino log method in its `(mergingObject, message)` form.\n */\ntype LogMethod = (properties: Record<string, unknown>, message: string) => void;\n\n/**\n * Maps a LogTape level onto the matching Pino method (`warning` becomes\n * `warn`). The methods are wrapped rather than bound because `bind()` would\n * pick the `(message, ...values)` overload instead of the merging-object one.\n */\nfunction logWith(logger: Logger, level: LogLevel): LogMethod | undefined {\n switch (level) {\n case \"trace\":\n return (properties, message) => logger.trace(properties, message);\n case \"debug\":\n return (properties, message) => logger.debug(properties, message);\n case \"info\":\n return (properties, message) => logger.info(properties, message);\n case \"warning\":\n return (properties, message) => logger.warn(properties, message);\n case \"error\":\n return (properties, message) => logger.error(properties, message);\n case \"fatal\":\n return (properties, message) => logger.fatal(properties, message);\n default:\n return undefined;\n }\n}\n\n/**\n * Turns a record's LogTape properties into Pino's merging object, so that\n * `redact` paths, serializers, and log aggregators see them as fields rather\n * than as text flattened into the message.\n *\n * An `error` property holding an `Error` is moved to `err`, the key Pino\n * serialises errors under. It is moved rather than copied because the\n * rendered message already carries the inspected value.\n */\nfunction toLogFields(\n properties: Record<string, unknown>,\n): Record<string, unknown> {\n const fields: Record<string, unknown> = { ...properties };\n\n if (fields.error instanceof Error && fields.err === undefined) {\n fields.err = fields.error;\n delete fields.error;\n }\n\n return fields;\n}\n\n/**\n * Configures LogTape so that Fedify's logs flow into the AdonisJS logger.\n * The service provider calls this during `boot()` unless `config/fedify.ts`\n * sets `logging: false`, the escape hatch for applications that configure\n * LogTape themselves.\n *\n * LogTape is a process-global singleton and `configure()` throws when called\n * twice. The usual causes (an application configuring LogTape itself without\n * `logging: false`, or a test process booting several applications) should\n * keep the existing configuration, so this function logs a debug message and\n * returns instead of throwing.\n *\n * Timestamps and levels are stripped from the rendered message because the\n * AdonisJS logger adds its own. Properties are also passed as Pino fields;\n * see {@link toLogFields}.\n *\n * @returns Whether this call configured LogTape and should therefore undo it.\n * The provider resets it in `shutdown()` so that a process booting a second\n * application (the test runner, an in-process dev-server restart) does not\n * keep logging into the old application's logger.\n */\nexport async function configureFedifyLogging(\n options: FedifyLoggingOptions,\n): Promise<boolean> {\n const { logger } = options;\n const categories = options.categories ?? [[\"logtape\", \"meta\"], [\"fedify\"]];\n\n if (getConfig() != null) {\n logger.debug(\n \"LogTape is already configured, so the Fedify logging bridge was left \" +\n 'alone. Set \"logging\" to false in config/fedify.ts to make that ' +\n \"explicit.\",\n );\n return false;\n }\n\n const formatter: TextFormatter = getTextFormatter({\n timestamp: \"disabled\",\n level: () => \"\",\n });\n\n await configure({\n sinks: {\n adonisjs: (record: LogRecord) => {\n // The formatter still emits an empty `[]` where the level would go.\n const message = formatter(record)\n .replace(/^\\[\\]\\s+/, \"\")\n .trimEnd();\n const fields = toLogFields(record.properties);\n\n const write = logWith(logger, record.level);\n /* c8 ignore next 3 -- LogTape may add levels in a future release */\n if (write === undefined) {\n logger.info(fields, message);\n return;\n }\n write(fields, message);\n },\n },\n filters: {},\n loggers: categories.map((category) => ({ category, sinks: [\"adonisjs\"] })),\n contextLocalStorage: new AsyncLocalStorage(),\n });\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqDA,SAAS,QAAQ,QAAgB,OAAwC;CACvE,QAAQ,OAAR;EACE,KAAK,SACH,QAAQ,YAAY,YAAY,OAAO,MAAM,YAAY,OAAO;EAClE,KAAK,SACH,QAAQ,YAAY,YAAY,OAAO,MAAM,YAAY,OAAO;EAClE,KAAK,QACH,QAAQ,YAAY,YAAY,OAAO,KAAK,YAAY,OAAO;EACjE,KAAK,WACH,QAAQ,YAAY,YAAY,OAAO,KAAK,YAAY,OAAO;EACjE,KAAK,SACH,QAAQ,YAAY,YAAY,OAAO,MAAM,YAAY,OAAO;EAClE,KAAK,SACH,QAAQ,YAAY,YAAY,OAAO,MAAM,YAAY,OAAO;EAClE,SACE,OAAO;CACX;AACF;;;;;;;;;;AAWA,SAAS,YACP,YACyB;CACzB,MAAM,SAAkC,EAAE,GAAG,WAAW;CAExD,IAAI,OAAO,iBAAiB,SAAS,OAAO,QAAQ,WAAW;EAC7D,OAAO,MAAM,OAAO;EACpB,OAAO,OAAO;CAChB;CAEA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;AAuBA,eAAsB,uBACpB,SACkB;CAClB,MAAM,EAAE,WAAW;CACnB,MAAM,aAAa,QAAQ,cAAc,CAAC,CAAC,WAAW,MAAM,GAAG,CAAC,QAAQ,CAAC;CAEzE,IAAI,UAAU,KAAK,MAAM;EACvB,OAAO,MACL,0EACE,sEACA,WACJ;EACA,OAAO;CACT;CAEA,MAAM,YAA2B,iBAAiB;EAChD,WAAW;EACX,aAAa;CACf,CAAC;CAED,MAAM,UAAU;EACd,OAAO,EACL,WAAW,WAAsB;GAE/B,MAAM,UAAU,UAAU,MAAM,CAAC,CAC9B,QAAQ,YAAY,EAAE,CAAC,CACvB,QAAQ;GACX,MAAM,SAAS,YAAY,OAAO,UAAU;GAE5C,MAAM,QAAQ,QAAQ,QAAQ,OAAO,KAAK;;GAE1C,IAAI,UAAU,WAAW;IACvB,OAAO,KAAK,QAAQ,OAAO;IAC3B;GACF;GACA,MAAM,QAAQ,OAAO;EACvB,EACF;EACA,SAAS,CAAC;EACV,SAAS,WAAW,KAAK,cAAc;GAAE;GAAU,OAAO,CAAC,UAAU;EAAE,EAAE;EACzE,qBAAqB,IAAI,kBAAkB;CAC7C,CAAC;CAED,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unusable_authority.cjs","names":[],"sources":["../../src/unusable_authority.ts"],"sourcesContent":["/**\n * The warning for a request whose authority cannot be used, and the budget\n * that keeps it from flooding the log.\n *\n * Internal to the package: this module is reachable through none of the\n * published subpaths. The two constants are exported for the tests, which\n * have to spend exactly this budget.\n *\n * @module\n */\nimport type { HttpContext } from \"@adonisjs/core/http\";\n\n/**\n * The host used when the request carries no usable authority.\n *\n * `FederationOptions.origin` covers the URLs Fedify *mints* — actor URIs,\n * activity IDs, collection URLs — so the placeholder never reaches a peer\n * through them, and only the path has to survive for routing. It does not\n * cover verification: RFC 9421's `@authority`, `@target-uri` and `@scheme`\n * are derived from this URL, so a request signed over `@authority` fails to\n * verify while the placeholder stands in. That is the cost of answering\n * instead of failing, and why the fallback is logged.\n */\nexport const PLACEHOLDER_HOST: string = \"localhost\";\n\n/**\n * Unusable authorities already warned about in the current window. Any\n * client can trigger the warning through `Host`, so each distinct value is\n * reported once and the set is capped, leaving neither it nor the log\n * unbounded. The key is the whole value, since two hostile values can share\n * a 128-character prefix.\n */\nconst warnedAuthorities = new Set<string>();\n\n/**\n * How many distinct values one window reports.\n */\nexport const WARNED_AUTHORITIES_LIMIT: number = 16;\n\n/**\n * How long the cap holds before the budget starts over.\n *\n * Without a window the cap is spent for the life of the process, and the\n * values that spend it are the client's to choose: sixteen junk `Host`\n * headers would silence the warning for good, so a proxy misconfigured an\n * hour later—every request falling back to {@link PLACEHOLDER_HOST}, every\n * signature over `@authority` failing to verify—would never be reported.\n * Starting over bounds the log at {@link WARNED_AUTHORITIES_LIMIT} lines per\n * window instead of over all time, which is what the log has to be protected\n * from, and leaves a standing misconfiguration visible.\n */\nexport const WARNED_AUTHORITIES_WINDOW_MS: number = 60 * 60 * 1000;\n\n/**\n * When the current window began; `0` so the first warning opens one. It\n * advances lazily, on the first warning after the window has elapsed, rather\n * than from a timer that would hold the event loop open on a quiet process.\n */\nlet warnedAuthoritiesWindowStart = 0;\n\n/**\n * Whether the cap has already been reported in this window. Reaching it\n * silences every later distinct value, which should not happen invisibly.\n */\nlet warnedAuthoritiesCapReported = false;\n\n/**\n * Reports an authority the request URL could not be built from, once per\n * distinct value and window.\n */\nexport function warnUnusableAuthority(\n logger: HttpContext[\"logger\"],\n host: string,\n): void {\n const now = Date.now();\n // `<` as well as the elapsed check: a backwards clock step (an NTP\n // correction) would otherwise freeze the window until real time caught up\n // with a start that lies in the future.\n if (\n now < warnedAuthoritiesWindowStart ||\n now - warnedAuthoritiesWindowStart >= WARNED_AUTHORITIES_WINDOW_MS\n ) {\n warnedAuthoritiesWindowStart = now;\n warnedAuthorities.clear();\n warnedAuthoritiesCapReported = false;\n }\n\n if (warnedAuthorities.has(host)) return;\n if (warnedAuthorities.size >= WARNED_AUTHORITIES_LIMIT) {\n if (warnedAuthoritiesCapReported) return;\n warnedAuthoritiesCapReported = true;\n logger.warn(\n \"Reached %d distinct unusable request authorities within %d minutes; \" +\n \"further distinct values are not reported until that window ends\",\n WARNED_AUTHORITIES_LIMIT,\n WARNED_AUTHORITIES_WINDOW_MS / 60_000,\n );\n return;\n }\n warnedAuthorities.add(host);\n // By code point, so an emoji straddling the boundary cannot leave a lone\n // surrogate in the key or the log line.\n const points = Array.from(host);\n const shown
|
|
1
|
+
{"version":3,"file":"unusable_authority.cjs","names":[],"sources":["../../src/unusable_authority.ts"],"sourcesContent":["/**\n * The warning for a request whose authority cannot be used, and the budget\n * that keeps it from flooding the log.\n *\n * Internal to the package: this module is reachable through none of the\n * published subpaths. The two constants are exported for the tests, which\n * have to spend exactly this budget.\n *\n * @module\n */\nimport type { HttpContext } from \"@adonisjs/core/http\";\n\n/**\n * The host used when the request carries no usable authority.\n *\n * `FederationOptions.origin` covers the URLs Fedify *mints* — actor URIs,\n * activity IDs, collection URLs — so the placeholder never reaches a peer\n * through them, and only the path has to survive for routing. It does not\n * cover verification: RFC 9421's `@authority`, `@target-uri` and `@scheme`\n * are derived from this URL, so a request signed over `@authority` fails to\n * verify while the placeholder stands in. That is the cost of answering\n * instead of failing, and why the fallback is logged.\n */\nexport const PLACEHOLDER_HOST: string = \"localhost\";\n\n/**\n * Unusable authorities already warned about in the current window. Any\n * client can trigger the warning through `Host`, so each distinct value is\n * reported once and the set is capped, leaving neither it nor the log\n * unbounded. The key is the whole value, since two hostile values can share\n * a 128-character prefix.\n */\nconst warnedAuthorities = new Set<string>();\n\n/**\n * How many distinct values one window reports.\n */\nexport const WARNED_AUTHORITIES_LIMIT: number = 16;\n\n/**\n * How long the cap holds before the budget starts over.\n *\n * Without a window the cap is spent for the life of the process, and the\n * values that spend it are the client's to choose: sixteen junk `Host`\n * headers would silence the warning for good, so a proxy misconfigured an\n * hour later—every request falling back to {@link PLACEHOLDER_HOST}, every\n * signature over `@authority` failing to verify—would never be reported.\n * Starting over bounds the log at {@link WARNED_AUTHORITIES_LIMIT} lines per\n * window instead of over all time, which is what the log has to be protected\n * from, and leaves a standing misconfiguration visible.\n */\nexport const WARNED_AUTHORITIES_WINDOW_MS: number = 60 * 60 * 1000;\n\n/**\n * When the current window began; `0` so the first warning opens one. It\n * advances lazily, on the first warning after the window has elapsed, rather\n * than from a timer that would hold the event loop open on a quiet process.\n */\nlet warnedAuthoritiesWindowStart = 0;\n\n/**\n * Whether the cap has already been reported in this window. Reaching it\n * silences every later distinct value, which should not happen invisibly.\n */\nlet warnedAuthoritiesCapReported = false;\n\n/**\n * Reports an authority the request URL could not be built from, once per\n * distinct value and window.\n */\nexport function warnUnusableAuthority(\n logger: HttpContext[\"logger\"],\n host: string,\n): void {\n const now = Date.now();\n // `<` as well as the elapsed check: a backwards clock step (an NTP\n // correction) would otherwise freeze the window until real time caught up\n // with a start that lies in the future.\n if (\n now < warnedAuthoritiesWindowStart ||\n now - warnedAuthoritiesWindowStart >= WARNED_AUTHORITIES_WINDOW_MS\n ) {\n warnedAuthoritiesWindowStart = now;\n warnedAuthorities.clear();\n warnedAuthoritiesCapReported = false;\n }\n\n if (warnedAuthorities.has(host)) return;\n if (warnedAuthorities.size >= WARNED_AUTHORITIES_LIMIT) {\n if (warnedAuthoritiesCapReported) return;\n warnedAuthoritiesCapReported = true;\n logger.warn(\n \"Reached %d distinct unusable request authorities within %d minutes; \" +\n \"further distinct values are not reported until that window ends\",\n WARNED_AUTHORITIES_LIMIT,\n WARNED_AUTHORITIES_WINDOW_MS / 60_000,\n );\n return;\n }\n warnedAuthorities.add(host);\n // By code point, so an emoji straddling the boundary cannot leave a lone\n // surrogate in the key or the log line.\n const points = Array.from(host);\n const shown =\n points.length > 128 ? `${points.slice(0, 128).join(\"\")}…` : host;\n logger.warn(\n 'Unusable request authority \"%s\"; the URL Fedify sees falls back to ' +\n '\"%s\", so signatures covering the authority will not verify. Behind a ' +\n \"proxy this is a misbehaving X-Forwarded-Host; otherwise a client sent \" +\n \"it directly. Each distinct value is reported once per %d minutes, up \" +\n \"to %d values in that window\",\n shown,\n PLACEHOLDER_HOST,\n WARNED_AUTHORITIES_WINDOW_MS / 60_000,\n WARNED_AUTHORITIES_LIMIT,\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,MAAa,mBAA2B;;;;;;;;AASxC,MAAM,oBAAoB,IAAI,IAAY;;;;AAK1C,MAAa,2BAAmC;;;;;;;;;;;;;AAchD,MAAa,+BAAuC,KAAK,KAAK;;;;;;AAO9D,IAAI,+BAA+B;;;;;AAMnC,IAAI,+BAA+B;;;;;AAMnC,SAAgB,sBACd,QACA,MACM;CACN,MAAM,MAAM,KAAK,IAAI;CAIrB,IACE,MAAM,gCACN,MAAM,sCACN;EACA,+BAA+B;EAC/B,kBAAkB,MAAM;EACxB,+BAA+B;CACjC;CAEA,IAAI,kBAAkB,IAAI,IAAI,GAAG;CACjC,IAAI,kBAAkB,YAAkC;EACtD,IAAI,8BAA8B;EAClC,+BAA+B;EAC/B,OAAO,KACL,yEACE,uEAEF,+BAA+B,GACjC;EACA;CACF;CACA,kBAAkB,IAAI,IAAI;CAG1B,MAAM,SAAS,MAAM,KAAK,IAAI;CAC9B,MAAM,QACJ,OAAO,SAAS,MAAM,GAAG,OAAO,MAAM,GAAG,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,KAAK;CAC9D,OAAO,KACL,0EACE,4EACA,2EACA,0EACA,+BACF,OACA,kBACA,+BAA+B,OAEjC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unusable_authority.js","names":[],"sources":["../../src/unusable_authority.ts"],"sourcesContent":["/**\n * The warning for a request whose authority cannot be used, and the budget\n * that keeps it from flooding the log.\n *\n * Internal to the package: this module is reachable through none of the\n * published subpaths. The two constants are exported for the tests, which\n * have to spend exactly this budget.\n *\n * @module\n */\nimport type { HttpContext } from \"@adonisjs/core/http\";\n\n/**\n * The host used when the request carries no usable authority.\n *\n * `FederationOptions.origin` covers the URLs Fedify *mints* — actor URIs,\n * activity IDs, collection URLs — so the placeholder never reaches a peer\n * through them, and only the path has to survive for routing. It does not\n * cover verification: RFC 9421's `@authority`, `@target-uri` and `@scheme`\n * are derived from this URL, so a request signed over `@authority` fails to\n * verify while the placeholder stands in. That is the cost of answering\n * instead of failing, and why the fallback is logged.\n */\nexport const PLACEHOLDER_HOST: string = \"localhost\";\n\n/**\n * Unusable authorities already warned about in the current window. Any\n * client can trigger the warning through `Host`, so each distinct value is\n * reported once and the set is capped, leaving neither it nor the log\n * unbounded. The key is the whole value, since two hostile values can share\n * a 128-character prefix.\n */\nconst warnedAuthorities = new Set<string>();\n\n/**\n * How many distinct values one window reports.\n */\nexport const WARNED_AUTHORITIES_LIMIT: number = 16;\n\n/**\n * How long the cap holds before the budget starts over.\n *\n * Without a window the cap is spent for the life of the process, and the\n * values that spend it are the client's to choose: sixteen junk `Host`\n * headers would silence the warning for good, so a proxy misconfigured an\n * hour later—every request falling back to {@link PLACEHOLDER_HOST}, every\n * signature over `@authority` failing to verify—would never be reported.\n * Starting over bounds the log at {@link WARNED_AUTHORITIES_LIMIT} lines per\n * window instead of over all time, which is what the log has to be protected\n * from, and leaves a standing misconfiguration visible.\n */\nexport const WARNED_AUTHORITIES_WINDOW_MS: number = 60 * 60 * 1000;\n\n/**\n * When the current window began; `0` so the first warning opens one. It\n * advances lazily, on the first warning after the window has elapsed, rather\n * than from a timer that would hold the event loop open on a quiet process.\n */\nlet warnedAuthoritiesWindowStart = 0;\n\n/**\n * Whether the cap has already been reported in this window. Reaching it\n * silences every later distinct value, which should not happen invisibly.\n */\nlet warnedAuthoritiesCapReported = false;\n\n/**\n * Reports an authority the request URL could not be built from, once per\n * distinct value and window.\n */\nexport function warnUnusableAuthority(\n logger: HttpContext[\"logger\"],\n host: string,\n): void {\n const now = Date.now();\n // `<` as well as the elapsed check: a backwards clock step (an NTP\n // correction) would otherwise freeze the window until real time caught up\n // with a start that lies in the future.\n if (\n now < warnedAuthoritiesWindowStart ||\n now - warnedAuthoritiesWindowStart >= WARNED_AUTHORITIES_WINDOW_MS\n ) {\n warnedAuthoritiesWindowStart = now;\n warnedAuthorities.clear();\n warnedAuthoritiesCapReported = false;\n }\n\n if (warnedAuthorities.has(host)) return;\n if (warnedAuthorities.size >= WARNED_AUTHORITIES_LIMIT) {\n if (warnedAuthoritiesCapReported) return;\n warnedAuthoritiesCapReported = true;\n logger.warn(\n \"Reached %d distinct unusable request authorities within %d minutes; \" +\n \"further distinct values are not reported until that window ends\",\n WARNED_AUTHORITIES_LIMIT,\n WARNED_AUTHORITIES_WINDOW_MS / 60_000,\n );\n return;\n }\n warnedAuthorities.add(host);\n // By code point, so an emoji straddling the boundary cannot leave a lone\n // surrogate in the key or the log line.\n const points = Array.from(host);\n const shown
|
|
1
|
+
{"version":3,"file":"unusable_authority.js","names":[],"sources":["../../src/unusable_authority.ts"],"sourcesContent":["/**\n * The warning for a request whose authority cannot be used, and the budget\n * that keeps it from flooding the log.\n *\n * Internal to the package: this module is reachable through none of the\n * published subpaths. The two constants are exported for the tests, which\n * have to spend exactly this budget.\n *\n * @module\n */\nimport type { HttpContext } from \"@adonisjs/core/http\";\n\n/**\n * The host used when the request carries no usable authority.\n *\n * `FederationOptions.origin` covers the URLs Fedify *mints* — actor URIs,\n * activity IDs, collection URLs — so the placeholder never reaches a peer\n * through them, and only the path has to survive for routing. It does not\n * cover verification: RFC 9421's `@authority`, `@target-uri` and `@scheme`\n * are derived from this URL, so a request signed over `@authority` fails to\n * verify while the placeholder stands in. That is the cost of answering\n * instead of failing, and why the fallback is logged.\n */\nexport const PLACEHOLDER_HOST: string = \"localhost\";\n\n/**\n * Unusable authorities already warned about in the current window. Any\n * client can trigger the warning through `Host`, so each distinct value is\n * reported once and the set is capped, leaving neither it nor the log\n * unbounded. The key is the whole value, since two hostile values can share\n * a 128-character prefix.\n */\nconst warnedAuthorities = new Set<string>();\n\n/**\n * How many distinct values one window reports.\n */\nexport const WARNED_AUTHORITIES_LIMIT: number = 16;\n\n/**\n * How long the cap holds before the budget starts over.\n *\n * Without a window the cap is spent for the life of the process, and the\n * values that spend it are the client's to choose: sixteen junk `Host`\n * headers would silence the warning for good, so a proxy misconfigured an\n * hour later—every request falling back to {@link PLACEHOLDER_HOST}, every\n * signature over `@authority` failing to verify—would never be reported.\n * Starting over bounds the log at {@link WARNED_AUTHORITIES_LIMIT} lines per\n * window instead of over all time, which is what the log has to be protected\n * from, and leaves a standing misconfiguration visible.\n */\nexport const WARNED_AUTHORITIES_WINDOW_MS: number = 60 * 60 * 1000;\n\n/**\n * When the current window began; `0` so the first warning opens one. It\n * advances lazily, on the first warning after the window has elapsed, rather\n * than from a timer that would hold the event loop open on a quiet process.\n */\nlet warnedAuthoritiesWindowStart = 0;\n\n/**\n * Whether the cap has already been reported in this window. Reaching it\n * silences every later distinct value, which should not happen invisibly.\n */\nlet warnedAuthoritiesCapReported = false;\n\n/**\n * Reports an authority the request URL could not be built from, once per\n * distinct value and window.\n */\nexport function warnUnusableAuthority(\n logger: HttpContext[\"logger\"],\n host: string,\n): void {\n const now = Date.now();\n // `<` as well as the elapsed check: a backwards clock step (an NTP\n // correction) would otherwise freeze the window until real time caught up\n // with a start that lies in the future.\n if (\n now < warnedAuthoritiesWindowStart ||\n now - warnedAuthoritiesWindowStart >= WARNED_AUTHORITIES_WINDOW_MS\n ) {\n warnedAuthoritiesWindowStart = now;\n warnedAuthorities.clear();\n warnedAuthoritiesCapReported = false;\n }\n\n if (warnedAuthorities.has(host)) return;\n if (warnedAuthorities.size >= WARNED_AUTHORITIES_LIMIT) {\n if (warnedAuthoritiesCapReported) return;\n warnedAuthoritiesCapReported = true;\n logger.warn(\n \"Reached %d distinct unusable request authorities within %d minutes; \" +\n \"further distinct values are not reported until that window ends\",\n WARNED_AUTHORITIES_LIMIT,\n WARNED_AUTHORITIES_WINDOW_MS / 60_000,\n );\n return;\n }\n warnedAuthorities.add(host);\n // By code point, so an emoji straddling the boundary cannot leave a lone\n // surrogate in the key or the log line.\n const points = Array.from(host);\n const shown =\n points.length > 128 ? `${points.slice(0, 128).join(\"\")}…` : host;\n logger.warn(\n 'Unusable request authority \"%s\"; the URL Fedify sees falls back to ' +\n '\"%s\", so signatures covering the authority will not verify. Behind a ' +\n \"proxy this is a misbehaving X-Forwarded-Host; otherwise a client sent \" +\n \"it directly. Each distinct value is reported once per %d minutes, up \" +\n \"to %d values in that window\",\n shown,\n PLACEHOLDER_HOST,\n WARNED_AUTHORITIES_WINDOW_MS / 60_000,\n WARNED_AUTHORITIES_LIMIT,\n );\n}\n"],"mappings":";;;;;;;;;;;;AAuBA,MAAa,mBAA2B;;;;;;;;AASxC,MAAM,oBAAoB,IAAI,IAAY;;;;AAK1C,MAAa,2BAAmC;;;;;;;;;;;;;AAchD,MAAa,+BAAuC,KAAK,KAAK;;;;;;AAO9D,IAAI,+BAA+B;;;;;AAMnC,IAAI,+BAA+B;;;;;AAMnC,SAAgB,sBACd,QACA,MACM;CACN,MAAM,MAAM,KAAK,IAAI;CAIrB,IACE,MAAM,gCACN,MAAM,sCACN;EACA,+BAA+B;EAC/B,kBAAkB,MAAM;EACxB,+BAA+B;CACjC;CAEA,IAAI,kBAAkB,IAAI,IAAI,GAAG;CACjC,IAAI,kBAAkB,YAAkC;EACtD,IAAI,8BAA8B;EAClC,+BAA+B;EAC/B,OAAO,KACL,yEACE,uEAEF,+BAA+B,GACjC;EACA;CACF;CACA,kBAAkB,IAAI,IAAI;CAG1B,MAAM,SAAS,MAAM,KAAK,IAAI;CAC9B,MAAM,QACJ,OAAO,SAAS,MAAM,GAAG,OAAO,MAAM,GAAG,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,KAAK;CAC9D,OAAO,KACL,0EACE,4EACA,2EACA,0EACA,+BACF,OACA,kBACA,+BAA+B,OAEjC;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fedify/adonisjs",
|
|
3
|
-
"version": "2.5.0-dev.
|
|
3
|
+
"version": "2.5.0-dev.2687+924da5ce",
|
|
4
4
|
"description": "Integration package for Fedify with AdonisJS",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Fedify",
|
|
@@ -94,7 +94,7 @@
|
|
|
94
94
|
"peerDependencies": {
|
|
95
95
|
"@adonisjs/assembler": "^8.0.0",
|
|
96
96
|
"@adonisjs/core": "^7.4.0",
|
|
97
|
-
"@fedify/fedify": "^2.5.0-dev.
|
|
97
|
+
"@fedify/fedify": "^2.5.0-dev.2687+924da5ce"
|
|
98
98
|
},
|
|
99
99
|
"peerDependenciesMeta": {
|
|
100
100
|
"@adonisjs/assembler": {
|
|
@@ -102,7 +102,7 @@
|
|
|
102
102
|
}
|
|
103
103
|
},
|
|
104
104
|
"dependencies": {
|
|
105
|
-
"@logtape/logtape": "
|
|
105
|
+
"@logtape/logtape": "2.4.2"
|
|
106
106
|
},
|
|
107
107
|
"devDependencies": {
|
|
108
108
|
"@adonisjs/assembler": "^8.0.0",
|
|
@@ -110,8 +110,8 @@
|
|
|
110
110
|
"@types/node": "^24.12.2",
|
|
111
111
|
"tsdown": "^0.22.0",
|
|
112
112
|
"typescript": "^6.0.3",
|
|
113
|
-
"@fedify/fedify": "^2.5.0-dev.
|
|
114
|
-
"@fedify/vocab": "^2.5.0-dev.
|
|
113
|
+
"@fedify/fedify": "^2.5.0-dev.2687+924da5ce",
|
|
114
|
+
"@fedify/vocab": "^2.5.0-dev.2687+924da5ce"
|
|
115
115
|
},
|
|
116
116
|
"scripts": {
|
|
117
117
|
"build:self": "tsdown",
|