@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.
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/dist/access-policy-metadata.d.ts +92 -0
- package/dist/access-policy-metadata.js +87 -0
- package/dist/asyncapi-channels.d.ts +46 -0
- package/dist/asyncapi-channels.js +399 -0
- package/dist/asyncapi.d.ts +40 -0
- package/dist/asyncapi.js +165 -0
- package/dist/authentication/api-key.d.ts +4 -0
- package/dist/authentication/api-key.js +114 -0
- package/dist/authentication/audit.d.ts +115 -0
- package/dist/authentication/audit.js +75 -0
- package/dist/authentication/credential-verifiers.d.ts +60 -0
- package/dist/authentication/credential-verifiers.js +102 -0
- package/dist/authentication/crypto.d.ts +7 -0
- package/dist/authentication/crypto.js +140 -0
- package/dist/authentication/index.d.ts +80 -0
- package/dist/authentication/index.js +212 -0
- package/dist/authentication/rate-limiter.d.ts +133 -0
- package/dist/authentication/rate-limiter.js +124 -0
- package/dist/authentication/redaction.d.ts +72 -0
- package/dist/authentication/redaction.js +118 -0
- package/dist/authentication/rotating-api-key-store.d.ts +127 -0
- package/dist/authentication/rotating-api-key-store.js +126 -0
- package/dist/authentication/types.d.ts +337 -0
- package/dist/authentication/types.js +26 -0
- package/dist/authentication.d.ts +1 -0
- package/dist/authentication.js +1 -0
- package/dist/authorization-scope.d.ts +109 -0
- package/dist/authorization-scope.js +144 -0
- package/dist/authorization.d.ts +55 -0
- package/dist/authorization.js +134 -0
- package/dist/bind-feed-lifetime.d.ts +45 -0
- package/dist/bind-feed-lifetime.js +55 -0
- package/dist/byte-arrays.d.ts +5 -0
- package/dist/byte-arrays.js +9 -0
- package/dist/client/catalog-client.d.ts +285 -0
- package/dist/client/catalog-client.js +74 -0
- package/dist/client/in-process-transport.d.ts +19 -0
- package/dist/client/in-process-transport.js +136 -0
- package/dist/client/index.d.ts +14 -0
- package/dist/client/index.js +14 -0
- package/dist/client/json-rpc-http-transport.d.ts +118 -0
- package/dist/client/json-rpc-http-transport.js +127 -0
- package/dist/client/server-sent-event-parser.d.ts +55 -0
- package/dist/client/server-sent-event-parser.js +78 -0
- package/dist/client/sse-subscription-transport.d.ts +72 -0
- package/dist/client/sse-subscription-transport.js +224 -0
- package/dist/client/subscription-client.d.ts +122 -0
- package/dist/client/subscription-client.js +28 -0
- package/dist/connection-lease.d.ts +10 -0
- package/dist/connection-lease.js +8 -0
- package/dist/discovery-filter.d.ts +13 -0
- package/dist/discovery-filter.js +16 -0
- package/dist/discovery-info.d.ts +94 -0
- package/dist/discovery-info.js +38 -0
- package/dist/event-selector.d.ts +7 -0
- package/dist/event-selector.js +7 -0
- package/dist/fault-code.d.ts +84 -0
- package/dist/fault-code.js +114 -0
- package/dist/fault-remediation.d.ts +30 -0
- package/dist/fault-remediation.js +52 -0
- package/dist/fault-to-http.d.ts +11 -0
- package/dist/fault-to-http.js +13 -0
- package/dist/fault-to-json-rpc.d.ts +53 -0
- package/dist/fault-to-json-rpc.js +143 -0
- package/dist/fault-wire-safety.d.ts +45 -0
- package/dist/fault-wire-safety.js +72 -0
- package/dist/generator.d.ts +9 -0
- package/dist/generator.js +9 -0
- package/dist/handler/auth-context-principal.d.ts +37 -0
- package/dist/handler/auth-context-principal.js +67 -0
- package/dist/handler/authentication-responses.d.ts +23 -0
- package/dist/handler/authentication-responses.js +34 -0
- package/dist/handler/json-responses.d.ts +15 -0
- package/dist/handler/json-responses.js +32 -0
- package/dist/handler/operation-handler-authentication.d.ts +64 -0
- package/dist/handler/operation-handler-authentication.js +58 -0
- package/dist/handler/operation-handler-discovery.d.ts +29 -0
- package/dist/handler/operation-handler-discovery.js +55 -0
- package/dist/handler/operation-handler-mounts.d.ts +100 -0
- package/dist/handler/operation-handler-mounts.js +134 -0
- package/dist/handler/operation-handler-subscription.d.ts +34 -0
- package/dist/handler/operation-handler-subscription.js +112 -0
- package/dist/handler/operation-handler.d.ts +162 -0
- package/dist/handler/operation-handler.js +236 -0
- package/dist/handler/workspace-release.d.ts +6 -0
- package/dist/handler/workspace-release.js +75 -0
- package/dist/in-memory-replay-live-backend.d.ts +47 -0
- package/dist/in-memory-replay-live-backend.js +129 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +30 -0
- package/dist/internal/cryptography/encryption.d.ts +108 -0
- package/dist/internal/cryptography/encryption.js +241 -0
- package/dist/internal/cryptography/hash.d.ts +72 -0
- package/dist/internal/cryptography/hash.js +233 -0
- package/dist/internal/cryptography/index.d.ts +4 -0
- package/dist/internal/cryptography/index.js +2 -0
- package/dist/internals.d.ts +58 -0
- package/dist/internals.js +54 -0
- package/dist/json-rpc-dispatch.d.ts +88 -0
- package/dist/json-rpc-dispatch.js +154 -0
- package/dist/json-rpc-framing.d.ts +42 -0
- package/dist/json-rpc-framing.js +50 -0
- package/dist/json-rpc-http.d.ts +36 -0
- package/dist/json-rpc-http.js +191 -0
- package/dist/json-rpc-parse.d.ts +69 -0
- package/dist/json-rpc-parse.js +206 -0
- package/dist/json-rpc-protocol.d.ts +76 -0
- package/dist/json-rpc-protocol.js +54 -0
- package/dist/json-rpc-session-runtime.d.ts +55 -0
- package/dist/json-rpc-session-runtime.js +111 -0
- package/dist/json-rpc-websocket-subscription-pump.d.ts +9 -0
- package/dist/json-rpc-websocket-subscription-pump.js +46 -0
- package/dist/json-rpc-websocket-subscriptions.d.ts +10 -0
- package/dist/json-rpc-websocket-subscriptions.js +33 -0
- package/dist/json-rpc-websocket-types.d.ts +34 -0
- package/dist/json-rpc-websocket-types.js +1 -0
- package/dist/json-rpc-websocket-validation.d.ts +45 -0
- package/dist/json-rpc-websocket-validation.js +154 -0
- package/dist/json-rpc-websocket.d.ts +20 -0
- package/dist/json-rpc-websocket.js +363 -0
- package/dist/json-schema-utilities.d.ts +5 -0
- package/dist/json-schema-utilities.js +17 -0
- package/dist/mcp-discovery-names.d.ts +11 -0
- package/dist/mcp-discovery-names.js +11 -0
- package/dist/openapi-canonical-json.d.ts +10 -0
- package/dist/openapi-canonical-json.js +23 -0
- package/dist/openapi-error-responses.d.ts +15 -0
- package/dist/openapi-error-responses.js +104 -0
- package/dist/openapi-schemas.d.ts +17 -0
- package/dist/openapi-schemas.js +94 -0
- package/dist/openapi.d.ts +60 -0
- package/dist/openapi.js +351 -0
- package/dist/openrpc-document-schema.d.ts +255 -0
- package/dist/openrpc-document-schema.js +84 -0
- package/dist/openrpc-errors.d.ts +93 -0
- package/dist/openrpc-errors.js +134 -0
- package/dist/openrpc.d.ts +66 -0
- package/dist/openrpc.js +260 -0
- package/dist/operation-catalog/behavior-types.d.ts +34 -0
- package/dist/operation-catalog/behavior-types.js +1 -0
- package/dist/operation-catalog/behavior-validation.d.ts +3 -0
- package/dist/operation-catalog/behavior-validation.js +298 -0
- package/dist/operation-catalog/dispatch-allowlist.d.ts +4 -0
- package/dist/operation-catalog/dispatch-allowlist.js +7 -0
- package/dist/operation-catalog/dispatch-preparation.d.ts +24 -0
- package/dist/operation-catalog/dispatch-preparation.js +49 -0
- package/dist/operation-catalog/index.d.ts +19 -0
- package/dist/operation-catalog/index.js +17 -0
- package/dist/operation-catalog/operation-dispatch.d.ts +14 -0
- package/dist/operation-catalog/operation-dispatch.js +115 -0
- package/dist/operation-catalog/operation-interceptors.d.ts +15 -0
- package/dist/operation-catalog/operation-interceptors.js +1 -0
- package/dist/operation-catalog/operation-metadata.d.ts +5 -0
- package/dist/operation-catalog/operation-metadata.js +104 -0
- package/dist/operation-catalog/pipeline-helpers.d.ts +70 -0
- package/dist/operation-catalog/pipeline-helpers.js +242 -0
- package/dist/operation-catalog/pipeline-stages.d.ts +23 -0
- package/dist/operation-catalog/pipeline-stages.js +226 -0
- package/dist/operation-catalog/pipeline.d.ts +7 -0
- package/dist/operation-catalog/pipeline.js +33 -0
- package/dist/operation-catalog/registry.d.ts +17 -0
- package/dist/operation-catalog/registry.js +132 -0
- package/dist/operation-catalog/stream-pipeline.d.ts +37 -0
- package/dist/operation-catalog/stream-pipeline.js +129 -0
- package/dist/operation-catalog/subscription-lifecycle.d.ts +6 -0
- package/dist/operation-catalog/subscription-lifecycle.js +27 -0
- package/dist/operation-catalog/types.d.ts +392 -0
- package/dist/operation-catalog/types.js +40 -0
- package/dist/operation-catalog/universal-faults.d.ts +11 -0
- package/dist/operation-catalog/universal-faults.js +15 -0
- package/dist/operation-catalog-snapshot.d.ts +215 -0
- package/dist/operation-catalog-snapshot.js +128 -0
- package/dist/operation-catalog.d.ts +1 -0
- package/dist/operation-catalog.js +1 -0
- package/dist/operation-description-audit.d.ts +44 -0
- package/dist/operation-description-audit.js +90 -0
- package/dist/operation-fault-helpers.d.ts +21 -0
- package/dist/operation-fault-helpers.js +32 -0
- package/dist/operation-fault.d.ts +245 -0
- package/dist/operation-fault.js +235 -0
- package/dist/operation-registry.d.ts +46 -0
- package/dist/operation-registry.js +46 -0
- package/dist/operations/closable-iterable.d.ts +23 -0
- package/dist/operations/closable-iterable.js +51 -0
- package/dist/operations/get-principal.d.ts +106 -0
- package/dist/operations/get-principal.js +107 -0
- package/dist/operations/sse-stream.d.ts +67 -0
- package/dist/operations/sse-stream.js +264 -0
- package/dist/principal.d.ts +253 -0
- package/dist/principal.js +254 -0
- package/dist/replay-live-feed-internals.d.ts +47 -0
- package/dist/replay-live-feed-internals.js +215 -0
- package/dist/replay-live-feed-types.d.ts +66 -0
- package/dist/replay-live-feed-types.js +7 -0
- package/dist/replay-live-feed.d.ts +49 -0
- package/dist/replay-live-feed.js +126 -0
- package/dist/rest-binding.d.ts +215 -0
- package/dist/rest-binding.js +95 -0
- package/dist/rest-body.d.ts +17 -0
- package/dist/rest-body.js +95 -0
- package/dist/route-model.d.ts +305 -0
- package/dist/route-model.js +320 -0
- package/dist/runtime/cors.d.ts +161 -0
- package/dist/runtime/cors.js +265 -0
- package/dist/scripts/generate-operation-client.d.ts +186 -0
- package/dist/scripts/generate-operation-client.js +561 -0
- package/dist/scripts/operation-behaviors.d.ts +3 -0
- package/dist/scripts/operation-behaviors.js +16 -0
- package/dist/scripts/operation-client-aliases.d.ts +32 -0
- package/dist/scripts/operation-client-aliases.js +255 -0
- package/dist/scripts/operation-client-domains.d.ts +21 -0
- package/dist/scripts/operation-client-domains.js +74 -0
- package/dist/scripts/operation-client-schema.d.ts +46 -0
- package/dist/scripts/operation-client-schema.js +310 -0
- package/dist/scripts/operation-client-svelte.d.ts +3 -0
- package/dist/scripts/operation-client-svelte.js +61 -0
- package/dist/sequence-cursor.d.ts +46 -0
- package/dist/sequence-cursor.js +62 -0
- package/dist/sse-error-payload-schema.d.ts +12 -0
- package/dist/sse-error-payload-schema.js +33 -0
- package/dist/stdio-session.d.ts +71 -0
- package/dist/stdio-session.js +347 -0
- package/dist/zod-json-schema.d.ts +22 -0
- package/dist/zod-json-schema.js +49 -0
- package/package.json +38 -3
|
@@ -0,0 +1,118 @@
|
|
|
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
|
+
* Header names whose values are credentials and must always be masked.
|
|
19
|
+
* Compared case-insensitively. The list is intentionally conservative: it
|
|
20
|
+
* covers the headers Weft's own authenticator reads (`Authorization`,
|
|
21
|
+
* `X-API-Key`) plus the browser session-cookie headers that a reverse proxy or
|
|
22
|
+
* embedder might attach.
|
|
23
|
+
*/
|
|
24
|
+
const SENSITIVE_HEADER_NAMES = new Set([
|
|
25
|
+
'authorization',
|
|
26
|
+
'x-api-key',
|
|
27
|
+
'cookie',
|
|
28
|
+
'set-cookie',
|
|
29
|
+
'proxy-authorization',
|
|
30
|
+
]);
|
|
31
|
+
/** Marker substituted for an empty or absent credential. */
|
|
32
|
+
const EMPTY_REDACTION = '<redacted:empty>';
|
|
33
|
+
/**
|
|
34
|
+
* Mask a credential value so it can appear in a log or audit record without
|
|
35
|
+
* disclosing the secret. The result reveals only the length bucket and a short
|
|
36
|
+
* non-reversible fingerprint, which is enough to tell whether two log lines
|
|
37
|
+
* concern the same credential without exposing it.
|
|
38
|
+
*
|
|
39
|
+
* The fingerprint is derived from a non-cryptographic hash of the value. It is
|
|
40
|
+
* deliberately *not* the raw prefix of the token — revealing even a prefix of a
|
|
41
|
+
* high-entropy API key narrows a brute-force search. Equal inputs produce equal
|
|
42
|
+
* fingerprints; differing inputs almost always differ.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* import { redactCredential } from '@lostgradient/backchannel';
|
|
47
|
+
*
|
|
48
|
+
* const masked = redactCredential('weft_key_super_secret_value');
|
|
49
|
+
* console.log(masked.startsWith('<redacted:')); // true
|
|
50
|
+
* console.log(masked.includes('secret')); // false
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export function redactCredential(value) {
|
|
54
|
+
if (value === null || value === undefined || value.length === 0) {
|
|
55
|
+
return EMPTY_REDACTION;
|
|
56
|
+
}
|
|
57
|
+
// Strip a leading `Bearer ` scheme so the fingerprint tracks the token, not
|
|
58
|
+
// the scheme — `Authorization: Bearer X` and `X-API-Key: X` fingerprint alike.
|
|
59
|
+
const token = value.startsWith('Bearer ') ? value.slice('Bearer '.length) : value;
|
|
60
|
+
const fingerprint = fingerprintToken(token);
|
|
61
|
+
return `<redacted:len=${token.length}:fp=${fingerprint}>`;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* FNV-1a 32-bit hash rendered as zero-padded hex. Non-cryptographic and
|
|
65
|
+
* one-way for log-correlation purposes only — never used for authentication.
|
|
66
|
+
*/
|
|
67
|
+
function fingerprintToken(token) {
|
|
68
|
+
let hash = 0x811c9dc5;
|
|
69
|
+
for (let index = 0; index < token.length; index++) {
|
|
70
|
+
hash ^= token.charCodeAt(index);
|
|
71
|
+
// FNV prime multiply, kept in 32-bit unsigned range via Math.imul + >>> 0.
|
|
72
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
73
|
+
}
|
|
74
|
+
return hash.toString(16).padStart(8, '0');
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Produce a plain object snapshot of a request's headers with every sensitive
|
|
78
|
+
* value masked via {@link redactCredential}. Use this when attaching request
|
|
79
|
+
* headers to a log line or audit record — it guarantees no credential header
|
|
80
|
+
* passes through verbatim.
|
|
81
|
+
*
|
|
82
|
+
* Header names are lower-cased (the `Headers` iterator already lower-cases
|
|
83
|
+
* them) so the result is stable regardless of the casing the client sent.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```ts
|
|
87
|
+
* import { redactHeaders } from '@lostgradient/backchannel';
|
|
88
|
+
*
|
|
89
|
+
* const request = new Request('http://localhost/v1/workflows', {
|
|
90
|
+
* headers: { Authorization: 'Bearer secret-token', 'X-Trace-Id': 'abc' },
|
|
91
|
+
* });
|
|
92
|
+
* const safe = redactHeaders(request.headers);
|
|
93
|
+
* console.log(safe['x-trace-id']); // 'abc'
|
|
94
|
+
* console.log(safe['authorization']?.startsWith('<redacted:')); // true
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
export function redactHeaders(headers) {
|
|
98
|
+
const snapshot = {};
|
|
99
|
+
for (const [name, value] of headers) {
|
|
100
|
+
snapshot[name] = SENSITIVE_HEADER_NAMES.has(name) ? redactCredential(value) : value;
|
|
101
|
+
}
|
|
102
|
+
return snapshot;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Whether a header name is treated as credential-bearing and therefore masked
|
|
106
|
+
* by {@link redactHeaders}. Comparison is case-insensitive.
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* ```ts
|
|
110
|
+
* import { isSensitiveHeader } from '@lostgradient/backchannel';
|
|
111
|
+
*
|
|
112
|
+
* console.log(isSensitiveHeader('Authorization')); // true
|
|
113
|
+
* console.log(isSensitiveHeader('X-Trace-Id')); // false
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
export function isSensitiveHeader(name) {
|
|
117
|
+
return SENSITIVE_HEADER_NAMES.has(name.toLowerCase());
|
|
118
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rotatable API-key store with overlapping-validity windows.
|
|
3
|
+
*
|
|
4
|
+
* Static `apiKeys` are fixed for the lifetime of a `serve()` call — rotating
|
|
5
|
+
* them means a config change and a restart, which forces downtime or a
|
|
6
|
+
* flag-day cutover. This store closes that gap: it is a mutable, in-process key
|
|
7
|
+
* registry that the authenticator consults on every request through the
|
|
8
|
+
* existing `resolveApiKeyPrincipal` hook, so an operator can introduce a new
|
|
9
|
+
* key, let it run alongside the old one, and revoke the old key — all without
|
|
10
|
+
* restarting the server.
|
|
11
|
+
*
|
|
12
|
+
* Overlapping validity is the core rotation primitive: add the replacement key
|
|
13
|
+
* (clients begin presenting it), keep the outgoing key valid until traffic has
|
|
14
|
+
* migrated, then revoke the outgoing key. During the overlap window both keys
|
|
15
|
+
* authenticate. Each key may also carry an absolute `expiresAt`, after which it
|
|
16
|
+
* is rejected automatically without an explicit revoke.
|
|
17
|
+
*
|
|
18
|
+
* Registration hashes stored keys to fixed-length digests once. Authentication
|
|
19
|
+
* lookups hash the presented key, then compare it with every stored digest
|
|
20
|
+
* without early exit. The digest step avoids raw length checks, and scanning
|
|
21
|
+
* every digest avoids key-position leaks during the overlap window.
|
|
22
|
+
*
|
|
23
|
+
* Hashing is asynchronous, so every method returns a promise. The store runs
|
|
24
|
+
* its calls one at a time, in call order, so a call behaves as if the calls
|
|
25
|
+
* before it had finished: a key revoked after an `add` is never admitted, and
|
|
26
|
+
* `size` counts only the calls that have completed.
|
|
27
|
+
*
|
|
28
|
+
* @module server/authentication/rotating-api-key-store
|
|
29
|
+
*/
|
|
30
|
+
import type { AuthorizationScope } from "../authorization-scope.js";
|
|
31
|
+
import { type AuthenticatedPrincipal } from "../principal.js";
|
|
32
|
+
/**
|
|
33
|
+
* Registration options for a single key in a {@link RotatingApiKeyStore}.
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```ts
|
|
37
|
+
* import { type ApiKeyRegistration } from '@lostgradient/backchannel';
|
|
38
|
+
*
|
|
39
|
+
* const registration: ApiKeyRegistration = {
|
|
40
|
+
* subject: 'service-account-7',
|
|
41
|
+
* scopes: ['inventory:read', 'inventory:write'],
|
|
42
|
+
* expiresAt: Date.now() + 86_400_000,
|
|
43
|
+
* };
|
|
44
|
+
* void registration;
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
export type ApiKeyRegistration = {
|
|
48
|
+
/** Principal subject minted for callers presenting this key. */
|
|
49
|
+
subject: string;
|
|
50
|
+
/** Authorization scopes granted to this key's principal. Defaults to `[]`. */
|
|
51
|
+
scopes?: ReadonlyArray<AuthorizationScope>;
|
|
52
|
+
/**
|
|
53
|
+
* Absolute expiry timestamp (epoch ms). After this instant the key is
|
|
54
|
+
* rejected automatically. Omit for a key with no scheduled expiry.
|
|
55
|
+
*/
|
|
56
|
+
expiresAt?: number;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* A mutable, rotatable API-key registry. Wire it into authentication by passing
|
|
60
|
+
* its {@link RotatingApiKeyStore.resolve} method as `resolveApiKeyPrincipal`.
|
|
61
|
+
* Mutate the live set with {@link RotatingApiKeyStore.add} and
|
|
62
|
+
* {@link RotatingApiKeyStore.revoke} to rotate keys without restarting.
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```ts
|
|
66
|
+
* import { createRotatingApiKeyStore, type RotatingApiKeyStore } from '@lostgradient/backchannel';
|
|
67
|
+
*
|
|
68
|
+
* const store: RotatingApiKeyStore = createRotatingApiKeyStore();
|
|
69
|
+
* await store.add('key-old', { subject: 'svc', scopes: ['inventory:read'] });
|
|
70
|
+
* await store.add('key-new', { subject: 'svc', scopes: ['inventory:read'] });
|
|
71
|
+
* // Both authenticate during the overlap window.
|
|
72
|
+
* await store.revoke('key-old');
|
|
73
|
+
* ```
|
|
74
|
+
*/
|
|
75
|
+
export interface ApiKeyStore {
|
|
76
|
+
/**
|
|
77
|
+
* Register or replace a key. Replacing an existing key updates its
|
|
78
|
+
* registration in place. Rejects an empty key by throwing synchronously,
|
|
79
|
+
* before it returns a promise. The promise settles once the key is
|
|
80
|
+
* registered.
|
|
81
|
+
*/
|
|
82
|
+
add(key: string, registration: ApiKeyRegistration): Promise<void>;
|
|
83
|
+
/** Remove a key. Resolves to `true` if the key was present. */
|
|
84
|
+
revoke(key: string): Promise<boolean>;
|
|
85
|
+
/** Whether `key` is currently registered and not expired (evaluated against `now()`). */
|
|
86
|
+
has(key: string): Promise<boolean>;
|
|
87
|
+
/** Number of registered keys after pending changes settle. */
|
|
88
|
+
count(): Promise<number>;
|
|
89
|
+
/**
|
|
90
|
+
* Resolve a presented key to a principal, or `null` when the key is unknown,
|
|
91
|
+
* revoked, or expired. Shaped to drop directly into
|
|
92
|
+
* `AuthConfig.resolveApiKeyPrincipal`.
|
|
93
|
+
*/
|
|
94
|
+
resolve(presentedKey: string): Promise<AuthenticatedPrincipal | null>;
|
|
95
|
+
}
|
|
96
|
+
/** In-memory {@link ApiKeyStore} with synchronous inspection of committed registrations. */
|
|
97
|
+
export type RotatingApiKeyStore = ApiKeyStore & {
|
|
98
|
+
/**
|
|
99
|
+
* Number of currently-registered keys (including not-yet-expired ones),
|
|
100
|
+
* counting only the calls that have completed.
|
|
101
|
+
*/
|
|
102
|
+
readonly size: number;
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* Create an empty {@link RotatingApiKeyStore}. The optional `now` clock is for
|
|
106
|
+
* deterministic testing of expiry; production callers omit it and the store
|
|
107
|
+
* reads `Date.now()`.
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* ```ts
|
|
111
|
+
* import { createRotatingApiKeyStore } from '@lostgradient/backchannel';
|
|
112
|
+
* import { serve } from '@lostgradient/weft';
|
|
113
|
+
* import { Engine } from '@lostgradient/weft';
|
|
114
|
+
* import { MemoryStorage } from '@lostgradient/storage';
|
|
115
|
+
*
|
|
116
|
+
* const store = createRotatingApiKeyStore();
|
|
117
|
+
* await store.add('initial-key', { subject: 'svc', scopes: ['inventory:read'] });
|
|
118
|
+
*
|
|
119
|
+
* await using engine = new Engine({ storage: new MemoryStorage() });
|
|
120
|
+
* await using server = serve({
|
|
121
|
+
* engine,
|
|
122
|
+
* auth: { resolveApiKeyPrincipal: store.resolve },
|
|
123
|
+
* });
|
|
124
|
+
* void server;
|
|
125
|
+
* ```
|
|
126
|
+
*/
|
|
127
|
+
export declare function createRotatingApiKeyStore(now?: () => number): RotatingApiKeyStore;
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rotatable API-key store with overlapping-validity windows.
|
|
3
|
+
*
|
|
4
|
+
* Static `apiKeys` are fixed for the lifetime of a `serve()` call — rotating
|
|
5
|
+
* them means a config change and a restart, which forces downtime or a
|
|
6
|
+
* flag-day cutover. This store closes that gap: it is a mutable, in-process key
|
|
7
|
+
* registry that the authenticator consults on every request through the
|
|
8
|
+
* existing `resolveApiKeyPrincipal` hook, so an operator can introduce a new
|
|
9
|
+
* key, let it run alongside the old one, and revoke the old key — all without
|
|
10
|
+
* restarting the server.
|
|
11
|
+
*
|
|
12
|
+
* Overlapping validity is the core rotation primitive: add the replacement key
|
|
13
|
+
* (clients begin presenting it), keep the outgoing key valid until traffic has
|
|
14
|
+
* migrated, then revoke the outgoing key. During the overlap window both keys
|
|
15
|
+
* authenticate. Each key may also carry an absolute `expiresAt`, after which it
|
|
16
|
+
* is rejected automatically without an explicit revoke.
|
|
17
|
+
*
|
|
18
|
+
* Registration hashes stored keys to fixed-length digests once. Authentication
|
|
19
|
+
* lookups hash the presented key, then compare it with every stored digest
|
|
20
|
+
* without early exit. The digest step avoids raw length checks, and scanning
|
|
21
|
+
* every digest avoids key-position leaks during the overlap window.
|
|
22
|
+
*
|
|
23
|
+
* Hashing is asynchronous, so every method returns a promise. The store runs
|
|
24
|
+
* its calls one at a time, in call order, so a call behaves as if the calls
|
|
25
|
+
* before it had finished: a key revoked after an `add` is never admitted, and
|
|
26
|
+
* `size` counts only the calls that have completed.
|
|
27
|
+
*
|
|
28
|
+
* @module server/authentication/rotating-api-key-store
|
|
29
|
+
*/
|
|
30
|
+
import { createConstantTimeApiKeyEntry, findConstantTimeApiKeyMatch, } from '@lostgradient/credentials/api-key-verification';
|
|
31
|
+
import { principalFromApiKey } from "../principal.js";
|
|
32
|
+
/** Whether a stored key has passed its absolute expiry as of `currentTime`. */
|
|
33
|
+
function isExpired(stored, currentTime) {
|
|
34
|
+
return stored.expiresAt !== undefined && currentTime >= stored.expiresAt;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Create an empty {@link RotatingApiKeyStore}. The optional `now` clock is for
|
|
38
|
+
* deterministic testing of expiry; production callers omit it and the store
|
|
39
|
+
* reads `Date.now()`.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```ts
|
|
43
|
+
* import { createRotatingApiKeyStore } from '@lostgradient/backchannel';
|
|
44
|
+
* import { serve } from '@lostgradient/weft';
|
|
45
|
+
* import { Engine } from '@lostgradient/weft';
|
|
46
|
+
* import { MemoryStorage } from '@lostgradient/storage';
|
|
47
|
+
*
|
|
48
|
+
* const store = createRotatingApiKeyStore();
|
|
49
|
+
* await store.add('initial-key', { subject: 'svc', scopes: ['inventory:read'] });
|
|
50
|
+
*
|
|
51
|
+
* await using engine = new Engine({ storage: new MemoryStorage() });
|
|
52
|
+
* await using server = serve({
|
|
53
|
+
* engine,
|
|
54
|
+
* auth: { resolveApiKeyPrincipal: store.resolve },
|
|
55
|
+
* });
|
|
56
|
+
* void server;
|
|
57
|
+
* ```
|
|
58
|
+
*/
|
|
59
|
+
export function createRotatingApiKeyStore(now = Date.now) {
|
|
60
|
+
const keys = new Map();
|
|
61
|
+
// Every call joins this chain, so each one runs to completion before the next
|
|
62
|
+
// begins, in call order. A call that fails settles its own promise and leaves
|
|
63
|
+
// the chain usable.
|
|
64
|
+
let tail = Promise.resolve();
|
|
65
|
+
function enqueue(task) {
|
|
66
|
+
const result = tail.then(task);
|
|
67
|
+
tail = result.then(() => undefined, () => undefined);
|
|
68
|
+
return result;
|
|
69
|
+
}
|
|
70
|
+
async function findStoredKey(presentedKey) {
|
|
71
|
+
const match = await findConstantTimeApiKeyMatch(presentedKey, [...keys.values()]);
|
|
72
|
+
return match?.value ?? null;
|
|
73
|
+
}
|
|
74
|
+
// The methods close over `keys` and `tail` directly (not `this`), so they stay
|
|
75
|
+
// correct when detached and passed as `AuthConfig.resolveApiKeyPrincipal`.
|
|
76
|
+
const store = {
|
|
77
|
+
add(key, registration) {
|
|
78
|
+
if (key.length === 0) {
|
|
79
|
+
throw new Error('Cannot register an empty API key');
|
|
80
|
+
}
|
|
81
|
+
// Snapshot the caller's registration now: the call runs later.
|
|
82
|
+
const stored = {
|
|
83
|
+
subject: registration.subject,
|
|
84
|
+
scopes: [...(registration.scopes ?? [])],
|
|
85
|
+
expiresAt: registration.expiresAt,
|
|
86
|
+
};
|
|
87
|
+
return enqueue(async () => {
|
|
88
|
+
keys.set(key, await createConstantTimeApiKeyEntry(key, { key, stored }));
|
|
89
|
+
});
|
|
90
|
+
},
|
|
91
|
+
revoke(key) {
|
|
92
|
+
return enqueue(() => keys.delete(key));
|
|
93
|
+
},
|
|
94
|
+
has(key) {
|
|
95
|
+
return enqueue(async () => {
|
|
96
|
+
const match = await findStoredKey(key);
|
|
97
|
+
if (match === null)
|
|
98
|
+
return false;
|
|
99
|
+
if (isExpired(match.stored, now())) {
|
|
100
|
+
// Lazily drop expired entries so the map does not accumulate them.
|
|
101
|
+
keys.delete(match.key);
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
return true;
|
|
105
|
+
});
|
|
106
|
+
},
|
|
107
|
+
count() {
|
|
108
|
+
return enqueue(() => keys.size);
|
|
109
|
+
},
|
|
110
|
+
get size() {
|
|
111
|
+
return keys.size;
|
|
112
|
+
},
|
|
113
|
+
resolve(presentedKey) {
|
|
114
|
+
return enqueue(async () => {
|
|
115
|
+
const match = await findStoredKey(presentedKey);
|
|
116
|
+
if (match === null || isExpired(match.stored, now())) {
|
|
117
|
+
if (match !== null)
|
|
118
|
+
keys.delete(match.key);
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
return principalFromApiKey({ subject: match.stored.subject, scopes: match.stored.scopes });
|
|
122
|
+
});
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
return store;
|
|
126
|
+
}
|