nucleus-core-ts 0.10.147 → 0.10.151

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 (204) hide show
  1. package/LICENSE +48 -48
  2. package/dist/.build-ok +1 -1
  3. package/dist/fe/components/AuthorizationPage/labels.js +13 -13
  4. package/dist/fe/components/Captcha/labels.js +17 -17
  5. package/dist/fe/components/ChatPanel/helpers.js +17 -17
  6. package/dist/fe/components/ChatPanel/labels.js +16 -16
  7. package/dist/fe/components/DataTable/labels.js +16 -16
  8. package/dist/fe/components/DevicesPage/components/DeviceCard.js +15 -15
  9. package/dist/fe/components/DevicesPage/components/DevicesPage.js +9 -9
  10. package/dist/fe/components/DevicesPage/labels.js +12 -12
  11. package/dist/fe/components/ForgotPasswordPage/labels.js +8 -8
  12. package/dist/fe/components/FormBuilder/components/FormField.js +5 -5
  13. package/dist/fe/components/FormBuilder/utils/fieldMapping.js +9 -9
  14. package/dist/fe/components/IntegrationsPage/components/ConnectionAuthFields.js +8 -8
  15. package/dist/fe/components/IntegrationsPage/components/ConnectionBasicFields.js +3 -3
  16. package/dist/fe/components/IntegrationsPage/components/ConnectionExport.js +23 -23
  17. package/dist/fe/components/IntegrationsPage/components/ConnectionForm.js +22 -22
  18. package/dist/fe/components/IntegrationsPage/components/ConnectionList.js +7 -7
  19. package/dist/fe/components/IntegrationsPage/components/ConnectionOauthFields.js +6 -6
  20. package/dist/fe/components/IntegrationsPage/components/ConnectionSettingsTab.js +24 -24
  21. package/dist/fe/components/IntegrationsPage/components/ConnectionSwitcher.js +19 -19
  22. package/dist/fe/components/IntegrationsPage/components/ConnectionTabs.js +15 -15
  23. package/dist/fe/components/IntegrationsPage/components/ConnectionTest.js +21 -21
  24. package/dist/fe/components/IntegrationsPage/components/ConnectionTransfer.js +18 -18
  25. package/dist/fe/components/IntegrationsPage/components/CredentialFields.js +19 -19
  26. package/dist/fe/components/IntegrationsPage/components/CredentialSlotRow.js +8 -8
  27. package/dist/fe/components/IntegrationsPage/components/EndpointForm.js +7 -7
  28. package/dist/fe/components/IntegrationsPage/components/EndpointFormFields.js +12 -12
  29. package/dist/fe/components/IntegrationsPage/components/EndpointList.js +7 -7
  30. package/dist/fe/components/IntegrationsPage/components/EndpointSample.js +36 -36
  31. package/dist/fe/components/IntegrationsPage/components/EndpointsTab.js +29 -29
  32. package/dist/fe/components/IntegrationsPage/components/FieldMappingRow.js +7 -7
  33. package/dist/fe/components/IntegrationsPage/components/FieldMappingRows.js +6 -6
  34. package/dist/fe/components/IntegrationsPage/components/IntegrationsPage.js +60 -60
  35. package/dist/fe/components/IntegrationsPage/components/MappingAccountFields.js +15 -15
  36. package/dist/fe/components/IntegrationsPage/components/MappingEditor.js +9 -9
  37. package/dist/fe/components/IntegrationsPage/components/MappingList.js +23 -23
  38. package/dist/fe/components/IntegrationsPage/components/MappingPasswordField.js +12 -12
  39. package/dist/fe/components/IntegrationsPage/components/MappingScheduleFields.js +23 -23
  40. package/dist/fe/components/IntegrationsPage/components/MappingWriteModeFields.js +31 -31
  41. package/dist/fe/components/IntegrationsPage/components/MappingsTab.js +56 -56
  42. package/dist/fe/components/IntegrationsPage/components/PaginationFields.js +11 -11
  43. package/dist/fe/components/IntegrationsPage/components/ParamBindingRows.js +15 -15
  44. package/dist/fe/components/IntegrationsPage/components/Primitives.js +28 -28
  45. package/dist/fe/components/IntegrationsPage/components/ReferenceCheckRows.js +9 -9
  46. package/dist/fe/components/IntegrationsPage/components/RunConfirmStep.js +6 -6
  47. package/dist/fe/components/IntegrationsPage/components/RunHistory.js +6 -6
  48. package/dist/fe/components/IntegrationsPage/components/RunHistoryRow.js +9 -9
  49. package/dist/fe/components/IntegrationsPage/components/RunPanel.js +40 -40
  50. package/dist/fe/components/IntegrationsPage/components/RunPasswordField.js +18 -18
  51. package/dist/fe/components/IntegrationsPage/components/RunPlanIssues.js +6 -6
  52. package/dist/fe/components/IntegrationsPage/components/RunPlanReferences.js +12 -12
  53. package/dist/fe/components/IntegrationsPage/components/RunPlanSuggestions.js +11 -11
  54. package/dist/fe/components/IntegrationsPage/components/RunPlanSummary.js +6 -6
  55. package/dist/fe/components/IntegrationsPage/components/RunProgressBar.js +6 -6
  56. package/dist/fe/components/IntegrationsPage/components/RunRevertConflicts.js +6 -6
  57. package/dist/fe/components/IntegrationsPage/components/Skeletons.js +7 -7
  58. package/dist/fe/components/IntegrationsPage/components/authOptions.js +4 -4
  59. package/dist/fe/components/IntegrationsPage/components/connectionDraft.js +27 -27
  60. package/dist/fe/components/IntegrationsPage/components/credentialSlots.js +25 -25
  61. package/dist/fe/components/IntegrationsPage/components/deleteIsConfirmed.js +9 -9
  62. package/dist/fe/components/IntegrationsPage/components/fieldMappingOptions.js +4 -4
  63. package/dist/fe/components/IntegrationsPage/components/formSupport.js +34 -34
  64. package/dist/fe/components/IntegrationsPage/components/jsonArray.js +14 -14
  65. package/dist/fe/components/IntegrationsPage/components/jsonObjectField.js +15 -15
  66. package/dist/fe/components/IntegrationsPage/components/mappingDraft.js +10 -10
  67. package/dist/fe/components/IntegrationsPage/components/mappingStaleness.js +22 -22
  68. package/dist/fe/components/IntegrationsPage/components/nextRuns.js +8 -8
  69. package/dist/fe/components/IntegrationsPage/components/passwordIsNeeded.js +13 -13
  70. package/dist/fe/components/IntegrationsPage/components/pathParams.js +6 -6
  71. package/dist/fe/components/IntegrationsPage/components/runFormat.js +18 -18
  72. package/dist/fe/components/IntegrationsPage/components/settleOwnership.js +18 -18
  73. package/dist/fe/components/IntegrationsPage/components/useInfiniteList.js +8 -8
  74. package/dist/fe/components/IntegrationsPage/store/index.js +20 -20
  75. package/dist/fe/components/IntegrationsPage/store/upsertInto.js +12 -12
  76. package/dist/fe/components/IntegrationsPage/text/context.js +6 -6
  77. package/dist/fe/components/IntegrationsPage/text/index.js +18 -18
  78. package/dist/fe/components/IntegrationsPage/theme/index.js +29 -29
  79. package/dist/fe/components/IntegrationsPage/types/records.js +10 -10
  80. package/dist/fe/components/IntegrationsPage/types/results.js +3 -3
  81. package/dist/fe/components/NotificationCenter/labels.js +17 -17
  82. package/dist/fe/components/ProfilePage/labels.js +10 -10
  83. package/dist/fe/components/ResetPasswordPage/labels.js +4 -4
  84. package/dist/fe/components/SetPasswordPage/labels.js +11 -11
  85. package/dist/fe/components/UsersPage/labels.js +14 -14
  86. package/dist/fe/utils/columnUtils.js +24 -24
  87. package/dist/fe/utils/searchFold.js +36 -36
  88. package/dist/index.js +6 -6
  89. package/dist/server.js +6 -6
  90. package/dist/src/Client/Proxy/authz.js +4 -4
  91. package/dist/src/Client/Proxy/httpProxy.js +136 -136
  92. package/dist/src/Client/Proxy/largeBody.js +29 -29
  93. package/dist/src/Client/Proxy/utils.js +32 -32
  94. package/dist/src/Client/Proxy/wsProxy.js +59 -59
  95. package/dist/src/Managers/Redis/index.d.ts +14 -0
  96. package/dist/src/Nucleus/routes/auth/admin/impersonationStore.d.ts +3 -4
  97. package/dist/src/Nucleus/routes/auth/refresh/issuedPair.d.ts +67 -0
  98. package/dist/src/Nucleus/routes/auth/refresh/recordIssued.d.ts +15 -6
  99. package/dist/src/Nucleus/routes/auth/refresh/refreshChain.d.ts +56 -0
  100. package/dist/src/Services/Auth/SessionStore/utils.d.ts +2 -0
  101. package/dist/src/Shared/cron.js +71 -71
  102. package/dist/src/Shared/redactSecrets.js +156 -156
  103. package/dist/src/Shared/redaction/bare.js +61 -61
  104. package/dist/src/Shared/redaction/floor.js +48 -48
  105. package/dist/src/Shared/redaction/freeText.js +70 -70
  106. package/dist/src/Shared/redaction/json.js +30 -30
  107. package/dist/src/Shared/redaction/lists.js +23 -23
  108. package/dist/src/Shared/redaction/markers.js +28 -28
  109. package/dist/src/Shared/redaction/names.js +49 -49
  110. package/dist/src/Shared/redaction/pairs.js +54 -54
  111. package/dist/src/Shared/redaction/secretString.js +29 -29
  112. package/dist/src/Shared/redaction/structured.js +52 -52
  113. package/dist/src/Shared/redaction/walk.js +25 -25
  114. package/infra/scripts/generate-project.ts +766 -766
  115. package/infra/templates/README.md +57 -57
  116. package/infra/templates/backend/.dockerignore +9 -9
  117. package/infra/templates/backend/.env.example +15 -15
  118. package/infra/templates/backend/README.md +28 -28
  119. package/infra/templates/backend/azure-pipelines.yml +135 -135
  120. package/infra/templates/backend/k8s/Dockerfile +31 -31
  121. package/infra/templates/backend/k8s/configmap.yaml +26 -26
  122. package/infra/templates/backend/k8s/deployment.yaml +85 -85
  123. package/infra/templates/backend/k8s/pvc.yaml +12 -12
  124. package/infra/templates/backend/k8s/service.yaml +13 -13
  125. package/infra/templates/backend/tsconfig.json +22 -22
  126. package/infra/templates/frontend/.dockerignore +10 -10
  127. package/infra/templates/frontend/.env.example +8 -8
  128. package/infra/templates/frontend/.env.local.example +10 -10
  129. package/infra/templates/frontend/README.md +69 -69
  130. package/infra/templates/frontend/app/[tablename]/page.tsx +37 -37
  131. package/infra/templates/frontend/app/_components/AuthWrapper/index.tsx +63 -63
  132. package/infra/templates/frontend/app/authorization/page.tsx +43 -43
  133. package/infra/templates/frontend/app/change-password/page.tsx +23 -23
  134. package/infra/templates/frontend/app/devices/page.tsx +127 -127
  135. package/infra/templates/frontend/app/forgot-password/page.tsx +20 -20
  136. package/infra/templates/frontend/app/globals.css +28 -28
  137. package/infra/templates/frontend/app/layout.tsx +35 -35
  138. package/infra/templates/frontend/app/login/page.tsx +33 -33
  139. package/infra/templates/frontend/app/page.tsx +565 -565
  140. package/infra/templates/frontend/app/profile/page.tsx +92 -92
  141. package/infra/templates/frontend/app/register/page.tsx +27 -27
  142. package/infra/templates/frontend/app/reset-password/page.tsx +60 -60
  143. package/infra/templates/frontend/app/set-password/page.tsx +43 -43
  144. package/infra/templates/frontend/app/ui-docs/page.tsx +52 -52
  145. package/infra/templates/frontend/app/users/page.tsx +52 -52
  146. package/infra/templates/frontend/app/verify-email/page.tsx +41 -41
  147. package/infra/templates/frontend/app/verify-magic-link/page.tsx +46 -46
  148. package/infra/templates/frontend/azure-pipelines.yml +137 -137
  149. package/infra/templates/frontend/code-and-design-principles.md +438 -438
  150. package/infra/templates/frontend/k8s/Dockerfile +50 -50
  151. package/infra/templates/frontend/k8s/configmap.yaml +18 -18
  152. package/infra/templates/frontend/k8s/deployment.yaml +72 -72
  153. package/infra/templates/frontend/k8s/ingress.yaml +36 -36
  154. package/infra/templates/frontend/k8s/service.yaml +14 -14
  155. package/infra/templates/frontend/lib/api/endpoints.ts +37 -37
  156. package/infra/templates/frontend/lib/api/factory.ts +44 -44
  157. package/infra/templates/frontend/lib/api/hook.ts +10 -10
  158. package/infra/templates/frontend/next.config.ts +19 -19
  159. package/infra/templates/frontend/package.json +34 -34
  160. package/infra/templates/frontend/postcss.config.mjs +5 -5
  161. package/infra/templates/frontend/server.ts +114 -114
  162. package/infra/templates/frontend/tsconfig.json +23 -23
  163. package/package.json +1 -1
  164. package/public/components/CTA.tsx +25 -25
  165. package/public/components/Capabilities.tsx +67 -67
  166. package/public/components/Features.tsx +107 -107
  167. package/public/components/Footer.tsx +58 -58
  168. package/public/components/Hero.tsx +51 -51
  169. package/public/components/Managers.tsx +55 -55
  170. package/public/components/Nav.tsx +91 -91
  171. package/public/components/Stack.tsx +36 -36
  172. package/public/components/docs/Docs.tsx +60 -60
  173. package/public/components/docs/DocsContent.tsx +176 -176
  174. package/public/components/docs/DocsRightSidebar.tsx +53 -53
  175. package/public/components/docs/DocsSidebar.tsx +54 -54
  176. package/public/components/docs/content/authentication.ts +836 -836
  177. package/public/components/docs/content/authorization.ts +268 -268
  178. package/public/components/docs/content/backupRestore.ts +173 -173
  179. package/public/components/docs/content/clientModule.ts +287 -287
  180. package/public/components/docs/content/entityCrud.ts +682 -682
  181. package/public/components/docs/content/monitoring.ts +313 -313
  182. package/public/components/docs/content/multiTenant.ts +269 -269
  183. package/public/components/docs/content/oauthApiKeys.ts +325 -325
  184. package/public/components/docs/content/pubsub.ts +131 -131
  185. package/public/components/docs/content/storageCdn.ts +171 -171
  186. package/public/components/docs/content/verification.ts +289 -289
  187. package/public/components/docs/docsData.ts +113 -113
  188. package/public/components/docs/index.ts +6 -6
  189. package/public/components/index.ts +9 -9
  190. package/public/docs.css +629 -629
  191. package/public/index.html +81 -81
  192. package/public/index.tsx +42 -42
  193. package/public/store.ts +76 -76
  194. package/public/styles.css +858 -858
  195. package/schemas/config.nucleus.json +2651 -2651
  196. package/scripts/audit-purge-noise.ts +120 -120
  197. package/scripts/build.ts +582 -582
  198. package/scripts/generate-system-tables-types.ts +18 -18
  199. package/scripts/generate-types-schema.test.ts +73 -73
  200. package/scripts/generate-types-schema.ts +1284 -1284
  201. package/scripts/packagedScripts.test.ts +87 -87
  202. package/scripts/publish.ts +276 -276
  203. package/scripts/skillCitations.test.ts +107 -107
  204. package/scripts/verify-publishable.ts +40 -40
