@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,114 @@
1
+ import { findConstantTimeApiKeyMatch, } from '@lostgradient/credentials/api-key-verification';
2
+ import { filterRecognizedScopes, } from "../authorization-scope.js";
3
+ import { principalFromApiKey, SHARED_API_KEY_SUBJECT, } from "../principal.js";
4
+ /**
5
+ * Method-mismatch guard. A resolver can return a principal with any
6
+ * `method` string; admitting under `method: 'api-key'` while the
7
+ * principal declares `method: 'jwt'` creates contradictory auth state.
8
+ * Returns `true` when the principal passes (method === 'api-key');
9
+ * logs + returns `false` otherwise. Separated from `deepFreezeApiKeyPrincipal`
10
+ * so each function has one responsibility — guard or copy/freeze.
11
+ */
12
+ function validateApiKeyPrincipalMethod(principal) {
13
+ if (principal.method !== 'api-key') {
14
+ console.warn(`resolveApiKeyPrincipal returned principal with method "${principal.method}"; expected "api-key". Rejecting.`);
15
+ return false;
16
+ }
17
+ return true;
18
+ }
19
+ /**
20
+ * Throws when a guarded scope set sees a mutation attempt. Named at
21
+ * module scope so the function is allocated once, not per-set.
22
+ */
23
+ function rejectScopeSetMutation(name) {
24
+ return () => {
25
+ throw new TypeError(`Cannot mutate scope set on admitted principal (attempted ${name})`);
26
+ };
27
+ }
28
+ function immutableScopeSet(source) {
29
+ const inner = new Set(source);
30
+ const guarded = {
31
+ has: (scope) => inner.has(scope),
32
+ get size() {
33
+ return inner.size;
34
+ },
35
+ forEach: (callback, thisArg) => inner.forEach((v, v2) => callback.call(thisArg, v, v2, guarded)),
36
+ keys: () => inner.keys(),
37
+ values: () => inner.values(),
38
+ entries: () => inner.entries(),
39
+ [Symbol.iterator]: () => inner[Symbol.iterator](),
40
+ // Mutation surface — exposed only so downstream leaks hit a loud
41
+ // error rather than silently succeeding against an unfrozen Set.
42
+ add: rejectScopeSetMutation('add'),
43
+ delete: rejectScopeSetMutation('delete'),
44
+ clear: rejectScopeSetMutation('clear'),
45
+ };
46
+ return Object.freeze(guarded);
47
+ }
48
+ function cloneClaims(claims) {
49
+ if (claims === undefined)
50
+ return undefined;
51
+ return deepFreeze(structuredClone(claims));
52
+ }
53
+ function deepFreeze(value) {
54
+ if (typeof value !== 'object' || value === null)
55
+ return value;
56
+ Object.freeze(value);
57
+ for (const key of Object.keys(value)) {
58
+ const child = value[key];
59
+ if (typeof child === 'object' && child !== null && !Object.isFrozen(child)) {
60
+ deepFreeze(child);
61
+ }
62
+ }
63
+ return value;
64
+ }
65
+ /**
66
+ * Copy and freeze an admitted API-key principal. Its scopes are narrowed to
67
+ * the ones this handler recognizes, as JWT claims are: built-in scopes plus
68
+ * the package scopes the handler registered. A resolver therefore cannot
69
+ * grant an unregistered package scope, or one in the reserved `weft`
70
+ * namespace, by returning it.
71
+ */
72
+ function deepFreezeApiKeyPrincipal(principal, additionalScopes, scopeVocabulary) {
73
+ const guardedScopes = immutableScopeSet(new Set(filterRecognizedScopes([...principal.scopes], additionalScopes, scopeVocabulary)));
74
+ const frozen = {
75
+ method: 'api-key',
76
+ scopes: guardedScopes,
77
+ claims: cloneClaims(principal.claims),
78
+ subject: principal.subject,
79
+ hasScope(scope) {
80
+ return guardedScopes.has(scope);
81
+ },
82
+ };
83
+ return Object.freeze(frozen);
84
+ }
85
+ export async function tryAdmitApiKey(presentedKey, resolver, apiKeyEntries, defaultApiKeyScopes, additionalScopes, scopeVocabulary) {
86
+ if (resolver !== undefined) {
87
+ let resolved;
88
+ try {
89
+ resolved = await resolver(presentedKey);
90
+ }
91
+ catch (error) {
92
+ // Resolver throw: log server-side, reject client. Never leak the
93
+ // thrown error's message to the wire — it may contain DB queries,
94
+ // secrets, or other sensitive context.
95
+ console.warn('resolveApiKeyPrincipal threw:', error instanceof Error ? error.message : error);
96
+ resolved = null;
97
+ }
98
+ if (resolved !== null && validateApiKeyPrincipalMethod(resolved)) {
99
+ const admitted = deepFreezeApiKeyPrincipal(resolved, additionalScopes, scopeVocabulary);
100
+ return { authenticated: true, method: 'api-key', principal: admitted };
101
+ }
102
+ return { authenticated: false, error: 'No valid credentials provided' };
103
+ }
104
+ if (apiKeyEntries !== null &&
105
+ (await findConstantTimeApiKeyMatch(presentedKey, apiKeyEntries)) !== null) {
106
+ const principal = principalFromApiKey({
107
+ subject: SHARED_API_KEY_SUBJECT,
108
+ scopes: defaultApiKeyScopes,
109
+ });
110
+ const admitted = deepFreezeApiKeyPrincipal(principal, additionalScopes, scopeVocabulary);
111
+ return { authenticated: true, method: 'api-key', principal: admitted };
112
+ }
113
+ return 'continue';
114
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Structured authentication audit trail.
3
+ *
4
+ * Every authentication decision the server makes — admission or rejection —
5
+ * emits one structured event so operators have a compliance-grade record of who
6
+ * authenticated, by which method, against which request, and whether it
7
+ * succeeded. The event is deliberately free of secrets: it carries the
8
+ * authenticated subject and method, never the presented credential.
9
+ *
10
+ * The default sink writes a single JSON line to `console.info` (success) or
11
+ * `console.warn` (failure), which standard log shippers collect. Embedders that
12
+ * forward audit events to a SIEM supply their own {@link AuthAuditSink} via
13
+ * `serve({ auth: { auditSink } })`.
14
+ *
15
+ * @module server/authentication/audit
16
+ */
17
+ /**
18
+ * A single authentication audit record. Emitted once per authenticated request
19
+ * (including public-path bypass and rejection). Contains no credential
20
+ * material — `credentialFingerprint`, when present, is the one-way mask from
21
+ * {@link redactCredential}, suitable for correlating events about the same key
22
+ * without revealing it.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * import { type AuthAuditEvent } from '@lostgradient/backchannel';
27
+ *
28
+ * const event: AuthAuditEvent = {
29
+ * outcome: 'success',
30
+ * method: 'api-key',
31
+ * subject: 'service-account-7',
32
+ * path: '/v1/workflows',
33
+ * httpMethod: 'POST',
34
+ * timestamp: new Date().toISOString(),
35
+ * };
36
+ * void event;
37
+ * ```
38
+ */
39
+ export type AuthAuditEvent = {
40
+ /** Whether the request was admitted (`success`) or rejected (`failure`). */
41
+ outcome: 'success' | 'failure';
42
+ /** Admission path that decided the request, or `unknown` when no method matched. */
43
+ method: string;
44
+ /** Authenticated principal subject, when one was established. */
45
+ subject?: string;
46
+ /** Request path the decision applied to (already prefix-normalized). */
47
+ path: string;
48
+ /** HTTP method of the request. */
49
+ httpMethod: string;
50
+ /** ISO-8601 timestamp of the decision. */
51
+ timestamp: string;
52
+ /** Client-safe rejection reason on failure. Never contains credential bytes. */
53
+ reason?: string;
54
+ /** One-way masked fingerprint of the presented credential, for correlation. */
55
+ credentialFingerprint?: string;
56
+ };
57
+ /**
58
+ * Sink that receives every {@link AuthAuditEvent}. Supply a custom sink via
59
+ * `serve({ auth: { auditSink } })` to forward audit records to a SIEM or
60
+ * structured-logging pipeline; omit it to use {@link defaultAuthAuditSink}.
61
+ *
62
+ * Implementations must be non-throwing and fast — the sink runs inline on the
63
+ * authentication path. Failures inside a sink must not break request handling.
64
+ *
65
+ * @example
66
+ * ```ts
67
+ * import { type AuthAuditEvent, type AuthAuditSink } from '@lostgradient/backchannel';
68
+ *
69
+ * const collected: AuthAuditEvent[] = [];
70
+ * const sink: AuthAuditSink = (event) => collected.push(event);
71
+ * void sink;
72
+ * ```
73
+ */
74
+ export type AuthAuditSink = (event: AuthAuditEvent) => void;
75
+ /**
76
+ * Default {@link AuthAuditSink}: writes one structured JSON line per event,
77
+ * routing successes to `console.info` and failures to `console.warn`. The
78
+ * `weft.auth-audit` discriminator lets log processors filter the audit stream.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * import { defaultAuthAuditSink } from '@lostgradient/backchannel';
83
+ *
84
+ * defaultAuthAuditSink({
85
+ * outcome: 'failure',
86
+ * method: 'unknown',
87
+ * path: '/v1/workflows',
88
+ * httpMethod: 'GET',
89
+ * timestamp: new Date().toISOString(),
90
+ * reason: 'No valid credentials provided',
91
+ * });
92
+ * ```
93
+ */
94
+ export declare function defaultAuthAuditSink(event: AuthAuditEvent): void;
95
+ /**
96
+ * Inputs needed to build and emit an audit event for a single request. The
97
+ * raw `presentedCredential` is masked here — it is never stored on the event
98
+ * or passed to the sink in cleartext.
99
+ */
100
+ export type AuthAuditContext = {
101
+ outcome: 'success' | 'failure';
102
+ method: string;
103
+ subject: string | undefined;
104
+ request: Request;
105
+ reason?: string | undefined;
106
+ presentedCredential?: string | null | undefined;
107
+ };
108
+ /**
109
+ * Build an {@link AuthAuditEvent} from request context and hand it to `sink`,
110
+ * masking the presented credential first. A throwing sink is swallowed (and
111
+ * logged) so audit-emission failures never break request handling.
112
+ *
113
+ * @internal
114
+ */
115
+ export declare function emitAuthAuditEvent(sink: AuthAuditSink, context: AuthAuditContext): void;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Structured authentication audit trail.
3
+ *
4
+ * Every authentication decision the server makes — admission or rejection —
5
+ * emits one structured event so operators have a compliance-grade record of who
6
+ * authenticated, by which method, against which request, and whether it
7
+ * succeeded. The event is deliberately free of secrets: it carries the
8
+ * authenticated subject and method, never the presented credential.
9
+ *
10
+ * The default sink writes a single JSON line to `console.info` (success) or
11
+ * `console.warn` (failure), which standard log shippers collect. Embedders that
12
+ * forward audit events to a SIEM supply their own {@link AuthAuditSink} via
13
+ * `serve({ auth: { auditSink } })`.
14
+ *
15
+ * @module server/authentication/audit
16
+ */
17
+ import { redactCredential } from "./redaction.js";
18
+ /**
19
+ * Default {@link AuthAuditSink}: writes one structured JSON line per event,
20
+ * routing successes to `console.info` and failures to `console.warn`. The
21
+ * `weft.auth-audit` discriminator lets log processors filter the audit stream.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { defaultAuthAuditSink } from '@lostgradient/backchannel';
26
+ *
27
+ * defaultAuthAuditSink({
28
+ * outcome: 'failure',
29
+ * method: 'unknown',
30
+ * path: '/v1/workflows',
31
+ * httpMethod: 'GET',
32
+ * timestamp: new Date().toISOString(),
33
+ * reason: 'No valid credentials provided',
34
+ * });
35
+ * ```
36
+ */
37
+ export function defaultAuthAuditSink(event) {
38
+ const line = JSON.stringify({ type: 'weft.auth-audit', ...event });
39
+ if (event.outcome === 'success') {
40
+ console.info(line);
41
+ }
42
+ else {
43
+ console.warn(line);
44
+ }
45
+ }
46
+ /**
47
+ * Build an {@link AuthAuditEvent} from request context and hand it to `sink`,
48
+ * masking the presented credential first. A throwing sink is swallowed (and
49
+ * logged) so audit-emission failures never break request handling.
50
+ *
51
+ * @internal
52
+ */
53
+ export function emitAuthAuditEvent(sink, context) {
54
+ const url = new URL(context.request.url);
55
+ const event = {
56
+ outcome: context.outcome,
57
+ method: context.method,
58
+ path: url.pathname,
59
+ httpMethod: context.request.method,
60
+ timestamp: new Date().toISOString(),
61
+ ...(context.subject !== undefined ? { subject: context.subject } : {}),
62
+ ...(context.reason !== undefined ? { reason: context.reason } : {}),
63
+ ...(context.presentedCredential !== undefined && context.presentedCredential !== null
64
+ ? { credentialFingerprint: redactCredential(context.presentedCredential) }
65
+ : {}),
66
+ };
67
+ try {
68
+ sink(event);
69
+ }
70
+ catch (error) {
71
+ // An audit sink must never break request handling. Log the sink failure
72
+ // (without the event payload, which could be voluminous) and continue.
73
+ console.error('[weft] auth audit sink threw:', error instanceof Error ? error.message : error);
74
+ }
75
+ }
@@ -0,0 +1,60 @@
1
+ import { type PackageAuthorizationScope, type ScopeVocabulary } from "../authorization-scope.js";
2
+ import type { AuthConfig, AuthContext, JWTConfig, MTLSConfig } from "./types.js";
3
+ export declare function extractApiKey(request: Request): string | null;
4
+ export declare function validateJwtConfig(config: JWTConfig | undefined): void;
5
+ /** The result of examining a request with one credential verifier. */
6
+ export type CredentialVerification = {
7
+ readonly kind: 'absent';
8
+ } | {
9
+ readonly kind: 'unrecognized';
10
+ } | {
11
+ readonly kind: 'reject';
12
+ } | {
13
+ readonly kind: 'admit';
14
+ readonly authentication: AuthContext;
15
+ };
16
+ /**
17
+ * One ordered credential check. An absent credential leaves the chain unchanged.
18
+ * An unrecognized credential lets later explicit verifiers try, while suppressing
19
+ * mTLS fallback. A rejection ends authentication. The method names successful
20
+ * admissions in audit records.
21
+ */
22
+ export type CredentialVerifier = {
23
+ /** The method recorded in the successful authentication audit. */
24
+ readonly method: string;
25
+ /** Inspect the request using the verifier’s credential rules. */
26
+ verify(request: Request, context: {
27
+ readonly explicitCredentialAttempted: boolean;
28
+ }): CredentialVerification | Promise<CredentialVerification>;
29
+ };
30
+ /** Check a static list of API keys or delegate to an authoritative resolver. */
31
+ export declare function createApiKeyVerifier(config: Pick<AuthConfig, 'apiKeys' | 'resolveApiKeyPrincipal' | 'defaultApiKeyScopes'>, options?: CreateAuthenticatorOptions): Promise<CredentialVerifier>;
32
+ /** Check a Bearer JWT and shape its verified claims into a principal. */
33
+ export declare function createJwtVerifier(config: JWTConfig, options?: CreateAuthenticatorOptions): Promise<CredentialVerifier>;
34
+ /** Admit an mTLS caller when the verifier has positive evidence of a verified certificate. */
35
+ export declare function createMutualTlsVerifier(config: Pick<MTLSConfig, 'verifyClientCertificate'>, options?: CreateAuthenticatorOptions): CredentialVerifier;
36
+ /**
37
+ * Options supplied by the code that owns the transport, not by `AuthConfig`.
38
+ */
39
+ export type CreateAuthenticatorOptions = {
40
+ /** Scopes issued by this host. */
41
+ scopeVocabulary?: ScopeVocabulary;
42
+ /**
43
+ * Attests that the listener carrying these requests requested a client
44
+ * certificate and refused every connection without a verified one, so a
45
+ * request reaching the authenticator is evidence of a verified certificate.
46
+ * `serve()` sets this from the TLS options it builds; leave it unset
47
+ * whenever TLS terminates anywhere else.
48
+ */
49
+ transportVerifiesClientCertificates?: boolean;
50
+ /**
51
+ * Package scopes this authenticator recognizes beyond Weft's built-in
52
+ * vocabulary, such as `bureau.tasks:read`. They are retained from JWT
53
+ * `scope`, `scp`, and `permissions` claims, from `defaultApiKeyScopes`, and
54
+ * from the principal `resolveApiKeyPrincipal` returns; any other unknown
55
+ * scope, including one in the reserved `weft` namespace, is dropped. The set belongs to this
56
+ * authenticator alone. An entry that is not `<namespace>.<resource>:<action>`
57
+ * or that uses the reserved `weft` namespace rejects construction.
58
+ */
59
+ additionalScopes?: readonly PackageAuthorizationScope[];
60
+ };
@@ -0,0 +1,102 @@
1
+ import { createConstantTimeApiKeyMatcher } from '@lostgradient/credentials/api-key-verification';
2
+ import { createAdditionalScopeSet, EMPTY_SCOPE_VOCABULARY, filterRecognizedScopes, } from "../authorization-scope.js";
3
+ import { principalFromJwtClaims } from "../principal.js";
4
+ import { tryAdmitApiKey } from "./api-key.js";
5
+ import { importJWTKey, verifyJWT } from "./crypto.js";
6
+ function extractBearerToken(request) {
7
+ const authorization = request.headers.get('Authorization');
8
+ if (authorization?.startsWith('Bearer ')) {
9
+ return authorization.slice(7);
10
+ }
11
+ return null;
12
+ }
13
+ export function extractApiKey(request) {
14
+ const headerKey = request.headers.get('X-API-Key');
15
+ if (headerKey)
16
+ return headerKey;
17
+ return extractBearerToken(request);
18
+ }
19
+ export function validateJwtConfig(config) {
20
+ if (config === undefined)
21
+ return;
22
+ const algorithm = config.algorithm ?? 'HS256';
23
+ if (algorithm.startsWith('HS') && !config.secret) {
24
+ throw new Error('JWT configuration requires "secret" for HMAC algorithms');
25
+ }
26
+ if ((algorithm.startsWith('RS') || algorithm.startsWith('ES')) && !config.publicKey) {
27
+ throw new Error('JWT configuration requires "publicKey" for RSA/ECDSA algorithms');
28
+ }
29
+ }
30
+ /** Check a static list of API keys or delegate to an authoritative resolver. */
31
+ export async function createApiKeyVerifier(config, options = {}) {
32
+ const resolver = config.resolveApiKeyPrincipal;
33
+ const additionalScopes = createAdditionalScopeSet(options.additionalScopes);
34
+ const scopeVocabulary = options.scopeVocabulary ?? EMPTY_SCOPE_VOCABULARY;
35
+ const defaultScopes = filterRecognizedScopes(config.defaultApiKeyScopes ?? [], additionalScopes, scopeVocabulary);
36
+ const matcher = config.apiKeys?.length
37
+ ? await createConstantTimeApiKeyMatcher(config.apiKeys)
38
+ : null;
39
+ return {
40
+ method: 'api-key',
41
+ async verify(request) {
42
+ const key = extractApiKey(request);
43
+ if (!key || (resolver === undefined && matcher === null))
44
+ return { kind: 'absent' };
45
+ const admission = await tryAdmitApiKey(key, resolver, matcher?.entries ?? null, defaultScopes, additionalScopes, scopeVocabulary);
46
+ if (admission === 'continue')
47
+ return { kind: 'unrecognized' };
48
+ return admission.authenticated
49
+ ? { kind: 'admit', authentication: admission }
50
+ : { kind: 'reject' };
51
+ },
52
+ };
53
+ }
54
+ /** Check a Bearer JWT and shape its verified claims into a principal. */
55
+ export async function createJwtVerifier(config, options = {}) {
56
+ validateJwtConfig(config);
57
+ const jwt = { ...config };
58
+ const additionalScopes = createAdditionalScopeSet(options.additionalScopes);
59
+ const scopeVocabulary = options.scopeVocabulary ?? EMPTY_SCOPE_VOCABULARY;
60
+ const key = await importJWTKey(jwt);
61
+ return {
62
+ method: 'jwt',
63
+ async verify(request) {
64
+ const token = extractBearerToken(request);
65
+ if (!token)
66
+ return { kind: 'absent' };
67
+ if (!token.includes('.'))
68
+ return { kind: 'unrecognized' };
69
+ try {
70
+ const claims = await verifyJWT(token, key, jwt);
71
+ const principal = principalFromJwtClaims(claims, { additionalScopes, scopeVocabulary });
72
+ return { kind: 'admit', authentication: { method: 'jwt', claims, principal } };
73
+ }
74
+ catch (error) {
75
+ console.warn('JWT verification failed:', error instanceof Error ? error.message : error);
76
+ return { kind: 'unrecognized' };
77
+ }
78
+ },
79
+ };
80
+ }
81
+ /** Admit an mTLS caller when the verifier has positive evidence of a verified certificate. */
82
+ export function createMutualTlsVerifier(config, options = {}) {
83
+ const verify = config.verifyClientCertificate;
84
+ const transportVerified = options.transportVerifiesClientCertificates === true;
85
+ return {
86
+ method: 'mtls',
87
+ async verify(request, { explicitCredentialAttempted }) {
88
+ if (explicitCredentialAttempted)
89
+ return { kind: 'absent' };
90
+ try {
91
+ const verified = verify === undefined ? transportVerified : await verify(request);
92
+ return verified === true
93
+ ? { kind: 'admit', authentication: { method: 'mtls' } }
94
+ : { kind: 'absent' };
95
+ }
96
+ catch (error) {
97
+ console.warn('Client certificate verification failed:', error instanceof Error ? error.message : error);
98
+ return { kind: 'absent' };
99
+ }
100
+ },
101
+ };
102
+ }
@@ -0,0 +1,7 @@
1
+ import { type JWTAlgorithm, type JWTConfig, type JWTPayload } from "./types.js";
2
+ /** Import a CryptoKey from JWT configuration for signature verification. */
3
+ export declare function importJWTKey(config: JWTConfig): Promise<CryptoKey>;
4
+ /** Sign a JWT payload. Primarily for testing. */
5
+ export declare function signJWT(payload: JWTPayload, secret: string, algorithm?: JWTAlgorithm): Promise<string>;
6
+ /** Verify a JWT token and return its decoded payload. */
7
+ export declare function verifyJWT(token: string, key: CryptoKey, config: JWTConfig): Promise<JWTPayload>;
@@ -0,0 +1,140 @@
1
+ import { DEFAULT_CLOCK_TOLERANCE, } from "./types.js";
2
+ const HMAC_IMPORT_PARAMS = {
3
+ HS256: { name: 'HMAC', hash: 'SHA-256' },
4
+ HS384: { name: 'HMAC', hash: 'SHA-384' },
5
+ HS512: { name: 'HMAC', hash: 'SHA-512' },
6
+ };
7
+ const RSA_IMPORT_PARAMS = {
8
+ RS256: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
9
+ RS384: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-384' },
10
+ RS512: { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-512' },
11
+ };
12
+ const ECDSA_IMPORT_PARAMS = {
13
+ ES256: { name: 'ECDSA', namedCurve: 'P-256' },
14
+ ES384: { name: 'ECDSA', namedCurve: 'P-384' },
15
+ ES512: { name: 'ECDSA', namedCurve: 'P-521' },
16
+ };
17
+ function getImportParams(algorithm) {
18
+ if (algorithm in HMAC_IMPORT_PARAMS)
19
+ return HMAC_IMPORT_PARAMS[algorithm];
20
+ if (algorithm in RSA_IMPORT_PARAMS)
21
+ return RSA_IMPORT_PARAMS[algorithm];
22
+ return ECDSA_IMPORT_PARAMS[algorithm];
23
+ }
24
+ function getVerifyParams(algorithm) {
25
+ if (algorithm.startsWith('ES')) {
26
+ return { name: 'ECDSA', hash: `SHA-${algorithm.slice(2)}` };
27
+ }
28
+ return getImportParams(algorithm);
29
+ }
30
+ /**
31
+ * Encode a string to an `ArrayBuffer` for use with Web Crypto APIs.
32
+ *
33
+ * `TextEncoder.encode().buffer` is typed as `ArrayBufferLike` (which includes
34
+ * `SharedArrayBuffer`), but `crypto.subtle` expects `BufferSource`. Copying
35
+ * into a fresh `ArrayBuffer` gives a properly typed result without needing
36
+ * a type assertion that conflicts between tsc and oxlint.
37
+ */
38
+ function textToBuffer(text) {
39
+ const encoded = new TextEncoder().encode(text);
40
+ const buffer = new ArrayBuffer(encoded.byteLength);
41
+ new Uint8Array(buffer).set(encoded);
42
+ return buffer;
43
+ }
44
+ /** Decode a binary string (from `atob`) into a fresh `ArrayBuffer`. */
45
+ function binaryStringToBuffer(binary) {
46
+ const buffer = new ArrayBuffer(binary.length);
47
+ const view = new Uint8Array(buffer);
48
+ for (let i = 0; i < binary.length; i++) {
49
+ view[i] = binary.charCodeAt(i);
50
+ }
51
+ return buffer;
52
+ }
53
+ function base64UrlDecode(input) {
54
+ const base64 = input.replace(/-/g, '+').replace(/_/g, '/');
55
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
56
+ return binaryStringToBuffer(atob(padded));
57
+ }
58
+ function base64UrlEncode(buffer) {
59
+ const bytes = new Uint8Array(buffer);
60
+ let binary = '';
61
+ for (const byte of bytes) {
62
+ binary += String.fromCharCode(byte);
63
+ }
64
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
65
+ }
66
+ function parsePEM(pem) {
67
+ const base64 = pem.replace(/-----[A-Z ]+-----/g, '').replace(/\s/g, '');
68
+ return binaryStringToBuffer(atob(base64));
69
+ }
70
+ /** Import a CryptoKey from JWT configuration for signature verification. */
71
+ export async function importJWTKey(config) {
72
+ const algorithm = config.algorithm ?? 'HS256';
73
+ const params = getImportParams(algorithm);
74
+ if (algorithm.startsWith('HS')) {
75
+ if (!config.secret) {
76
+ throw new Error('JWT configuration requires "secret" for HMAC algorithms');
77
+ }
78
+ return crypto.subtle.importKey('raw', textToBuffer(config.secret), params, false, ['verify']);
79
+ }
80
+ if (!config.publicKey) {
81
+ throw new Error('JWT configuration requires "publicKey" for RSA/ECDSA algorithms');
82
+ }
83
+ return crypto.subtle.importKey('spki', parsePEM(config.publicKey), params, false, ['verify']);
84
+ }
85
+ /** Sign a JWT payload. Primarily for testing. */
86
+ export async function signJWT(payload, secret, algorithm = 'HS256') {
87
+ const header = { alg: algorithm, typ: 'JWT' };
88
+ const headerB64 = base64UrlEncode(textToBuffer(JSON.stringify(header)));
89
+ const payloadB64 = base64UrlEncode(textToBuffer(JSON.stringify(payload)));
90
+ const signingInput = textToBuffer(`${headerB64}.${payloadB64}`);
91
+ const params = getImportParams(algorithm);
92
+ const key = await crypto.subtle.importKey('raw', textToBuffer(secret), params, false, ['sign']);
93
+ const signature = await crypto.subtle.sign(params, key, signingInput);
94
+ return `${headerB64}.${payloadB64}.${base64UrlEncode(signature)}`;
95
+ }
96
+ function validateTemporalClaims(payload, config) {
97
+ const now = Math.floor(Date.now() / 1000);
98
+ const tolerance = config.clockTolerance ?? DEFAULT_CLOCK_TOLERANCE;
99
+ if (typeof payload['exp'] === 'number' && now > payload['exp'] + tolerance) {
100
+ throw new Error('JWT expired');
101
+ }
102
+ if (typeof payload['nbf'] === 'number' && now < payload['nbf'] - tolerance) {
103
+ throw new Error('JWT not yet valid');
104
+ }
105
+ }
106
+ function validateClaimsIdentity(payload, config) {
107
+ if (config.issuer !== undefined && payload['iss'] !== config.issuer) {
108
+ throw new Error(`Invalid issuer: expected "${config.issuer}", got "${String(payload['iss'])}"`);
109
+ }
110
+ if (config.audience !== undefined) {
111
+ const aud = Array.isArray(payload['aud']) ? payload['aud'] : [payload['aud']];
112
+ if (!aud.includes(config.audience)) {
113
+ throw new Error(`Invalid audience: expected "${config.audience}"`);
114
+ }
115
+ }
116
+ }
117
+ /** Verify a JWT token and return its decoded payload. */
118
+ export async function verifyJWT(token, key, config) {
119
+ const parts = token.split('.');
120
+ if (parts.length !== 3) {
121
+ throw new Error('Invalid JWT format');
122
+ }
123
+ const [headerB64, payloadB64, signatureB64] = parts;
124
+ const header = JSON.parse(new TextDecoder().decode(base64UrlDecode(headerB64)));
125
+ const expectedAlgorithm = config.algorithm ?? 'HS256';
126
+ if (header.alg !== expectedAlgorithm) {
127
+ throw new Error(`Algorithm mismatch: expected ${expectedAlgorithm}, got ${header.alg}`);
128
+ }
129
+ const signingInput = textToBuffer(`${headerB64}.${payloadB64}`);
130
+ const signature = base64UrlDecode(signatureB64);
131
+ const verifyParams = getVerifyParams(expectedAlgorithm);
132
+ const valid = await crypto.subtle.verify(verifyParams, key, signature, signingInput);
133
+ if (!valid) {
134
+ throw new Error('Invalid JWT signature');
135
+ }
136
+ const payload = JSON.parse(new TextDecoder().decode(base64UrlDecode(payloadB64)));
137
+ validateTemporalClaims(payload, config);
138
+ validateClaimsIdentity(payload, config);
139
+ return payload;
140
+ }