@lostgradient/backchannel 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -2
  3. package/dist/access-policy-metadata.d.ts +92 -0
  4. package/dist/access-policy-metadata.js +87 -0
  5. package/dist/asyncapi-channels.d.ts +46 -0
  6. package/dist/asyncapi-channels.js +399 -0
  7. package/dist/asyncapi.d.ts +40 -0
  8. package/dist/asyncapi.js +165 -0
  9. package/dist/authentication/api-key.d.ts +4 -0
  10. package/dist/authentication/api-key.js +114 -0
  11. package/dist/authentication/audit.d.ts +115 -0
  12. package/dist/authentication/audit.js +75 -0
  13. package/dist/authentication/credential-verifiers.d.ts +60 -0
  14. package/dist/authentication/credential-verifiers.js +102 -0
  15. package/dist/authentication/crypto.d.ts +7 -0
  16. package/dist/authentication/crypto.js +140 -0
  17. package/dist/authentication/index.d.ts +80 -0
  18. package/dist/authentication/index.js +212 -0
  19. package/dist/authentication/rate-limiter.d.ts +133 -0
  20. package/dist/authentication/rate-limiter.js +124 -0
  21. package/dist/authentication/redaction.d.ts +72 -0
  22. package/dist/authentication/redaction.js +118 -0
  23. package/dist/authentication/rotating-api-key-store.d.ts +127 -0
  24. package/dist/authentication/rotating-api-key-store.js +126 -0
  25. package/dist/authentication/types.d.ts +337 -0
  26. package/dist/authentication/types.js +26 -0
  27. package/dist/authentication.d.ts +1 -0
  28. package/dist/authentication.js +1 -0
  29. package/dist/authorization-scope.d.ts +109 -0
  30. package/dist/authorization-scope.js +144 -0
  31. package/dist/authorization.d.ts +55 -0
  32. package/dist/authorization.js +134 -0
  33. package/dist/bind-feed-lifetime.d.ts +45 -0
  34. package/dist/bind-feed-lifetime.js +55 -0
  35. package/dist/byte-arrays.d.ts +5 -0
  36. package/dist/byte-arrays.js +9 -0
  37. package/dist/client/catalog-client.d.ts +285 -0
  38. package/dist/client/catalog-client.js +74 -0
  39. package/dist/client/in-process-transport.d.ts +19 -0
  40. package/dist/client/in-process-transport.js +136 -0
  41. package/dist/client/index.d.ts +14 -0
  42. package/dist/client/index.js +14 -0
  43. package/dist/client/json-rpc-http-transport.d.ts +118 -0
  44. package/dist/client/json-rpc-http-transport.js +127 -0
  45. package/dist/client/server-sent-event-parser.d.ts +55 -0
  46. package/dist/client/server-sent-event-parser.js +78 -0
  47. package/dist/client/sse-subscription-transport.d.ts +72 -0
  48. package/dist/client/sse-subscription-transport.js +224 -0
  49. package/dist/client/subscription-client.d.ts +122 -0
  50. package/dist/client/subscription-client.js +28 -0
  51. package/dist/connection-lease.d.ts +10 -0
  52. package/dist/connection-lease.js +8 -0
  53. package/dist/discovery-filter.d.ts +13 -0
  54. package/dist/discovery-filter.js +16 -0
  55. package/dist/discovery-info.d.ts +94 -0
  56. package/dist/discovery-info.js +38 -0
  57. package/dist/event-selector.d.ts +7 -0
  58. package/dist/event-selector.js +7 -0
  59. package/dist/fault-code.d.ts +84 -0
  60. package/dist/fault-code.js +114 -0
  61. package/dist/fault-remediation.d.ts +30 -0
  62. package/dist/fault-remediation.js +52 -0
  63. package/dist/fault-to-http.d.ts +11 -0
  64. package/dist/fault-to-http.js +13 -0
  65. package/dist/fault-to-json-rpc.d.ts +53 -0
  66. package/dist/fault-to-json-rpc.js +143 -0
  67. package/dist/fault-wire-safety.d.ts +45 -0
  68. package/dist/fault-wire-safety.js +72 -0
  69. package/dist/generator.d.ts +9 -0
  70. package/dist/generator.js +9 -0
  71. package/dist/handler/auth-context-principal.d.ts +37 -0
  72. package/dist/handler/auth-context-principal.js +67 -0
  73. package/dist/handler/authentication-responses.d.ts +23 -0
  74. package/dist/handler/authentication-responses.js +34 -0
  75. package/dist/handler/json-responses.d.ts +15 -0
  76. package/dist/handler/json-responses.js +32 -0
  77. package/dist/handler/operation-handler-authentication.d.ts +64 -0
  78. package/dist/handler/operation-handler-authentication.js +58 -0
  79. package/dist/handler/operation-handler-discovery.d.ts +29 -0
  80. package/dist/handler/operation-handler-discovery.js +55 -0
  81. package/dist/handler/operation-handler-mounts.d.ts +100 -0
  82. package/dist/handler/operation-handler-mounts.js +134 -0
  83. package/dist/handler/operation-handler-subscription.d.ts +34 -0
  84. package/dist/handler/operation-handler-subscription.js +112 -0
  85. package/dist/handler/operation-handler.d.ts +162 -0
  86. package/dist/handler/operation-handler.js +236 -0
  87. package/dist/handler/workspace-release.d.ts +6 -0
  88. package/dist/handler/workspace-release.js +75 -0
  89. package/dist/in-memory-replay-live-backend.d.ts +47 -0
  90. package/dist/in-memory-replay-live-backend.js +129 -0
  91. package/dist/index.d.ts +37 -0
  92. package/dist/index.js +30 -0
  93. package/dist/internal/cryptography/encryption.d.ts +108 -0
  94. package/dist/internal/cryptography/encryption.js +241 -0
  95. package/dist/internal/cryptography/hash.d.ts +72 -0
  96. package/dist/internal/cryptography/hash.js +233 -0
  97. package/dist/internal/cryptography/index.d.ts +4 -0
  98. package/dist/internal/cryptography/index.js +2 -0
  99. package/dist/internals.d.ts +58 -0
  100. package/dist/internals.js +54 -0
  101. package/dist/json-rpc-dispatch.d.ts +88 -0
  102. package/dist/json-rpc-dispatch.js +154 -0
  103. package/dist/json-rpc-framing.d.ts +42 -0
  104. package/dist/json-rpc-framing.js +50 -0
  105. package/dist/json-rpc-http.d.ts +36 -0
  106. package/dist/json-rpc-http.js +191 -0
  107. package/dist/json-rpc-parse.d.ts +69 -0
  108. package/dist/json-rpc-parse.js +206 -0
  109. package/dist/json-rpc-protocol.d.ts +76 -0
  110. package/dist/json-rpc-protocol.js +54 -0
  111. package/dist/json-rpc-session-runtime.d.ts +55 -0
  112. package/dist/json-rpc-session-runtime.js +111 -0
  113. package/dist/json-rpc-websocket-subscription-pump.d.ts +9 -0
  114. package/dist/json-rpc-websocket-subscription-pump.js +46 -0
  115. package/dist/json-rpc-websocket-subscriptions.d.ts +10 -0
  116. package/dist/json-rpc-websocket-subscriptions.js +33 -0
  117. package/dist/json-rpc-websocket-types.d.ts +34 -0
  118. package/dist/json-rpc-websocket-types.js +1 -0
  119. package/dist/json-rpc-websocket-validation.d.ts +45 -0
  120. package/dist/json-rpc-websocket-validation.js +154 -0
  121. package/dist/json-rpc-websocket.d.ts +20 -0
  122. package/dist/json-rpc-websocket.js +363 -0
  123. package/dist/json-schema-utilities.d.ts +5 -0
  124. package/dist/json-schema-utilities.js +17 -0
  125. package/dist/mcp-discovery-names.d.ts +11 -0
  126. package/dist/mcp-discovery-names.js +11 -0
  127. package/dist/openapi-canonical-json.d.ts +10 -0
  128. package/dist/openapi-canonical-json.js +23 -0
  129. package/dist/openapi-error-responses.d.ts +15 -0
  130. package/dist/openapi-error-responses.js +104 -0
  131. package/dist/openapi-schemas.d.ts +17 -0
  132. package/dist/openapi-schemas.js +94 -0
  133. package/dist/openapi.d.ts +60 -0
  134. package/dist/openapi.js +351 -0
  135. package/dist/openrpc-document-schema.d.ts +255 -0
  136. package/dist/openrpc-document-schema.js +84 -0
  137. package/dist/openrpc-errors.d.ts +93 -0
  138. package/dist/openrpc-errors.js +134 -0
  139. package/dist/openrpc.d.ts +66 -0
  140. package/dist/openrpc.js +260 -0
  141. package/dist/operation-catalog/behavior-types.d.ts +34 -0
  142. package/dist/operation-catalog/behavior-types.js +1 -0
  143. package/dist/operation-catalog/behavior-validation.d.ts +3 -0
  144. package/dist/operation-catalog/behavior-validation.js +298 -0
  145. package/dist/operation-catalog/dispatch-allowlist.d.ts +4 -0
  146. package/dist/operation-catalog/dispatch-allowlist.js +7 -0
  147. package/dist/operation-catalog/dispatch-preparation.d.ts +24 -0
  148. package/dist/operation-catalog/dispatch-preparation.js +49 -0
  149. package/dist/operation-catalog/index.d.ts +19 -0
  150. package/dist/operation-catalog/index.js +17 -0
  151. package/dist/operation-catalog/operation-dispatch.d.ts +14 -0
  152. package/dist/operation-catalog/operation-dispatch.js +115 -0
  153. package/dist/operation-catalog/operation-interceptors.d.ts +15 -0
  154. package/dist/operation-catalog/operation-interceptors.js +1 -0
  155. package/dist/operation-catalog/operation-metadata.d.ts +5 -0
  156. package/dist/operation-catalog/operation-metadata.js +104 -0
  157. package/dist/operation-catalog/pipeline-helpers.d.ts +70 -0
  158. package/dist/operation-catalog/pipeline-helpers.js +242 -0
  159. package/dist/operation-catalog/pipeline-stages.d.ts +23 -0
  160. package/dist/operation-catalog/pipeline-stages.js +226 -0
  161. package/dist/operation-catalog/pipeline.d.ts +7 -0
  162. package/dist/operation-catalog/pipeline.js +33 -0
  163. package/dist/operation-catalog/registry.d.ts +17 -0
  164. package/dist/operation-catalog/registry.js +132 -0
  165. package/dist/operation-catalog/stream-pipeline.d.ts +37 -0
  166. package/dist/operation-catalog/stream-pipeline.js +129 -0
  167. package/dist/operation-catalog/subscription-lifecycle.d.ts +6 -0
  168. package/dist/operation-catalog/subscription-lifecycle.js +27 -0
  169. package/dist/operation-catalog/types.d.ts +392 -0
  170. package/dist/operation-catalog/types.js +40 -0
  171. package/dist/operation-catalog/universal-faults.d.ts +11 -0
  172. package/dist/operation-catalog/universal-faults.js +15 -0
  173. package/dist/operation-catalog-snapshot.d.ts +215 -0
  174. package/dist/operation-catalog-snapshot.js +128 -0
  175. package/dist/operation-catalog.d.ts +1 -0
  176. package/dist/operation-catalog.js +1 -0
  177. package/dist/operation-description-audit.d.ts +44 -0
  178. package/dist/operation-description-audit.js +90 -0
  179. package/dist/operation-fault-helpers.d.ts +21 -0
  180. package/dist/operation-fault-helpers.js +32 -0
  181. package/dist/operation-fault.d.ts +245 -0
  182. package/dist/operation-fault.js +235 -0
  183. package/dist/operation-registry.d.ts +46 -0
  184. package/dist/operation-registry.js +46 -0
  185. package/dist/operations/closable-iterable.d.ts +23 -0
  186. package/dist/operations/closable-iterable.js +51 -0
  187. package/dist/operations/get-principal.d.ts +106 -0
  188. package/dist/operations/get-principal.js +107 -0
  189. package/dist/operations/sse-stream.d.ts +67 -0
  190. package/dist/operations/sse-stream.js +264 -0
  191. package/dist/principal.d.ts +253 -0
  192. package/dist/principal.js +254 -0
  193. package/dist/replay-live-feed-internals.d.ts +47 -0
  194. package/dist/replay-live-feed-internals.js +215 -0
  195. package/dist/replay-live-feed-types.d.ts +66 -0
  196. package/dist/replay-live-feed-types.js +7 -0
  197. package/dist/replay-live-feed.d.ts +49 -0
  198. package/dist/replay-live-feed.js +126 -0
  199. package/dist/rest-binding.d.ts +215 -0
  200. package/dist/rest-binding.js +95 -0
  201. package/dist/rest-body.d.ts +17 -0
  202. package/dist/rest-body.js +95 -0
  203. package/dist/route-model.d.ts +305 -0
  204. package/dist/route-model.js +320 -0
  205. package/dist/runtime/cors.d.ts +161 -0
  206. package/dist/runtime/cors.js +265 -0
  207. package/dist/scripts/generate-operation-client.d.ts +186 -0
  208. package/dist/scripts/generate-operation-client.js +561 -0
  209. package/dist/scripts/operation-behaviors.d.ts +3 -0
  210. package/dist/scripts/operation-behaviors.js +16 -0
  211. package/dist/scripts/operation-client-aliases.d.ts +32 -0
  212. package/dist/scripts/operation-client-aliases.js +255 -0
  213. package/dist/scripts/operation-client-domains.d.ts +21 -0
  214. package/dist/scripts/operation-client-domains.js +74 -0
  215. package/dist/scripts/operation-client-schema.d.ts +46 -0
  216. package/dist/scripts/operation-client-schema.js +310 -0
  217. package/dist/scripts/operation-client-svelte.d.ts +3 -0
  218. package/dist/scripts/operation-client-svelte.js +61 -0
  219. package/dist/sequence-cursor.d.ts +46 -0
  220. package/dist/sequence-cursor.js +62 -0
  221. package/dist/sse-error-payload-schema.d.ts +12 -0
  222. package/dist/sse-error-payload-schema.js +33 -0
  223. package/dist/stdio-session.d.ts +71 -0
  224. package/dist/stdio-session.js +347 -0
  225. package/dist/zod-json-schema.d.ts +22 -0
  226. package/dist/zod-json-schema.js +49 -0
  227. package/package.json +38 -3
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Authentication middleware for the Weft HTTP server.
3
+ *
4
+ * Supports three authentication methods, all optional and configurable:
5
+ * - **API keys**: validated via `Authorization: Bearer <key>` or `X-API-Key` header
6
+ * - **JWT**: HMAC or RSA/ECDSA signature verification with claims validation
7
+ * - **mTLS**: mutual TLS at the transport layer (configured via Bun.serve tls options),
8
+ * admitted only on positive evidence of a verified client certificate
9
+ *
10
+ * @module server/authentication
11
+ */
12
+ import { type CreateAuthenticatorOptions } from "./credential-verifiers.js";
13
+ import { type AuthConfig, type Authenticator } from "./types.js";
14
+ export { defaultAuthAuditSink, emitAuthAuditEvent, type AuthAuditContext, type AuthAuditEvent, type AuthAuditSink, } from "./audit.js";
15
+ export { importJWTKey, signJWT, verifyJWT } from "./crypto.js";
16
+ export { createRateLimiter, validateRateLimitConfig, type RateLimitConfig, type RateLimitDecision, type RateLimiter, } from "./rate-limiter.js";
17
+ export { isSensitiveHeader, redactCredential, redactHeaders } from "./redaction.js";
18
+ export { createRotatingApiKeyStore, type ApiKeyRegistration, type RotatingApiKeyStore, } from "./rotating-api-key-store.js";
19
+ export { DEFAULT_CLOCK_TOLERANCE, DEFAULT_PUBLIC_PATHS, type AuthConfig, type AuthContext, type Authenticator, type AuthMethod, type AuthResult, type JWTAlgorithm, type JWTConfig, type JWTPayload, type MTLSConfig, } from "./types.js";
20
+ export { createApiKeyVerifier, createJwtVerifier, createMutualTlsVerifier, type CreateAuthenticatorOptions, type CredentialVerification, type CredentialVerifier, } from "./credential-verifiers.js";
21
+ /**
22
+ * Whether TLS options built by {@link buildTLSOptions} refuse every
23
+ * connection that lacks a verified client certificate.
24
+ */
25
+ export declare function tlsOptionsVerifyClientCertificates(tlsOptions: ReturnType<typeof buildTLSOptions>): boolean;
26
+ /**
27
+ * Validate an `AuthConfig` eagerly, throwing on invalid combinations.
28
+ * Called synchronously in `serve()` so misconfigurations fail fast.
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * import { validateAuthConfig } from '@lostgradient/backchannel';
33
+ *
34
+ * // Throws if config is invalid (e.g. missing secret for HS256)
35
+ * validateAuthConfig({
36
+ * apiKeys: ['secret-key-1'],
37
+ * defaultApiKeyScopes: ['inventory:read'],
38
+ * });
39
+ * console.log('Config is valid');
40
+ * ```
41
+ */
42
+ export declare function validateAuthConfig(config: AuthConfig): void;
43
+ /**
44
+ * Create an authenticator function from an auth configuration.
45
+ *
46
+ * The returned function checks each configured method in order:
47
+ * 1. Public path bypass
48
+ * 2. API key (constant-time digest scan)
49
+ * 3. JWT (signature + claims verification)
50
+ * 4. mTLS, only when no explicit credential was presented and a verified client
51
+ * certificate is evidenced by `verifyClientCertificate` or by
52
+ * `options.transportVerifiesClientCertificates`
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { createAuthenticator } from '@lostgradient/backchannel';
57
+ *
58
+ * const authenticate = await createAuthenticator({
59
+ * apiKeys: ['my-secret-key'],
60
+ * defaultApiKeyScopes: ['inventory:read'],
61
+ * });
62
+ * const request = new Request('http://localhost/v1/workflows', {
63
+ * headers: { 'X-API-Key': 'my-secret-key' },
64
+ * });
65
+ * const result = await authenticate(request);
66
+ * console.log(result.authenticated); // true
67
+ * ```
68
+ */
69
+ export declare function createAuthenticator(config: AuthConfig, options?: CreateAuthenticatorOptions): Promise<Authenticator>;
70
+ /**
71
+ * Build Bun.serve-compatible TLS options from an mTLS configuration.
72
+ * Returns `undefined` when no mTLS is configured.
73
+ */
74
+ export declare function buildTLSOptions(config: AuthConfig | undefined): {
75
+ cert: string;
76
+ key: string;
77
+ ca: string | string[];
78
+ requestCert: boolean;
79
+ rejectUnauthorized: boolean;
80
+ } | undefined;
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Authentication middleware for the Weft HTTP server.
3
+ *
4
+ * Supports three authentication methods, all optional and configurable:
5
+ * - **API keys**: validated via `Authorization: Bearer <key>` or `X-API-Key` header
6
+ * - **JWT**: HMAC or RSA/ECDSA signature verification with claims validation
7
+ * - **mTLS**: mutual TLS at the transport layer (configured via Bun.serve tls options),
8
+ * admitted only on positive evidence of a verified client certificate
9
+ *
10
+ * @module server/authentication
11
+ */
12
+ import { createAdditionalScopeSet } from "../authorization-scope.js";
13
+ import { defaultAuthAuditSink, emitAuthAuditEvent } from "./audit.js";
14
+ import { createApiKeyVerifier, createJwtVerifier, createMutualTlsVerifier, extractApiKey, validateJwtConfig, } from "./credential-verifiers.js";
15
+ import { DEFAULT_PUBLIC_PATHS, normalizeRequestPathname, } from "./types.js";
16
+ export { defaultAuthAuditSink, emitAuthAuditEvent, } from "./audit.js";
17
+ export { importJWTKey, signJWT, verifyJWT } from "./crypto.js";
18
+ export { createRateLimiter, validateRateLimitConfig, } from "./rate-limiter.js";
19
+ export { isSensitiveHeader, redactCredential, redactHeaders } from "./redaction.js";
20
+ export { createRotatingApiKeyStore, } from "./rotating-api-key-store.js";
21
+ export { DEFAULT_CLOCK_TOLERANCE, DEFAULT_PUBLIC_PATHS, } from "./types.js";
22
+ function assertAtLeastOneMethod(config) {
23
+ const hasMethod = (config.apiKeys && config.apiKeys.length > 0) ||
24
+ config.jwt !== undefined ||
25
+ config.mtls !== undefined ||
26
+ config.resolveApiKeyPrincipal !== undefined;
27
+ if (!hasMethod) {
28
+ throw new Error('AuthConfig must specify at least one authentication method ' +
29
+ '(apiKeys, resolveApiKeyPrincipal, jwt, or mtls)');
30
+ }
31
+ }
32
+ function assertNoConflictingMethods(config) {
33
+ if (config.resolveApiKeyPrincipal !== undefined && config.jwt !== undefined) {
34
+ throw new Error('AuthConfig cannot combine resolveApiKeyPrincipal with jwt: ' +
35
+ 'the resolver consumes every Authorization: Bearer token before JWT verification, ' +
36
+ 'so the JWT method would be unreachable.');
37
+ }
38
+ }
39
+ export { createApiKeyVerifier, createJwtVerifier, createMutualTlsVerifier, } from "./credential-verifiers.js";
40
+ /**
41
+ * Whether TLS options built by {@link buildTLSOptions} refuse every
42
+ * connection that lacks a verified client certificate.
43
+ */
44
+ export function tlsOptionsVerifyClientCertificates(tlsOptions) {
45
+ return tlsOptions !== undefined && tlsOptions.requestCert && tlsOptions.rejectUnauthorized;
46
+ }
47
+ /**
48
+ * Validate an `AuthConfig` eagerly, throwing on invalid combinations.
49
+ * Called synchronously in `serve()` so misconfigurations fail fast.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * import { validateAuthConfig } from '@lostgradient/backchannel';
54
+ *
55
+ * // Throws if config is invalid (e.g. missing secret for HS256)
56
+ * validateAuthConfig({
57
+ * apiKeys: ['secret-key-1'],
58
+ * defaultApiKeyScopes: ['inventory:read'],
59
+ * });
60
+ * console.log('Config is valid');
61
+ * ```
62
+ */
63
+ export function validateAuthConfig(config) {
64
+ if (config.verifiers !== undefined) {
65
+ if (config.apiKeys !== undefined ||
66
+ config.resolveApiKeyPrincipal !== undefined ||
67
+ config.jwt !== undefined ||
68
+ config.mtls !== undefined) {
69
+ throw new Error('AuthConfig.verifiers cannot be combined with legacy authentication methods');
70
+ }
71
+ if (config.verifiers.length === 0) {
72
+ throw new Error('AuthConfig must specify at least one authentication method');
73
+ }
74
+ return;
75
+ }
76
+ validateJwtConfig(config.jwt);
77
+ assertAtLeastOneMethod(config);
78
+ assertNoConflictingMethods(config);
79
+ }
80
+ /**
81
+ * Create an authenticator function from an auth configuration.
82
+ *
83
+ * The returned function checks each configured method in order:
84
+ * 1. Public path bypass
85
+ * 2. API key (constant-time digest scan)
86
+ * 3. JWT (signature + claims verification)
87
+ * 4. mTLS, only when no explicit credential was presented and a verified client
88
+ * certificate is evidenced by `verifyClientCertificate` or by
89
+ * `options.transportVerifiesClientCertificates`
90
+ *
91
+ * @example
92
+ * ```ts
93
+ * import { createAuthenticator } from '@lostgradient/backchannel';
94
+ *
95
+ * const authenticate = await createAuthenticator({
96
+ * apiKeys: ['my-secret-key'],
97
+ * defaultApiKeyScopes: ['inventory:read'],
98
+ * });
99
+ * const request = new Request('http://localhost/v1/workflows', {
100
+ * headers: { 'X-API-Key': 'my-secret-key' },
101
+ * });
102
+ * const result = await authenticate(request);
103
+ * console.log(result.authenticated); // true
104
+ * ```
105
+ */
106
+ export async function createAuthenticator(config, options = {}) {
107
+ validateAuthConfig(config);
108
+ // Validate the scope registration even when the configured verifiers do not use scopes.
109
+ createAdditionalScopeSet(options.additionalScopes);
110
+ const publicPaths = new Set(config.publicPaths ?? DEFAULT_PUBLIC_PATHS);
111
+ const auditSink = config.auditSink ?? defaultAuthAuditSink;
112
+ const verifiers = config.verifiers === undefined
113
+ ? await legacyVerifiers(config, options)
114
+ : config.verifiers.map((verifier) => ({
115
+ method: verifier.method,
116
+ verify: verifier.verify.bind(verifier),
117
+ }));
118
+ return async (request) => {
119
+ if (publicPaths.has(normalizeRequestPathname(request))) {
120
+ return { authenticated: true, method: 'public' };
121
+ }
122
+ let explicitCredentialAttempted = false;
123
+ for (const verifier of verifiers) {
124
+ try {
125
+ const outcome = await verifier.verify(request, { explicitCredentialAttempted });
126
+ if (outcome.kind === 'admit') {
127
+ return auditDecision(auditSink, request, {
128
+ ...outcome.authentication,
129
+ authenticated: true,
130
+ }, verifier.method);
131
+ }
132
+ if (outcome.kind === 'reject')
133
+ break;
134
+ if (outcome.kind === 'unrecognized')
135
+ explicitCredentialAttempted = true;
136
+ }
137
+ catch (error) {
138
+ console.warn('Credential verification failed:', error instanceof Error ? error.message : error);
139
+ break;
140
+ }
141
+ }
142
+ return auditDecision(auditSink, request, {
143
+ authenticated: false,
144
+ error: 'No valid credentials provided',
145
+ });
146
+ };
147
+ }
148
+ async function legacyVerifiers(config, options) {
149
+ // Start both async preparations before either settles so they snapshot the configuration together.
150
+ const apiKey = config.apiKeys?.length || config.resolveApiKeyPrincipal !== undefined
151
+ ? createApiKeyVerifier(config, options)
152
+ : Promise.resolve(undefined);
153
+ const jwt = config.jwt === undefined ? Promise.resolve(undefined) : createJwtVerifier(config.jwt, options);
154
+ const mtls = config.mtls === undefined ? undefined : createMutualTlsVerifier(config.mtls, options);
155
+ const verifiers = [...(await Promise.all([apiKey, jwt])), mtls];
156
+ return verifiers.filter((verifier) => verifier !== undefined);
157
+ }
158
+ /**
159
+ * Emit one audit event for a finalized authentication decision and return the
160
+ * result unchanged. Centralizes the success/failure mapping so every terminal
161
+ * return in the authenticator is audited identically. Never logs the presented
162
+ * credential in cleartext — only its one-way fingerprint, derived inside
163
+ * `emitAuthAuditEvent`.
164
+ */
165
+ function auditDecision(sink, request, result, verifierMethod) {
166
+ if (result.authenticated) {
167
+ emitAuthAuditEvent(sink, {
168
+ outcome: 'success',
169
+ method: verifierMethod ?? result.method,
170
+ subject: subjectFromResult(result),
171
+ request,
172
+ });
173
+ }
174
+ else {
175
+ emitAuthAuditEvent(sink, {
176
+ outcome: 'failure',
177
+ method: 'unknown',
178
+ subject: undefined,
179
+ request,
180
+ reason: result.error,
181
+ presentedCredential: extractApiKey(request),
182
+ });
183
+ }
184
+ return result;
185
+ }
186
+ /**
187
+ * Derive the principal subject from a successful {@link AuthResult} for the
188
+ * audit record. Prefers the forwarded principal's `subject`, falling back to a
189
+ * JWT `sub` claim, and leaving it undefined for mTLS / claimless admissions.
190
+ */
191
+ function subjectFromResult(result) {
192
+ if (result.principal?.subject !== undefined) {
193
+ return result.principal.subject;
194
+ }
195
+ const sub = result.claims?.['sub'];
196
+ return typeof sub === 'string' ? sub : undefined;
197
+ }
198
+ /**
199
+ * Build Bun.serve-compatible TLS options from an mTLS configuration.
200
+ * Returns `undefined` when no mTLS is configured.
201
+ */
202
+ export function buildTLSOptions(config) {
203
+ if (!config?.mtls)
204
+ return undefined;
205
+ return {
206
+ cert: config.mtls.cert,
207
+ key: config.mtls.key,
208
+ ca: config.mtls.ca,
209
+ requestCert: true,
210
+ rejectUnauthorized: config.mtls.rejectUnauthorized ?? true,
211
+ };
212
+ }
@@ -0,0 +1,133 @@
1
+ /**
2
+ * In-process request rate limiting keyed by principal or client address.
3
+ *
4
+ * Weft's request pipeline previously capped only body size (1 MB) and JSON-RPC
5
+ * batch length (100 items); a single principal or IP could otherwise flood the
6
+ * server with unbounded request volume. This limiter adds a configurable
7
+ * fixed-window counter so a hostile or runaway caller is throttled with HTTP
8
+ * 429 once it exceeds its budget.
9
+ *
10
+ * **Scope and trust posture.** This is a single-process, in-memory limiter — it
11
+ * is a load-shedding guardrail, not a distributed quota. Behind multiple server
12
+ * instances each process keeps its own counters; deployments that need a global
13
+ * budget should still front Weft with a shared reverse-proxy limiter. The
14
+ * in-process limiter exists so a single instance cannot be trivially flooded
15
+ * even when no proxy is present.
16
+ *
17
+ * The window clock is injectable so tests advance time deterministically rather
18
+ * than sleeping against the wall clock.
19
+ *
20
+ * @module server/authentication/rate-limiter
21
+ */
22
+ /**
23
+ * Configuration for the request rate limiter, supplied via
24
+ * `serve({ rateLimit })`. Omitting `rateLimit` entirely disables limiting (the
25
+ * historical behavior), so it is opt-in and never silently changes an existing
26
+ * deployment.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { type RateLimitConfig } from '@lostgradient/backchannel';
31
+ *
32
+ * const rateLimit: RateLimitConfig = {
33
+ * maxRequests: 100,
34
+ * windowMs: 60_000,
35
+ * };
36
+ * void rateLimit;
37
+ * ```
38
+ */
39
+ export type RateLimitConfig = {
40
+ /** Maximum requests permitted per key within each `windowMs` window. Must be a positive integer. */
41
+ maxRequests: number;
42
+ /** Length of the fixed window in milliseconds. Must be positive. */
43
+ windowMs: number;
44
+ /**
45
+ * Upper bound on the number of distinct keys tracked at once. When exceeded,
46
+ * the oldest-expiring entries are evicted so a high-cardinality flood of
47
+ * unique keys cannot grow memory without bound. Defaults to 10 000.
48
+ */
49
+ maxTrackedKeys?: number;
50
+ };
51
+ /**
52
+ * Outcome of a single {@link RateLimiter.check} call.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { type RateLimitDecision } from '@lostgradient/backchannel';
57
+ *
58
+ * function describe(decision: RateLimitDecision): string {
59
+ * return decision.allowed ? 'ok' : `retry after ${decision.retryAfterSeconds}s`;
60
+ * }
61
+ * void describe;
62
+ * ```
63
+ */
64
+ export type RateLimitDecision = {
65
+ /** Whether the request is within budget and may proceed. */
66
+ allowed: boolean;
67
+ /** Requests still available in the current window after this one. */
68
+ remaining: number;
69
+ /** Seconds until the current window resets — surfaced as the `Retry-After` header on a 429. */
70
+ retryAfterSeconds: number;
71
+ /** The configured per-window ceiling, surfaced as `X-RateLimit-Limit`. */
72
+ limit: number;
73
+ };
74
+ /**
75
+ * A request rate limiter. Call {@link RateLimiter.check} once per request with
76
+ * a stable key (principal subject when authenticated, otherwise client
77
+ * address). `dispose` clears the internal state and is invoked on server
78
+ * shutdown.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * import { createRateLimiter, type RateLimiter } from '@lostgradient/backchannel';
83
+ *
84
+ * const limiter: RateLimiter = createRateLimiter({ maxRequests: 2, windowMs: 1_000 });
85
+ * console.log(limiter.check('caller-1').allowed); // true
86
+ * console.log(limiter.check('caller-1').allowed); // true
87
+ * console.log(limiter.check('caller-1').allowed); // false
88
+ * limiter.dispose();
89
+ * ```
90
+ */
91
+ export interface RateLimitStore {
92
+ /** Counts one attempt atomically and reports the decision. */
93
+ check(key: string): RateLimitDecision | Promise<RateLimitDecision>;
94
+ }
95
+ /** The in-memory store and its timer lifecycle. */
96
+ export interface RateLimiter extends RateLimitStore {
97
+ /** Counts one attempt for the key and says whether it is allowed. */
98
+ check(key: string): RateLimitDecision;
99
+ /** Stops the limiter's timers and forgets its counts. */
100
+ dispose(): void;
101
+ }
102
+ /**
103
+ * Validate a {@link RateLimitConfig}, throwing on invalid values so a
104
+ * misconfiguration fails fast at `serve()` time rather than admitting an
105
+ * accidentally-unlimited or always-zero limiter.
106
+ *
107
+ * @example
108
+ * ```ts
109
+ * import { validateRateLimitConfig } from '@lostgradient/backchannel';
110
+ *
111
+ * validateRateLimitConfig({ maxRequests: 100, windowMs: 60_000 });
112
+ * console.log('config is valid');
113
+ * ```
114
+ */
115
+ export declare function validateRateLimitConfig(config: RateLimitConfig): void;
116
+ /**
117
+ * Create a fixed-window {@link RateLimiter}. The optional `now` clock is for
118
+ * deterministic testing; production callers omit it and the limiter reads
119
+ * `Date.now()`.
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * import { createRateLimiter } from '@lostgradient/backchannel';
124
+ *
125
+ * let clock = 0;
126
+ * const limiter = createRateLimiter({ maxRequests: 1, windowMs: 1_000 }, () => clock);
127
+ * console.log(limiter.check('a').allowed); // true
128
+ * console.log(limiter.check('a').allowed); // false — window not yet reset
129
+ * clock = 1_000;
130
+ * console.log(limiter.check('a').allowed); // true — window rolled over
131
+ * ```
132
+ */
133
+ export declare function createRateLimiter(config: RateLimitConfig, now?: () => number): RateLimiter;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * In-process request rate limiting keyed by principal or client address.
3
+ *
4
+ * Weft's request pipeline previously capped only body size (1 MB) and JSON-RPC
5
+ * batch length (100 items); a single principal or IP could otherwise flood the
6
+ * server with unbounded request volume. This limiter adds a configurable
7
+ * fixed-window counter so a hostile or runaway caller is throttled with HTTP
8
+ * 429 once it exceeds its budget.
9
+ *
10
+ * **Scope and trust posture.** This is a single-process, in-memory limiter — it
11
+ * is a load-shedding guardrail, not a distributed quota. Behind multiple server
12
+ * instances each process keeps its own counters; deployments that need a global
13
+ * budget should still front Weft with a shared reverse-proxy limiter. The
14
+ * in-process limiter exists so a single instance cannot be trivially flooded
15
+ * even when no proxy is present.
16
+ *
17
+ * The window clock is injectable so tests advance time deterministically rather
18
+ * than sleeping against the wall clock.
19
+ *
20
+ * @module server/authentication/rate-limiter
21
+ */
22
+ const DEFAULT_MAX_TRACKED_KEYS = 10_000;
23
+ /**
24
+ * Validate a {@link RateLimitConfig}, throwing on invalid values so a
25
+ * misconfiguration fails fast at `serve()` time rather than admitting an
26
+ * accidentally-unlimited or always-zero limiter.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { validateRateLimitConfig } from '@lostgradient/backchannel';
31
+ *
32
+ * validateRateLimitConfig({ maxRequests: 100, windowMs: 60_000 });
33
+ * console.log('config is valid');
34
+ * ```
35
+ */
36
+ export function validateRateLimitConfig(config) {
37
+ if (!Number.isInteger(config.maxRequests) || config.maxRequests <= 0) {
38
+ throw new Error('rateLimit.maxRequests must be a positive integer');
39
+ }
40
+ if (!Number.isFinite(config.windowMs) || config.windowMs <= 0) {
41
+ throw new Error('rateLimit.windowMs must be a positive number');
42
+ }
43
+ if (config.maxTrackedKeys !== undefined &&
44
+ (!Number.isInteger(config.maxTrackedKeys) || config.maxTrackedKeys <= 0)) {
45
+ throw new Error('rateLimit.maxTrackedKeys must be a positive integer when set');
46
+ }
47
+ }
48
+ /**
49
+ * Create a fixed-window {@link RateLimiter}. The optional `now` clock is for
50
+ * deterministic testing; production callers omit it and the limiter reads
51
+ * `Date.now()`.
52
+ *
53
+ * @example
54
+ * ```ts
55
+ * import { createRateLimiter } from '@lostgradient/backchannel';
56
+ *
57
+ * let clock = 0;
58
+ * const limiter = createRateLimiter({ maxRequests: 1, windowMs: 1_000 }, () => clock);
59
+ * console.log(limiter.check('a').allowed); // true
60
+ * console.log(limiter.check('a').allowed); // false — window not yet reset
61
+ * clock = 1_000;
62
+ * console.log(limiter.check('a').allowed); // true — window rolled over
63
+ * ```
64
+ */
65
+ export function createRateLimiter(config, now = Date.now) {
66
+ validateRateLimitConfig(config);
67
+ const maxTrackedKeys = config.maxTrackedKeys ?? DEFAULT_MAX_TRACKED_KEYS;
68
+ const windows = new Map();
69
+ function evictIfOverCapacity() {
70
+ if (windows.size <= maxTrackedKeys)
71
+ return;
72
+ // Map iteration order is insertion order. Re-inserting on each window roll
73
+ // (delete + set below) keeps the most recently active keys at the tail, so
74
+ // evicting from the head sheds the keys idle longest first.
75
+ const overflow = windows.size - maxTrackedKeys;
76
+ let removed = 0;
77
+ for (const key of windows.keys()) {
78
+ windows.delete(key);
79
+ removed += 1;
80
+ if (removed >= overflow)
81
+ break;
82
+ }
83
+ }
84
+ return {
85
+ check(key) {
86
+ const currentTime = now();
87
+ const existing = windows.get(key);
88
+ if (existing === undefined || currentTime >= existing.resetAt) {
89
+ // Fresh window. Re-insert (delete first when rolling over) so the key
90
+ // moves to the Map tail for LRU-style eviction ordering.
91
+ if (existing !== undefined)
92
+ windows.delete(key);
93
+ const resetAt = currentTime + config.windowMs;
94
+ windows.set(key, { count: 1, resetAt });
95
+ evictIfOverCapacity();
96
+ return {
97
+ allowed: true,
98
+ remaining: config.maxRequests - 1,
99
+ retryAfterSeconds: Math.ceil(config.windowMs / 1_000),
100
+ limit: config.maxRequests,
101
+ };
102
+ }
103
+ const retryAfterSeconds = Math.max(1, Math.ceil((existing.resetAt - currentTime) / 1_000));
104
+ if (existing.count >= config.maxRequests) {
105
+ return {
106
+ allowed: false,
107
+ remaining: 0,
108
+ retryAfterSeconds,
109
+ limit: config.maxRequests,
110
+ };
111
+ }
112
+ existing.count += 1;
113
+ return {
114
+ allowed: true,
115
+ remaining: config.maxRequests - existing.count,
116
+ retryAfterSeconds,
117
+ limit: config.maxRequests,
118
+ };
119
+ },
120
+ dispose() {
121
+ windows.clear();
122
+ },
123
+ };
124
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Credential redaction for logs and audit events.
3
+ *
4
+ * Authentication code logs request context (auth outcomes, JWT failures,
5
+ * resolver throws) and the audit trail records who called what. None of that
6
+ * may ever carry a live credential: an `Authorization: Bearer <token>` value,
7
+ * an `X-API-Key`, or a `Cookie`/`Set-Cookie` session token leaking into a log
8
+ * line is a credential disclosure. These helpers mask such values *before* they
9
+ * reach `console.*` or an audit sink.
10
+ *
11
+ * The redaction is one-way and irreversible. A masked value keeps just enough
12
+ * shape to correlate two log lines about the same credential (a short stable
13
+ * fingerprint) without revealing the secret itself.
14
+ *
15
+ * @module server/authentication/redaction
16
+ */
17
+ /**
18
+ * Mask a credential value so it can appear in a log or audit record without
19
+ * disclosing the secret. The result reveals only the length bucket and a short
20
+ * non-reversible fingerprint, which is enough to tell whether two log lines
21
+ * concern the same credential without exposing it.
22
+ *
23
+ * The fingerprint is derived from a non-cryptographic hash of the value. It is
24
+ * deliberately *not* the raw prefix of the token — revealing even a prefix of a
25
+ * high-entropy API key narrows a brute-force search. Equal inputs produce equal
26
+ * fingerprints; differing inputs almost always differ.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { redactCredential } from '@lostgradient/backchannel';
31
+ *
32
+ * const masked = redactCredential('weft_key_super_secret_value');
33
+ * console.log(masked.startsWith('<redacted:')); // true
34
+ * console.log(masked.includes('secret')); // false
35
+ * ```
36
+ */
37
+ export declare function redactCredential(value: string | null | undefined): string;
38
+ /**
39
+ * Produce a plain object snapshot of a request's headers with every sensitive
40
+ * value masked via {@link redactCredential}. Use this when attaching request
41
+ * headers to a log line or audit record — it guarantees no credential header
42
+ * passes through verbatim.
43
+ *
44
+ * Header names are lower-cased (the `Headers` iterator already lower-cases
45
+ * them) so the result is stable regardless of the casing the client sent.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * import { redactHeaders } from '@lostgradient/backchannel';
50
+ *
51
+ * const request = new Request('http://localhost/v1/workflows', {
52
+ * headers: { Authorization: 'Bearer secret-token', 'X-Trace-Id': 'abc' },
53
+ * });
54
+ * const safe = redactHeaders(request.headers);
55
+ * console.log(safe['x-trace-id']); // 'abc'
56
+ * console.log(safe['authorization']?.startsWith('<redacted:')); // true
57
+ * ```
58
+ */
59
+ export declare function redactHeaders(headers: Headers): Record<string, string>;
60
+ /**
61
+ * Whether a header name is treated as credential-bearing and therefore masked
62
+ * by {@link redactHeaders}. Comparison is case-insensitive.
63
+ *
64
+ * @example
65
+ * ```ts
66
+ * import { isSensitiveHeader } from '@lostgradient/backchannel';
67
+ *
68
+ * console.log(isSensitiveHeader('Authorization')); // true
69
+ * console.log(isSensitiveHeader('X-Trace-Id')); // false
70
+ * ```
71
+ */
72
+ export declare function isSensitiveHeader(name: string): boolean;