@@ -80,10 +80,10 @@ function matchesGlob(path, patterns) {
80
80
  }
81
81
  return false;
82
82
  }
83
- /**
84
- * Pure authorization decision. `claims`/`roles` are ALREADY resolved by the caller
85
- * (from the JWT in embed mode, or via the role-claims manifest in resolve mode), so
86
- * this stays mode-agnostic and easy to test.
83
+ /**
84
+ * Pure authorization decision. `claims`/`roles` are ALREADY resolved by the caller
85
+ * (from the JWT in embed mode, or via the role-claims manifest in resolve mode), so
86
+ * this stays mode-agnostic and easy to test.
87
87
  */ export function evaluateAccess(args) {
88
88
  const { manifest, method, path, authenticated, roles, claims, onUnmapped, publicPaths, godminRole, suppressedClaims, firedGuards } = args;
89
89
  if (matchesGlob(path, publicPaths)) return {
@@ -136,33 +136,33 @@ async function performTokenRefresh(refreshConfig, refreshToken, logger, original
136
136
  };
137
137
  }
138
138
  }
139
- /**
140
- * A refresh that DEFINITIVELY failed, remembered just long enough to stop the
141
- * next twenty requests from asking again.
142
- *
143
- * `pendingRefreshes` collapses refreshes that overlap in time; the moment one
144
- * settles its key is dropped, so a page whose widgets fire in sequence gets a
145
- * fresh attempt per widget. Measured on a live install with a revoked session:
146
- * 16 refresh calls in one minute and 51 over ten, every one answered 401, every
147
- * one a round trip to the auth service for an answer that could not change.
148
- *
149
- * Keyed by the same token tail as the dedupe, so a NEW sign-in — a different
150
- * token — is never suppressed. Short-lived on purpose: this is here to collapse
151
- * one page's burst, not to cache a verdict. Anything longer would turn a
152
- * transient blip into a sign-out the user cannot retry their way out of.
139
+ /**
140
+ * A refresh that DEFINITIVELY failed, remembered just long enough to stop the
141
+ * next twenty requests from asking again.
142
+ *
143
+ * `pendingRefreshes` collapses refreshes that overlap in time; the moment one
144
+ * settles its key is dropped, so a page whose widgets fire in sequence gets a
145
+ * fresh attempt per widget. Measured on a live install with a revoked session:
146
+ * 16 refresh calls in one minute and 51 over ten, every one answered 401, every
147
+ * one a round trip to the auth service for an answer that could not change.
148
+ *
149
+ * Keyed by the same token tail as the dedupe, so a NEW sign-in — a different
150
+ * token — is never suppressed. Short-lived on purpose: this is here to collapse
151
+ * one page's burst, not to cache a verdict. Anything longer would turn a
152
+ * transient blip into a sign-out the user cannot retry their way out of.
153
153
  */ const failedRefreshes = new Map();
