@drfed/drfed 0.0.0-stage → 0.1.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1198 -2
  3. package/bin/drfed-account.mjs +20 -0
  4. package/bin/drfed-migrate.mjs +20 -0
  5. package/bin/drfed-server.mjs +20 -0
  6. package/bin/drfed-web.mjs +20 -0
  7. package/completions/bash/drfed-account +219 -0
  8. package/completions/bash/drfed-migrate +219 -0
  9. package/completions/bash/drfed-server +219 -0
  10. package/completions/bash/drfed-web +219 -0
  11. package/completions/fish/drfed-account.fish +264 -0
  12. package/completions/fish/drfed-migrate.fish +264 -0
  13. package/completions/fish/drfed-server.fish +264 -0
  14. package/completions/fish/drfed-web.fish +264 -0
  15. package/completions/nu/drfed-account.nu +293 -0
  16. package/completions/nu/drfed-migrate.nu +293 -0
  17. package/completions/nu/drfed-server.nu +293 -0
  18. package/completions/nu/drfed-web.nu +293 -0
  19. package/completions/pwsh/drfed-account.ps1 +183 -0
  20. package/completions/pwsh/drfed-migrate.ps1 +183 -0
  21. package/completions/pwsh/drfed-server.ps1 +183 -0
  22. package/completions/pwsh/drfed-web.ps1 +183 -0
  23. package/completions/zsh/_drfed-account +145 -0
  24. package/completions/zsh/_drfed-migrate +145 -0
  25. package/completions/zsh/_drfed-server +145 -0
  26. package/completions/zsh/_drfed-web +145 -0
  27. package/dist/api-mail-parser.d.mts +106 -0
  28. package/dist/api-mail-parser.d.mts.map +1 -0
  29. package/dist/api-mail-parser.mjs +145 -0
  30. package/dist/api-mail-parser.mjs.map +1 -0
  31. package/dist/api-mail-settings-BcGaqQ9f.d.mts +142 -0
  32. package/dist/api-mail-settings-BcGaqQ9f.d.mts.map +1 -0
  33. package/dist/api-mail-settings.d.mts +2 -0
  34. package/dist/api-mail-settings.mjs +272 -0
  35. package/dist/api-mail-settings.mjs.map +1 -0
  36. package/dist/bounded-mail-runtime.d.mts +9 -0
  37. package/dist/bounded-mail-runtime.d.mts.map +1 -0
  38. package/dist/bounded-mail-runtime.mjs +66 -0
  39. package/dist/bounded-mail-runtime.mjs.map +1 -0
  40. package/dist/commands/account-create.d.mts +37 -0
  41. package/dist/commands/account-create.d.mts.map +1 -0
  42. package/dist/commands/account-create.mjs +87 -0
  43. package/dist/commands/account-create.mjs.map +1 -0
  44. package/dist/commands/account-program.d.mts +223 -0
  45. package/dist/commands/account-program.d.mts.map +1 -0
  46. package/dist/commands/account-program.mjs +116 -0
  47. package/dist/commands/account-program.mjs.map +1 -0
  48. package/dist/commands/account.d.mts +6 -0
  49. package/dist/commands/account.d.mts.map +1 -0
  50. package/dist/commands/account.mjs +91 -0
  51. package/dist/commands/account.mjs.map +1 -0
  52. package/dist/commands/migrate-program.d.mts +219 -0
  53. package/dist/commands/migrate-program.d.mts.map +1 -0
  54. package/dist/commands/migrate-program.mjs +116 -0
  55. package/dist/commands/migrate-program.mjs.map +1 -0
  56. package/dist/commands/migrate.d.mts +6 -0
  57. package/dist/commands/migrate.d.mts.map +1 -0
  58. package/dist/commands/migrate.mjs +85 -0
  59. package/dist/commands/migrate.mjs.map +1 -0
  60. package/dist/commands/web-program.d.mts +213 -0
  61. package/dist/commands/web-program.d.mts.map +1 -0
  62. package/dist/commands/web-program.mjs +112 -0
  63. package/dist/commands/web-program.mjs.map +1 -0
  64. package/dist/commands/web.d.mts +6 -0
  65. package/dist/commands/web.d.mts.map +1 -0
  66. package/dist/commands/web.mjs +184 -0
  67. package/dist/commands/web.mjs.map +1 -0
  68. package/dist/configuration-DVVF7xNv.d.mts +432 -0
  69. package/dist/configuration-DVVF7xNv.d.mts.map +1 -0
  70. package/dist/configuration.d.mts +2 -0
  71. package/dist/configuration.mjs +469 -0
  72. package/dist/configuration.mjs.map +1 -0
  73. package/dist/data-path.d.mts +9 -0
  74. package/dist/data-path.d.mts.map +1 -0
  75. package/dist/data-path.mjs +21 -0
  76. package/dist/data-path.mjs.map +1 -0
  77. package/dist/database-runtime.d.mts +26 -0
  78. package/dist/database-runtime.d.mts.map +1 -0
  79. package/dist/database-runtime.mjs +92 -0
  80. package/dist/database-runtime.mjs.map +1 -0
  81. package/dist/database-settings.d.mts +36 -0
  82. package/dist/database-settings.d.mts.map +1 -0
  83. package/dist/database-settings.mjs +67 -0
  84. package/dist/database-settings.mjs.map +1 -0
  85. package/dist/diagnostics.d.mts +29 -0
  86. package/dist/diagnostics.d.mts.map +1 -0
  87. package/dist/diagnostics.mjs +61 -0
  88. package/dist/diagnostics.mjs.map +1 -0
  89. package/dist/index.d.mts +5 -0
  90. package/dist/index.d.mts.map +1 -0
  91. package/dist/index.mjs +344 -0
  92. package/dist/index.mjs.map +1 -0
  93. package/dist/jmap-parser.d.mts +35 -0
  94. package/dist/jmap-parser.d.mts.map +1 -0
  95. package/dist/jmap-parser.mjs +42 -0
  96. package/dist/jmap-parser.mjs.map +1 -0
  97. package/dist/jmap-runtime.d.mts +10 -0
  98. package/dist/jmap-runtime.d.mts.map +1 -0
  99. package/dist/jmap-runtime.mjs +17 -0
  100. package/dist/jmap-runtime.mjs.map +1 -0
  101. package/dist/jmap-settings-BXNAF1ep.d.mts +41 -0
  102. package/dist/jmap-settings-BXNAF1ep.d.mts.map +1 -0
  103. package/dist/jmap-settings.d.mts +2 -0
  104. package/dist/jmap-settings.mjs +104 -0
  105. package/dist/jmap-settings.mjs.map +1 -0
  106. package/dist/logging.d.mts +33 -0
  107. package/dist/logging.d.mts.map +1 -0
  108. package/dist/logging.mjs +56 -0
  109. package/dist/logging.mjs.map +1 -0
  110. package/dist/mail-parser-DyI4wuQp.d.mts +246 -0
  111. package/dist/mail-parser-DyI4wuQp.d.mts.map +1 -0
  112. package/dist/mail-parser.d.mts +2 -0
  113. package/dist/mail-parser.mjs +100 -0
  114. package/dist/mail-parser.mjs.map +1 -0
  115. package/dist/mail-runtime-YROIQ8up.mjs +314 -0
  116. package/dist/mail-runtime-YROIQ8up.mjs.map +1 -0
  117. package/dist/mail-runtime.d.mts +68 -0
  118. package/dist/mail-runtime.d.mts.map +1 -0
  119. package/dist/mail-runtime.mjs +2 -0
  120. package/dist/mail-settings-BD1TQ0rt.mjs +427 -0
  121. package/dist/mail-settings-BD1TQ0rt.mjs.map +1 -0
  122. package/dist/mail-settings-DjWMAUaE.d.mts +80 -0
  123. package/dist/mail-settings-DjWMAUaE.d.mts.map +1 -0
  124. package/dist/mail-settings.d.mts +2 -0
  125. package/dist/mail-settings.mjs +2 -0
  126. package/dist/operations.d.mts +32 -0
  127. package/dist/operations.d.mts.map +1 -0
  128. package/dist/operations.mjs +55 -0
  129. package/dist/operations.mjs.map +1 -0
  130. package/dist/package-7FOUqcPO.mjs +6 -0
  131. package/dist/package-7FOUqcPO.mjs.map +1 -0
  132. package/dist/parser-DGIQTgS7.mjs +178 -0
  133. package/dist/parser-DGIQTgS7.mjs.map +1 -0
  134. package/dist/parser-TANGHRjL.d.mts +305 -0
  135. package/dist/parser-TANGHRjL.d.mts.map +1 -0
  136. package/dist/postgres-settings.d.mts +20 -0
  137. package/dist/postgres-settings.d.mts.map +1 -0
  138. package/dist/postgres-settings.mjs +60 -0
  139. package/dist/postgres-settings.mjs.map +1 -0
  140. package/dist/query-logger.d.mts +9 -0
  141. package/dist/query-logger.d.mts.map +1 -0
  142. package/dist/query-logger.mjs +17 -0
  143. package/dist/query-logger.mjs.map +1 -0
  144. package/dist/resources.d.mts +20 -0
  145. package/dist/resources.d.mts.map +1 -0
  146. package/dist/resources.mjs +34 -0
  147. package/dist/resources.mjs.map +1 -0
  148. package/dist/secret-source-BeZx72Ue.d.mts +21 -0
  149. package/dist/secret-source-BeZx72Ue.d.mts.map +1 -0
  150. package/dist/secret-source.d.mts +2 -0
  151. package/dist/secret-source.mjs +58 -0
  152. package/dist/secret-source.mjs.map +1 -0
  153. package/dist/serving.d.mts +82 -0
  154. package/dist/serving.d.mts.map +1 -0
  155. package/dist/serving.mjs +138 -0
  156. package/dist/serving.mjs.map +1 -0
  157. package/dist/smtp-settings.d.mts +11 -0
  158. package/dist/smtp-settings.d.mts.map +1 -0
  159. package/dist/smtp-settings.mjs +38 -0
  160. package/dist/smtp-settings.mjs.map +1 -0
  161. package/dist/valueparser.d.mts +46 -0
  162. package/dist/valueparser.d.mts.map +1 -0
  163. package/dist/valueparser.mjs +121 -0
  164. package/dist/valueparser.mjs.map +1 -0
  165. package/package.json +275 -3
