@aglyn/tenant-data-admin 1.0.0-beta.143

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 (374) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +7 -0
  3. package/jest.integration.config.d.ts +39 -0
  4. package/jest.integration.setup.d.ts +17 -0
  5. package/package.json +51 -0
  6. package/src/index.d.ts +17 -0
  7. package/src/index.js +18 -0
  8. package/src/index.js.map +1 -0
  9. package/src/lib/render-cache.d.ts +184 -0
  10. package/src/lib/render-cache.js +198 -0
  11. package/src/lib/render-cache.js.map +1 -0
  12. package/src/lib/server/account-addresses.d.ts +160 -0
  13. package/src/lib/server/account-addresses.js +311 -0
  14. package/src/lib/server/account-addresses.js.map +1 -0
  15. package/src/lib/server/account-emails.d.ts +219 -0
  16. package/src/lib/server/account-emails.js +640 -0
  17. package/src/lib/server/account-emails.js.map +1 -0
  18. package/src/lib/server/admin-audit.d.ts +180 -0
  19. package/src/lib/server/admin-audit.js +233 -0
  20. package/src/lib/server/admin-audit.js.map +1 -0
  21. package/src/lib/server/analytics-retention.d.ts +63 -0
  22. package/src/lib/server/analytics-retention.js +66 -0
  23. package/src/lib/server/analytics-retention.js.map +1 -0
  24. package/src/lib/server/api-http.d.ts +159 -0
  25. package/src/lib/server/api-http.js +230 -0
  26. package/src/lib/server/api-http.js.map +1 -0
  27. package/src/lib/server/api-keys.d.ts +117 -0
  28. package/src/lib/server/api-keys.js +298 -0
  29. package/src/lib/server/api-keys.js.map +1 -0
  30. package/src/lib/server/auth-handoff.d.ts +165 -0
  31. package/src/lib/server/auth-handoff.js +482 -0
  32. package/src/lib/server/auth-handoff.js.map +1 -0
  33. package/src/lib/server/auth-pools.d.ts +246 -0
  34. package/src/lib/server/auth-pools.js +551 -0
  35. package/src/lib/server/auth-pools.js.map +1 -0
  36. package/src/lib/server/billing-addons.d.ts +171 -0
  37. package/src/lib/server/billing-addons.js +277 -0
  38. package/src/lib/server/billing-addons.js.map +1 -0
  39. package/src/lib/server/campaign-attribution-store.d.ts +55 -0
  40. package/src/lib/server/campaign-attribution-store.js +95 -0
  41. package/src/lib/server/campaign-attribution-store.js.map +1 -0
  42. package/src/lib/server/campaign-conversion-attribution.d.ts +205 -0
  43. package/src/lib/server/campaign-conversion-attribution.js +279 -0
  44. package/src/lib/server/campaign-conversion-attribution.js.map +1 -0
  45. package/src/lib/server/client-error-report.d.ts +301 -0
  46. package/src/lib/server/client-error-report.js +755 -0
  47. package/src/lib/server/client-error-report.js.map +1 -0
  48. package/src/lib/server/connect-account-status.d.ts +74 -0
  49. package/src/lib/server/connect-account-status.js +94 -0
  50. package/src/lib/server/connect-account-status.js.map +1 -0
  51. package/src/lib/server/connect-payout-failure.d.ts +103 -0
  52. package/src/lib/server/connect-payout-failure.js +127 -0
  53. package/src/lib/server/connect-payout-failure.js.map +1 -0
  54. package/src/lib/server/console-api-rate-limit.d.ts +81 -0
  55. package/src/lib/server/console-api-rate-limit.js +111 -0
  56. package/src/lib/server/console-api-rate-limit.js.map +1 -0
  57. package/src/lib/server/console-domains.d.ts +326 -0
  58. package/src/lib/server/console-domains.js +779 -0
  59. package/src/lib/server/console-domains.js.map +1 -0
  60. package/src/lib/server/consume-once.d.ts +91 -0
  61. package/src/lib/server/consume-once.js +96 -0
  62. package/src/lib/server/consume-once.js.map +1 -0
  63. package/src/lib/server/contact-company-link.d.ts +85 -0
  64. package/src/lib/server/contact-company-link.js +105 -0
  65. package/src/lib/server/contact-company-link.js.map +1 -0
  66. package/src/lib/server/contact-email-engagement.d.ts +32 -0
  67. package/src/lib/server/contact-email-engagement.js +145 -0
  68. package/src/lib/server/contact-email-engagement.js.map +1 -0
  69. package/src/lib/server/contact-email-index.d.ts +56 -0
  70. package/src/lib/server/contact-email-index.js +158 -0
  71. package/src/lib/server/contact-email-index.js.map +1 -0
  72. package/src/lib/server/contact-lifecycle-floor.d.ts +89 -0
  73. package/src/lib/server/contact-lifecycle-floor.js +88 -0
  74. package/src/lib/server/contact-lifecycle-floor.js.map +1 -0
  75. package/src/lib/server/contact-merge.d.ts +55 -0
  76. package/src/lib/server/contact-merge.js +279 -0
  77. package/src/lib/server/contact-merge.js.map +1 -0
  78. package/src/lib/server/contact-suppression.d.ts +153 -0
  79. package/src/lib/server/contact-suppression.js +259 -0
  80. package/src/lib/server/contact-suppression.js.map +1 -0
  81. package/src/lib/server/crm-booking-activity.d.ts +86 -0
  82. package/src/lib/server/crm-booking-activity.js +251 -0
  83. package/src/lib/server/crm-booking-activity.js.map +1 -0
  84. package/src/lib/server/crm-email-activity.d.ts +112 -0
  85. package/src/lib/server/crm-email-activity.js +143 -0
  86. package/src/lib/server/crm-email-activity.js.map +1 -0
  87. package/src/lib/server/crm-inbound-email.d.ts +145 -0
  88. package/src/lib/server/crm-inbound-email.js +287 -0
  89. package/src/lib/server/crm-inbound-email.js.map +1 -0
  90. package/src/lib/server/crm-next-activity.d.ts +74 -0
  91. package/src/lib/server/crm-next-activity.js +194 -0
  92. package/src/lib/server/crm-next-activity.js.map +1 -0
  93. package/src/lib/server/crm-records.d.ts +144 -0
  94. package/src/lib/server/crm-records.js +218 -0
  95. package/src/lib/server/crm-records.js.map +1 -0
  96. package/src/lib/server/csp-aggregate.d.ts +62 -0
  97. package/src/lib/server/csp-aggregate.js +276 -0
  98. package/src/lib/server/csp-aggregate.js.map +1 -0
  99. package/src/lib/server/data-storage-gate.d.ts +66 -0
  100. package/src/lib/server/data-storage-gate.js +48 -0
  101. package/src/lib/server/data-storage-gate.js.map +1 -0
  102. package/src/lib/server/dataset-live-pages.d.ts +179 -0
  103. package/src/lib/server/dataset-live-pages.js +421 -0
  104. package/src/lib/server/dataset-live-pages.js.map +1 -0
  105. package/src/lib/server/dns-probe.d.ts +53 -0
  106. package/src/lib/server/dns-probe.js +184 -0
  107. package/src/lib/server/dns-probe.js.map +1 -0
  108. package/src/lib/server/document-id.d.ts +29 -0
  109. package/src/lib/server/document-id.js +100 -0
  110. package/src/lib/server/document-id.js.map +1 -0
  111. package/src/lib/server/domain-provider-vercel.d.ts +33 -0
  112. package/src/lib/server/domain-provider-vercel.js +298 -0
  113. package/src/lib/server/domain-provider-vercel.js.map +1 -0
  114. package/src/lib/server/domain-provider-webhook.d.ts +73 -0
  115. package/src/lib/server/domain-provider-webhook.js +223 -0
  116. package/src/lib/server/domain-provider-webhook.js.map +1 -0
  117. package/src/lib/server/domain-provider-wildcard.d.ts +54 -0
  118. package/src/lib/server/domain-provider-wildcard.js +163 -0
  119. package/src/lib/server/domain-provider-wildcard.js.map +1 -0
  120. package/src/lib/server/domain-provider.d.ts +197 -0
  121. package/src/lib/server/domain-provider.js +221 -0
  122. package/src/lib/server/domain-provider.js.map +1 -0
  123. package/src/lib/server/duplicate-activity.d.ts +54 -0
  124. package/src/lib/server/duplicate-activity.js +67 -0
  125. package/src/lib/server/duplicate-activity.js.map +1 -0
  126. package/src/lib/server/duplicate-resource.d.ts +55 -0
  127. package/src/lib/server/duplicate-resource.js +474 -0
  128. package/src/lib/server/duplicate-resource.js.map +1 -0
  129. package/src/lib/server/dynamic-list-materialize.d.ts +153 -0
  130. package/src/lib/server/dynamic-list-materialize.js +581 -0
  131. package/src/lib/server/dynamic-list-materialize.js.map +1 -0
  132. package/src/lib/server/edit-access-authz.d.ts +56 -0
  133. package/src/lib/server/edit-access-authz.js +107 -0
  134. package/src/lib/server/edit-access-authz.js.map +1 -0
  135. package/src/lib/server/edit-access-token.d.ts +72 -0
  136. package/src/lib/server/edit-access-token.js +116 -0
  137. package/src/lib/server/edit-access-token.js.map +1 -0
  138. package/src/lib/server/edit-hint-token.d.ts +83 -0
  139. package/src/lib/server/edit-hint-token.js +119 -0
  140. package/src/lib/server/edit-hint-token.js.map +1 -0
  141. package/src/lib/server/email-delivery-log.d.ts +509 -0
  142. package/src/lib/server/email-delivery-log.js +1043 -0
  143. package/src/lib/server/email-delivery-log.js.map +1 -0
  144. package/src/lib/server/email-flow-gate.d.ts +80 -0
  145. package/src/lib/server/email-flow-gate.js +153 -0
  146. package/src/lib/server/email-flow-gate.js.map +1 -0
  147. package/src/lib/server/email-marketing-gate.d.ts +333 -0
  148. package/src/lib/server/email-marketing-gate.js +639 -0
  149. package/src/lib/server/email-marketing-gate.js.map +1 -0
  150. package/src/lib/server/email-metering.d.ts +293 -0
  151. package/src/lib/server/email-metering.js +359 -0
  152. package/src/lib/server/email-metering.js.map +1 -0
  153. package/src/lib/server/email-revenue-attribution.d.ts +185 -0
  154. package/src/lib/server/email-revenue-attribution.js +300 -0
  155. package/src/lib/server/email-revenue-attribution.js.map +1 -0
  156. package/src/lib/server/email-send-rate.d.ts +232 -0
  157. package/src/lib/server/email-send-rate.js +417 -0
  158. package/src/lib/server/email-send-rate.js.map +1 -0
  159. package/src/lib/server/email-sender-reputation.d.ts +317 -0
  160. package/src/lib/server/email-sender-reputation.js +464 -0
  161. package/src/lib/server/email-sender-reputation.js.map +1 -0
  162. package/src/lib/server/email-suppression.d.ts +490 -0
  163. package/src/lib/server/email-suppression.js +648 -0
  164. package/src/lib/server/email-suppression.js.map +1 -0
  165. package/src/lib/server/email-topic-confirmation.d.ts +150 -0
  166. package/src/lib/server/email-topic-confirmation.js +272 -0
  167. package/src/lib/server/email-topic-confirmation.js.map +1 -0
  168. package/src/lib/server/email-unsubscribe-link.d.ts +174 -0
  169. package/src/lib/server/email-unsubscribe-link.js +236 -0
  170. package/src/lib/server/email-unsubscribe-link.js.map +1 -0
  171. package/src/lib/server/erase-person.d.ts +116 -0
  172. package/src/lib/server/erase-person.js +272 -0
  173. package/src/lib/server/erase-person.js.map +1 -0
  174. package/src/lib/server/erase.d.ts +458 -0
  175. package/src/lib/server/erase.js +1506 -0
  176. package/src/lib/server/erase.js.map +1 -0
  177. package/src/lib/server/firebase-admin.d.ts +71 -0
  178. package/src/lib/server/firebase-admin.js +343 -0
  179. package/src/lib/server/firebase-admin.js.map +1 -0
  180. package/src/lib/server/form-dataset-binding-token.d.ts +35 -0
  181. package/src/lib/server/form-dataset-binding-token.js +107 -0
  182. package/src/lib/server/form-dataset-binding-token.js.map +1 -0
  183. package/src/lib/server/free-workspace-cap.d.ts +201 -0
  184. package/src/lib/server/free-workspace-cap.js +404 -0
  185. package/src/lib/server/free-workspace-cap.js.map +1 -0
  186. package/src/lib/server/ga4-measurement-protocol.d.ts +256 -0
  187. package/src/lib/server/ga4-measurement-protocol.js +558 -0
  188. package/src/lib/server/ga4-measurement-protocol.js.map +1 -0
  189. package/src/lib/server/host-email-tokens.d.ts +47 -0
  190. package/src/lib/server/host-email-tokens.js +72 -0
  191. package/src/lib/server/host-email-tokens.js.map +1 -0
  192. package/src/lib/server/host-memberships.d.ts +54 -0
  193. package/src/lib/server/host-memberships.js +194 -0
  194. package/src/lib/server/host-memberships.js.map +1 -0
  195. package/src/lib/server/host-sending-domain.d.ts +292 -0
  196. package/src/lib/server/host-sending-domain.js +451 -0
  197. package/src/lib/server/host-sending-domain.js.map +1 -0
  198. package/src/lib/server/host-visitor-records.d.ts +150 -0
  199. package/src/lib/server/host-visitor-records.js +262 -0
  200. package/src/lib/server/host-visitor-records.js.map +1 -0
  201. package/src/lib/server/id-token-refusal.d.ts +28 -0
  202. package/src/lib/server/id-token-refusal.js +111 -0
  203. package/src/lib/server/id-token-refusal.js.map +1 -0
  204. package/src/lib/server/legal-acceptance.d.ts +214 -0
  205. package/src/lib/server/legal-acceptance.js +305 -0
  206. package/src/lib/server/legal-acceptance.js.map +1 -0
  207. package/src/lib/server/list-members.d.ts +211 -0
  208. package/src/lib/server/list-members.js +176 -0
  209. package/src/lib/server/list-members.js.map +1 -0
  210. package/src/lib/server/live-page-usage.d.ts +202 -0
  211. package/src/lib/server/live-page-usage.js +300 -0
  212. package/src/lib/server/live-page-usage.js.map +1 -0
  213. package/src/lib/server/lockdown.d.ts +313 -0
  214. package/src/lib/server/lockdown.js +643 -0
  215. package/src/lib/server/lockdown.js.map +1 -0
  216. package/src/lib/server/media-cdn-rate-limit.d.ts +188 -0
  217. package/src/lib/server/media-cdn-rate-limit.js +204 -0
  218. package/src/lib/server/media-cdn-rate-limit.js.map +1 -0
  219. package/src/lib/server/media-delivery.d.ts +267 -0
  220. package/src/lib/server/media-delivery.js +485 -0
  221. package/src/lib/server/media-delivery.js.map +1 -0
  222. package/src/lib/server/media-download-tokens.d.ts +161 -0
  223. package/src/lib/server/media-download-tokens.js +386 -0
  224. package/src/lib/server/media-download-tokens.js.map +1 -0
  225. package/src/lib/server/media-quarantine.d.ts +127 -0
  226. package/src/lib/server/media-quarantine.js +170 -0
  227. package/src/lib/server/media-quarantine.js.map +1 -0
  228. package/src/lib/server/media-signing.d.ts +126 -0
  229. package/src/lib/server/media-signing.js +159 -0
  230. package/src/lib/server/media-signing.js.map +1 -0
  231. package/src/lib/server/media-storage-path.d.ts +96 -0
  232. package/src/lib/server/media-storage-path.js +111 -0
  233. package/src/lib/server/media-storage-path.js.map +1 -0
  234. package/src/lib/server/media-strong-digest.d.ts +85 -0
  235. package/src/lib/server/media-strong-digest.js +190 -0
  236. package/src/lib/server/media-strong-digest.js.map +1 -0
  237. package/src/lib/server/media-tombstone.d.ts +276 -0
  238. package/src/lib/server/media-tombstone.js +421 -0
  239. package/src/lib/server/media-tombstone.js.map +1 -0
  240. package/src/lib/server/media-variants.d.ts +309 -0
  241. package/src/lib/server/media-variants.js +428 -0
  242. package/src/lib/server/media-variants.js.map +1 -0
  243. package/src/lib/server/member-email-aliases.d.ts +180 -0
  244. package/src/lib/server/member-email-aliases.js +420 -0
  245. package/src/lib/server/member-email-aliases.js.map +1 -0
  246. package/src/lib/server/member-photo.d.ts +88 -0
  247. package/src/lib/server/member-photo.js +185 -0
  248. package/src/lib/server/member-photo.js.map +1 -0
  249. package/src/lib/server/membership-recover-throttle.d.ts +211 -0
  250. package/src/lib/server/membership-recover-throttle.js +231 -0
  251. package/src/lib/server/membership-recover-throttle.js.map +1 -0
  252. package/src/lib/server/notifications.d.ts +55 -0
  253. package/src/lib/server/notifications.js +134 -0
  254. package/src/lib/server/notifications.js.map +1 -0
  255. package/src/lib/server/org-billing.d.ts +97 -0
  256. package/src/lib/server/org-billing.js +236 -0
  257. package/src/lib/server/org-billing.js.map +1 -0
  258. package/src/lib/server/organizations.d.ts +837 -0
  259. package/src/lib/server/organizations.js +1814 -0
  260. package/src/lib/server/organizations.js.map +1 -0
  261. package/src/lib/server/password-reset-throttle.d.ts +84 -0
  262. package/src/lib/server/password-reset-throttle.js +102 -0
  263. package/src/lib/server/password-reset-throttle.js.map +1 -0
  264. package/src/lib/server/personal-data-export.d.ts +241 -0
  265. package/src/lib/server/personal-data-export.js +858 -0
  266. package/src/lib/server/personal-data-export.js.map +1 -0
  267. package/src/lib/server/platform-domain-names.d.ts +62 -0
  268. package/src/lib/server/platform-domain-names.js +197 -0
  269. package/src/lib/server/platform-domain-names.js.map +1 -0
  270. package/src/lib/server/platform-marketing-consent.d.ts +133 -0
  271. package/src/lib/server/platform-marketing-consent.js +209 -0
  272. package/src/lib/server/platform-marketing-consent.js.map +1 -0
  273. package/src/lib/server/rate-limit-store.d.ts +702 -0
  274. package/src/lib/server/rate-limit-store.js +1220 -0
  275. package/src/lib/server/rate-limit-store.js.map +1 -0
  276. package/src/lib/server/realm-plugins.d.ts +67 -0
  277. package/src/lib/server/realm-plugins.js +250 -0
  278. package/src/lib/server/realm-plugins.js.map +1 -0
  279. package/src/lib/server/recaptcha-allowlist.d.ts +90 -0
  280. package/src/lib/server/recaptcha-allowlist.js +409 -0
  281. package/src/lib/server/recaptcha-allowlist.js.map +1 -0
  282. package/src/lib/server/release-flags.d.ts +105 -0
  283. package/src/lib/server/release-flags.js +183 -0
  284. package/src/lib/server/release-flags.js.map +1 -0
  285. package/src/lib/server/replay-erasures.d.ts +126 -0
  286. package/src/lib/server/replay-erasures.js +217 -0
  287. package/src/lib/server/replay-erasures.js.map +1 -0
  288. package/src/lib/server/resolve-people.d.ts +66 -0
  289. package/src/lib/server/resolve-people.js +112 -0
  290. package/src/lib/server/resolve-people.js.map +1 -0
  291. package/src/lib/server/safe-equal.d.ts +45 -0
  292. package/src/lib/server/safe-equal.js +58 -0
  293. package/src/lib/server/safe-equal.js.map +1 -0
  294. package/src/lib/server/sending-domain-debt.d.ts +127 -0
  295. package/src/lib/server/sending-domain-debt.js +268 -0
  296. package/src/lib/server/sending-domain-debt.js.map +1 -0
  297. package/src/lib/server/sending-domain-recheck.d.ts +151 -0
  298. package/src/lib/server/sending-domain-recheck.js +253 -0
  299. package/src/lib/server/sending-domain-recheck.js.map +1 -0
  300. package/src/lib/server/sending-domains.d.ts +364 -0
  301. package/src/lib/server/sending-domains.js +683 -0
  302. package/src/lib/server/sending-domains.js.map +1 -0
  303. package/src/lib/server/serve-media-cdn.d.ts +433 -0
  304. package/src/lib/server/serve-media-cdn.js +1370 -0
  305. package/src/lib/server/serve-media-cdn.js.map +1 -0
  306. package/src/lib/server/serve-plugin-fetch.d.ts +61 -0
  307. package/src/lib/server/serve-plugin-fetch.js +294 -0
  308. package/src/lib/server/serve-plugin-fetch.js.map +1 -0
  309. package/src/lib/server/sms-keywords.d.ts +63 -0
  310. package/src/lib/server/sms-keywords.js +146 -0
  311. package/src/lib/server/sms-keywords.js.map +1 -0
  312. package/src/lib/server/sso-break-glass-owners.d.ts +91 -0
  313. package/src/lib/server/sso-break-glass-owners.js +227 -0
  314. package/src/lib/server/sso-break-glass-owners.js.map +1 -0
  315. package/src/lib/server/sso-domain-policy.d.ts +140 -0
  316. package/src/lib/server/sso-domain-policy.js +239 -0
  317. package/src/lib/server/sso-domain-policy.js.map +1 -0
  318. package/src/lib/server/sso-drift-logic.d.ts +106 -0
  319. package/src/lib/server/sso-drift-logic.js +95 -0
  320. package/src/lib/server/sso-drift-logic.js.map +1 -0
  321. package/src/lib/server/sso-enforcement.d.ts +204 -0
  322. package/src/lib/server/sso-enforcement.js +309 -0
  323. package/src/lib/server/sso-enforcement.js.map +1 -0
  324. package/src/lib/server/sso-provisioning.d.ts +320 -0
  325. package/src/lib/server/sso-provisioning.js +715 -0
  326. package/src/lib/server/sso-provisioning.js.map +1 -0
  327. package/src/lib/server/staff-alert-email.d.ts +41 -0
  328. package/src/lib/server/staff-alert-email.js +63 -0
  329. package/src/lib/server/staff-alert-email.js.map +1 -0
  330. package/src/lib/server/stripe-account-mode.d.ts +156 -0
  331. package/src/lib/server/stripe-account-mode.js +162 -0
  332. package/src/lib/server/stripe-account-mode.js.map +1 -0
  333. package/src/lib/server/tenant-write-lockdown.d.ts +131 -0
  334. package/src/lib/server/tenant-write-lockdown.js +176 -0
  335. package/src/lib/server/tenant-write-lockdown.js.map +1 -0
  336. package/src/lib/server/test-firestore.d.ts +45 -0
  337. package/src/lib/server/test-firestore.js +124 -0
  338. package/src/lib/server/test-firestore.js.map +1 -0
  339. package/src/lib/server/token-revocation.d.ts +140 -0
  340. package/src/lib/server/token-revocation.js +255 -0
  341. package/src/lib/server/token-revocation.js.map +1 -0
  342. package/src/lib/server/update-existing.d.ts +32 -0
  343. package/src/lib/server/update-existing.js +73 -0
  344. package/src/lib/server/update-existing.js.map +1 -0
  345. package/src/lib/server/upload-cors-reconcile.d.ts +118 -0
  346. package/src/lib/server/upload-cors-reconcile.js +234 -0
  347. package/src/lib/server/upload-cors-reconcile.js.map +1 -0
  348. package/src/lib/server/upsert-contact.d.ts +262 -0
  349. package/src/lib/server/upsert-contact.js +546 -0
  350. package/src/lib/server/upsert-contact.js.map +1 -0
  351. package/src/lib/server/usage-invoice.d.ts +203 -0
  352. package/src/lib/server/usage-invoice.js +397 -0
  353. package/src/lib/server/usage-invoice.js.map +1 -0
  354. package/src/lib/server/user-profiles.d.ts +151 -0
  355. package/src/lib/server/user-profiles.js +364 -0
  356. package/src/lib/server/user-profiles.js.map +1 -0
  357. package/src/lib/server/vercel-drain-signature.d.ts +30 -0
  358. package/src/lib/server/vercel-drain-signature.js +61 -0
  359. package/src/lib/server/vercel-drain-signature.js.map +1 -0
  360. package/src/lib/server/vercel-log-drain.d.ts +259 -0
  361. package/src/lib/server/vercel-log-drain.js +479 -0
  362. package/src/lib/server/vercel-log-drain.js.map +1 -0
  363. package/src/lib/server/verify-email-cooldown.d.ts +102 -0
  364. package/src/lib/server/verify-email-cooldown.js +114 -0
  365. package/src/lib/server/verify-email-cooldown.js.map +1 -0
  366. package/src/lib/server/visitor-write-rate-limit.d.ts +87 -0
  367. package/src/lib/server/visitor-write-rate-limit.js +117 -0
  368. package/src/lib/server/visitor-write-rate-limit.js.map +1 -0
  369. package/src/lib/server/workspace-domains.d.ts +156 -0
  370. package/src/lib/server/workspace-domains.js +271 -0
  371. package/src/lib/server/workspace-domains.js.map +1 -0
  372. package/src/tenancy.d.ts +115 -0
  373. package/src/tenancy.js +142 -0
  374. package/src/tenancy.js.map +1 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/serve-media-cdn.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { pipeline } from 'node:stream/promises'\nimport {\n isLockdownActive,\n type LockdownState,\n MEDIA_CDN_POSTER_PARAM,\n MEDIA_CDN_RENDITION_AUTO,\n MEDIA_CDN_RENDITION_PARAM,\n MEDIA_CDN_ROUTE,\n MEDIA_POSTER_OBJECT_SUFFIX,\n mediaPosterObjectPath,\n mediaRenditionObjectPath,\n type MediaVideoRendition,\n normalizeHostLockdown,\n normalizeOrgLockdown,\n parseMediaRenditions,\n} from '@aglyn/aglyn/server'\n// By path, and out of every barrel: see the module note in `media-cdn-scope`.\nimport {\n MEDIA_CDN_SEGMENT,\n type MediaCdnScope,\n mediaCdnScopeRefusal,\n parseMediaCdnScope,\n} from '@aglyn/aglyn/app-utils/media-cdn-scope'\nimport { mediaDeliveryProvider } from '@aglyn/aglyn/plugin-manager/media-delivery-provider'\nimport type { NextApiRequest, NextApiResponse } from 'next'\nimport { analyticsDayExpiresAt } from './analytics-retention'\nimport { firebaseAdmin } from './firebase-admin'\nimport { getPlatformLockdown } from './lockdown'\nimport { mediaCdnRateLimitRefusal } from './media-cdn-rate-limit'\nimport { mediaDeliveryOrgIdFor, mediaDeliveryRedirect } from './media-delivery'\nimport { getMediaQuarantine } from './media-quarantine'\nimport { verifyMediaAccess } from './media-signing'\nimport { mediaStoragePathInScope } from './media-storage-path'\n\n/**\n * Variant widths generated at upload (AGL-175).\n *\n * Re-exported, not defined: the list now lives in `@aglyn/aglyn`'s media-ref\n * so the RENDERER can reach it too. `image.tsx` carried its own\n * `[320, 640, 1280]` literal, so a width added here never reached the srcSet.\n */\nexport { MEDIA_CDN_VARIANT_WIDTHS } from '@aglyn/aglyn/server'\n\n/**\n * The scope grammar and the refusal this handler enforces (AGL-1043).\n *\n * Re-exported, not defined: the pure rule lives in `@aglyn/aglyn`'s\n * `media-cdn-scope`, so the readers that must reach this handler's verdict —\n * the composition's video facts and the besigner canvas — call the functions\n * it calls.\n */\nexport {\n mediaCdnAllows,\n type MediaCdnScope,\n type MediaCdnScopeRefusal,\n mediaCdnScopeRefusal,\n parseMediaCdnScope,\n} from '@aglyn/aglyn/app-utils/media-cdn-scope'\n\nconst SEGMENT = MEDIA_CDN_SEGMENT\n\n/**\n * The query string to carry onto the stable URL when a stale content pin\n * redirects (AGL-2685).\n *\n * REBUILT from the four parameters this handler reads, never forwarded whole.\n * Two reasons, and the second is the one that matters:\n *\n * 1. Everything else is inert here — it would only split the CDN cache key\n * for a response that is identical either way.\n * 2. `Location` is a header, and the value would otherwise be caller-supplied\n * text. Node rejects a CR or LF in a header value rather than splitting\n * the response, so this is a second lock on a door that is already shut —\n * which is the right number of locks for a header built from user input.\n *\n * `exp` and `sig` ride along because a private asset's signature covers\n * (scope, mediaId, exp) and never the hash, so it is still valid at the\n * target. Dropping them would turn a redirect into a 404 for exactly the\n * assets whose delivery is most sensitive.\n */\nexport function mediaCdnForwardedQuery(query: NextApiRequest['query']): string {\n const params = new URLSearchParams()\n // `poster` and `r` join the set for the reason the others are in it: the\n // redirect must name the SAME representation the caller asked for, or a\n // stale content pin on a poster URL lands the browser on the master video\n // (AGL-2743).\n for (const key of ['w', 'poster', 'r', 'download', 'exp', 'sig'] as const) {\n const raw = query[key]\n const value = Array.isArray(raw) ? raw[0] : raw\n if (value !== undefined && value !== '') params.set(key, String(value))\n }\n const encoded = params.toString()\n return encoded ? `?${encoded}` : ''\n}\n\n/**\n * The stable (non-content-hashed) URL's caching contract.\n *\n * This was `public, max-age=3600, stale-while-revalidate=86400`, and that\n * header contradicted the promise the stable URL exists to make. Measured on\n * production 2026-08-12: Vercel's edge DOES cache this route on a bare\n * `max-age` (`x-vercel-cache: MISS` then `HIT`, `age` climbing) — so the\n * saving was never in question. What a browser `max-age` breaks is\n * *propagation*. `max-age=3600` reaches the client, so a browser holding a\n * replaced asset will not send a conditional request for a full hour: the\n * ETag below never gets a chance to answer, and nothing on our side can bust\n * a browser cache. Every other cacheable route in the repo already uses\n * `s-maxage` for exactly this reason — see `seo-origin.spec.ts`, \"never a\n * browser `max-age`, which nothing could bust\".\n *\n * So: a short browser `max-age` that still collapses the burst of repeat\n * requests within one page view (an image referenced by four `srcSet`\n * candidates, a tile rendered in a grid and again in a drawer), and the full\n * hour moved to `s-maxage` where it belongs. Worst stale read is now 60 s of\n * replaced bytes in one browser rather than an hour, at the cost of one\n * conditional request per image per minute — answered by the EDGE from its\n * own copy, so it adds no Storage read and no Firestore read.\n *\n * The immutable content-hashed form is untouched: its URL changes with its\n * bytes, so it can and should be pinned in the browser for a year.\n *\n * Since AGL-1515 this policy applies to IMAGE responses only — see\n * {@link mediaCdnEdgeCacheable}.\n */\nexport const MEDIA_CDN_STABLE_CACHE_CONTROL =\n 'public, max-age=60, s-maxage=3600, stale-while-revalidate=86400'\n\n/**\n * The stable URL's policy for types the edge must never hold (AGL-1515):\n * the same 60-second browser window and the same ETag/304 contract, with\n * `private` in place of `public, s-maxage` so no shared cache stores a\n * full body.\n *\n * Why the edge must never hold one: Vercel's edge, holding a cached\n * full-body 200, answers a `Range` request FROM that entry as a\n * spec-violating hybrid — status 200, a `Content-Range` header, and only\n * the requested slice as the body (`x-vercel-cache: HIT`; reproduced twice\n * on production, 2026-08-13). A video player seeking into such an asset\n * adopts a 100-byte slice as the complete file: silent playback corruption.\n *\n * The S4 shape below this constant was built on Vercel's documented\n * cacheable-response criteria (\"Request doesn't contain Range header\"),\n * read as \"ranged requests bypass the edge\". Production falsified that\n * reading: the criteria govern what the edge STORES, not what it SERVES. A\n * ranged request is still matched against the URL-keyed entry a previous\n * plain GET left behind, and the edge's slicing layer rewrites the body\n * and adds `Content-Range` without rewriting the stored 200 status.\n *\n * `private` is the lever because it is in the same documented criteria\n * list as an absolute storage preventer (\"Response doesn't contain the\n * `private` … directives\"), where `Vary: Range` is undocumented on\n * Vercel, discouraged by RFC 9110, and untestable anywhere but a\n * production deploy. What it costs: edge caching for non-image assets\n * under Vercel's 10 MB cacheable-size cap. Real video mostly sits ABOVE\n * the cap and was never edge-cached — the mangling reproduced on a 186 KB\n * asset precisely because small ones are the ones that get cached.\n */\nexport const MEDIA_CDN_STABLE_EDGE_BYPASS_CACHE_CONTROL =\n 'private, max-age=60'\n\n/** The immutable content-hashed URL's policy for edge-cacheable (image) types. */\nexport const MEDIA_CDN_IMMUTABLE_CACHE_CONTROL =\n 'public, max-age=31536000, immutable'\n\n/**\n * The immutable URL's policy for edge-bypassing types (AGL-1515): the\n * browser keeps its year — the URL still changes with the bytes — while\n * the edge holds nothing it could mangle.\n */\nexport const MEDIA_CDN_IMMUTABLE_EDGE_BYPASS_CACHE_CONTROL =\n 'private, max-age=31536000, immutable'\n\n/**\n * Whether a response of this content type may be edge-cached (AGL-1515).\n *\n * The split is \"types no realistic client ranges into\": browsers fetch\n * images with plain GETs (`<img>`, `srcSet`, save-as — all of them), while\n * every consumer that seeks or resumes — `<video>`/`<audio>` players, PDF\n * viewers, download managers — operates on the non-image types. Images stay\n * on the shared edge policy because they are the DAM grid's hot path (4.3 KB\n * WebP tiles at volume), and pushing them to origin to fix video would trade\n * a real regression for a theoretical one.\n *\n * Accepted residual, recorded here on purpose: a hand-built `Range` request\n * against an edge-cached IMAGE can still be answered with the hybrid (that\n * is exactly the AGL-1515 favicon repro). No browser or player issues one,\n * and the alternative — `private` on images too — costs the hot path an\n * edge hit rate it measurably has.\n *\n * Unknown or absent types return false: correctness over cache.\n */\nexport function mediaCdnEdgeCacheable(contentType: unknown): boolean {\n return String(contentType ?? '')\n .split(';')[0]\n .trim()\n .toLowerCase()\n .startsWith('image/')\n}\n\n/**\n * The CDN's OWN Content-Security-Policy (AGL-1474).\n *\n * An uploaded `image/svg+xml` is a document, not a picture. It passes the\n * `image/*` allowlist, it is stored under whatever type the client declared,\n * and this handler serves it `inline` from the console's own origin — and\n * from every tenant site's, since the same handler mounts in both apps. So\n * `<script>alert(document.domain)</script>` inside an uploaded logo executed\n * on `app.aglyn.com` the moment the asset URL was opened top-level, for\n * anyone with editor rights.\n *\n * Nothing already in place stopped it. `X-Content-Type-Options: nosniff`\n * blocks HTML *mislabelled* as an image; it says nothing about a file\n * honestly labelled `image/svg+xml`, which browsers render as a scripted\n * document. And there was no CSP on this response **at all**: since AGL-523\n * the policy is built per-response in each app's middleware, and both\n * middlewares' matchers exclude `api` (`apps/console/middleware.ts`,\n * `apps/tenant/middleware.ts`), so a directly-navigated CDN URL never passed\n * through the code that sets one.\n *\n * That is precisely why the header is set HERE, on the response, rather than\n * added to a matcher: a route-level header cannot be lost to a matcher edit,\n * a rewrite, or a new mount of `serveMediaCdn` in a third app. It is also\n * what makes this the containment rather than the remediation — it covers\n * every asset already in the bucket, including the SVGs uploaded before the\n * sanitizer existed, without rewriting a byte.\n *\n * **It does not touch `<img src>`, which is how logos and marks are used\n * across this product.** A browser loading an SVG as an image neither runs\n * its script nor applies the response's CSP — CSP governs documents and\n * workers. The policy only becomes live in the case that is the vector: the\n * asset opened as a top-level document (or framed via `<object>`/`<iframe>`).\n */\nexport const MEDIA_CDN_BASE_CSP =\n \"default-src 'none'; script-src 'none'; object-src 'none'; \" +\n \"base-uri 'none'; form-action 'none'\"\n\n/**\n * The policy for a type a browser will treat as an ACTIVE DOCUMENT. Adds\n * `sandbox` — an opaque origin, so even a hypothetical execution has no\n * `document.domain`, no cookies and no storage to reach for.\n *\n * `style-src 'unsafe-inline'` and the two `data:` allowances are not\n * concessions to script: with `script-src 'none'` and `sandbox` in force,\n * nothing in CSS or a data URI can execute. They exist so that opening a\n * logo's URL directly still shows the logo — `default-src 'none'` alone\n * would blank an SVG's own `<style>` block and its embedded raster fills,\n * which is a visible regression on legitimate assets and buys no safety.\n */\nexport const MEDIA_CDN_ACTIVE_DOCUMENT_CSP =\n `${MEDIA_CDN_BASE_CSP}; style-src 'unsafe-inline'; img-src data:; ` +\n 'font-src data:; sandbox'\n\n/**\n * Types a browser parses as a document rather than rendering as an image.\n *\n * Keying off the SERVED content type is sound only because this response also\n * carries `nosniff`: the browser is bound to the label we send, so an SVG\n * uploaded under a `image/png` label is decoded as a PNG and is inert. Every\n * type here except SVG is refused by the upload allowlist today; they are\n * listed anyway because the allowlist has moved before (AGL-1465) and because\n * a legacy fourth upload route accepted arbitrary types for its whole life\n * before AGL-1485 deleted it.\n */\nconst MEDIA_CDN_ACTIVE_DOCUMENT_TYPES = new Set([\n 'image/svg+xml',\n 'image/svg',\n 'text/html',\n 'application/xhtml+xml',\n 'application/xml',\n 'text/xml',\n 'text/xsl',\n 'application/xslt+xml',\n 'application/mathml+xml',\n])\n\n/**\n * Types this CDN will serve `inline`.\n *\n * `?download=1` has always been able to force `attachment`, but it is the\n * REQUESTER's flag — the safe disposition cannot depend on a caller asking\n * for it. Anything not on this list is served as a download whatever the\n * query says, so opening its URL top-level saves a file instead of handing\n * the type to a renderer on the customer's own domain.\n *\n * The list is what a browser has a real inline use for on this route:\n * pictures, media a player streams, and PDFs, which people expect to open in\n * a tab. Everything else — the office and text formats, JSON, ZIP, and any\n * legacy `text/html` still sitting in the bucket from before the allowlist\n * narrowed — has no inline use case here and every one of them is a document\n * a browser would happily parse.\n *\n * SVG stays INLINE deliberately. AGL-1474 chose the sandboxing CSP over a\n * forced download precisely so that opening a logo's URL still shows the\n * logo, and that policy already denies it script, an origin, and everything\n * it could reach for. Turning it into a download now would take that\n * decision back without adding to it.\n */\nfunction servesInline(contentType: string): boolean {\n const type = String(contentType ?? '')\n .split(';')[0]\n .trim()\n .toLowerCase()\n return (\n type.startsWith('image/') ||\n type.startsWith('video/') ||\n type.startsWith('audio/') ||\n type === 'application/pdf'\n )\n}\n\n/** The `Content-Security-Policy` for a response serving `contentType`. */\nexport function mediaCdnContentSecurityPolicy(contentType: string): string {\n const type = String(contentType ?? '')\n .split(';')[0]\n .trim()\n .toLowerCase()\n return MEDIA_CDN_ACTIVE_DOCUMENT_TYPES.has(type)\n ? MEDIA_CDN_ACTIVE_DOCUMENT_CSP\n : MEDIA_CDN_BASE_CSP\n}\n\n/**\n * Lockdown on the delivery path (AGL-1520).\n *\n * A security-locked org's SITE stops within seconds (the tenant middleware\n * 503s, AGL-1501) — but until this gate existed its public media kept\n * serving worldwide: to hot-links, to third-party embeds, and to the\n * infected asset's own URL, which for an \"infected host\" security lock is\n * the exact thing the lock was pressed to stop.\n *\n * **Which reasons stop delivery — decided per reason, not blanket:**\n *\n * - `security` — REFUSE. The point of the lock: the org's content, media\n * included, must stop serving.\n * - `manual` — REFUSE. A staff suspension with no reason code (every\n * pre-lockdown `suspendedAt` normalizes to `manual`) is \"we turned this\n * org off\"; content continuing to serve would make the kill partial.\n * - `maintenance` — SERVE. The maintenance notice surface may itself\n * reference org assets (a logo on the notice page), the window is\n * temporary and non-adversarial, and blanking every image buys no safety.\n * - `billing` — SERVE. The AGL-1506 principle: billing-locked orgs keep the\n * surfaces that let them come back (members can still reach billing to\n * pay). The site already 503s, so whether a hot-linked image serves is\n * nearly moot — and refusing would punish e.g. an email-signature logo\n * for a payment lapse. Serving is the cheap, reversible answer.\n *\n * Scopes are checked INDIVIDUALLY against that matrix rather than through\n * `resolveLockdown`, on purpose: the resolver answers \"which notice does a\n * visitor see\" and returns the WIDEST active scope — so a platform\n * `maintenance` window would mask a concurrent org `security` lock and the\n * infected asset would keep serving. Delivery has no notice to pick; the\n * question is only \"does ANY active lockdown demand these bytes stop\".\n */\nexport function lockdownStopsMediaDelivery(\n state: LockdownState | null | undefined,\n nowMs: number,\n): boolean {\n if (!state || !isLockdownActive(state, nowMs)) return false\n return state.reason === 'security' || state.reason === 'manual'\n}\n\n/**\n * **Read cost (AGL-1302):** the verdict inputs are TTL-cached in-process\n * per CDN scope — one lookup per scope per {@link MEDIA_CDN_LOCK_TTL_MS},\n * not per asset. A DAM grid firing dozens of requests coalesces into one;\n * the platform doc rides `getPlatformLockdown`'s existing 15s cache. Same\n * fail-open posture as the verdict core: an unreachable Firestore is an\n * outage, not a lockdown, and must not blank every customer image.\n *\n * That lookup is one BatchGetDocuments at org scope, and two at host scope\n * — `hosts` and `hostIndex` batched together, then the owning org, whose id\n * is what `hostIndex` returns and so cannot join the batch. Every one of\n * them is projected to {@link SUSPENSION_FIELDS}: the verdict needs three\n * fields, and the host document is the largest in the product. Measured\n * against production, projecting the three reads and batching two of them\n * took the host branch from 3 round trips and 2,964 B to 2 and 34 B.\n *\n * **Staleness bound, stated rather than hidden:** a warm origin refuses\n * within ≤15s of the org-doc write (the platform panic number). What the\n * origin cannot reach: browsers hold the stable URL up to 60s\n * (`max-age=60`); Vercel's edge holds image responses up to `s-maxage=3600`\n * (+ one stale serve while revalidating) — so an already-edge-cached image\n * URL can serve up to ~1h into a lock; non-image types are `private`\n * (AGL-1515) and never edge-held. The immutable content-hashed form is\n * browser-pinned for a year in clients that already fetched it — there is\n * no per-asset purge API, so that copy is out of reach by design; NEW\n * fetchers of the same URL refuse at the next origin miss. Compare the\n * AGL-1501 drill: host pages flip ≤10s; assets lag minutes-to-an-hour at\n * the caching tiers, which is the accepted trade for a near-zero read cost\n * on the hottest unauthenticated path.\n *\n * **Out of this control's reach entirely:** free-tier raw\n * `firebasestorage.googleapis.com` URLs — no code of ours runs there.\n * Stated on AGL-1520, and now answered elsewhere rather than here: a\n * `security` lock rotates those objects' download tokens\n * (`media-download-tokens.ts`, AGL-1526), which kills the URL at Google's\n * edge. That is a SIBLING control, not an extension of this one — it is\n * `security`-only, it is irreversible for embeds, and like this gate it\n * stops only new origin fetches (AGL-1615). Bytes already cached anywhere\n * remain out of reach of both.\n */\nconst MEDIA_CDN_LOCK_TTL_MS = 15_000\n\nconst lockCache = new Map<string, { at: number; blocked: boolean }>()\nconst lockPending = new Map<string, Promise<boolean>>()\n\n/**\n * Drop the per-scope lock cache. Tests need it between cases; production\n * convergence is the TTL — the lock is written by the console app and served\n * by the tenant app, different processes an in-process invalidation can\n * never reach.\n */\nexport function invalidateMediaCdnLockCache(): void {\n lockCache.clear()\n lockPending.clear()\n}\n\n/**\n * Every field the delivery verdict reads off a host or org document, and\n * the projection sent to Firestore — ONE list, because the carrier below is\n * built from it. A mask that omitted a field the carrier reads would leave\n * that field `undefined` and silently soften the lock: drop\n * `suspendedReasonCode` and every lock normalizes to `manual`, which\n * REFUSES delivery for locks that should serve; drop `suspendedAt` and no\n * lock is ever seen at all. Neither failure can be introduced here without\n * changing the one array both sides use.\n *\n * `suspendedMode` and `suspendedEnforcement` are deliberately absent:\n * {@link lockdownStopsMediaDelivery} decides on `reason` and the active\n * window alone, so a read-only or takedown-class lock stops these bytes on\n * exactly the same terms as a full one.\n */\nconst SUSPENSION_FIELDS = [\n 'suspendedAt',\n 'suspendedReasonCode',\n 'suspendedUntilMs',\n] as const\n\n/** Which host owns the asset's scope — the only field read off `hostIndex`. */\nconst HOST_INDEX_ORG_FIELD = 'orgId'\n\n/** The `suspended*` field family off a snapshot, for the normalizers. */\nconst suspensionCarrier = (snapshot: {\n get: (field: string) => unknown\n}): {\n suspendedAt?: unknown\n suspendedReasonCode?: unknown\n suspendedUntilMs?: unknown\n} =>\n Object.fromEntries(\n SUSPENSION_FIELDS.map((field) => [field, snapshot.get(field)]),\n )\n\n/** TTL-cached: does any lockdown covering `scope` stop delivery? */\nasync function mediaCdnScopeLocked(scope: MediaCdnScope): Promise<boolean> {\n const key = `${scope.isOrg ? 'org' : 'host'}:${scope.scopeId}`\n const cached = lockCache.get(key)\n if (cached && Date.now() - cached.at < MEDIA_CDN_LOCK_TTL_MS) {\n return cached.blocked\n }\n let pending = lockPending.get(key)\n if (!pending) {\n pending = (async () => {\n let blocked: boolean\n try {\n const nowMs = Date.now()\n // Platform first: cached, and a platform security lock is the panic\n // button — asset delivery is part of what it stops.\n blocked = lockdownStopsMediaDelivery(await getPlatformLockdown(), nowMs)\n const firestore = firebaseAdmin.app().firestore()\n if (!blocked && scope.isOrg) {\n // Org forms (`org:{orgId}` and `org:{orgId}:{hostId}`): the org\n // doc governs. The context host's own lock is not consulted — a\n // suspended HOST's pages 503 already, and which sites may USE an\n // org asset is `visibleTo`'s question, not the lock's.\n const [org] = await firestore.getAll(\n firestore.collection('orgs').doc(scope.scopeId),\n { fieldMask: [...SUSPENSION_FIELDS] },\n )\n blocked = lockdownStopsMediaDelivery(\n normalizeOrgLockdown(suspensionCarrier(org)),\n nowMs,\n )\n } else if (!blocked) {\n // Host-library form: the host's own lock, and the OWNING org's —\n // an org lock never stamps host docs (AGL-1506), so a host-only\n // read would silently miss the very lock this issue is about.\n //\n // One `getAll`, not two parallel gets: `DocumentReference.get()`\n // is `getAll([ref])`, so a `Promise.all` of two of them is two\n // BatchGetDocuments round trips where the batch is one. The org\n // read below cannot join them — its id is what `hostIndex`\n // returns — so two is the floor for this branch, not three.\n const [host, hostIndex] = await firestore.getAll(\n firestore.collection('hosts').doc(scope.scopeId),\n firestore.collection('hostIndex').doc(scope.scopeId),\n { fieldMask: [...SUSPENSION_FIELDS, HOST_INDEX_ORG_FIELD] },\n )\n blocked = lockdownStopsMediaDelivery(\n normalizeHostLockdown(suspensionCarrier(host)),\n nowMs,\n )\n const orgId = hostIndex.get(HOST_INDEX_ORG_FIELD)\n if (!blocked && typeof orgId === 'string' && orgId) {\n const [org] = await firestore.getAll(\n firestore.collection('orgs').doc(orgId),\n { fieldMask: [...SUSPENSION_FIELDS] },\n )\n blocked = lockdownStopsMediaDelivery(\n normalizeOrgLockdown(suspensionCarrier(org)),\n nowMs,\n )\n }\n }\n } catch {\n // Fail open — the lockdown core's posture (see lockdown.ts): an\n // unreachable Firestore is an outage, not a lockdown.\n blocked = false\n }\n lockCache.set(key, { at: Date.now(), blocked })\n return blocked\n })().finally(() => {\n lockPending.delete(key)\n })\n lockPending.set(key, pending)\n }\n return pending\n}\n\n/**\n * THE delivery-policy seam: \"may this asset be served at all?\" — one\n * question, one function, consulted once per request before any caching\n * exit. Distinct from `mediaCdnAllows` (which site may use it under this\n * URL) and from the signature check (may the public fetch it): this asks\n * whether the platform is willing to serve the bytes to ANYONE.\n *\n * Two independent reasons to refuse, both answered here so the handler\n * keeps ONE refusal path:\n *\n * - `'locked'` — a lockdown covering this SCOPE (AGL-1520): the whole org\n * or host is off.\n * - `'quarantined'` — this ASSET is on the deny list (AGL-1512): one\n * infected, abusive or DMCA-noticed file is off while everything else in\n * the same workspace keeps serving. That proportionality is the point —\n * a single bad object should not cost a customer their whole site.\n *\n * Order is scope-then-asset because the scope verdict is the cheaper cached\n * one and the wider fact; the caller does not distinguish them on the wire\n * (both are the same neutral 410), so the order is a cost decision only.\n *\n * Read cost, since this sits on the hottest unauthenticated path: the scope\n * verdict is one read per SCOPE per 15s, and the quarantine deny list is\n * one read per PROCESS per 15s for every asset in existence — it is a\n * single document. Fifty DAM tiles pay two reads between them, not a\n * hundred.\n */\nexport async function mediaCdnServeBlock(\n scope: MediaCdnScope,\n asset: {\n /**\n * The strong full-width digest (AGL-1614) when the document has one.\n * Preferred over `contentHash` as a quarantine key — it is one\n * algorithm at full width, where `contentHash` is a 64-bit truncation\n * of either sha256 or md5 depending on the ingesting route.\n */\n contentSha256?: string\n contentHash?: string\n /**\n * The raw URL scope segment and media id — the fallback quarantine key\n * for the assets that carry no `contentHash` at all (legacy uploads,\n * and composite objects GCS gives no md5 for). Without it the largest\n * files in the product would be the ones a takedown could not touch.\n */\n scopeSegment?: string\n mediaId?: string\n },\n): Promise<'locked' | 'quarantined' | null> {\n if (await mediaCdnScopeLocked(scope)) return 'locked'\n const quarantined = await getMediaQuarantine({\n contentSha256: asset.contentSha256,\n contentHash: asset.contentHash,\n scopeSegment: asset.scopeSegment,\n mediaId: asset.mediaId,\n })\n return quarantined ? 'quarantined' : null\n}\n\n/**\n * Whether `?download=1` was asked for (AGL-1411). Strictly opt-in: absent,\n * `0`, `false` or junk all keep the historical `inline`, because the default\n * is what every `<img src>` in every published site relies on.\n *\n * Only `1` and `true` count, rather than \"any truthy-looking string\". The\n * query string is part of the CDN cache key, so every accepted spelling is a\n * separate edge entry for identical bytes; two is enough.\n */\nexport function wantsMediaDownload(value: unknown): boolean {\n const raw = Array.isArray(value) ? value[0] : value\n const normalized = String(raw ?? '').toLowerCase()\n return normalized === '1' || normalized === 'true'\n}\n\n/**\n * Whether `?poster=1` was asked for (AGL-2743).\n *\n * Deliberately the same two-spelling rule as {@link wantsMediaDownload},\n * and for the same reason rather than out of symmetry: the query string is\n * part of the CDN cache key, so every accepted spelling of \"yes\" is another\n * edge entry holding identical bytes. A poster is the response most likely\n * to be requested at volume from a grid, which makes cache-key discipline\n * worth more here than anywhere else on the route.\n */\nexport function mediaCdnWantsPoster(value: unknown): boolean {\n return wantsMediaDownload(value)\n}\n\n/**\n * The container every browser has decoded for a decade, and the encoding the\n * producer always emits (`720p`, H.264 High in MP4). WebM/VP9 is opt-in there\n * and is the only entry a client has to earn.\n */\nconst MEDIA_CDN_BASELINE_RENDITION_TYPE = 'video/mp4'\n\n/**\n * What a client said about media types, split into the two answers that\n * matter: types it NAMED, and types it explicitly refused with `q=0`.\n *\n * Wildcards are deliberately dropped rather than expanded. `video/*` and\n * `*\\/*` are a client declining to answer the question, and the browsers that\n * matter mostly decline: Chrome and Safari send `*\\/*` for a media element's\n * request and only Firefox enumerates containers. Reading `*\\/*` as \"every\n * container decodes here\" is how a Safari 13 gets handed a WebM.\n */\nfunction parseAcceptedTypes(header: unknown): {\n named: Set<string>\n refused: Set<string>\n} {\n const raw = Array.isArray(header) ? header[0] : header\n const named = new Set<string>()\n const refused = new Set<string>()\n for (const part of String(raw ?? '').split(',')) {\n const [type, ...params] = part.split(';')\n const name = type.trim().toLowerCase()\n if (!name || name.includes('*')) continue\n // `q=0` is a refusal in RFC 9110, so it removes an entry rather than\n // selecting it — the one case where naming a type argues against it.\n const isRefusal = params.some(\n (param) => /^\\s*q\\s*=/i.test(param) && Number(param.split('=')[1]) === 0,\n )\n if (isRefusal) refused.add(name)\n else named.add(name)\n }\n return { named, refused }\n}\n\n/**\n * Which rendition `?r=auto` resolves to, or undefined for \"serve the master\"\n * (AGL-2753).\n *\n * ## Why the CDN chooses at all\n *\n * Because it is the only participant holding the media document when the\n * bytes are asked for. A page cannot name a rendition — the encodings are\n * produced out of band, after the placement, and the page is ISR-cached HTML\n * that neither regenerates when one lands nor varies on a visitor's `Accept`.\n * The composition does read a placed film's document for its length and\n * shape (AGL-2807), but that answer is frozen into the cached page. The\n * alternatives were a node backfill that rewrites published screens nobody\n * edited, or naming encodings in that same frozen page. This costs neither:\n * the document is already in hand on this request.\n *\n * ## Why the stored order is not simply obeyed\n *\n * The producer writes most-efficient-codec first, which is the right order for\n * `<source>` elements — there the BROWSER picks, using what it actually knows\n * about its own decoders. A single negotiated URL has no such luxury, so\n * taking the head of the list would hand a WebM to anything that could not\n * decode one and turn a saving into a black player.\n *\n * So an entry is selected on an EXPLICIT type match, and everything else falls\n * to the MP4 baseline the producer always emits. A client that names\n * `video/webm` gets the 30%-smaller file; a client that says `*\\/*` gets the\n * universally decodable one; a client that refused every candidate gets the\n * master. Every outcome is a video that plays.\n *\n * ## Why negotiating here is safe under a cache\n *\n * A rendition response is `video/*`, so `mediaCdnEdgeCacheable` is false and\n * it is served `private` (AGL-1515) — no shared cache stores it, which is the\n * invariant `serve-media-cdn.video.spec.ts` pins. The only cache that can hold\n * one is the requesting browser's own, and a browser's `Accept` for media does\n * not change between the first request and the Range requests that follow it.\n * That matters more than it looks: negotiation on a RANGEABLE resource that\n * could flip mid-playback would stitch byte ranges from two different files\n * together, which is the AGL-1515 corruption reached by a new road.\n */\nexport function selectAutoRendition(\n renditions: readonly MediaVideoRendition[],\n acceptHeader: unknown,\n): MediaVideoRendition | undefined {\n if (renditions.length === 0) return undefined\n const { named, refused } = parseAcceptedTypes(acceptHeader)\n const typeOf = (entry: MediaVideoRendition) => entry.contentType.toLowerCase()\n return (\n renditions.find((entry) => named.has(typeOf(entry))) ??\n renditions.find(\n (entry) =>\n typeOf(entry) === MEDIA_CDN_BASELINE_RENDITION_TYPE &&\n !refused.has(MEDIA_CDN_BASELINE_RENDITION_TYPE),\n )\n )\n}\n\n/** Anything that cannot appear literally in an HTTP field-value. */\nconst NON_ASCII_FIELD_VALUE = /[^\\x20-\\x7e]/g\n/** ...and what additionally cannot appear inside a quoted-string. */\nconst NOT_QUOTED_STRING_SAFE = /[\"\\\\]/g\n\n/**\n * The download name for an asset: the stored `fileName`, reduced to its\n * basename, falling back to the media id (the URL is id-keyed and\n * extensionless, so without a name a \"save as\" lands as a nameless blob).\n */\nexport function mediaDownloadName(fileName: unknown, mediaId: string): string {\n const raw = String(fileName ?? '').trim()\n // A stored name can carry a path from whatever uploaded it; only the last\n // segment is a filename, and `..` must never reach a client's save dialog.\n const base = raw.split(/[\\\\/]/).pop() ?? ''\n // Cap by CODE POINT so a truncation can't split a surrogate pair into a\n // lone half, which is exactly the kind of thing that later throws in a\n // header encoder.\n return Array.from(base).slice(0, 200).join('') || mediaId\n}\n\n/**\n * A `Content-Disposition` value for `name` (AGL-1411).\n *\n * A filename is attacker-adjacent data — it is whatever the uploader typed —\n * and it is being pasted into a header, so a quote or a CRLF in it is a\n * header-injection vector. The old code stripped `[\"\\\\\\r\\n]` and left\n * everything else, which is safe against injection but silently mangles the\n * name and passes non-ASCII through raw: a byte above 0x7e in a header is\n * either mojibake at the client or, on a stricter encoder than ours, a\n * throw. So both forms of RFC 6266 §4.1 are emitted:\n *\n * - `filename=\"…\"` — ASCII only, every unrepresentable character replaced\n * (not dropped) so the extension and the shape of the name survive. This\n * is the fallback, and it always exists.\n * - `filename*=UTF-8''…` — RFC 8187 percent-encoding of the real name, added\n * only when the ASCII form actually lost something. Every current browser\n * prefers it, so a non-ASCII name arrives intact.\n */\nexport function mediaContentDisposition(\n name: string,\n options: { download: boolean },\n): string {\n const type = options.download ? 'attachment' : 'inline'\n const ascii = name\n .replace(NON_ASCII_FIELD_VALUE, '_')\n .replace(NOT_QUOTED_STRING_SAFE, '_')\n const header = `${type}; filename=\"${ascii}\"`\n if (ascii === name) return header\n // `encodeURIComponent` leaves `!'()*` alone, and `'`, `(`, `)` and `*` are\n // not `attr-char` (RFC 8187 §3.2.1) — a bare `'` in particular would be\n // read as the charset/language delimiter. Encode them too.\n const encoded = encodeURIComponent(name).replace(\n /['()*]/g,\n (character) =>\n `%${character.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`,\n )\n return `${header}; filename*=UTF-8''${encoded}`\n}\n\n/**\n * A parsed `Range` request (AGL-1442 S4). Three answers, and the difference\n * between the last two is the whole game:\n *\n * - `{ start, end }` — a single satisfiable byte range, both ends INCLUSIVE\n * (matching `createReadStream`, which is where the numbers go).\n * - `'unsatisfiable'` — syntactically a range, but nothing in it can be\n * served (`start` past EOF, `-0`, an empty object). RFC 9110 §14.1.2 says\n * this one earns a 416.\n * - `null` — everything else: no header, another unit, a multi-range, or\n * malformed syntax. RFC 9110 §14.2 lets a server ignore a Range header\n * outright, and ignoring means a full 200 — which is both the safe answer\n * and the pre-S4 behavior, so every shape this parser does not positively\n * recognise degrades to exactly what shipped before it existed.\n *\n * Multi-range requests land in `null` DELIBERATELY. Serving them needs a\n * `multipart/byteranges` body with generated boundaries; no browser sends\n * them for media (a `<video>` seek is always one range), and a 416 would be\n * wrong because a multi-range over a real file is satisfiable. A full 200\n * is the RFC-sanctioned refusal that no client can misread.\n */\nexport type MediaCdnRange = { start: number; end: number } | 'unsatisfiable' | null\n\nexport function parseMediaCdnRange(\n header: unknown,\n size: number,\n): MediaCdnRange {\n if (typeof header !== 'string') return null\n const unit = /^bytes=(.*)$/i.exec(header.trim())\n if (!unit) return null\n const specs = unit[1].split(',')\n if (specs.length !== 1) return null\n const spec = /^(\\d*)-(\\d*)$/.exec(specs[0].trim())\n if (!spec) return null\n const [, startRaw, endRaw] = spec\n if (!startRaw && !endRaw) return null\n if (!startRaw) {\n // Suffix form `bytes=-N`: the LAST N bytes. `-0` names zero bytes and a\n // 200 would over-answer it, so it is the one suffix that 416s.\n const suffix = Number(endRaw)\n if (!Number.isSafeInteger(suffix)) return null\n if (suffix === 0 || size === 0) return 'unsatisfiable'\n return { start: Math.max(0, size - suffix), end: size - 1 }\n }\n const start = Number(startRaw)\n if (!Number.isSafeInteger(start)) return null\n const end = endRaw ? Number(endRaw) : size - 1\n if (!Number.isSafeInteger(end)) return null\n // `bytes=5-2` is a syntax error, not an unsatisfiable range — ignore it.\n if (endRaw && end < start) return null\n if (start >= size) return 'unsatisfiable'\n return { start, end: Math.min(end, size - 1) }\n}\n\n/**\n * Whether a delivery ended early only because its client stopped reading\n * (AGL-2810).\n *\n * A `<video>` element abandons its opening request once it has buffered\n * enough, and abandons another on every seek, so this is the ordinary way a\n * streamed response ends early — and it is not a delivery failure, so it is\n * neither logged nor answered.\n *\n * `pipeline` reports it as a premature close, and reports a Storage read that\n * closed early the same way. The response tells them apart: a client that\n * canceled destroyed it without an error, while a failed read makes\n * `pipeline` destroy it WITH the read's error.\n */\nfunction mediaCdnClientWentAway(\n error: unknown,\n res: { errored?: Error | null },\n): boolean {\n return (\n (error as { code?: unknown } | null)?.code === 'ERR_STREAM_PREMATURE_CLOSE' &&\n !res.errored\n )\n}\n\n/**\n * The headers that describe the file, removed from an answer that will not\n * carry it.\n *\n * A failure found after the representation was chosen would otherwise go out\n * under the file's own headers: a `Content-Length` of the whole object on a\n * short JSON body leaves the client waiting for bytes that never come, a\n * `video/mp4` type misdescribes the body outright, and the validator would\n * attach the file's identity to an error. `no-store` because the answer is\n * about this request, not the URL.\n */\nfunction clearMediaCdnRepresentation(res: NextApiResponse): void {\n for (const header of [\n 'Content-Type',\n 'Content-Length',\n 'Content-Range',\n 'Content-Disposition',\n 'Accept-Ranges',\n 'ETag',\n ]) {\n res.removeHeader(header)\n }\n res.setHeader('Cache-Control', 'no-store')\n}\n\n/**\n * CDN media delivery (AGL-175 / AGL-829). Two URL shapes resolve the same\n * asset by `mediaId`, so delivery never depends on the object's storage\n * location (folder moves don't change the URL):\n *\n * - **Stable** `/api/media/cdn/[scope]/[mediaId]` — always serves the\n * asset's CURRENT bytes, so it survives a **replace** too. Revalidated\n * with an ETag (the content hash) + `stale-while-revalidate`, so a\n * replaced asset propagates without ever breaking references. This is\n * the URL the console hands out.\n * - **Immutable** `/api/media/cdn/[scope]/[mediaId]/[contentHash]` —\n * year-long `immutable` cache; bytes are served only while the hash\n * matches the current content, and a stale hash 302s to the stable URL\n * (AGL-2685). No renderer names this form (AGL-2798): an edge or a browser\n * holding an immutable response never asks again, so a replace could not\n * reach a page that did. It is answered for the URLs already handed out.\n *\n * `?w=[width]` selects a generated WebP variant. `?download=1` swaps the\n * `Content-Disposition` from `inline` to `attachment` (AGL-1411) — the press\n * kit hands out links that must SAVE rather than open a tab. Both are read\n * only after every access gate, so neither can widen what is served; both\n * are part of the CDN cache key, so neither variant can poison the other.\n * The same handler mounts in both the tenant and console apps; raw storage\n * URLs already embedded in screens keep working unchanged.\n *\n * Single byte-range requests are honored with a 206 (AGL-1442 S4) — see\n * {@link parseMediaCdnRange} and the block below `Accept-Ranges` for the\n * exact semantics. This is the capability whose absence kept video on raw\n * `firebasestorage.googleapis.com` URLs (S8): a `<video>` seek is a Range\n * request, and a server that ignores it forces the player to re-download\n * the whole file.\n *\n * The body streams (AGL-2810): each chunk leaves as Storage produces it, so no\n * file is held whole in function memory. A GET that will read the file is\n * first counted against its caller (AGL-2812); see\n * {@link mediaCdnRateLimitRefusal}.\n */\nexport async function serveMediaCdn(\n req: NextApiRequest,\n res: NextApiResponse,\n): Promise<void> {\n // AGL-1474, set FIRST so no exit from this handler can be reached without\n // it — including the refusals, the 304 and the 500. Upgraded below to the\n // sandboxing form once the served content type is known. `nosniff` is\n // repeated here rather than left to the app config's `/(.*)` header: the\n // policy above keys off the declared type, so this response has to carry\n // the header that makes the declared type binding, on its own.\n res.setHeader('Content-Security-Policy', MEDIA_CDN_BASE_CSP)\n res.setHeader('X-Content-Type-Options', 'nosniff')\n if (req.method !== 'GET' && req.method !== 'HEAD') {\n res.setHeader('Allow', 'GET, HEAD')\n res.status(405).end()\n return\n }\n const path = Array.isArray(req.query['path']) ? req.query['path'] : []\n const [scopeSegment, mediaId, hash] = path.map((value) =>\n String(value ?? ''),\n )\n const scope = parseMediaCdnScope(scopeSegment)\n const isOrg = scope?.isOrg ?? false\n const scopeId = scope?.scopeId ?? ''\n // 3 segments = the immutable content-hashed URL; 2 = the stable URL.\n const hashed = path.length === 3\n if (\n !scope ||\n (path.length !== 2 && path.length !== 3) ||\n !SEGMENT.test(mediaId) ||\n (hashed && !SEGMENT.test(hash))\n ) {\n res.status(400).json({ error: 'Bad media path' })\n return\n }\n\n try {\n const firestore = firebaseAdmin.app().firestore()\n const snapshot = await firestore\n .collection(isOrg ? 'orgs' : 'hosts')\n .doc(scopeId)\n .collection('media')\n .doc(mediaId)\n .get()\n const currentHash = String(snapshot.get('contentHash') ?? '')\n if (!snapshot.exists || snapshot.get('deletedAt')) {\n res.setHeader('Cache-Control', 'public, max-age=60')\n res.status(404).json({ error: 'Not found' })\n return\n }\n // Delivery gate — scope lockdown (AGL-1520) and asset quarantine\n // (AGL-1512). See mediaCdnServeBlock for the reason matrix, the\n // read-cost accounting and the staleness bound. Three shape decisions,\n // argued, and all three apply to BOTH refusal kinds:\n //\n // **Before the ETag/304 exit**, necessarily: a browser revalidating its\n // 60s copy during a lock or a quarantine must be refused, not handed a\n // 304 that renews the copy for another minute.\n //\n // **410, not 423, and identical for both kinds.** The 423 body is the\n // AGL-1506 discipline for authenticated API consumers who deserve\n // \"suspended: billing\"; this response answers anonymous `<img>` fetches\n // nobody parses, and a 423 would confirm to any prober that a lock\n // exists — which for a security lock is information. It is information\n // for a quarantine too, and of a worse kind: the existence of a DMCA\n // notice or a malware finding on a specific file is not something an\n // anonymous fetcher has standing to learn, and telling quarantine apart\n // from lockdown on the wire would leak which one it was. So the owning\n // org learns the reason in the console (`mediaQuarantineNotice`), and\n // the CDN says only `410 Gone` — neutral, indistinguishable in kind\n // from a deleted asset, and a hint to well-behaved consumers to drop\n // the link. (404 would also be neutral, but 410's \"permanently gone\"\n // semantics discourage retry loops from embedders.)\n //\n // **`no-store`, absolutely** (the AGL-1515 lesson): the refusal is a\n // function of a TTL'd verdict, not of the URL — a cached refusal would\n // weld the asset's URL identity to \"gone\" past the unlock, and edge\n // entries have no per-asset purge. The 60s negative window the 404s use\n // is not acceptable here either. For quarantine that argument is\n // strictly stronger than for lockdown: REVERSIBILITY is the whole\n // reason quarantine exists instead of deletion, so a cached 410 that\n // outlived the lift would defeat the feature's only advantage over the\n // irreversible option. The refusal is also nearly free to re-serve —\n // the verdict is one Firestore read per process per 15s for the entire\n // deny list, and the body is a few bytes with no Storage read — so\n // there is no saving to weigh against it. CSP + nosniff are already on\n // the response (set first, before any exit).\n const blockedBy = await mediaCdnServeBlock(scope, {\n // The strong digest is read for the quarantine key ONLY. It is\n // deliberately not the ETag and not the immutable URL segment\n // (AGL-1614): changing either of those would change live URLs and\n // cache validators for every existing asset, and this change must be\n // additive to the point of being invisible on the wire.\n contentSha256: String(snapshot.get('contentSha256') ?? ''),\n contentHash: currentHash,\n scopeSegment,\n mediaId,\n })\n if (blockedBy) {\n res.setHeader('Cache-Control', 'no-store')\n res.status(410).json({ error: 'Gone' })\n return\n }\n // Scope check (AGL-1043). The bare `org:` form serves ORG-WIDE assets\n // only; a restricted asset must be requested through the form that\n // names the site using it, which is when AGL-1045's confirmation already\n // warns which pages are affected.\n //\n // An asset carrying no `visibleTo` is refused here rather than treated as\n // org-wide: absent is \"nobody has said who may see this\", not \"everybody\"\n // (`app-utils/scope-tokens`). The scope backfill stamps such documents and\n // the weekly drift detector reports the ones it has not reached, so the\n // repair is a stamp rather than a wider read.\n //\n // 404 rather than 403: whether a restricted asset exists is itself\n // something the caller has no standing to learn. Short max-age so\n // re-widening a scope propagates quickly instead of being pinned by a\n // long-lived negative cache entry.\n const refusal = mediaCdnScopeRefusal(scope, snapshot.get('visibleTo'))\n if (refusal) {\n /**\n * A `restricted` refusal is the gate WORKING and is deliberately\n * silent: it is the ordinary consequence of an internal asset's URL\n * being shared outside the site it belongs to, it can be provoked by\n * anyone who can guess a scope segment, and a log line per anonymous\n * request would make this route amplify traffic into the drain.\n *\n * The other two cannot be provoked from outside — they are properties\n * of the document, not of the request — and they are the ones nothing\n * else says out loud. An asset undeliverable under every URL form\n * shows up as an image that stopped rendering on a live site, and\n * until the weekly drift detector runs the only trace it leaves is a\n * 404 indistinguishable from a deleted asset. Naming it here is what\n * makes the next occurrence readable from the logs.\n */\n if (refusal !== 'restricted') {\n console.error(\n '[media-cdn] asset has no site it can be served to',\n JSON.stringify({ scopeId, mediaId, refusal }),\n )\n }\n res.setHeader('Cache-Control', 'public, max-age=60')\n res.status(404).json({ error: 'Not found' })\n return\n }\n /**\n * Private assets (AGL-1051) leave the public model entirely: no\n * `cdnPath`, and no bytes without an unexpired signature. This is a\n * different question from the scope check above — that one asks which\n * SITE may use the asset, this one asks whether the public may fetch\n * it at all.\n *\n * `no-store`, not a short max-age. Every other response here is safe to\n * cache because it is the same answer for everyone, but a signed\n * request is per-caller and time-boxed: letting a shared cache keep\n * either the denial OR the bytes would outlive the signature and hand\n * the asset to the next requester on the same URL.\n *\n * Which is why the header goes through `setCacheControl` from here on\n * rather than `res.setHeader` — the private case has to win at EVERY\n * exit, and remembering that at each of six call sites is precisely\n * the kind of thing that gets missed when a seventh is added. It\n * already was: the stale-hash 404 below used to overwrite `no-store`\n * with `public, max-age=60`.\n */\n const isPrivate = snapshot.get('private') === true\n const setCacheControl = (value: string) => {\n res.setHeader('Cache-Control', isPrivate ? 'private, no-store' : value)\n }\n if (isPrivate) {\n const signed = verifyMediaAccess(scopeSegment, mediaId, {\n exp: Number(req.query['exp'] ?? 0),\n sig: String(req.query['sig'] ?? ''),\n })\n setCacheControl('private, no-store')\n if (!signed) {\n res.status(404).json({ error: 'Not found' })\n return\n }\n }\n /**\n * A stale hash on the immutable form REDIRECTS to the stable URL\n * (AGL-2685). It used to 404.\n *\n * The invariant the 404 protected is intact and is the reason this is a\n * redirect rather than a body: **no version of this URL ever serves bytes\n * that are not the ones its hash names.** A stale one now serves a\n * pointer to the URL that is allowed to change instead of a dead end.\n *\n * What the 404 cost was every copy of this URL breaking on the first\n * **replace** of its asset. With a redirect, a stale URL that reaches\n * this handler costs one extra hop and self-heals. It does NOT make the\n * form safe to publish: an edge or a browser already holding the\n * immutable response answers from its copy and never reaches this line,\n * which is why no renderer names this form (AGL-2798).\n *\n * **302, not 301.** A hash can become current again — a replace reverted\n * to the previous bytes restores it — and a permanent redirect is exactly\n * the thing browsers refuse to forget.\n *\n * **The stable URL's own cache policy**, not a shorter one. The redirect\n * is as re-checkable as the resource it points at, and it is the same\n * answer for every caller, so there is no reason for the edge to hold it\n * less well than it holds the target. `setCacheControl` still forces\n * `private, no-store` for a signed asset.\n *\n * The query string is REBUILT from the parameters this handler reads\n * rather than forwarded: `?w=`, `?download=` and the signature pair are\n * the whole set, they are already validated by the code below, and\n * echoing arbitrary caller input into a `Location` header is a habit\n * worth not having. Dropping an unknown parameter costs a cache-key\n * split and nothing else.\n */\n if (hashed && currentHash !== hash) {\n setCacheControl(MEDIA_CDN_STABLE_CACHE_CONTROL)\n res.setHeader(\n 'Location',\n `${MEDIA_CDN_ROUTE}/${scopeSegment}/${mediaId}${mediaCdnForwardedQuery(req.query)}`,\n )\n res.status(302).end()\n return\n }\n\n const width = Number(req.query['w'] ?? 0)\n const variants: number[] = snapshot.get('variants') ?? []\n /*\n * WHICH REPRESENTATION OF THIS ASSET (AGL-2743).\n *\n * Three derived forms now sit behind one media id — the image variants\n * `?w=` has selected since AGL-175, a video's poster still, and its\n * encoded renditions. They are resolved here, together, because they are\n * mutually exclusive and because every one of them has to reach the ETag,\n * the cache tier and the object path in agreement. A second lookup later\n * in the handler is how a poster ends up cached under the master's\n * validator.\n *\n * Precedence is poster, then rendition, then width, and it is total: a\n * caller sending `?poster=1&r=720p` gets the poster rather than an error,\n * because the parameters are a REQUEST for a representation and the only\n * useful answer to an incoherent one is the safest coherent one.\n *\n * ## Falling back to the master is right for a WIDTH and wrong for a POSTER\n *\n * `?w=` on an asset with no such variant serves the original, and that has\n * always been safe because both answers are the same KIND of thing: an\n * image, larger than asked for. A rendition inherits it for the same\n * reason — an unknown `?r=` serves the master, which is the same video in\n * more bytes.\n *\n * `?poster=1` cannot. The caller asked for a still and the master is a\n * film, so the fallback would answer a `<video poster>` with 60 MB of\n * `video/mp4` — a request for 40 KB satisfied with the entire asset,\n * which is the precise cost this feature exists to remove, delivered by\n * the feature itself. So a poster that does not exist is a **404**, and\n * that is the better answer in the browser too: a `<video>` whose\n * `poster` 404s behaves exactly like a `<video>` with no `poster`, which\n * is what every video did before AGL-2742. It also lets a renderer emit\n * the attribute without first reading the document — the property the\n * fallback was supposed to buy, bought honestly.\n */\n const poster = snapshot.get('poster')\n const posterVariants: number[] = poster?.variants ?? []\n const wantsPoster = mediaCdnWantsPoster(req.query[MEDIA_CDN_POSTER_PARAM])\n if (wantsPoster && !poster) {\n // See above: a still is not a film, so this is the one representation\n // that must refuse rather than degrade. `no-store` because the answer\n // is about a DOCUMENT field that a poster backfill can change at any\n // time, and a cached 404 would outlive the fix.\n setCacheControl('private, no-store')\n res.status(404).json({ error: 'No poster' })\n return\n }\n const usePoster = wantsPoster\n const usePosterVariant = usePoster && Boolean(width) && posterVariants.includes(width)\n const renditionParam = req.query[MEDIA_CDN_RENDITION_PARAM]\n const renditionKey = String(\n Array.isArray(renditionParam) ? renditionParam[0] : (renditionParam ?? ''),\n )\n /*\n * `?r=auto` is the form a PAGE emits (AGL-2753), because a page cannot\n * know which encodings an asset has — they are produced out of band, long\n * after the placement. `selectAutoRendition` answers from the document\n * already read above, so serving the encodings costs no extra read\n * anywhere and a rendition made today reaches a video placed last month.\n *\n * An explicit key stays exact and stays supported: the producer's report\n * and the specs address one encoding by name, and a debugging request for\n * `?r=720p-vp9` should get that file or the master, never a negotiation.\n */\n const negotiated = !usePoster && renditionKey === MEDIA_CDN_RENDITION_AUTO\n const availableRenditions = usePoster\n ? []\n : parseMediaRenditions(snapshot.get('videoRenditions'))\n const rendition = usePoster\n ? undefined\n : negotiated\n ? selectAutoRendition(availableRenditions, req.headers['accept'])\n : availableRenditions.find((entry) => entry.key === renditionKey)\n if (negotiated) {\n // Declared for correctness rather than as the thing keeping this safe.\n // What keeps it safe is `private` (AGL-1515): a video response is never\n // held by a shared cache, so there is no entry for a second client's\n // `Accept` to be answered from. This tells the BROWSER's own cache — and\n // any intermediary that ignored `private` — that the URL alone does not\n // identify the bytes. Set before the 304 exit below, because a validator\n // handed out without it would be reused across representations.\n res.setHeader('Vary', 'Accept')\n }\n const useVariant =\n !usePoster && !rendition && Boolean(width) && variants.includes(width)\n /**\n * The ETag's representation tag, and the cache key's conscience.\n *\n * A validator is not scoped to a URL in practice — the reasoning the\n * `-dl` suffix below was added for — so two representations of one asset\n * that share a validator can be swapped for each other by any cache that\n * revalidates. Between an image variant and its original that is a wrong\n * size; between a poster and its video it is a 40 KB still standing in\n * for a 40 MB film, or the reverse.\n */\n const representation = usePoster\n ? `-poster${usePosterVariant ? `-w${width}` : ''}`\n : rendition\n ? `-r${rendition.key}`\n : useVariant\n ? `-w${width}`\n : ''\n // Read only here, past every gate — a refusal above returns before the\n // parameter is ever looked at, so `?download=1` can never be the reason\n // a response happens (AGL-1411).\n const download = wantsMediaDownload(req.query['download'])\n\n // Stable URL: revalidate against an ETag so a replaced asset is picked\n // up (a conditional GET returns 304 while the content is unchanged).\n //\n // The disposition is part of the ETag for the same reason the variant\n // width is. The query string is already part of the CDN cache key, so\n // the two URLs are separate edge entries — but a validator is not scoped\n // to a URL in practice: a client holding the inline ETag that revalidates\n // the download URL would be answered 304 and reuse its stored INLINE\n // headers, and the file would open in a tab anyway. Same bytes, different\n // representation, so: different validator.\n const etag = currentHash\n ? `\"${currentHash}${representation}${download ? '-dl' : ''}\"`\n : null\n // AGL-1515: which cache tier may hold this response is a function of the\n // served type — see mediaCdnEdgeCacheable. Decided here from the DOC's\n // type (a variant serve is always `image/webp`) because the 304 exit\n // below runs before the Storage metadata read; re-derived from the\n // authoritative served type once metadata is in hand.\n const stableCacheControlFor = (type: unknown) =>\n mediaCdnEdgeCacheable(type)\n ? MEDIA_CDN_STABLE_CACHE_CONTROL\n : MEDIA_CDN_STABLE_EDGE_BYPASS_CACHE_CONTROL\n // A poster is `image/webp` and therefore edge-cacheable through the rule\n // that already exists — which is the whole delivery argument for it\n // (AGL-2743). `mediaCdnEdgeCacheable` is untouched: nothing here relaxes\n // AGL-1515, because a poster genuinely IS an image and no player ranges\n // into a `<video poster>`. A RENDITION reports its own `video/*` type and\n // stays origin-only, deliberately — a small fixed-size rendition is\n // exactly the size class Vercel's 10 MB cap admits, so edge-caching one\n // would maximize exposure to the very hybrid AGL-1515 recorded rather\n // than avoid it.\n const docServedType =\n usePoster || useVariant\n ? 'image/webp'\n : rendition\n ? rendition.contentType\n : snapshot.get('contentType')\n /*\n * VIDEO FROM THE DELIVERY PROVIDER (AGL-2824).\n *\n * Every gate above has run: the scope, lockdown and quarantine, the\n * private signature and the stale-pin redirect. With the representation\n * chosen, a video whose current copy sits at the configured delivery\n * provider is answered with a `302` to a short-lived signed URL there, and\n * the provider serves the bytes and their ranges. `mediaDeliveryRedirect`\n * says null for everything else — an image, a poster, no copy of this\n * representation made from the current bytes, the release flag off for\n * the owning org — and the request carries on below exactly as before.\n *\n * With no provider configured to deliver, nothing here runs: the check is\n * synchronous and reads nothing.\n *\n * A download stays here, because its disposition is this route's to set.\n * The redirect is decided before the ETag and the 304: it names a URL\n * that expires, so it carries no validator and `private, no-store`, and a\n * private asset's URL expires no later than the signature that reached\n * it. It is not counted against the caller's delivery budget, which\n * guards the bytes this route sends; a redirect sends none.\n */\n const deliveryProvider =\n usePoster || useVariant || download ? null : mediaDeliveryProvider('deliver')\n if (deliveryProvider) {\n const delivery = await mediaDeliveryRedirect({\n provider: deliveryProvider,\n asset: { collection: isOrg ? 'orgs' : 'hosts', scopeId, mediaId },\n document: snapshot,\n rendition,\n servedType: docServedType,\n claims: {\n scope: scopeSegment,\n mediaId,\n hostId: isOrg ? (scope.contextHostId ?? null) : scopeId,\n },\n orgId: () => mediaDeliveryOrgIdFor(isOrg ? 'orgs' : 'hosts', scopeId),\n ...(isPrivate ? { notAfterMs: Number(req.query['exp']) } : {}),\n }).catch((error) => {\n // The provider is an alternative to the path below, never a reason\n // for this request to fail.\n console.error('[media-cdn] delivery redirect failed', scopeSegment, mediaId, error)\n return null\n })\n if (delivery) {\n res.setHeader('Cache-Control', 'private, no-store')\n res.setHeader('Location', delivery.location)\n // A play starts here, so it is counted here. `redirects` says how many\n // of the serves left through the provider; the bytes are the\n // provider's to measure, because none leave from this route.\n if (req.method === 'GET') {\n const day = new Date().toISOString().slice(0, 10)\n void firestore\n .collection(isOrg ? 'orgs' : 'hosts')\n .doc(scopeId)\n .collection('analytics')\n .doc(day)\n .set(\n {\n expiresAt: analyticsDayExpiresAt(day),\n media: {\n [mediaId]: {\n serves: firebaseAdmin.firestore.FieldValue.increment(1),\n redirects: firebaseAdmin.firestore.FieldValue.increment(1),\n },\n },\n },\n { merge: true },\n )\n .catch(() => undefined)\n }\n res.status(302).end()\n return\n }\n }\n if (!hashed) {\n setCacheControl(stableCacheControlFor(docServedType))\n if (etag) res.setHeader('ETag', etag)\n if (etag && req.headers['if-none-match'] === etag) {\n res.status(304).end()\n return\n }\n }\n\n const bucket = firebaseAdmin\n .app()\n .storage()\n .bucket(process.env['NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET'])\n // Real folders: the doc records its object path; legacy assets fall\n // back to the flat layout.\n //\n // The recorded path is CLIENT DATA and this is an ADMIN-SDK bucket read,\n // which the Storage rules do not constrain — so it is honoured only when\n // it is genuinely inside this scope's media prefix (AGL-1881). Without\n // that check a host or org editor could point their own media document at\n // any key in the shared bucket and have this route stream it to an\n // anonymous caller behind a `s-maxage=3600` edge-cached URL, including the\n // fixed `adminAudit-archive/` and `erasures/` retention prefixes.\n const basePath = mediaStoragePathInScope({\n storagePath: snapshot.get('storagePath'),\n base: `${isOrg ? 'orgs' : 'hosts'}/${scopeId}`,\n mediaId,\n onRefused: (candidate) => {\n console.error(\n '[media-cdn] out-of-scope storagePath refused',\n JSON.stringify({ scopeId, mediaId, candidate }),\n )\n },\n })\n // Every derived path is built from `basePath`, which `mediaStoragePathInScope`\n // has already proved is inside this scope's prefix (AGL-1881), plus a\n // suffix whose grammar admits no separator: the widths are numbers,\n // and `parseMediaRendition` refuses a key or extension that is not\n // `[a-z0-9-]`. So no representation can address an object the master\n // could not.\n const objectPath = usePoster\n ? usePosterVariant\n ? `${basePath}${MEDIA_POSTER_OBJECT_SUFFIX}__w${width}.webp`\n : mediaPosterObjectPath(basePath)\n : rendition\n ? mediaRenditionObjectPath(basePath, rendition)\n : useVariant\n ? `${basePath}__w${width}.webp`\n : basePath\n const file = bucket.file(objectPath)\n // The caller's count (AGL-2812), asked here and nowhere earlier: past every\n // gate and the 304 exit, where the Storage reads begin. It starts before the\n // metadata read and is awaited after it, so the two run together. It never\n // rejects, and answers `null` whenever it could not count.\n const callerCount =\n req.method === 'GET'\n ? mediaCdnRateLimitRefusal({\n headers: req.headers,\n remoteAddress: req.socket?.remoteAddress,\n rateClass: mediaCdnEdgeCacheable(docServedType) ? 'image' : 'non-image',\n })\n : null\n const [metadata] = await file.getMetadata().catch(() => [null as any])\n if (!metadata) {\n res.status(404).json({ error: 'Not found' })\n return\n }\n const refused = await callerCount\n if (refused) {\n // The file's validator and cache policy are already set. A refusal is\n // about this caller rather than the URL, so no cache may keep it: an\n // edge holding a 429 would refuse every visitor to that image for an\n // hour.\n clearMediaCdnRepresentation(res)\n res.setHeader('Retry-After', String(refused.retryAfterSeconds))\n res.status(429).json({ error: 'Too many requests' })\n return\n }\n\n const servedType =\n usePoster || useVariant\n ? 'image/webp'\n : rendition\n ? rendition.contentType\n : String(\n metadata.contentType ??\n snapshot.get('contentType') ??\n 'application/octet-stream',\n )\n res.setHeader('Content-Type', servedType)\n // AGL-1474: an SVG (or anything else a browser treats as a document) gets\n // the sandboxing policy. Everything else keeps the base one set above —\n // `sandbox` is withheld from raster and PDF responses on purpose, since it\n // would change how a directly-opened PDF is handled for no security gain.\n res.setHeader(\n 'Content-Security-Policy',\n mediaCdnContentSecurityPolicy(servedType),\n )\n // Range support (AGL-1442 S4) — this is what lets video ride this route\n // at all: a `<video>` seek is a Range request, and before S4 the raw\n // storage URL was the only server that would answer one.\n //\n // `Accept-Ranges` is advertised unconditionally because it is now TRUE\n // unconditionally — the handler honors a single byte-range for every\n // asset class. Limiting it to \"types that benefit\" would only teach a\n // PDF viewer or a download manager not to ask for something we would\n // happily serve, and the header is not part of any cache key.\n //\n // Caching shape (AGL-1515): S4 read Vercel's cacheable-response\n // criteria (\"Request doesn't contain Range header\") as \"a cached full\n // body and a function-served partial can never cross\". Production\n // falsified that: the criteria govern what the edge STORES, not what it\n // SERVES, and the edge answers a ranged request from an existing cached\n // full-body 200 as a 200 + Content-Range + sliced-body hybrid. The fix\n // is upstream of this line — every type a ranged consumer actually uses\n // is served `private` (see mediaCdnEdgeCacheable), so the entry the\n // edge would mangle never exists and every ranged request reaches this\n // function for a real 206. In the browser the 206 rides the same\n // Cache-Control as its URL class: a 206 under a STRONG validator is\n // exactly what lets a player reuse the segments it already fetched.\n res.setHeader('Accept-Ranges', 'bytes')\n // The authoritative tier decision, now that the served type is known\n // from Storage metadata rather than inferred from the doc. Overwrites\n // the header set before the 304 exit iff the two disagree — and the\n // BODY-serving response is the one the edge could store, so this one\n // must win.\n if (!hashed) setCacheControl(stableCacheControlFor(servedType))\n const size = Number(metadata.size ?? NaN)\n // Range applies to GET only (RFC 9110 §14.2); a HEAD answers the full\n // representation's metadata. And with no known size there is no honest\n // `Content-Range` to write, so the header is ignored and the full body\n // served — the degradation every unrecognised shape shares.\n const parsed =\n req.method === 'GET' && Number.isFinite(size) && size >= 0\n ? parseMediaCdnRange(req.headers['range'], size)\n : null\n // `If-Range`: the client is saying \"this range is against version X; if\n // you hold anything else, send me the whole file\". Honoring the range on\n // a mismatch is how a stale player splices two versions of a video into\n // one stream — so anything but an exact match with the CURRENT strong\n // validator (including a date form, and including the no-hash legacy\n // shape that has no validator at all) collapses to a full 200.\n const ifRange = req.headers['if-range']\n const range =\n parsed !== null && typeof ifRange === 'string' && ifRange !== etag\n ? null\n : parsed\n if (range === 'unsatisfiable') {\n // The refusal is a function of the REQUEST header, not the URL, and\n // shared caches key on the URL — no cache may keep it.\n setCacheControl('private, no-store')\n res.setHeader('Content-Range', `bytes */${size}`)\n res.status(416).end()\n return\n }\n const partial = range !== null && typeof range === 'object'\n const servedBytes = partial\n ? range.end - range.start + 1\n : Number(metadata.size ?? 0)\n if (partial) {\n res.setHeader('Content-Range', `bytes ${range.start}-${range.end}/${size}`)\n res.setHeader('Content-Length', String(servedBytes))\n } else if (metadata.size) {\n res.setHeader('Content-Length', String(metadata.size))\n }\n // Give downloads a real filename+extension (AGL-834): the URL is\n // mediaId-keyed and extensionless, so without this a \"save image\" lands\n // as a name-less blob. `?download=1` makes it an actual download rather\n // than a tab (AGL-1411).\n res.setHeader(\n 'Content-Disposition',\n mediaContentDisposition(\n mediaDownloadName(snapshot.get('fileName'), mediaId),\n // `?download=1` can force a download; nothing can force an INLINE\n // render of a type that has no inline use here.\n { download: download || !servesInline(servedType) },\n ),\n )\n // `immutable` for a year is the strongest possible caching, and on a\n // private asset it would be a permanent public copy of a file whose\n // whole point is that it expires (AGL-1051) — `setCacheControl` holds\n // that line. The year stays browser-only for non-image types\n // (AGL-1515): the URL still changes with the bytes, but the edge must\n // hold no full body it could slice.\n if (hashed) {\n setCacheControl(\n mediaCdnEdgeCacheable(servedType)\n ? MEDIA_CDN_IMMUTABLE_CACHE_CONTROL\n : MEDIA_CDN_IMMUTABLE_EDGE_BYPASS_CACHE_CONTROL,\n )\n }\n\n // HEAD returns here, before the delivery counter below (AGL-2811). It\n // carries a GET's headers and no body, and `servedBytes` is the whole\n // object for any request without a range. `serves` and `bytes` count\n // representations that left, which is also why the 304 and 416 exits\n // above return before this point.\n if (req.method === 'HEAD') {\n res.status(200).end()\n return\n }\n\n // Delivery volume (AGL-176): per-asset serves/bytes on the AGL-82\n // analytics day-doc, fire-and-forget. Only cache MISSES reach this\n // code — edge-cached responses aren't counted, so these are origin\n // serves, not user-facing totals (billing accuracy is AGL-41's job).\n // Hot-doc note: a single day-doc caps at ~1 write/sec sustained;\n // acceptable at current traffic, shard or sample if an asset gets hot.\n //\n // Written before the first byte, so `bytes` is what this request asked\n // the origin to send. A client that abandons the stream receives less;\n // the figure is the ceiling on what left, not a count of what arrived.\n const day = new Date().toISOString().slice(0, 10)\n void firestore\n .collection(isOrg ? 'orgs' : 'hosts')\n .doc(scopeId)\n .collection('analytics')\n .doc(day)\n .set(\n {\n // Retention (AGL-1844): every writer of a day doc stamps the\n // day-anchored expiry the TTL policy sweeps on.\n expiresAt: analyticsDayExpiresAt(day),\n media: {\n [mediaId]: {\n serves: firebaseAdmin.firestore.FieldValue.increment(1),\n // The bytes that actually leave, not the object's size — a\n // seek in a 200 MB video is a few MB of egress, and counting\n // the full object per range would overstate delivery by the\n // number of seeks (AGL-1442 S4).\n bytes: firebaseAdmin.firestore.FieldValue.increment(servedBytes),\n },\n },\n },\n { merge: true },\n )\n .catch(() => undefined)\n if (partial) res.status(206)\n // `start`/`end` are inclusive in `createReadStream`, matching the parsed\n // range — GCS is asked for exactly the requested bytes and nothing is\n // over-read from Storage on a partial serve.\n //\n // The response streams (AGL-2810): each chunk leaves as Storage produces\n // it, and the next is read only once the client has taken the last, so a\n // file is never held in function memory whatever its size. `pipeline`\n // rather than `pipe` because streaming needs teardown in both directions,\n // which `pipe` does not give — a failed Storage read must fail the\n // response, and a client that stops reading must stop the Storage read.\n await pipeline(\n file.createReadStream(partial ? { start: range.start, end: range.end } : {}),\n res,\n )\n } catch (error) {\n if (mediaCdnClientWentAway(error, res)) return\n console.error('serveMediaCdn failed', scopeSegment, mediaId, error)\n if (!res.headersSent) {\n clearMediaCdnRepresentation(res)\n res.status(500).json({ error: 'Delivery failed' })\n } else {\n // The status line has already left, so the body is the only place the\n // failure can surface. A destroyed response is a broken transfer to the\n // client; ending it would pass a truncated file off as a whole one.\n res.destroy(error instanceof Error ? error : new Error(String(error)))\n }\n }\n}\n"],"names":["pipeline","isLockdownActive","MEDIA_CDN_POSTER_PARAM","MEDIA_CDN_RENDITION_AUTO","MEDIA_CDN_RENDITION_PARAM","MEDIA_CDN_ROUTE","MEDIA_POSTER_OBJECT_SUFFIX","mediaPosterObjectPath","mediaRenditionObjectPath","normalizeHostLockdown","normalizeOrgLockdown","parseMediaRenditions","MEDIA_CDN_SEGMENT","mediaCdnScopeRefusal","parseMediaCdnScope","mediaDeliveryProvider","analyticsDayExpiresAt","firebaseAdmin","getPlatformLockdown","mediaCdnRateLimitRefusal","mediaDeliveryOrgIdFor","mediaDeliveryRedirect","getMediaQuarantine","verifyMediaAccess","mediaStoragePathInScope","MEDIA_CDN_VARIANT_WIDTHS","mediaCdnAllows","SEGMENT","mediaCdnForwardedQuery","query","params","URLSearchParams","key","raw","value","Array","isArray","undefined","set","String","encoded","toString","MEDIA_CDN_STABLE_CACHE_CONTROL","MEDIA_CDN_STABLE_EDGE_BYPASS_CACHE_CONTROL","MEDIA_CDN_IMMUTABLE_CACHE_CONTROL","MEDIA_CDN_IMMUTABLE_EDGE_BYPASS_CACHE_CONTROL","mediaCdnEdgeCacheable","contentType","split","trim","toLowerCase","startsWith","MEDIA_CDN_BASE_CSP","MEDIA_CDN_ACTIVE_DOCUMENT_CSP","MEDIA_CDN_ACTIVE_DOCUMENT_TYPES","Set","servesInline","type","mediaCdnContentSecurityPolicy","has","lockdownStopsMediaDelivery","state","nowMs","reason","MEDIA_CDN_LOCK_TTL_MS","lockCache","Map","lockPending","invalidateMediaCdnLockCache","clear","SUSPENSION_FIELDS","HOST_INDEX_ORG_FIELD","suspensionCarrier","snapshot","Object","fromEntries","map","field","get","mediaCdnScopeLocked","scope","isOrg","scopeId","cached","Date","now","at","blocked","pending","firestore","app","org","getAll","collection","doc","fieldMask","host","hostIndex","orgId","finally","delete","mediaCdnServeBlock","asset","quarantined","contentSha256","contentHash","scopeSegment","mediaId","wantsMediaDownload","normalized","mediaCdnWantsPoster","MEDIA_CDN_BASELINE_RENDITION_TYPE","parseAcceptedTypes","header","named","refused","part","name","includes","isRefusal","some","param","test","Number","add","selectAutoRendition","renditions","acceptHeader","length","typeOf","entry","find","NON_ASCII_FIELD_VALUE","NOT_QUOTED_STRING_SAFE","mediaDownloadName","fileName","base","pop","from","slice","join","mediaContentDisposition","options","download","ascii","replace","encodeURIComponent","character","charCodeAt","toUpperCase","padStart","parseMediaCdnRange","size","unit","exec","specs","spec","startRaw","endRaw","suffix","isSafeInteger","start","Math","max","end","min","mediaCdnClientWentAway","error","res","code","errored","clearMediaCdnRepresentation","removeHeader","setHeader","serveMediaCdn","req","method","status","path","hash","hashed","json","metadata","currentHash","exists","blockedBy","refusal","console","JSON","stringify","isPrivate","setCacheControl","signed","exp","sig","width","variants","poster","posterVariants","wantsPoster","usePoster","usePosterVariant","Boolean","renditionParam","renditionKey","negotiated","availableRenditions","rendition","headers","useVariant","representation","etag","stableCacheControlFor","docServedType","deliveryProvider","delivery","provider","document","servedType","claims","hostId","contextHostId","notAfterMs","catch","location","day","toISOString","expiresAt","media","serves","FieldValue","increment","redirects","merge","bucket","storage","process","env","basePath","storagePath","onRefused","candidate","objectPath","file","callerCount","remoteAddress","socket","rateClass","getMetadata","retryAfterSeconds","NaN","parsed","isFinite","ifRange","range","partial","servedBytes","bytes","createReadStream","headersSent","destroy","Error"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,QAAQ,QAAQ,uBAAsB;AAC/C,SACEC,gBAAgB,EAEhBC,sBAAsB,EACtBC,wBAAwB,EACxBC,yBAAyB,EACzBC,eAAe,EACfC,0BAA0B,EAC1BC,qBAAqB,EACrBC,wBAAwB,EAExBC,qBAAqB,EACrBC,oBAAoB,EACpBC,oBAAoB,QACf,sBAAqB;AAC5B,8EAA8E;AAC9E,SACEC,iBAAiB,EAEjBC,oBAAoB,EACpBC,kBAAkB,QACb,yCAAwC;AAC/C,SAASC,qBAAqB,QAAQ,sDAAqD;AAE3F,SAASC,qBAAqB,QAAQ,2BAAuB;AAC7D,SAASC,aAAa,QAAQ,sBAAkB;AAChD,SAASC,mBAAmB,QAAQ,gBAAY;AAChD,SAASC,wBAAwB,QAAQ,4BAAwB;AACjE,SAASC,qBAAqB,EAAEC,qBAAqB,QAAQ,sBAAkB;AAC/E,SAASC,kBAAkB,QAAQ,wBAAoB;AACvD,SAASC,iBAAiB,QAAQ,qBAAiB;AACnD,SAASC,uBAAuB,QAAQ,0BAAsB;AAE9D;;;;;;CAMC,GACD,SAASC,wBAAwB,QAAQ,sBAAqB;AAE9D;;;;;;;CAOC,GACD,SACEC,cAAc,EAGdb,oBAAoB,EACpBC,kBAAkB,QACb,yCAAwC;AAE/C,MAAMa,UAAUf;AAEhB;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAAS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CAACC,SAAS,CAAC;oBACrD,2DAA2D;oBAC3D,6DAA6D;oBAC7D,4DAA4D;oBAC5D,iCAAiC;oBACjC0B,OAAOhP,cAAcwE,SAAS,CAAC6I,UAAU,CAACC,SAAS,CAACyB;gBACtD;YACF;QACF,GACA;YAAEvB,OAAO;QAAK,GAEfV,KAAK,CAAC,IAAM1L;QACf,IAAI0N,SAASvF,IAAIS,MAAM,CAAC;QACxB,yEAAyE;QACzE,sEAAsE;QACtE,6CAA6C;QAC7C,EAAE;QACF,yEAAyE;QACzE,yEAAyE;QACzE,sEAAsE;QACtE,0EAA0E;QAC1E,mEAAmE;QACnE,wEAAwE;QACxE,MAAMjL,SACJmP,KAAKe,gBAAgB,CAACH,UAAU;YAAE9F,OAAO6F,MAAM7F,KAAK;YAAEG,KAAK0F,MAAM1F,GAAG;QAAC,IAAI,CAAC,IAC1EI;IAEJ,EAAE,OAAOD,OAAO;QACd,IAAID,uBAAuBC,OAAOC,MAAM;QACxCmB,QAAQpB,KAAK,CAAC,wBAAwB7D,cAAcC,SAAS4D;QAC7D,IAAI,CAACC,IAAI2F,WAAW,EAAE;YACpBxF,4BAA4BH;YAC5BA,IAAIS,MAAM,CAAC,KAAKI,IAAI,CAAC;gBAAEd,OAAO;YAAkB;QAClD,OAAO;YACL,sEAAsE;YACtE,wEAAwE;YACxE,oEAAoE;YACpEC,IAAI4F,OAAO,CAAC7F,iBAAiB8F,QAAQ9F,QAAQ,IAAI8F,MAAM9N,OAAOgI;QAChE;IACF;AACF"}
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ import type { NextApiRequest, NextApiResponse } from 'next';
18
+ import { Agent } from 'undici';
19
+ /**
20
+ * SSRF hardening (AGL-515): even an https, allowlisted origin can resolve to
21
+ * an internal address (a plugin author pointing DNS at 127.0.0.1 / the cloud
22
+ * metadata endpoint). Resolve the host and return a single validated PUBLIC
23
+ * address to pin the connection to (null if any resolved address is private).
24
+ * Pinning the exact IP the fetch connects to closes the DNS-rebinding TOCTOU —
25
+ * the name can't re-resolve to an internal target between check and connect.
26
+ */
27
+ export declare function resolvePublicIp(hostname: string): Promise<string | null>;
28
+ /**
29
+ * Build the dispatcher that pins the socket to `pinnedIp` (AGL-515). A custom
30
+ * `connect.lookup` forces the connection to the address `resolvePublicIp`
31
+ * already validated, so the name can't be rebound to an internal target
32
+ * between the check and the connect. TLS SNI / certificate validation still
33
+ * use the original hostname, because only the address resolution is replaced.
34
+ *
35
+ * Exported so the transport itself is covered by a spec (AGL-2480). `undici`
36
+ * is a **declared direct dependency** for exactly this reason: it used to
37
+ * arrive only as a transitive of the dev-only `jsdom`, which meant a
38
+ * `--omit=dev` install had no `undici` at all and a jsdom bump silently
39
+ * re-versioned the HTTP client behind a production security control. undici 8
40
+ * rejects this `lookup` shape with `UND_ERR_INVALID_ARG` on every request —
41
+ * fail-closed, but the plugin-fetch route stops working outright. The spec
42
+ * drives a real request through this dispatcher so that break is a red test,
43
+ * not a production discovery.
44
+ */
45
+ export declare function createPinnedDispatcher(pinnedIp: string): Agent;
46
+ /**
47
+ * Host-mediated plugin fetch (AGL-191). The sandboxed plugin can't reach
48
+ * the network directly under a strict plugin-origin CSP, so `PluginFrame`
49
+ * forwards a `fetch-request` here and the host proxies it. Mounted in BOTH
50
+ * apps (console for the editor/preview, tenant for the published site) so
51
+ * plugin fetches work wherever the plugin renders — hence public, no
52
+ * admin auth: the security boundary is the ALLOWLIST, re-derived from the
53
+ * host's server-side install record and never trusting the client's claim.
54
+ * https-only, exact-origin, method/body/time capped, and no host
55
+ * credentials are ever forwarded — a plugin can only reach origins it
56
+ * declared at install (surfaced on the install screen).
57
+ *
58
+ * Abuse note: this uses platform egress to origins the plugin already
59
+ * declared; a per-listing rate limit is a sensible follow-up.
60
+ */
61
+ export declare function servePluginFetch(req: NextApiRequest, res: NextApiResponse): Promise<void>;
@@ -0,0 +1,294 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ /**
3
+ * @license
4
+ * Copyright 2026 Aglyn LLC
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */ import { isPluginNetworkAllowed, PLUGIN_FETCH_MAX_BODY_BYTES } from "@aglyn/aglyn/server";
18
+ import { lookup } from "node:dns/promises";
19
+ import { isIPv4, isIPv6 } from "net";
20
+ import { Agent } from "undici";
21
+ import { firebaseAdmin } from "./firebase-admin.js";
22
+ const FETCH_TIMEOUT_MS = 8000;
23
+ /**
24
+ * Redirect hops the proxy will follow, each one re-validated (AGL-1881).
25
+ * Small on purpose: a legitimate API redirects once (http->https is refused
26
+ * outright by the allowlist, so in practice this is a path or host alias).
27
+ */ const MAX_REDIRECT_HOPS = 3;
28
+ /** The statuses `redirect: 'manual'` hands back instead of following. */ const REDIRECT_STATUSES = new Set([
29
+ 301,
30
+ 302,
31
+ 303,
32
+ 307,
33
+ 308
34
+ ]);
35
+ /** True for loopback / private / link-local / CGNAT / ULA addresses. */ function isPrivateIp(ip) {
36
+ if (isIPv4(ip)) {
37
+ const [a, b] = ip.split('.').map(Number);
38
+ if (a === 0 || a === 10 || a === 127) return true;
39
+ if (a === 169 && b === 254) return true // link-local + cloud metadata
40
+ ;
41
+ if (a === 172 && b >= 16 && b <= 31) return true;
42
+ if (a === 192 && b === 168) return true;
43
+ if (a === 100 && b >= 64 && b <= 127) return true // CGNAT
44
+ ;
45
+ // The ranges AGL-1881 found missing. None is routable on the public
46
+ // internet, so refusing them costs a plugin nothing:
47
+ if (a === 192 && b === 0) return true // 192.0.0.0/24 IETF protocol
48
+ ;
49
+ if (a === 198 && (b === 18 || b === 19)) return true // 198.18/15 benchmark
50
+ ;
51
+ if (a >= 224) return true // 224/4 multicast, 240/4 reserved, broadcast
52
+ ;
53
+ return false;
54
+ }
55
+ if (isIPv6(ip)) {
56
+ const low = ip.toLowerCase();
57
+ if (low === '::1' || low === '::') return true;
58
+ if (low.startsWith('fc') || low.startsWith('fd')) return true // ULA
59
+ ;
60
+ // Link-local is fe80::/10 — fe80 through febf, not the fe80 prefix
61
+ // alone (AGL-1881). `fec0::/10` site-local is deprecated but inside the
62
+ // same span, so one test covers both.
63
+ if (/^fe[89ab]/.test(low)) return true // link-local fe80::/10
64
+ ;
65
+ if (low.startsWith('::ffff:')) return isPrivateIp(low.slice(7)) // v4-mapped
66
+ ;
67
+ return false;
68
+ }
69
+ return true // unparseable → refuse
70
+ ;
71
+ }
72
+ /**
73
+ * SSRF hardening (AGL-515): even an https, allowlisted origin can resolve to
74
+ * an internal address (a plugin author pointing DNS at 127.0.0.1 / the cloud
75
+ * metadata endpoint). Resolve the host and return a single validated PUBLIC
76
+ * address to pin the connection to (null if any resolved address is private).
77
+ * Pinning the exact IP the fetch connects to closes the DNS-rebinding TOCTOU —
78
+ * the name can't re-resolve to an internal target between check and connect.
79
+ */ export async function resolvePublicIp(hostname) {
80
+ try {
81
+ const addresses = await lookup(hostname, {
82
+ all: true
83
+ });
84
+ if (!addresses.length) return null;
85
+ if (addresses.some((a)=>isPrivateIp(a.address))) return null;
86
+ return addresses[0].address;
87
+ } catch (unused) {
88
+ return null;
89
+ }
90
+ }
91
+ /**
92
+ * Build the dispatcher that pins the socket to `pinnedIp` (AGL-515). A custom
93
+ * `connect.lookup` forces the connection to the address `resolvePublicIp`
94
+ * already validated, so the name can't be rebound to an internal target
95
+ * between the check and the connect. TLS SNI / certificate validation still
96
+ * use the original hostname, because only the address resolution is replaced.
97
+ *
98
+ * Exported so the transport itself is covered by a spec (AGL-2480). `undici`
99
+ * is a **declared direct dependency** for exactly this reason: it used to
100
+ * arrive only as a transitive of the dev-only `jsdom`, which meant a
101
+ * `--omit=dev` install had no `undici` at all and a jsdom bump silently
102
+ * re-versioned the HTTP client behind a production security control. undici 8
103
+ * rejects this `lookup` shape with `UND_ERR_INVALID_ARG` on every request —
104
+ * fail-closed, but the plugin-fetch route stops working outright. The spec
105
+ * drives a real request through this dispatcher so that break is a red test,
106
+ * not a production discovery.
107
+ */ export function createPinnedDispatcher(pinnedIp) {
108
+ const family = isIPv6(pinnedIp) ? 6 : 4;
109
+ return new Agent({
110
+ connect: {
111
+ lookup: (_host, options, cb)=>options && options.all ? cb(null, [
112
+ {
113
+ address: pinnedIp,
114
+ family
115
+ }
116
+ ]) : cb(null, pinnedIp, family)
117
+ }
118
+ });
119
+ }
120
+ /**
121
+ * Host-mediated plugin fetch (AGL-191). The sandboxed plugin can't reach
122
+ * the network directly under a strict plugin-origin CSP, so `PluginFrame`
123
+ * forwards a `fetch-request` here and the host proxies it. Mounted in BOTH
124
+ * apps (console for the editor/preview, tenant for the published site) so
125
+ * plugin fetches work wherever the plugin renders — hence public, no
126
+ * admin auth: the security boundary is the ALLOWLIST, re-derived from the
127
+ * host's server-side install record and never trusting the client's claim.
128
+ * https-only, exact-origin, method/body/time capped, and no host
129
+ * credentials are ever forwarded — a plugin can only reach origins it
130
+ * declared at install (surfaced on the install screen).
131
+ *
132
+ * Abuse note: this uses platform egress to origins the plugin already
133
+ * declared; a per-listing rate limit is a sensible follow-up.
134
+ */ export async function servePluginFetch(req, res) {
135
+ var _req_body, _body_hostId, _body_listingId, _body_url;
136
+ if (req.method !== 'POST') {
137
+ res.setHeader('Allow', 'POST');
138
+ res.status(405).json({
139
+ ok: false,
140
+ status: 0,
141
+ error: 'Method not allowed'
142
+ });
143
+ return;
144
+ }
145
+ const body = typeof req.body === 'string' ? safeJson(req.body) : (_req_body = req.body) != null ? _req_body : {};
146
+ const hostId = String((_body_hostId = body.hostId) != null ? _body_hostId : '');
147
+ const listingId = String((_body_listingId = body.listingId) != null ? _body_listingId : '');
148
+ const url = String((_body_url = body.url) != null ? _body_url : '');
149
+ const method = body.method === 'POST' ? 'POST' : 'GET';
150
+ const requestBody = typeof body.body === 'string' ? body.body : undefined;
151
+ if (!hostId || !listingId || !url) {
152
+ res.status(400).json({
153
+ ok: false,
154
+ status: 0,
155
+ error: 'Bad request'
156
+ });
157
+ return;
158
+ }
159
+ if (requestBody && Buffer.byteLength(requestBody) > PLUGIN_FETCH_MAX_BODY_BYTES) {
160
+ res.status(413).json({
161
+ ok: false,
162
+ status: 0,
163
+ error: 'Body too large'
164
+ });
165
+ return;
166
+ }
167
+ try {
168
+ const install = (await firebaseAdmin.app().firestore().collection('hosts').doc(hostId).collection('installs').doc(listingId).get()).data();
169
+ if (!(install == null ? void 0 : install.manifest)) {
170
+ res.status(404).json({
171
+ ok: false,
172
+ status: 0,
173
+ error: 'Not installed'
174
+ });
175
+ return;
176
+ }
177
+ if (!isPluginNetworkAllowed(url, install.manifest.capabilities)) {
178
+ res.status(403).json({
179
+ ok: false,
180
+ status: 0,
181
+ error: 'URL not in allowlist'
182
+ });
183
+ return;
184
+ }
185
+ // Follow redirects OURSELVES, re-validating every hop (AGL-1881).
186
+ //
187
+ // `fetch` defaults to `redirect: 'follow'`, and every control above runs
188
+ // on the FIRST url only: the allowlist, the https-only check and the
189
+ // pinned dispatcher. A declared, allowlisted, genuinely public origin
190
+ // answering `302 Location: http://169.254.169.254/...` therefore reached
191
+ // the cloud metadata service and returned its body to the caller — on an
192
+ // unauthenticated route. The IP pin did not stop it: Node skips a custom
193
+ // `connect.lookup` when the target is an IP literal, so the redirect
194
+ // connected directly and the pinned lookup was consulted exactly once,
195
+ // for the original hostname.
196
+ //
197
+ // `redirect: 'manual'` hands us each hop instead. Every one re-enters the
198
+ // same two gates the first url passed — the manifest allowlist (which is
199
+ // also what enforces https and the exact origin) and a fresh
200
+ // `resolvePublicIp` with its own pinned dispatcher — so a redirect can
201
+ // only ever reach somewhere the plugin could have named directly.
202
+ let currentUrl = url;
203
+ let upstream;
204
+ for(let hop = 0;; hop++){
205
+ if (hop > MAX_REDIRECT_HOPS) {
206
+ res.status(403).json({
207
+ ok: false,
208
+ status: 0,
209
+ error: 'Too many redirects'
210
+ });
211
+ return;
212
+ }
213
+ const pinnedIp = await resolvePublicIp(new URL(currentUrl).hostname);
214
+ if (!pinnedIp) {
215
+ res.status(403).json({
216
+ ok: false,
217
+ status: 0,
218
+ error: 'URL resolves to a non-public address'
219
+ });
220
+ return;
221
+ }
222
+ // Pin the socket to the address we just validated (AGL-515).
223
+ const dispatcher = createPinnedDispatcher(pinnedIp);
224
+ const controller = new AbortController();
225
+ const timeout = setTimeout(()=>controller.abort(), FETCH_TIMEOUT_MS);
226
+ // `dispatcher` is an undici extension not in the DOM RequestInit type;
227
+ // assigning to a variable first avoids the object-literal excess-property
228
+ // check while still passing it through to the (undici) global fetch.
229
+ const requestInit = _extends({
230
+ method,
231
+ signal: controller.signal,
232
+ dispatcher,
233
+ redirect: 'manual',
234
+ headers: {
235
+ Accept: 'application/json, text/*;q=0.9, */*;q=0.1'
236
+ }
237
+ }, method === 'POST' && requestBody ? {
238
+ body: requestBody
239
+ } : {});
240
+ try {
241
+ upstream = await fetch(currentUrl, requestInit);
242
+ } finally{
243
+ clearTimeout(timeout);
244
+ await dispatcher.close().catch(()=>undefined);
245
+ }
246
+ if (!REDIRECT_STATUSES.has(upstream.status)) break;
247
+ const location = upstream.headers.get('location');
248
+ if (!location) break; // a redirect status with no target is just a body
249
+ let nextUrl;
250
+ try {
251
+ nextUrl = new URL(location, currentUrl).toString();
252
+ } catch (unused) {
253
+ res.status(403).json({
254
+ ok: false,
255
+ status: 0,
256
+ error: 'Redirect target is not a URL'
257
+ });
258
+ return;
259
+ }
260
+ if (!isPluginNetworkAllowed(nextUrl, install.manifest.capabilities)) {
261
+ res.status(403).json({
262
+ ok: false,
263
+ status: 0,
264
+ error: 'Redirect target not in allowlist'
265
+ });
266
+ return;
267
+ }
268
+ currentUrl = nextUrl;
269
+ }
270
+ const text = await upstream.text();
271
+ const clipped = Buffer.byteLength(text) > PLUGIN_FETCH_MAX_BODY_BYTES ? text.slice(0, PLUGIN_FETCH_MAX_BODY_BYTES) : text;
272
+ res.status(200).json({
273
+ ok: upstream.ok,
274
+ status: upstream.status,
275
+ body: clipped
276
+ });
277
+ } catch (error) {
278
+ console.error('servePluginFetch failed', hostId, listingId, error);
279
+ res.status(502).json({
280
+ ok: false,
281
+ status: 0,
282
+ error: 'Fetch failed'
283
+ });
284
+ }
285
+ }
286
+ function safeJson(value) {
287
+ try {
288
+ return JSON.parse(value);
289
+ } catch (unused) {
290
+ return {};
291
+ }
292
+ }
293
+
294
+ //# sourceMappingURL=serve-plugin-fetch.js.map