154
154
  /** How long a failed refresh suppresses another attempt. */ export const REFRESH_FAILURE_MEMORY_MS = 5000;
155
- /**
156
- * A refresh that WORKED, handed to the next requests that still carry the token it
157
- * replaced (0.10.147).
158
- *
159
- * The IDP rotates the refresh token on every refresh and forgives a superseded one
160
- * only inside a 30 s grace. Requests that arrive one after another with the old
161
- * cookie (the browser has not stored the answer yet) each refreshed again, each got
162
- * a different successor, and the browser kept whichever arrived last; the next
163
- * refresh of a token the IDP had already replaced again was taken for a replay and
164
- * the whole session was revoked. Handing every such request the SAME answer keeps
165
- * the pair the browser ends with the one the IDP holds. Kept below the grace.
155
+ /**
156
+ * A refresh that WORKED, handed to the next requests that still carry the token it
157
+ * replaced (0.10.147).
158
+ *
159
+ * The IDP rotates the refresh token on every refresh and forgives a superseded one
160
+ * only inside a 30 s grace. Requests that arrive one after another with the old
161
+ * cookie (the browser has not stored the answer yet) each refreshed again, each got
162
+ * a different successor, and the browser kept whichever arrived last; the next
163
+ * refresh of a token the IDP had already replaced again was taken for a replay and
164
+ * the whole session was revoked. Handing every such request the SAME answer keeps
165
+ * the pair the browser ends with the one the IDP holds. Kept below the grace.
166
166
  */ const recentRefreshes = new Map();