@@ -0,0 +1,60 @@
1
+ //#region src/postgres-settings.ts
2
+ function validateQueryParameters(url) {
3
+ const allowed = /* @__PURE__ */ new Set([
4
+ "sslmode",
5
+ "search_path",
6
+ "application_name"
7
+ ]);
8
+ const seen = /* @__PURE__ */ new Set();
9
+ for (const [key, value] of url.searchParams) {
10
+ if (!allowed.has(key) || seen.has(key) || value.includes("\0")) throw new Error("Invalid or unsupported PostgreSQL connection URL.");
11
+ seen.add(key);
12
+ }
13
+ }
14
+ /**
15
+ * Resolve the same single-host connection and TLS policy for both database drivers.
16
+ * Unsupported URL features are rejected without opening a connection.
17
+ * @returns Normalized URLs and explicit runtime transport options.
18
+ */
19
+ function resolvePostgresConnection(url) {
20
+ const invalid = () => /* @__PURE__ */ new Error("Invalid or unsupported PostgreSQL connection URL.");
21
+ try {
22
+ validateQueryParameters(url);
23
+ const host = decodeURIComponent(url.hostname).replace(/^\[|\]$/gu, "");
24
+ const database = decodeURIComponent(url.pathname.slice(1));
25
+ const user = decodeURIComponent(url.username);
26
+ if (!["postgres:", "postgresql:"].includes(url.protocol) || [
27
+ host,
28
+ user,
29
+ database
30
+ ].some((value) => !value || value.includes("\0")) || host.includes(",") || host.includes("/") || url.hash || decodeURIComponent(url.password).includes("\0") || url.port === "0") throw invalid();
31
+ const mode = url.searchParams.get("sslmode") ?? "disable";
32
+ if (mode !== "disable" && mode !== "verify-full") throw invalid();
33
+ const searchPath = url.searchParams.get("search_path") ?? "public";
34
+ const applicationName = url.searchParams.get("application_name") ?? "drfed";
35
+ if (!searchPath.trim() || !applicationName.trim()) throw invalid();
36
+ const runtime = new URL(url.href);
37
+ runtime.port = url.port || "5432";
38
+ runtime.searchParams.set("sslmode", mode);
39
+ runtime.searchParams.set("search_path", searchPath);
40
+ runtime.searchParams.set("application_name", applicationName);
41
+ const escaped = searchPath.replace(/(?<character>[\\\s])/gu, "\\$<character>");
42
+ return {
43
+ runtimeUrl: runtime.href,
44
+ options: `-csearch_path=${escaped}`,
45
+ applicationName,
46
+ password: decodeURIComponent(url.password),
47
+ host,
48
+ database,
49
+ user,
50
+ port: Number(runtime.port),
51
+ tls: mode === "verify-full"
52
+ };
53
+ } catch {
54
+ throw invalid();
55
+ }
56
+ }
57
+ //#endregion
58
+ export { resolvePostgresConnection };
59
+
60
+ //# sourceMappingURL=postgres-settings.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres-settings.mjs","names":[],"sources":["../src/postgres-settings.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nfunction validateQueryParameters(url: URL): void {\n const allowed = new Set([\"sslmode\", \"search_path\", \"application_name\"]);\n const seen = new Set<string>();\n for (const [key, value] of url.searchParams) {\n if (!allowed.has(key) || seen.has(key) || value.includes(\"\\0\")) {\n throw new Error(\"Invalid or unsupported PostgreSQL connection URL.\");\n }\n seen.add(key);\n }\n}\n\n/**\n * Resolve the same single-host connection and TLS policy for both database drivers.\n * Unsupported URL features are rejected without opening a connection.\n * @returns Normalized URLs and explicit runtime transport options.\n */\nexport function resolvePostgresConnection(url: URL) {\n const invalid = () =>\n new Error(\"Invalid or unsupported PostgreSQL connection URL.\");\n try {\n validateQueryParameters(url);\n const host = decodeURIComponent(url.hostname).replace(/^\\[|\\]$/gu, \"\");\n const database = decodeURIComponent(url.pathname.slice(1));\n const user = decodeURIComponent(url.username);\n if (\n ![\"postgres:\", \"postgresql:\"].includes(url.protocol) ||\n [host, user, database].some((value) => !value || value.includes(\"\\0\")) ||\n host.includes(\",\") ||\n host.includes(\"/\") ||\n url.hash ||\n decodeURIComponent(url.password).includes(\"\\0\") ||\n url.port === \"0\"\n ) {\n throw invalid();\n }\n const mode = url.searchParams.get(\"sslmode\") ?? \"disable\";\n if (mode !== \"disable\" && mode !== \"verify-full\") throw invalid();\n const searchPath = url.searchParams.get(\"search_path\") ?? \"public\";\n const applicationName = url.searchParams.get(\"application_name\") ?? \"drfed\";\n if (!searchPath.trim() || !applicationName.trim()) throw invalid();\n const runtime = new URL(url.href);\n runtime.port = url.port || \"5432\";\n runtime.searchParams.set(\"sslmode\", mode);\n runtime.searchParams.set(\"search_path\", searchPath);\n runtime.searchParams.set(\"application_name\", applicationName);\n const escaped = searchPath.replace(\n /(?<character>[\\\\\\s])/gu,\n \"\\\\$<character>\",\n );\n return {\n runtimeUrl: runtime.href,\n options: `-csearch_path=${escaped}`,\n applicationName,\n password: decodeURIComponent(url.password),\n host,\n database,\n user,\n port: Number(runtime.port),\n tls: mode === \"verify-full\",\n };\n } catch {\n throw invalid();\n }\n}\n"],"mappings":";AAgBA,SAAS,wBAAwB,KAAgB;CAC/C,MAAM,0BAAU,IAAI,IAAI;EAAC;EAAW;EAAe;CAAkB,CAAC;CACtE,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,CAAC,KAAK,UAAU,IAAI,cAAc;EAC3C,IAAI,CAAC,QAAQ,IAAI,GAAG,KAAK,KAAK,IAAI,GAAG,KAAK,MAAM,SAAS,IAAI,GAC3D,MAAM,IAAI,MAAM,mDAAmD;EAErE,KAAK,IAAI,GAAG;CACd;AACF;;;;;;AAOA,SAAgB,0BAA0B,KAAU;CAClD,MAAM,gCACJ,IAAI,MAAM,mDAAmD;CAC/D,IAAI;EACF,wBAAwB,GAAG;EAC3B,MAAM,OAAO,mBAAmB,IAAI,QAAQ,CAAC,CAAC,QAAQ,aAAa,EAAE;EACrE,MAAM,WAAW,mBAAmB,IAAI,SAAS,MAAM,CAAC,CAAC;EACzD,MAAM,OAAO,mBAAmB,IAAI,QAAQ;EAC5C,IACE,CAAC,CAAC,aAAa,aAAa,CAAC,CAAC,SAAS,IAAI,QAAQ,KACnD;GAAC;GAAM;GAAM;EAAQ,CAAC,CAAC,MAAM,UAAU,CAAC,SAAS,MAAM,SAAS,IAAI,CAAC,KACrE,KAAK,SAAS,GAAG,KACjB,KAAK,SAAS,GAAG,KACjB,IAAI,QACJ,mBAAmB,IAAI,QAAQ,CAAC,CAAC,SAAS,IAAI,KAC9C,IAAI,SAAS,KAEb,MAAM,QAAQ;EAEhB,MAAM,OAAO,IAAI,aAAa,IAAI,SAAS,KAAK;EAChD,IAAI,SAAS,aAAa,SAAS,eAAe,MAAM,QAAQ;EAChE,MAAM,aAAa,IAAI,aAAa,IAAI,aAAa,KAAK;EAC1D,MAAM,kBAAkB,IAAI,aAAa,IAAI,kBAAkB,KAAK;EACpE,IAAI,CAAC,WAAW,KAAK,KAAK,CAAC,gBAAgB,KAAK,GAAG,MAAM,QAAQ;EACjE,MAAM,UAAU,IAAI,IAAI,IAAI,IAAI;EAChC,QAAQ,OAAO,IAAI,QAAQ;EAC3B,QAAQ,aAAa,IAAI,WAAW,IAAI;EACxC,QAAQ,aAAa,IAAI,eAAe,UAAU;EAClD,QAAQ,aAAa,IAAI,oBAAoB,eAAe;EAC5D,MAAM,UAAU,WAAW,QACzB,0BACA,gBACF;EACA,OAAO;GACL,YAAY,QAAQ;GACpB,SAAS,iBAAiB;GAC1B;GACA,UAAU,mBAAmB,IAAI,QAAQ;GACzC;GACA;GACA;GACA,MAAM,OAAO,QAAQ,IAAI;GACzB,KAAK,SAAS;EAChB;CACF,QAAQ;EACN,MAAM,QAAQ;CAChB;AACF"}
@@ -0,0 +1,9 @@
1
+ import { Logger } from "drizzle-orm/logger";
2
+ //#region src/query-logger.d.ts
3
+ /** Suppress parameters for SQL that reads or writes private signing material.
4
+ * @returns A logger that never logs private-key parameters.
5
+ */
6
+ declare function privateKeySafeLogger(delegate?: Logger): Logger;
7
+ //#endregion
8
+ export { privateKeySafeLogger };
9
+ //# sourceMappingURL=query-logger.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-logger.d.mts","names":[],"sources":["../src/query-logger.ts"],"mappings":";;;;;iBAsBgB,qBACd,WAAU,SACT"}
@@ -0,0 +1,17 @@
1
+ import { getLogger } from "@logtape/logtape";
2
+ import { getLogger as getLogger$1 } from "@logtape/drizzle-orm";
3
+ //#region src/query-logger.ts
4
+ /** Suppress parameters for SQL that reads or writes private signing material.
5
+ * @returns A logger that never logs private-key parameters.
6
+ */
7
+ function privateKeySafeLogger(delegate = getLogger$1()) {
8
+ const logger = getLogger(["drfed", "database"]);
9
+ return { logQuery(query, params) {
10
+ if (query.toLowerCase().includes("local_actor_keys")) logger.debug("Query: {query}", { query });
11
+ else delegate.logQuery(query, params);
12
+ } };
13
+ }
14
+ //#endregion
15
+ export { privateKeySafeLogger };
16
+
17
+ //# sourceMappingURL=query-logger.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-logger.mjs","names":["getQueryLogger"],"sources":["../src/query-logger.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { getLogger as getQueryLogger } from \"@logtape/drizzle-orm\";\nimport { getLogger } from \"@logtape/logtape\";\nimport type { Logger } from \"drizzle-orm/logger\";\n/** Suppress parameters for SQL that reads or writes private signing material.\n * @returns A logger that never logs private-key parameters.\n */\nexport function privateKeySafeLogger(\n delegate: Logger = getQueryLogger(),\n): Logger {\n const logger = getLogger([\"drfed\", \"database\"]);\n return {\n logQuery(query, params) {\n if (query.toLowerCase().includes(\"local_actor_keys\")) {\n logger.debug(\"Query: {query}\", { query });\n } else delegate.logQuery(query, params);\n },\n };\n}\n"],"mappings":";;;;;;AAsBA,SAAgB,qBACd,WAAmBA,YAAe,GAC1B;CACR,MAAM,SAAS,UAAU,CAAC,SAAS,UAAU,CAAC;CAC9C,OAAO,EACL,SAAS,OAAO,QAAQ;EACtB,IAAI,MAAM,YAAY,CAAC,CAAC,SAAS,kBAAkB,GACjD,OAAO,MAAM,kBAAkB,EAAE,MAAM,CAAC;OACnC,SAAS,SAAS,OAAO,MAAM;CACxC,EACF;AACF"}
@@ -0,0 +1,20 @@
1
+ //#region src/resources.d.ts
2
+ /** Own cleanup callbacks independently of the resources a caller borrows. */
3
+ declare class ResourceOwner {
4
+ #private;
5
+ /**
6
+ * Register a resource immediately after acquisition.
7
+ * @returns The same resource, with cleanup registered only when owned.
8
+ */
9
+ register<T>(resource: T, dispose: (resource: T) => void | Promise<void>, options: {
10
+ readonly owned: boolean;
11
+ }): T;
12
+ /**
13
+ * Close owned resources in reverse acquisition order, attempting every cleanup.
14
+ * @returns One shared completion promise; cleanup failures are aggregated.
15
+ */
16
+ close(): Promise<void>;
17
+ }
18
+ //#endregion
19
+ export { ResourceOwner };
20
+ //# sourceMappingURL=resources.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resources.d.mts","names":[],"sources":["../src/resources.ts"],"mappings":";;cAiBa;;;;;;EAQX,SAAS,GACP,UAAU,GACV,UAAU,UAAU,aAAa,eACjC;aAAoB;MACnB;;;;;EAYH,SAAS"}
@@ -0,0 +1,34 @@
1
+ //#region src/resources.ts
2
+ /** Own cleanup callbacks independently of the resources a caller borrows. */
3
+ var ResourceOwner = class {
4
+ #cleanups = [];
5
+ #closing;
6
+ /**
7
+ * Register a resource immediately after acquisition.
8
+ * @returns The same resource, with cleanup registered only when owned.
9
+ */
10
+ register(resource, dispose, options) {
11
+ if (this.#closing != null) throw new Error("Cannot register resources during cleanup.");
12
+ if (options.owned) this.#cleanups.push(() => dispose(resource));
13
+ return resource;
14
+ }
15
+ /**
16
+ * Close owned resources in reverse acquisition order, attempting every cleanup.
17
+ * @returns One shared completion promise; cleanup failures are aggregated.
18
+ */
19
+ close() {
20
+ return this.#closing ??= Promise.resolve().then(async () => {
21
+ const errors = [];
22
+ for (const dispose of this.#cleanups.splice(0).reverse()) try {
23
+ await dispose();
24
+ } catch (error) {
25
+ errors.push(error);
26
+ }
27
+ if (errors.length > 0) throw new AggregateError(errors, "Resource cleanup failed.");
28
+ });
29
+ }
30
+ };
31
+ //#endregion
32
+ export { ResourceOwner };
33
+
34
+ //# sourceMappingURL=resources.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resources.mjs","names":["#cleanups","#closing"],"sources":["../src/resources.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n/** Own cleanup callbacks independently of the resources a caller borrows. */\nexport class ResourceOwner {\n readonly #cleanups: (() => void | Promise<void>)[] = [];\n #closing: Promise<void> | undefined;\n\n /**\n * Register a resource immediately after acquisition.\n * @returns The same resource, with cleanup registered only when owned.\n */\n register<T>(\n resource: T,\n dispose: (resource: T) => void | Promise<void>,\n options: { readonly owned: boolean },\n ): T {\n if (this.#closing != null) {\n throw new Error(\"Cannot register resources during cleanup.\");\n }\n if (options.owned) this.#cleanups.push(() => dispose(resource));\n return resource;\n }\n\n /**\n * Close owned resources in reverse acquisition order, attempting every cleanup.\n * @returns One shared completion promise; cleanup failures are aggregated.\n */\n close(): Promise<void> {\n // Defer callbacks until the shared promise is assigned, including reentrancy.\n // oxlint-disable-next-line promise/prefer-await-to-then\n return (this.#closing ??= Promise.resolve().then(async () => {\n const errors: unknown[] = [];\n for (const dispose of this.#cleanups.splice(0).reverse()) {\n try {\n // oxlint-disable-next-line no-await-in-loop\n await dispose();\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Resource cleanup failed.\");\n }\n return undefined;\n }));\n }\n}\n"],"mappings":";;AAiBA,IAAa,gBAAb,MAA2B;CACzB,YAAqD,CAAC;CACtD;;;;;CAMA,SACE,UACA,SACA,SACG;EACH,IAAI,KAAKC,YAAY,MACnB,MAAM,IAAI,MAAM,2CAA2C;EAE7D,IAAI,QAAQ,OAAO,KAAKD,UAAU,WAAW,QAAQ,QAAQ,CAAC;EAC9D,OAAO;CACT;;;;;CAMA,QAAuB;EAGrB,OAAQ,KAAKC,aAAa,QAAQ,QAAQ,CAAC,CAAC,KAAK,YAAY;GAC3D,MAAM,SAAoB,CAAC;GAC3B,KAAK,MAAM,WAAW,KAAKD,UAAU,OAAO,CAAC,CAAC,CAAC,QAAQ,GACrD,IAAI;IAEF,MAAM,QAAQ;GAChB,SAAS,OAAO;IACd,OAAO,KAAK,KAAK;GACnB;GAEF,IAAI,OAAO,SAAS,GAClB,MAAM,IAAI,eAAe,QAAQ,0BAA0B;EAG/D,CAAC;CACH;AACF"}
@@ -0,0 +1,21 @@
1
+ import { s as Sourced } from "./configuration-DVVF7xNv.mjs";
2
+ //#region src/secret-source.d.ts
3
+ /** A credential variant selected without reading its file. */
4
+ type SecretSource = {
5
+ readonly type: "literal";
6
+ readonly value: string;
7
+ } | {
8
+ readonly type: "file";
9
+ readonly path: string;
10
+ };
11
+ /** Select one source-aware literal/file variant without opening anything.
12
+ * @returns The highest-priority variant, or undefined when neither is supplied.
13
+ */
14
+ declare function resolveSecretSource(literal: Sourced<string | undefined> | undefined, file: Sourced<string | undefined> | undefined, field: string, cwd?: string): SecretSource | undefined;
15
+ /** Read only a selected credential; file paths and contents stay out of errors.
16
+ * @returns The credential, removing exactly one final LF or CRLF from files.
17
+ */
18
+ declare function readSecretSource(source: SecretSource, field: string, signal?: AbortSignal): Promise<string>;
19
+ //#endregion
20
+ export { readSecretSource as n, resolveSecretSource as r, SecretSource as t };
21
+ //# sourceMappingURL=secret-source-BeZx72Ue.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-source-BeZx72Ue.d.mts","names":[],"sources":["../src/secret-source.ts"],"mappings":";;;KA0BY;WACG;WAA0B;;WAC1B;WAAuB;;;;;iBAYtB,oBACd,SAAS,yCACT,MAAM,yCACN,eACA,eACC;;;;iBAuBmB,iBACpB,QAAQ,cACR,eACA,SAAS,cACR"}
@@ -0,0 +1,2 @@
1
+ import { n as readSecretSource, r as resolveSecretSource, t as SecretSource } from "./secret-source-BeZx72Ue.mjs";
2
+ export { SecretSource, readSecretSource, resolveSecretSource };
@@ -0,0 +1,58 @@
1
+ import { configurationPath } from "./configuration.mjs";
2
+ import { open } from "node:fs/promises";
3
+ import { constants } from "node:fs";
4
+ //#region src/secret-source.ts
5
+ const priority = {
6
+ default: 0,
7
+ config: 1,
8
+ env: 2,
9
+ cli: 3
10
+ };
11
+ /** Select one source-aware literal/file variant without opening anything.
12
+ * @returns The highest-priority variant, or undefined when neither is supplied.
13
+ */
14
+ function resolveSecretSource(literal, file, field, cwd = process.cwd()) {
15
+ const literalRank = literal?.value === void 0 ? -1 : priority[literal.source];
16
+ const fileRank = file?.value === void 0 ? -1 : priority[file.source];
17
+ if (literalRank < 0 && fileRank < 0) return void 0;
18
+ if (literalRank === fileRank) throw new Error(`Conflicting secret variants for ${field}.`);
19
+ if (fileRank > literalRank && file?.value !== void 0) {
20
+ if (file.value.trim() === "") throw new Error(`Invalid secret file setting for ${field}.`);
21
+ return {
22
+ type: "file",
23
+ path: configurationPath(file, cwd)
24
+ };
25
+ }
26
+ return {
27
+ type: "literal",
28
+ value: literal?.value ?? ""
29
+ };
30
+ }
31
+ /** Read only a selected credential; file paths and contents stay out of errors.
32
+ * @returns The credential, removing exactly one final LF or CRLF from files.
33
+ */
34
+ async function readSecretSource(source, field, signal) {
35
+ signal?.throwIfAborted();
36
+ if (source.type === "literal") return source.value;
37
+ try {
38
+ const nonblocking = process.platform === "win32" ? 0 : constants.O_NONBLOCK;
39
+ const flags = constants.O_RDONLY | nonblocking;
40
+ const file = await open(source.path, flags);
41
+ try {
42
+ const stat = await file.stat();
43
+ if (!stat.isFile() || stat.size > 65536) throw new Error();
44
+ const bytes = await file.readFile({ signal });
45
+ if (bytes.byteLength > 65536) throw new Error();
46
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/\r?\n$/u, "");
47
+ } finally {
48
+ await file.close();
49
+ }
50
+ } catch {
51
+ signal?.throwIfAborted();
52
+ throw new Error(`Unable to read secret for ${field}.`);
53
+ }
54
+ }
55
+ //#endregion
56
+ export { readSecretSource, resolveSecretSource };
57
+
58
+ //# sourceMappingURL=secret-source.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"secret-source.mjs","names":[],"sources":["../src/secret-source.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { constants } from \"node:fs\";\nimport { open } from \"node:fs/promises\";\n\nimport {\n type ConfigurationSource,\n type Sourced,\n configurationPath,\n} from \"./configuration.ts\";\n\n/** A credential variant selected without reading its file. */\nexport type SecretSource =\n | { readonly type: \"literal\"; readonly value: string }\n | { readonly type: \"file\"; readonly path: string };\n\nconst priority: Readonly<Record<ConfigurationSource, number>> = {\n default: 0,\n config: 1,\n env: 2,\n cli: 3,\n};\n\n/** Select one source-aware literal/file variant without opening anything.\n * @returns The highest-priority variant, or undefined when neither is supplied.\n */\nexport function resolveSecretSource(\n literal: Sourced<string | undefined> | undefined,\n file: Sourced<string | undefined> | undefined,\n field: string,\n cwd = process.cwd(),\n): SecretSource | undefined {\n const literalRank =\n literal?.value === undefined ? -1 : priority[literal.source];\n const fileRank = file?.value === undefined ? -1 : priority[file.source];\n if (literalRank < 0 && fileRank < 0) return undefined;\n if (literalRank === fileRank) {\n throw new Error(`Conflicting secret variants for ${field}.`);\n }\n if (fileRank > literalRank && file?.value !== undefined) {\n if (file.value.trim() === \"\") {\n throw new Error(`Invalid secret file setting for ${field}.`);\n }\n return {\n type: \"file\",\n path: configurationPath(file as Sourced<string>, cwd),\n };\n }\n return { type: \"literal\", value: literal?.value ?? \"\" };\n}\n\n/** Read only a selected credential; file paths and contents stay out of errors.\n * @returns The credential, removing exactly one final LF or CRLF from files.\n */\nexport async function readSecretSource(\n source: SecretSource,\n field: string,\n signal?: AbortSignal,\n): Promise<string> {\n signal?.throwIfAborted();\n if (source.type === \"literal\") return source.value;\n try {\n // O_NONBLOCK prevents a mistaken FIFO path from blocking before fstat.\n // Windows exposes only its supported file-open flags.\n const nonblocking = process.platform === \"win32\" ? 0 : constants.O_NONBLOCK;\n // oxlint-disable-next-line no-bitwise\n const flags = constants.O_RDONLY | nonblocking;\n const file = await open(source.path, flags);\n try {\n const stat = await file.stat();\n if (!stat.isFile() || stat.size > 65_536) throw new Error();\n const bytes = await file.readFile({ signal });\n if (bytes.byteLength > 65_536) throw new Error();\n const value = new TextDecoder(\"utf-8\", { fatal: true }).decode(bytes);\n return value.replace(/\\r?\\n$/u, \"\");\n } finally {\n await file.close();\n }\n } catch {\n signal?.throwIfAborted();\n throw new Error(`Unable to read secret for ${field}.`);\n }\n}\n"],"mappings":";;;;AA8BA,MAAM,WAA0D;CAC9D,SAAS;CACT,QAAQ;CACR,KAAK;CACL,KAAK;AACP;;;;AAKA,SAAgB,oBACd,SACA,MACA,OACA,MAAM,QAAQ,IAAI,GACQ;CAC1B,MAAM,cACJ,SAAS,UAAU,KAAA,IAAY,KAAK,SAAS,QAAQ;CACvD,MAAM,WAAW,MAAM,UAAU,KAAA,IAAY,KAAK,SAAS,KAAK;CAChE,IAAI,cAAc,KAAK,WAAW,GAAG,OAAO,KAAA;CAC5C,IAAI,gBAAgB,UAClB,MAAM,IAAI,MAAM,mCAAmC,MAAM,EAAE;CAE7D,IAAI,WAAW,eAAe,MAAM,UAAU,KAAA,GAAW;EACvD,IAAI,KAAK,MAAM,KAAK,MAAM,IACxB,MAAM,IAAI,MAAM,mCAAmC,MAAM,EAAE;EAE7D,OAAO;GACL,MAAM;GACN,MAAM,kBAAkB,MAAyB,GAAG;EACtD;CACF;CACA,OAAO;EAAE,MAAM;EAAW,OAAO,SAAS,SAAS;CAAG;AACxD;;;;AAKA,eAAsB,iBACpB,QACA,OACA,QACiB;CACjB,QAAQ,eAAe;CACvB,IAAI,OAAO,SAAS,WAAW,OAAO,OAAO;CAC7C,IAAI;EAGF,MAAM,cAAc,QAAQ,aAAa,UAAU,IAAI,UAAU;EAEjE,MAAM,QAAQ,UAAU,WAAW;EACnC,MAAM,OAAO,MAAM,KAAK,OAAO,MAAM,KAAK;EAC1C,IAAI;GACF,MAAM,OAAO,MAAM,KAAK,KAAK;GAC7B,IAAI,CAAC,KAAK,OAAO,KAAK,KAAK,OAAO,OAAQ,MAAM,IAAI,MAAM;GAC1D,MAAM,QAAQ,MAAM,KAAK,SAAS,EAAE,OAAO,CAAC;GAC5C,IAAI,MAAM,aAAa,OAAQ,MAAM,IAAI,MAAM;GAE/C,OADc,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,OAAO,KACpD,CAAC,CAAC,QAAQ,WAAW,EAAE;EACpC,UAAU;GACR,MAAM,KAAK,MAAM;EACnB;CACF,QAAQ;EACN,QAAQ,eAAe;EACvB,MAAM,IAAI,MAAM,6BAA6B,MAAM,EAAE;CACvD;AACF"}
@@ -0,0 +1,82 @@
1
+ import { Database } from "@drfed/models";
2
+ //#region src/serving.d.ts
3
+ /**
4
+ * The federation surface (including the inbound recorder) that the router
5
+ * needs, narrowed so that the routing can be exercised without building one.
6
+ */
7
+ interface FederationHandler {
8
+ fetch(request: Request, options: {
9
+ onNotFound(request: Request): Response | Promise<Response>;
10
+ onNotAcceptable(request: Request): Response | Promise<Response>;
11
+ contextData: undefined;
12
+ }): Promise<Response>;
13
+ }
14
+ /**
15
+ * Options for {@link createFetchHandler}.
16
+ */
17
+ interface FetchHandlerOptions {
18
+ /**
19
+ * The root origin this deployment serves instances under.
20
+ */
21
+ readonly rootOrigin: URL;
22
+ /**
23
+ * The ActivityPub surface with inbox recording, served on instance subdomains.
24
+ */
25
+ readonly federation: FederationHandler;
26
+ /**
27
+ * The control surface (GraphQL and optionally web), served everywhere else.
28
+ */
29
+ readonly serveControlSurface: (request: Request) => Response | Promise<Response>;
30
+ }
31
+ /**
32
+ * Builds the server's request handler, which decides from the authority alone
33
+ * which of DrFed's two faces answers.
34
+ *
35
+ * An instance's subdomain serves ActivityPub and nothing else, so that a
36
+ * tenant can never reach the control surface; every other authority is the
37
+ * control surface and never answers as an instance. A subdomain nobody has
38
+ * claimed still routes to ActivityPub, where every dispatcher resolves to
39
+ * nothing and the request ends in a 404, which keeps the routing from having
40
+ * to ask the database what exists.
41
+ * @param options The surfaces to route between, and the root origin to route
42
+ * by.
43
+ * @returns A handler suitable for passing to `serve()`.
44
+ */
45
+ declare function createFetchHandler(options: FetchHandlerOptions): (request: Request) => Promise<Response>;
46
+ /** Compose the exact GraphQL endpoint with an optional embedded web handler.
47
+ * @returns The control handler; federation routing remains outside this layer.
48
+ */
49
+ declare function createControlSurface(options: {
50
+ readonly graphql: (request: Request) => Response | Promise<Response>;
51
+ readonly web?: (request: Request) => Response | Promise<Response>;
52
+ }): (request: Request) => Response | Promise<Response>;
53
+ /** Retrieve private ingress metadata for a publicly restored instance request.
54
+ * @returns Original adapter URL and headers for delivery recording, if restored.
55
+ */
56
+ declare function getIngressMetadata(request: Request): {
57
+ readonly url: string;
58
+ readonly headers: Headers;
59
+ } | undefined;
60
+ /**
61
+ * Finds local instances whose host does not sit one label below the given root
62
+ * origin, which is what happens when a deployment's root origin is changed
63
+ * after instances already exist.
64
+ * @param db The database to look in.
65
+ * @param rootOrigin The configured root origin.
66
+ * @returns The hosts that are no longer reachable, in no particular order.
67
+ */
68
+ declare function findStrandedInstances(db: Database, rootOrigin: URL): Promise<string[]>;
69
+ /**
70
+ * Warns about local instances the configured root origin no longer covers.
71
+ *
72
+ * Nothing is repaired. An instance's host is woven into the actor URIs that
73
+ * the rest of the fediverse has already seen and stored, so rewriting it would
74
+ * break exactly the federation it was meant to fix. Say what is wrong, and
75
+ * leave the decision to a human.
76
+ * @param db The database to look in.
77
+ * @param rootOrigin The configured root origin.
78
+ */
79
+ declare function warnAboutStrandedInstances(db: Database, rootOrigin: URL): Promise<void>;
80
+ //#endregion
81
+ export { FederationHandler, FetchHandlerOptions, createControlSurface, createFetchHandler, findStrandedInstances, getIngressMetadata, warnAboutStrandedInstances };
82
+ //# sourceMappingURL=serving.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serving.d.mts","names":[],"sources":["../src/serving.ts"],"mappings":";;;;;;UAwBiB;EACf,MACE,SAAS,SACT;IACE,WAAW,SAAS,UAAU,WAAW,QAAQ;IACjD,gBAAgB,SAAS,UAAU,WAAW,QAAQ;IACtD;MAED,QAAQ;;;;;UAMI;;;;WAIN,YAAY;;;;WAKZ,YAAY;;;;WAKZ,sBACP,SAAS,YACN,WAAW,QAAQ;;;;;;;;;;;;;;;;iBAiBV,mBACd,SAAS,uBACP,SAAS,YAAY,QAAQ;;;;iBAkEjB,qBAAqB;WAC1B,UAAU,SAAS,YAAY,WAAW,QAAQ;WAClD,OAAO,SAAS,YAAY,WAAW,QAAQ;KACrD,SAAS,YAAY,WAAW,QAAQ;;;;iBAiB7B,mBACd,SAAS;WACG;WAAsB,SAAS;;;;;;;;;;iBAwDvB,sBACpB,IAAI,UACJ,YAAY,MACX;;;;;;;;;;;iBA4BmB,2BACpB,IAAI,UACJ,YAAY,MACX"}
@@ -0,0 +1,138 @@
1
+ import { getLogger } from "@logtape/logtape";
2
+ import { canonicalizeAuthority, classifyHost } from "@drfed/federation/origin";
3
+ //#region src/serving.ts
4
+ /**
5
+ * Builds the server's request handler, which decides from the authority alone
6
+ * which of DrFed's two faces answers.
7
+ *
8
+ * An instance's subdomain serves ActivityPub and nothing else, so that a
9
+ * tenant can never reach the control surface; every other authority is the
10
+ * control surface and never answers as an instance. A subdomain nobody has
11
+ * claimed still routes to ActivityPub, where every dispatcher resolves to
12
+ * nothing and the request ends in a 404, which keeps the routing from having
13
+ * to ask the database what exists.
14
+ * @param options The surfaces to route between, and the root origin to route
15
+ * by.
16
+ * @returns A handler suitable for passing to `serve()`.
17
+ */
18
+ function createFetchHandler(options) {
19
+ const { federation, rootOrigin, serveControlSurface } = options;
20
+ return async (request) => {
21
+ if (!URL.canParse(request.url)) return invalidHost();
22
+ const url = new URL(request.url);
23
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) return invalidHost();
24
+ const host = request.headers.get("host");
25
+ if (host != null && canonicalizeAuthority(host) !== canonicalizeAuthority(url.host)) return invalidHost();
26
+ switch (classifyHost(url, rootOrigin)) {
27
+ case "instance": try {
28
+ return await federation.fetch(restorePublicScheme(request, rootOrigin.protocol), {
29
+ onNotFound: notFound,
30
+ onNotAcceptable: notFound,
31
+ contextData: void 0
32
+ });
33
+ } catch (error) {
34
+ getLogger(["drfed", "serving"]).error("Federation request {method} {path} failed ({errorType}).", {
35
+ method: request.method,
36
+ path: url.pathname,
37
+ errorType: error instanceof Error ? "Error" : typeof error
38
+ });
39
+ return new Response("Internal server error", { status: 500 });
40
+ }
41
+ case "misdirected": return misdirected();
42
+ default: return await serveControlSurface(request);
43
+ }
44
+ };
45
+ }
46
+ /** Compose the exact GraphQL endpoint with an optional embedded web handler.
47
+ * @returns The control handler; federation routing remains outside this layer.
48
+ */
49
+ function createControlSurface(options) {
50
+ return (request) => {
51
+ if (new URL(request.url).pathname === "/graphql") return options.graphql(request);
52
+ return options.web === void 0 ? notFound() : options.web(request);
53
+ };
54
+ }
55
+ const ingress = /* @__PURE__ */ new WeakMap();
56
+ /** Retrieve private ingress metadata for a publicly restored instance request.
57
+ * @returns Original adapter URL and headers for delivery recording, if restored.
58
+ */
59
+ function getIngressMetadata(request) {
60
+ return ingress.get(request);
61
+ }
62
+ function restorePublicScheme(request, protocol) {
63
+ const url = new URL(request.url);
64
+ url.protocol = protocol;
65
+ const headers = new Headers(request.headers);
66
+ const restored = new Request(url, {
67
+ method: request.method,
68
+ headers,
69
+ body: request.body,
70
+ signal: request.signal,
71
+ duplex: "half"
72
+ });
73
+ ingress.set(restored, {
74
+ url: request.url,
75
+ headers: new Headers(request.headers)
76
+ });
77
+ return restored;
78
+ }
79
+ function notFound() {
80
+ return new Response("Not found.", {
81
+ headers: { "content-type": "text/plain; charset=utf-8" },
82
+ status: 404
83
+ });
84
+ }
85
+ function invalidHost() {
86
+ return new Response("Bad request: invalid Host header.", {
87
+ headers: { "content-type": "text/plain; charset=utf-8" },
88
+ status: 400
89
+ });
90
+ }
91
+ function misdirected() {
92
+ return new Response("Misdirected request: this server does not serve that host.", {
93
+ headers: { "content-type": "text/plain; charset=utf-8" },
94
+ status: 421
95
+ });
96
+ }
97
+ /**
98
+ * Finds local instances whose host does not sit one label below the given root
99
+ * origin, which is what happens when a deployment's root origin is changed
100
+ * after instances already exist.
101
+ * @param db The database to look in.
102
+ * @param rootOrigin The configured root origin.
103
+ * @returns The hosts that are no longer reachable, in no particular order.
104
+ */
105
+ async function findStrandedInstances(db, rootOrigin) {
106
+ return (await db.query.instances.findMany({
107
+ columns: { host: true },
108
+ where: { localId: { isNotNull: true } }
109
+ })).map(({ host }) => host).filter((host) => {
110
+ const url = `${rootOrigin.protocol}//${host}`;
111
+ if (!URL.canParse(url)) return true;
112
+ return classifyHost(new URL(url), rootOrigin) !== "instance";
113
+ });
114
+ }
115
+ /**
116
+ * Warns about local instances the configured root origin no longer covers.
117
+ *
118
+ * Nothing is repaired. An instance's host is woven into the actor URIs that
119
+ * the rest of the fediverse has already seen and stored, so rewriting it would
120
+ * break exactly the federation it was meant to fix. Say what is wrong, and
121
+ * leave the decision to a human.
122
+ * @param db The database to look in.
123
+ * @param rootOrigin The configured root origin.
124
+ */
125
+ async function warnAboutStrandedInstances(db, rootOrigin) {
126
+ const stranded = await findStrandedInstances(db, rootOrigin);
127
+ if (stranded.length < 1) return;
128
+ logger.warn("{count} local instance(s) are hosted outside the configured root origin {rootOrigin}, and are no longer reachable: {hosts}. Their actor URIs already name those hosts, so nothing has been changed.", {
129
+ count: stranded.length,
130
+ hosts: stranded,
131
+ rootOrigin: rootOrigin.origin
132
+ });
133
+ }
134
+ const logger = getLogger(["drfed", "instances"]);
135
+ //#endregion
136
+ export { createControlSurface, createFetchHandler, findStrandedInstances, getIngressMetadata, warnAboutStrandedInstances };
137
+
138
+ //# sourceMappingURL=serving.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serving.mjs","names":[],"sources":["../src/serving.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { canonicalizeAuthority, classifyHost } from \"@drfed/federation/origin\";\nimport type { Database } from \"@drfed/models\";\nimport { getLogger } from \"@logtape/logtape\";\n\n/**\n * The federation surface (including the inbound recorder) that the router\n * needs, narrowed so that the routing can be exercised without building one.\n */\nexport interface FederationHandler {\n fetch(\n request: Request,\n options: {\n onNotFound(request: Request): Response | Promise<Response>;\n onNotAcceptable(request: Request): Response | Promise<Response>;\n contextData: undefined;\n },\n ): Promise<Response>;\n}\n\n/**\n * Options for {@link createFetchHandler}.\n */\nexport interface FetchHandlerOptions {\n /**\n * The root origin this deployment serves instances under.\n */\n readonly rootOrigin: URL;\n\n /**\n * The ActivityPub surface with inbox recording, served on instance subdomains.\n */\n readonly federation: FederationHandler;\n\n /**\n * The control surface (GraphQL and optionally web), served everywhere else.\n */\n readonly serveControlSurface: (\n request: Request,\n ) => Response | Promise<Response>;\n}\n\n/**\n * Builds the server's request handler, which decides from the authority alone\n * which of DrFed's two faces answers.\n *\n * An instance's subdomain serves ActivityPub and nothing else, so that a\n * tenant can never reach the control surface; every other authority is the\n * control surface and never answers as an instance. A subdomain nobody has\n * claimed still routes to ActivityPub, where every dispatcher resolves to\n * nothing and the request ends in a 404, which keeps the routing from having\n * to ask the database what exists.\n * @param options The surfaces to route between, and the root origin to route\n * by.\n * @returns A handler suitable for passing to `serve()`.\n */\nexport function createFetchHandler(\n options: FetchHandlerOptions,\n): (request: Request) => Promise<Response> {\n const { federation, rootOrigin, serveControlSurface } = options;\n return async (request: Request): Promise<Response> => {\n // A server adapter may accept a `Host` that `URL` will not. srvx checks\n // it against a structural pattern and builds the request URL by\n // concatenation, so `1.2.3.4.5`, `999.1.1.1` and undecodable A-labels such\n // as `xn--a` all arrive here as URLs that cannot be parsed. Parsing one\n // throws inside this handler, and srvx attaches no rejection handler, so\n // the process would die on a single unauthenticated request.\n if (!URL.canParse(request.url)) return invalidHost();\n const url = new URL(request.url);\n if (\n ![\"http:\", \"https:\"].includes(url.protocol) ||\n url.username ||\n url.password\n ) {\n return invalidHost();\n }\n // An adapter may also substitute something for a `Host` it cannot make\n // sense of rather than refuse the request: srvx uses the literal\n // `_invalid_`, which does parse. Routing on that would quietly hand the\n // control surface to a request that was aiming at a tenant.\n const host = request.headers.get(\"host\");\n if (\n host != null &&\n canonicalizeAuthority(host) !== canonicalizeAuthority(url.host)\n ) {\n return invalidHost();\n }\n switch (classifyHost(url, rootOrigin)) {\n case \"instance\":\n try {\n return await federation.fetch(\n restorePublicScheme(request, rootOrigin.protocol),\n {\n onNotFound: notFound,\n onNotAcceptable: notFound,\n contextData: undefined,\n },\n );\n } catch (error) {\n // Error messages, names and causes can contain private key material.\n getLogger([\"drfed\", \"serving\"]).error(\n \"Federation request {method} {path} failed ({errorType}).\",\n {\n method: request.method,\n path: url.pathname,\n errorType: error instanceof Error ? \"Error\" : typeof error,\n },\n );\n return new Response(\"Internal server error\", { status: 500 });\n }\n case \"misdirected\":\n // Below the root domain but deeper than the single label an instance\n // occupies, so nothing here will ever answer. Saying so is more use\n // to whoever misconfigured the DNS than a bare 404 would be.\n return misdirected();\n default:\n return await serveControlSurface(request);\n }\n };\n}\n\n/** Compose the exact GraphQL endpoint with an optional embedded web handler.\n * @returns The control handler; federation routing remains outside this layer.\n */\nexport function createControlSurface(options: {\n readonly graphql: (request: Request) => Response | Promise<Response>;\n readonly web?: (request: Request) => Response | Promise<Response>;\n}): (request: Request) => Response | Promise<Response> {\n return (request) => {\n if (new URL(request.url).pathname === \"/graphql\") {\n return options.graphql(request);\n }\n return options.web === undefined ? notFound() : options.web(request);\n };\n}\n\nconst ingress = new WeakMap<\n Request,\n { readonly url: string; readonly headers: Headers }\n>();\n\n/** Retrieve private ingress metadata for a publicly restored instance request.\n * @returns Original adapter URL and headers for delivery recording, if restored.\n */\nexport function getIngressMetadata(\n request: Request,\n): { readonly url: string; readonly headers: Headers } | undefined {\n return ingress.get(request);\n}\n\nfunction restorePublicScheme(request: Request, protocol: string): Request {\n const url = new URL(request.url);\n url.protocol = protocol;\n const headers = new Headers(request.headers);\n const restored = new Request(url, {\n method: request.method,\n headers,\n body: request.body,\n signal: request.signal,\n duplex: \"half\",\n } as RequestInit & { duplex: \"half\" });\n ingress.set(restored, {\n url: request.url,\n headers: new Headers(request.headers),\n });\n return restored;\n}\n\nfunction notFound(): Response {\n return new Response(\"Not found.\", {\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n status: 404,\n });\n}\n\nfunction invalidHost(): Response {\n // RFC 9110 section 7.2 asks for 400 when the Host field value is invalid,\n // which covers both a host `URL` rejects and one the adapter replaced.\n return new Response(\"Bad request: invalid Host header.\", {\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n status: 400,\n });\n}\n\nfunction misdirected(): Response {\n return new Response(\n \"Misdirected request: this server does not serve that host.\",\n {\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n status: 421,\n },\n );\n}\n\n/**\n * Finds local instances whose host does not sit one label below the given root\n * origin, which is what happens when a deployment's root origin is changed\n * after instances already exist.\n * @param db The database to look in.\n * @param rootOrigin The configured root origin.\n * @returns The hosts that are no longer reachable, in no particular order.\n */\nexport async function findStrandedInstances(\n db: Database,\n rootOrigin: URL,\n): Promise<string[]> {\n const instances = await db.query.instances.findMany({\n columns: { host: true },\n where: { localId: { isNotNull: true } },\n });\n return instances\n .map(({ host }) => host)\n .filter((host) => {\n // A stored host need not be a parseable authority at all: an older,\n // laxer rule may have let one through, and whether a given host parses\n // can even move with the runtime's ICU. A startup check is the last\n // place that should throw over it.\n const url = `${rootOrigin.protocol}//${host}`;\n if (!URL.canParse(url)) return true;\n return classifyHost(new URL(url), rootOrigin) !== \"instance\";\n });\n}\n\n/**\n * Warns about local instances the configured root origin no longer covers.\n *\n * Nothing is repaired. An instance's host is woven into the actor URIs that\n * the rest of the fediverse has already seen and stored, so rewriting it would\n * break exactly the federation it was meant to fix. Say what is wrong, and\n * leave the decision to a human.\n * @param db The database to look in.\n * @param rootOrigin The configured root origin.\n */\nexport async function warnAboutStrandedInstances(\n db: Database,\n rootOrigin: URL,\n): Promise<void> {\n const stranded = await findStrandedInstances(db, rootOrigin);\n if (stranded.length < 1) return;\n logger.warn(\n \"{count} local instance(s) are hosted outside the configured root \" +\n \"origin {rootOrigin}, and are no longer reachable: {hosts}. Their \" +\n \"actor URIs already name those hosts, so nothing has been changed.\",\n { count: stranded.length, hosts: stranded, rootOrigin: rootOrigin.origin },\n );\n}\n\nconst logger = getLogger([\"drfed\", \"instances\"]);\n"],"mappings":";;;;;;;;;;;;;;;;;AAuEA,SAAgB,mBACd,SACyC;CACzC,MAAM,EAAE,YAAY,YAAY,wBAAwB;CACxD,OAAO,OAAO,YAAwC;EAOpD,IAAI,CAAC,IAAI,SAAS,QAAQ,GAAG,GAAG,OAAO,YAAY;EACnD,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;EAC/B,IACE,CAAC,CAAC,SAAS,QAAQ,CAAC,CAAC,SAAS,IAAI,QAAQ,KAC1C,IAAI,YACJ,IAAI,UAEJ,OAAO,YAAY;EAMrB,MAAM,OAAO,QAAQ,QAAQ,IAAI,MAAM;EACvC,IACE,QAAQ,QACR,sBAAsB,IAAI,MAAM,sBAAsB,IAAI,IAAI,GAE9D,OAAO,YAAY;EAErB,QAAQ,aAAa,KAAK,UAAU,GAApC;GACE,KAAK,YACH,IAAI;IACF,OAAO,MAAM,WAAW,MACtB,oBAAoB,SAAS,WAAW,QAAQ,GAChD;KACE,YAAY;KACZ,iBAAiB;KACjB,aAAa,KAAA;IACf,CACF;GACF,SAAS,OAAO;IAEd,UAAU,CAAC,SAAS,SAAS,CAAC,CAAC,CAAC,MAC9B,4DACA;KACE,QAAQ,QAAQ;KAChB,MAAM,IAAI;KACV,WAAW,iBAAiB,QAAQ,UAAU,OAAO;IACvD,CACF;IACA,OAAO,IAAI,SAAS,yBAAyB,EAAE,QAAQ,IAAI,CAAC;GAC9D;GACF,KAAK,eAIH,OAAO,YAAY;GACrB,SACE,OAAO,MAAM,oBAAoB,OAAO;EAC5C;CACF;AACF;;;;AAKA,SAAgB,qBAAqB,SAGkB;CACrD,QAAQ,YAAY;EAClB,IAAI,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC,aAAa,YACpC,OAAO,QAAQ,QAAQ,OAAO;EAEhC,OAAO,QAAQ,QAAQ,KAAA,IAAY,SAAS,IAAI,QAAQ,IAAI,OAAO;CACrE;AACF;AAEA,MAAM,0BAAU,IAAI,QAGlB;;;;AAKF,SAAgB,mBACd,SACiE;CACjE,OAAO,QAAQ,IAAI,OAAO;AAC5B;AAEA,SAAS,oBAAoB,SAAkB,UAA2B;CACxE,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;CAC/B,IAAI,WAAW;CACf,MAAM,UAAU,IAAI,QAAQ,QAAQ,OAAO;CAC3C,MAAM,WAAW,IAAI,QAAQ,KAAK;EAChC,QAAQ,QAAQ;EAChB;EACA,MAAM,QAAQ;EACd,QAAQ,QAAQ;EAChB,QAAQ;CACV,CAAqC;CACrC,QAAQ,IAAI,UAAU;EACpB,KAAK,QAAQ;EACb,SAAS,IAAI,QAAQ,QAAQ,OAAO;CACtC,CAAC;CACD,OAAO;AACT;AAEA,SAAS,WAAqB;CAC5B,OAAO,IAAI,SAAS,cAAc;EAChC,SAAS,EAAE,gBAAgB,4BAA4B;EACvD,QAAQ;CACV,CAAC;AACH;AAEA,SAAS,cAAwB;CAG/B,OAAO,IAAI,SAAS,qCAAqC;EACvD,SAAS,EAAE,gBAAgB,4BAA4B;EACvD,QAAQ;CACV,CAAC;AACH;AAEA,SAAS,cAAwB;CAC/B,OAAO,IAAI,SACT,8DACA;EACE,SAAS,EAAE,gBAAgB,4BAA4B;EACvD,QAAQ;CACV,CACF;AACF;;;;;;;;;AAUA,eAAsB,sBACpB,IACA,YACmB;CAKnB,QAAO,MAJiB,GAAG,MAAM,UAAU,SAAS;EAClD,SAAS,EAAE,MAAM,KAAK;EACtB,OAAO,EAAE,SAAS,EAAE,WAAW,KAAK,EAAE;CACxC,CAAC,EAAA,CAEE,KAAK,EAAE,WAAW,IAAI,CAAC,CACvB,QAAQ,SAAS;EAKhB,MAAM,MAAM,GAAG,WAAW,SAAS,IAAI;EACvC,IAAI,CAAC,IAAI,SAAS,GAAG,GAAG,OAAO;EAC/B,OAAO,aAAa,IAAI,IAAI,GAAG,GAAG,UAAU,MAAM;CACpD,CAAC;AACL;;;;;;;;;;;AAYA,eAAsB,2BACpB,IACA,YACe;CACf,MAAM,WAAW,MAAM,sBAAsB,IAAI,UAAU;CAC3D,IAAI,SAAS,SAAS,GAAG;CACzB,OAAO,KACL,wMAGA;EAAE,OAAO,SAAS;EAAQ,OAAO;EAAU,YAAY,WAAW;CAAO,CAC3E;AACF;AAEA,MAAM,SAAS,UAAU,CAAC,SAAS,WAAW,CAAC"}
@@ -0,0 +1,11 @@
1
+ import { SmtpConfig } from "@upyo/smtp";
2
+ //#region src/smtp-settings.d.ts
3
+ /**
4
+ * Normalize an SMTP URL without opening a connection or exposing credentials.
5
+ * Authentication on smtp: requires STARTTLS; smtps: uses implicit TLS.
6
+ * @returns Explicit Upyo settings with certificate verification enabled.
7
+ */
8
+ declare function resolveSmtpConnection(value: URL): SmtpConfig;
9
+ //#endregion
10
+ export { resolveSmtpConnection };
11
+ //# sourceMappingURL=smtp-settings.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smtp-settings.d.mts","names":[],"sources":["../src/smtp-settings.ts"],"mappings":";;;;;;;iBAuBgB,sBAAsB,OAAO,MAAM"}
@@ -0,0 +1,38 @@
1
+ //#region src/smtp-settings.ts
2
+ /**
3
+ * Normalize an SMTP URL without opening a connection or exposing credentials.
4
+ * Authentication on smtp: requires STARTTLS; smtps: uses implicit TLS.
5
+ * @returns Explicit Upyo settings with certificate verification enabled.
6
+ */
7
+ function resolveSmtpConnection(value) {
8
+ if (!["smtp:", "smtps:"].includes(value.protocol) || value.hostname === "" || value.pathname !== "" && value.pathname !== "/" || value.search !== "" || value.hash !== "") throw new Error("Invalid SMTP connection URL.");
9
+ try {
10
+ const host = new URL(`http://${value.host}`).hostname;
11
+ const user = decodeURIComponent(value.username);
12
+ const pass = decodeURIComponent(value.password);
13
+ if (pass !== "" && user === "" || /[^\x20-\x7e]/u.test(user) || /[^\x20-\x7e]/u.test(pass)) throw new Error();
14
+ const port = value.port === "" ? value.protocol === "smtps:" ? 465 : 587 : Number(value.port);
15
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error();
16
+ const secure = value.protocol === "smtps:";
17
+ return {
18
+ host: host.startsWith("[") ? host.slice(1, -1) : host,
19
+ port,
20
+ secure,
21
+ requireTls: !secure && user !== "",
22
+ ...user === "" ? {} : { auth: {
23
+ user,
24
+ pass
25
+ } },
26
+ tls: {
27
+ rejectUnauthorized: true,
28
+ minVersion: "TLSv1.2"
29
+ }
30
+ };
31
+ } catch {
32
+ throw new Error("Invalid SMTP connection URL.");
33
+ }
34
+ }
35
+ //#endregion
36
+ export { resolveSmtpConnection };
37
+
38
+ //# sourceMappingURL=smtp-settings.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"smtp-settings.mjs","names":[],"sources":["../src/smtp-settings.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport type { SmtpConfig } from \"@upyo/smtp\";\n\n/**\n * Normalize an SMTP URL without opening a connection or exposing credentials.\n * Authentication on smtp: requires STARTTLS; smtps: uses implicit TLS.\n * @returns Explicit Upyo settings with certificate verification enabled.\n */\nexport function resolveSmtpConnection(value: URL): SmtpConfig {\n if (\n ![\"smtp:\", \"smtps:\"].includes(value.protocol) ||\n value.hostname === \"\" ||\n (value.pathname !== \"\" && value.pathname !== \"/\") ||\n value.search !== \"\" ||\n value.hash !== \"\"\n ) {\n throw new Error(\"Invalid SMTP connection URL.\");\n }\n try {\n const host = new URL(`http://${value.host}`).hostname;\n const user = decodeURIComponent(value.username);\n const pass = decodeURIComponent(value.password);\n if (\n (pass !== \"\" && user === \"\") ||\n /[^\\x20-\\x7e]/u.test(user) ||\n /[^\\x20-\\x7e]/u.test(pass)\n ) {\n throw new Error();\n }\n const port =\n value.port === \"\"\n ? value.protocol === \"smtps:\"\n ? 465\n : 587\n : Number(value.port);\n if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error();\n const secure = value.protocol === \"smtps:\";\n return {\n host: host.startsWith(\"[\") ? host.slice(1, -1) : host,\n port,\n secure,\n requireTls: !secure && user !== \"\",\n ...(user === \"\" ? {} : { auth: { user, pass } }),\n tls: { rejectUnauthorized: true, minVersion: \"TLSv1.2\" },\n };\n } catch {\n throw new Error(\"Invalid SMTP connection URL.\");\n }\n}\n"],"mappings":";;;;;;AAuBA,SAAgB,sBAAsB,OAAwB;CAC5D,IACE,CAAC,CAAC,SAAS,QAAQ,CAAC,CAAC,SAAS,MAAM,QAAQ,KAC5C,MAAM,aAAa,MAClB,MAAM,aAAa,MAAM,MAAM,aAAa,OAC7C,MAAM,WAAW,MACjB,MAAM,SAAS,IAEf,MAAM,IAAI,MAAM,8BAA8B;CAEhD,IAAI;EACF,MAAM,OAAO,IAAI,IAAI,UAAU,MAAM,MAAM,CAAC,CAAC;EAC7C,MAAM,OAAO,mBAAmB,MAAM,QAAQ;EAC9C,MAAM,OAAO,mBAAmB,MAAM,QAAQ;EAC9C,IACG,SAAS,MAAM,SAAS,MACzB,gBAAgB,KAAK,IAAI,KACzB,gBAAgB,KAAK,IAAI,GAEzB,MAAM,IAAI,MAAM;EAElB,MAAM,OACJ,MAAM,SAAS,KACX,MAAM,aAAa,WACjB,MACA,MACF,OAAO,MAAM,IAAI;EACvB,IAAI,CAAC,OAAO,UAAU,IAAI,KAAK,OAAO,KAAK,OAAO,OAAO,MAAM,IAAI,MAAM;EACzE,MAAM,SAAS,MAAM,aAAa;EAClC,OAAO;GACL,MAAM,KAAK,WAAW,GAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;GACjD;GACA;GACA,YAAY,CAAC,UAAU,SAAS;GAChC,GAAI,SAAS,KAAK,CAAC,IAAI,EAAE,MAAM;IAAE;IAAM;GAAK,EAAE;GAC9C,KAAK;IAAE,oBAAoB;IAAM,YAAY;GAAU;EACzD;CACF,QAAQ;EACN,MAAM,IAAI,MAAM,8BAA8B;CAChD;AACF"}