167
167
  /** How long a successful refresh is reused for the token it replaced. */ export const REFRESH_REUSE_MS = 20000;
168
168
  /** Drops what is past its window, so neither map grows with dead tokens. */ function sweepRefreshMemory(nowMs) {
@@ -187,14 +187,14 @@ function recentSuccess(dedupeKey, nowMs) {
187
187
  await response.body?.cancel().catch(()=>undefined);
188
188
  }
189
189
  }
190
- /**
191
- * The key every refresh memory is held under: the SHA-256 of the WHOLE refresh token.
192
- *
193
- * Until 0.10.147 it was the token's last 16 characters. That only ever merged
194
- * overlapping refreshes, but the success memory below hands a fresh access token to
195
- * whoever presents the key for 20 s, and a tail is not the token: anyone who knew a
196
- * session's last 16 characters could have been handed its successor. A full hash
197
- * also keeps raw tokens out of the maps.
190
+ /**
191
+ * The key every refresh memory is held under: the SHA-256 of the WHOLE refresh token.
192
+ *
193
+ * Until 0.10.147 it was the token's last 16 characters. That only ever merged
194
+ * overlapping refreshes, but the success memory below hands a fresh access token to
195
+ * whoever presents the key for 20 s, and a tail is not the token: anyone who knew a
196
+ * session's last 16 characters could have been handed its successor. A full hash
197
+ * also keeps raw tokens out of the maps.
198
198
  */ export function refreshKeyOf(refreshToken) {
199
199
  return new Bun.CryptoHasher('sha256').update(refreshToken).digest('hex');
200
200
  }
@@ -212,11 +212,11 @@ function recentFailure(dedupeKey, nowMs) {
212
212
  failedRefreshes.delete(dedupeKey);
213
213
  return null;
214
214
  }
215
- /**
216
- * One refresh per token at a time, and none again for {@link REFRESH_FAILURE_MEMORY_MS}
217
- * after one failed. A suppressed attempt answers with the remembered failure, so the
218
- * twentieth request of a burst is told `refused` exactly like the first. A refresh that
219
- * worked is handed to the same token's later requests for {@link REFRESH_REUSE_MS}.
215
+ /**
216
+ * One refresh per token at a time, and none again for {@link REFRESH_FAILURE_MEMORY_MS}
217
+ * after one failed. A suppressed attempt answers with the remembered failure, so the
218
+ * twentieth request of a burst is told `refused` exactly like the first. A refresh that
219
+ * worked is handed to the same token's later requests for {@link REFRESH_REUSE_MS}.
220
220
  */ export function deduplicatedRefreshAttempt(refreshConfig, refreshToken, logger, originalCookieHeader) {
221
221
  const dedupeKey = refreshKeyOf(refreshToken);
222
222
  const existing = pendingRefreshes.get(dedupeKey);
@@ -243,11 +243,11 @@ function recentFailure(dedupeKey, nowMs) {
243
243
  });
244
244
  }
245
245
  const promise = performTokenRefresh(refreshConfig, refreshToken, logger, originalCookieHeader).then((attempt)=>{
246
- /*
247
- * Both failures are remembered for the short window: a refusal cannot change
248
- * while that token is in the cookie, and a burst of attempts against an auth
249
- * service that is down only adds load to it. The window is what keeps a
250
- * transient failure retryable.
246
+ /*
247
+ * Both failures are remembered for the short window: a refusal cannot change
248
+ * while that token is in the cookie, and a burst of attempts against an auth
249
+ * service that is down only adds load to it. The window is what keeps a
250
+ * transient failure retryable.
251
251
  */ const now = Date.now();
252
252
  sweepRefreshMemory(now);
253
253
  if (attempt.ok) {
@@ -276,11 +276,11 @@ function appendSetCookieHeaders(responseHeaders, setCookieHeaders) {
276
276
  responseHeaders.append('Set-Cookie', cookie);
277
277
  }
278
278
  }
279
- /**
280
- * Preserve individual Set-Cookie headers when copying via new Headers().
281
- * new Headers(response.headers) may combine multiple Set-Cookie headers
282
- * into a single comma-separated value — browsers cannot parse this for
283
- * Set-Cookie (RFC 6265). This function re-adds them individually.
279
+ /**
280
+ * Preserve individual Set-Cookie headers when copying via new Headers().
281
+ * new Headers(response.headers) may combine multiple Set-Cookie headers
282
+ * into a single comma-separated value — browsers cannot parse this for
283
+ * Set-Cookie (RFC 6265). This function re-adds them individually.
284
284
  */ function preserveSetCookieHeaders(target, source) {
285
285
  const setCookies = typeof source.getSetCookie === 'function' ? source.getSetCookie() : [];
286
286
  if (setCookies.length > 1) {
@@ -290,10 +290,10 @@ function appendSetCookieHeaders(responseHeaders, setCookieHeaders) {
290
290
  }
291
291
  }
292
292
  }
293
- /**
294
- * Resolve the user id to inject as x-user-id from a bearer token, or null if it can't be
295
- * TRUSTED. Fail-closed: returns null unless BOTH a secret and a token are present AND the token
296
- * passes HS256 signature + expiry verification. Never trusts a bare/forged/unsigned token.
293
+ /**
294
+ * Resolve the user id to inject as x-user-id from a bearer token, or null if it can't be
295
+ * TRUSTED. Fail-closed: returns null unless BOTH a secret and a token are present AND the token
296
+ * passes HS256 signature + expiry verification. Never trusts a bare/forged/unsigned token.
297
297
  */ export function resolveInjectedUserId(token, secret) {
298
298
  if (!secret || !token) return null;
299
299
  const payload = verifyJwtHS256(token, secret);
@@ -320,9 +320,9 @@ export function createHttpProxyHandler(config) {
320
320
  }
321
321
  }
322
322
  }
323
- /**
324
- * Claim-gate a request for a target. Returns a 403 Response to block (enforce
325
- * mode), or null to allow (also null in audit mode, where a would-block is logged).
323
+ /**
324
+ * Claim-gate a request for a target. Returns a 403 Response to block (enforce
325
+ * mode), or null to allow (also null in audit mode, where a would-block is logged).
326
326
  */ async function checkAuthorize(req, target, path) {
327
327
  const az = target.authorize;
328
328
  if (!az) return null;
@@ -421,18 +421,18 @@ export function createHttpProxyHandler(config) {
421
421
  }
422
422
  return `${baseUrl}${finalPath}`;
423
423
  }
424
- /**
425
- * The caller's address, from the inbound chain when hops are trusted.
426
- *
427
- * `X-Forwarded-For` is appended left-to-right, so with N trusted proxies in
428
- * front the caller is the entry N from the RIGHT. Counting from the right is
429
- * what makes it unspoofable: a client can prepend anything to the left, but
430
- * it cannot control what the trusted hops append after it.
431
- *
432
- * Returns undefined when the chain is too short to satisfy the configured
433
- * hop count — a chain that does not reach means the deployment is not what
434
- * the configuration says, and inventing an address there would be worse than
435
- * having none.
424
+ /**
425
+ * The caller's address, from the inbound chain when hops are trusted.
426
+ *
427
+ * `X-Forwarded-For` is appended left-to-right, so with N trusted proxies in
428
+ * front the caller is the entry N from the RIGHT. Counting from the right is
429
+ * what makes it unspoofable: a client can prepend anything to the left, but
430
+ * it cannot control what the trusted hops append after it.
431
+ *
432
+ * Returns undefined when the chain is too short to satisfy the configured
433
+ * hop count — a chain that does not reach means the deployment is not what
434
+ * the configuration says, and inventing an address there would be worse than
435
+ * having none.
436
436
  */ function clientFromChain(req, hops) {
437
437
  if (hops <= 0) return undefined;
438
438
  const chain = (req.headers.get('x-forwarded-for') ?? '').split(',').map((one)=>one.trim()).filter(Boolean);
@@ -480,17 +480,17 @@ export function createHttpProxyHandler(config) {
480
480
  'true-client-ip',
481
481
  'x-client-ip'
482
482
  ])headers.delete(h);
483
- /*
484
- * With trusted hops configured, the CHAIN wins over the socket.
485
- *
486
- * The socket peer is only the client when this proxy is the edge. Behind an
487
- * ingress it is the ingress pod, and overwriting the chain with it threw
488
- * away the one value that identified the caller — so everything downstream
489
- * keyed on the address saw a single visitor for the whole cluster.
490
- *
491
- * Still an OVERWRITE, never an append: what is written is a value derived
492
- * from a position the client cannot reach, so a spoofed prefix on the left
493
- * is discarded rather than forwarded.
483
+ /*
484
+ * With trusted hops configured, the CHAIN wins over the socket.
485
+ *
486
+ * The socket peer is only the client when this proxy is the edge. Behind an
487
+ * ingress it is the ingress pod, and overwriting the chain with it threw
488
+ * away the one value that identified the caller — so everything downstream
489
+ * keyed on the address saw a single visitor for the whole cluster.
490
+ *
491
+ * Still an OVERWRITE, never an append: what is written is a value derived
492
+ * from a position the client cannot reach, so a spoofed prefix on the left
493
+ * is discarded rather than forwarded.
494
494
  */ const resolved = clientFromChain(req, config.trustedProxyHops ?? 0) ?? clientIp;
495
495
  if (resolved) {
496
496
  headers.set('x-forwarded-for', resolved);
@@ -540,30 +540,30 @@ export function createHttpProxyHandler(config) {
540
540
  function injectToken(headers, token, headerName) {
541
541
  headers.set(headerName, `Bearer ${token}`);
542
542
  }
543
- /**
544
- * Forward one request upstream, bounded by BOTH clocks that can end it.
545
- *
546
- * The timeout below only bounds time-to-first-headers: it is cleared the
547
- * moment headers arrive, because a streamed body (SSE, a long download, a
548
- * model's token stream) legitimately takes as long as it takes. That is
549
- * correct — but on its own it left a streamed request with NO way to end.
550
- *
551
- * So when the person closed the tab, the browser's connection went away and
552
- * ours did not. The upstream request stayed open, holding one of the
553
- * runtime's outgoing connection slots, forever.
554
- *
555
- * That is not a slow leak. Measured on Bun 1.3.14: 256 clients that connect
556
- * and hang up leave 256 upstream requests open (0 cancelled), and the process
557
- * can then make no outgoing request at all — every later fetch times out.
558
- * A single tab reconnecting an EventSource 256 times does it alone.
559
- *
560
- * Cancelling the body we hand back (`body.cancel()`) does NOT release the
561
- * slot; only aborting the upstream fetch does. Measured both ways.
562
- *
563
- * Hence `clientSignal`: the client's hangup is wired to the same controller
564
- * the timeout uses, so whichever ends first ends the upstream request. The
565
- * listener is left attached deliberately — it belongs to this one request and
566
- * is collected with it, and aborting an already-finished fetch is a no-op.
543
+ /**
544
+ * Forward one request upstream, bounded by BOTH clocks that can end it.
545
+ *
546
+ * The timeout below only bounds time-to-first-headers: it is cleared the
547
+ * moment headers arrive, because a streamed body (SSE, a long download, a
548
+ * model's token stream) legitimately takes as long as it takes. That is
549
+ * correct — but on its own it left a streamed request with NO way to end.
550
+ *
551
+ * So when the person closed the tab, the browser's connection went away and
552
+ * ours did not. The upstream request stayed open, holding one of the
553
+ * runtime's outgoing connection slots, forever.
554
+ *
555
+ * That is not a slow leak. Measured on Bun 1.3.14: 256 clients that connect
556
+ * and hang up leave 256 upstream requests open (0 cancelled), and the process
557
+ * can then make no outgoing request at all — every later fetch times out.
558
+ * A single tab reconnecting an EventSource 256 times does it alone.
559
+ *
560
+ * Cancelling the body we hand back (`body.cancel()`) does NOT release the
561
+ * slot; only aborting the upstream fetch does. Measured both ways.
562
+ *
563
+ * Hence `clientSignal`: the client's hangup is wired to the same controller
564
+ * the timeout uses, so whichever ends first ends the upstream request. The
565
+ * listener is left attached deliberately — it belongs to this one request and
566
+ * is collected with it, and aborting an already-finished fetch is a no-op.
567
567
  */ async function forwardRequest(finalUrl, method, headers, body, timeout, followRedirects, clientSignal) {
568
568
  const controller = new AbortController();
569
569
  const timeoutId = setTimeout(()=>controller.abort(), timeout);
@@ -579,13 +579,13 @@ export function createHttpProxyHandler(config) {
579
579
  clientGone = true;
580
580
  clearTimeout(timeoutId);
581
581
  controller.abort();
582
- /*
583
- * Logged HERE, not in the catch below, because the common case
584
- * never reaches the catch: once headers have arrived this function
585
- * has already returned, and the hangup happens while the body is
586
- * still streaming. That is exactly the case that used to leak, so
587
- * it is exactly the case that has to be visible — a cancellation
588
- * nobody can see is how this went unnoticed for months.
582
+ /*
583
+ * Logged HERE, not in the catch below, because the common case
584
+ * never reaches the catch: once headers have arrived this function
585
+ * has already returned, and the hangup happens while the body is
586
+ * still streaming. That is exactly the case that used to leak, so
587
+ * it is exactly the case that has to be visible — a cancellation
588
+ * nobody can see is how this went unnoticed for months.
589
589
  */ logger.info(`Client disconnected, upstream cancelled: ${redactSecrets(finalUrl)}`);
590
590
  }, {
591
591
  once: true
@@ -687,30 +687,30 @@ export function createHttpProxyHandler(config) {
687
687
  logger.warn(`[Auth:proxy] NO TOKEN available for ${path} — request will likely fail with 401`);
688
688
  }
689
689
  const baseTimeout = target.timeout ?? 30000;
690
- /*
691
- * A file needs minutes, not thirty seconds.
692
- *
693
- * The fixed timeout aborted a 200 MB video long before the last byte, and
694
- * the browser had no way to tell that from a slow line — the bar simply
695
- * stopped. The allowance now grows with the declared size.
690
+ /*
691
+ * A file needs minutes, not thirty seconds.
692
+ *
693
+ * The fixed timeout aborted a 200 MB video long before the last byte, and
694
+ * the browser had no way to tell that from a slow line — the bar simply
695
+ * stopped. The allowance now grows with the declared size.
696
696
  */ const timeout = timeoutForBody(req.headers, baseTimeout);
697
697
  const followRedirects = target.followRedirects !== false;
698
698
  // Buffer body for potential retry (only if 401 retry is enabled)
699
699
  let bodyForRetry = null;
700
700
  let bodyToSend = req.body;
701
- /*
702
- * Only a body small enough to hold.
703
- *
704
- * Buffering exists so a 401 can be answered by refreshing the token and
705
- * sending the same request again — worth it for a form post, fatal for a
706
- * file. An 800 MB video was read into an ArrayBuffer inside a container
707
- * limited to 256 MiB: the upload appeared to run, because the browser
708
- * really was sending bytes, and then died with nothing to show for it.
709
- *
710
- * A large body streams straight through and gives up the retry. That is
711
- * the right way round: an upload that is refused can be started again by
712
- * the person who chose the file; an upload that never completes cannot be
713
- * rescued by anybody.
701
+ /*
702
+ * Only a body small enough to hold.
703
+ *
704
+ * Buffering exists so a 401 can be answered by refreshing the token and
705
+ * sending the same request again — worth it for a form post, fatal for a
706
+ * file. An 800 MB video was read into an ArrayBuffer inside a container
707
+ * limited to 256 MiB: the upload appeared to run, because the browser
708
+ * really was sending bytes, and then died with nothing to show for it.
709
+ *
710
+ * A large body streams straight through and gives up the retry. That is
711
+ * the right way round: an upload that is refused can be started again by
712
+ * the person who chose the file; an upload that never completes cannot be
713
+ * rescued by anybody.
714
714
  */ const bufferable = canBufferForRetry(req.headers);
715
715
  if (refreshEnabled && (refreshConfig.retryOn401 ?? true) && req.body && bufferable) {
716
716
  try {
@@ -778,14 +778,14 @@ export function createHttpProxyHandler(config) {
778
778
  } catch (error) {
779
779
  const duration = performance.now() - startTime;
780
780
  const err = error instanceof Error ? error : new Error(String(error));
781
- /*
782
- * The person closed the tab. Nothing failed, and there is nobody left
783
- * to send a status to — so this is not an error, and calling it one
784
- * sends whoever reads the log hunting a timeout that never happened.
785
- *
786
- * Reported with the elapsed time, because on a streaming path "the
787
- * client left after 4 minutes" is genuinely useful and "Gateway
788
- * Timeout" is genuinely misleading.
781
+ /*
782
+ * The person closed the tab. Nothing failed, and there is nobody left
783
+ * to send a status to — so this is not an error, and calling it one
784
+ * sends whoever reads the log hunting a timeout that never happened.
785
+ *
786
+ * Reported with the elapsed time, because on a streaming path "the
787
+ * client left after 4 minutes" is genuinely useful and "Gateway
788
+ * Timeout" is genuinely misleading.
789
789
  */ if (err.name === 'ClientGoneError') {
790
790
  logger.info(`Client disconnected after ${duration.toFixed(0)}ms, upstream cancelled: ${path}`);
791
791
  return new Response(null, {
@@ -1,26 +1,26 @@
1
- /**
2
- * Whether a request body is small enough to hold in memory for a retry.
3
- *
4
- * The proxy buffers the whole body so that a 401 can be answered by refreshing
5
- * the token and sending the same request again. That is a good trade for a form
6
- * post and a catastrophic one for a file: an eight-hundred-megabyte video was
7
- * read into `ArrayBuffer` inside a container limited to 256 MiB, so the upload
8
- * appeared to run — the browser really was sending bytes — and then died with
9
- * nothing to show for it. Measured on the customer's install: the video module
10
- * accepts up to 1 GB, the ingress passes 1 GB, and the proxy in between could
11
- * never carry more than a fraction of it.
12
- *
13
- * A large body is streamed straight through instead. The cost is that it cannot
14
- * be replayed after a token refresh, which is the right way round: an upload
15
- * that is refused can be started again by the person who chose the file, while
16
- * an upload that never completes cannot be rescued by anybody.
1
+ /**
2
+ * Whether a request body is small enough to hold in memory for a retry.
3
+ *
4
+ * The proxy buffers the whole body so that a 401 can be answered by refreshing
5
+ * the token and sending the same request again. That is a good trade for a form
6
+ * post and a catastrophic one for a file: an eight-hundred-megabyte video was
7
+ * read into `ArrayBuffer` inside a container limited to 256 MiB, so the upload
8
+ * appeared to run — the browser really was sending bytes — and then died with
9
+ * nothing to show for it. Measured on the customer's install: the video module
10
+ * accepts up to 1 GB, the ingress passes 1 GB, and the proxy in between could
11
+ * never carry more than a fraction of it.
12
+ *
13
+ * A large body is streamed straight through instead. The cost is that it cannot
14
+ * be replayed after a token refresh, which is the right way round: an upload
15
+ * that is refused can be started again by the person who chose the file, while
16
+ * an upload that never completes cannot be rescued by anybody.
17
17
  */ export const RETRY_BUFFER_LIMIT_BYTES = 2 * 1024 * 1024;
18
- /**
19
- * `null` when the size is not declared.
20
- *
21
- * An undeclared length is treated as LARGE: a chunked upload announces nothing,
22
- * and guessing "small" there is how the buffer gets filled by the one request
23
- * that must not fill it.
18
+ /**
19
+ * `null` when the size is not declared.
20
+ *
21
+ * An undeclared length is treated as LARGE: a chunked upload announces nothing,
22
+ * and guessing "small" there is how the buffer gets filled by the one request
23
+ * that must not fill it.
24
24
  */ export function declaredBodySize(headers) {
25
25
  const raw = headers.get('content-length');
26
26
  if (!raw) return null;
@@ -32,13 +32,13 @@ export function canBufferForRetry(headers, limit = RETRY_BUFFER_LIMIT_BYTES) {
32
32
  if (size === null) return false;
33
33
  return size <= limit;
34
34
  }
35
- /**
36
- * How long to allow, given what is being carried.
37
- *
38
- * Thirty seconds is right for an API call and absurd for a file: a 200 MB video
39
- * over an office line needs minutes, and the old fixed timeout aborted it long
40
- * before the last byte. The allowance grows with the declared size — a minute
41
- * per fifty megabytes — and is never shorter than the configured default.
35
+ /**
36
+ * How long to allow, given what is being carried.
37
+ *
38
+ * Thirty seconds is right for an API call and absurd for a file: a 200 MB video
39
+ * over an office line needs minutes, and the old fixed timeout aborted it long
40
+ * before the last byte. The allowance grows with the declared size — a minute
41
+ * per fifty megabytes — and is never shorter than the configured default.
42
42
  */ export function timeoutForBody(headers, baseTimeoutMs) {
43
43
  const size = declaredBodySize(headers);
44
44
  if (size === null || size <= RETRY_BUFFER_LIMIT_BYTES) return baseTimeoutMs;
@@ -46,10 +46,10 @@ export function httpToWs(url) {
46
46
  export function wsToHttp(url) {
47
47
  return url.replace(/^ws/, 'http');
48
48
  }
49
- /**
50
- * The proxies' logger. Every argument passes {@link redactSecrets} on the way out,
51
- * so a log line written at a call site nobody audited — a backend URL, an upstream
52
- * error message that quotes it — still cannot carry a credential to the pod log.
49
+ /**
50
+ * The proxies' logger. Every argument passes {@link redactSecrets} on the way out,
51
+ * so a log line written at a call site nobody audited — a backend URL, an upstream
52
+ * error message that quotes it — still cannot carry a credential to the pod log.
53
53
  */ export function createProxyLogger(prefix, debug) {
54
54
  return {
55
55
  info: (...args)=>{
@@ -91,40 +91,40 @@ export function sanitizeForLog(value, maxLength = 50) {
91
91
  if (value.length <= maxLength) return value;
92
92
  return `${value.slice(0, maxLength)}...`;
93
93
  }
94
- /**
95
- * The proxy's replacement text. Angle brackets rather than the server's
96
- * `[REDACTED]`, because consumers already scrub their own console with a
97
- * `<redacted>`-aware pass, and a marker that pass does not recognise would be
98
- * re-matched as a value and stacked.
94
+ /**
95
+ * The proxy's replacement text. Angle brackets rather than the server's
96
+ * `[REDACTED]`, because consumers already scrub their own console with a
97
+ * `<redacted>`-aware pass, and a marker that pass does not recognise would be
98
+ * re-matched as a value and stacked.
99
99
  */ const PROXY_MARKER = '<redacted>';
100
- /**
101
- * The same string with every credential in it replaced by `<redacted>`, as
102
- * `redactSecretsInText` reads text (`src/Shared/redactSecrets.ts` lists what it
103
- * reads and what it does not): a credential query parameter, an Authorization,
104
- * Cookie or other credential header value, a credential-named field of printed
105
- * data, a Bearer or Basic value, a JWT, a URL userinfo password. The parameter,
106
- * header or cookie NAME stays, so the line still says what was sent.
107
- *
108
- * The WS proxy logs the backend URL it dialled, and a target with
109
- * `injectTokenFromCookie` puts the handshake bearer IN that URL. Unredacted, every
110
- * connect and every failed connect wrote a live access token into the process log,
111
- * valid for the rest of its TTL and readable by anyone who can read those logs.
112
- * Nothing about a connection failure needs the credential; the path and host are
113
- * the diagnosis.
100
+ /**
101
+ * The same string with every credential in it replaced by `<redacted>`, as
102
+ * `redactSecretsInText` reads text (`src/Shared/redactSecrets.ts` lists what it
103
+ * reads and what it does not): a credential query parameter, an Authorization,
104
+ * Cookie or other credential header value, a credential-named field of printed
105
+ * data, a Bearer or Basic value, a JWT, a URL userinfo password. The parameter,
106
+ * header or cookie NAME stays, so the line still says what was sent.
107
+ *
108
+ * The WS proxy logs the backend URL it dialled, and a target with
109
+ * `injectTokenFromCookie` puts the handshake bearer IN that URL. Unredacted, every
110
+ * connect and every failed connect wrote a live access token into the process log,
111
+ * valid for the rest of its TTL and readable by anyone who can read those logs.
112
+ * Nothing about a connection failure needs the credential; the path and host are
113
+ * the diagnosis.
114
114
  */ export function redactSecrets(value) {
115
115
  return redactSecretsInText(value, {
116
116
  marker: PROXY_MARKER
117
117
  });
118
118
  }
119
- /**
120
- * One log argument made safe to print. A string is read as text. Anything else is
121
- * walked by key first (`redactValue`: objects, arrays, Maps, Headers, URLs,
122
- * Request, Response, Errors), so a credential is replaced while its key still
123
- * says what it is, and only then printed with Bun.inspect. The printed form is
124
- * read as text too, for what the walk cannot see: a class's internal slots, an
125
- * object whose getter threw, an ErrorEvent's message. An Error prints as its
126
- * redacted stack, then its own fields and cause: Bun.inspect of the Error itself
127
- * would print its message as written.
119
+ /**
120
+ * One log argument made safe to print. A string is read as text. Anything else is
121
+ * walked by key first (`redactValue`: objects, arrays, Maps, Headers, URLs,
122
+ * Request, Response, Errors), so a credential is replaced while its key still
123
+ * says what it is, and only then printed with Bun.inspect. The printed form is
124
+ * read as text too, for what the walk cannot see: a class's internal slots, an
125
+ * object whose getter threw, an ErrorEvent's message. An Error prints as its
126
+ * redacted stack, then its own fields and cause: Bun.inspect of the Error itself
127
+ * would print its message as written.
128
128
  */ function redactLogArg(arg) {
129
129
  if (typeof arg === 'string') return redactSecrets(arg);
130
130
  if (arg === null || arg === undefined) return arg;