@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,337 @@
|
|
|
1
|
+
import type { AuthorizationScope } from "../authorization-scope.js";
|
|
2
|
+
import type { AuthenticatedPrincipal } from "../principal.js";
|
|
3
|
+
import type { AuthAuditSink } from "./audit.js";
|
|
4
|
+
import type { CredentialVerifier } from "./credential-verifiers.js";
|
|
5
|
+
type HMACAlgorithm = 'HS256' | 'HS384' | 'HS512';
|
|
6
|
+
type RSAAlgorithm = 'RS256' | 'RS384' | 'RS512';
|
|
7
|
+
type ECDSAAlgorithm = 'ES256' | 'ES384' | 'ES512';
|
|
8
|
+
/**
|
|
9
|
+
* JWT signing algorithm supported by {@link JWTConfig}.
|
|
10
|
+
*
|
|
11
|
+
* HMAC variants (`HS256`, `HS384`, `HS512`) use a shared secret; RSA variants
|
|
12
|
+
* (`RS256`, `RS384`, `RS512`) and ECDSA variants (`ES256`, `ES384`, `ES512`) use
|
|
13
|
+
* asymmetric keys configured via `publicKey` in the {@link JWTConfig}.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* import { type JWTAlgorithm, type JWTConfig } from '@lostgradient/backchannel';
|
|
18
|
+
*
|
|
19
|
+
* const algorithm: JWTAlgorithm = 'RS256';
|
|
20
|
+
* const config: JWTConfig = {
|
|
21
|
+
* algorithm,
|
|
22
|
+
* publicKey: '-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----',
|
|
23
|
+
* issuer: 'https://auth.example.com',
|
|
24
|
+
* };
|
|
25
|
+
* void config;
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export type JWTAlgorithm = HMACAlgorithm | RSAAlgorithm | ECDSAAlgorithm;
|
|
29
|
+
/**
|
|
30
|
+
* Configuration for JWT signature verification in the Weft HTTP server.
|
|
31
|
+
*
|
|
32
|
+
* Supply either `secret` (for HMAC algorithms) or `publicKey` (for RSA/ECDSA).
|
|
33
|
+
* Optional `issuer`, `audience`, and `clockTolerance` fields guard against
|
|
34
|
+
* token reuse and clock-skew rejection.
|
|
35
|
+
*
|
|
36
|
+
* @example
|
|
37
|
+
* ```ts
|
|
38
|
+
* import { type JWTConfig } from '@lostgradient/backchannel';
|
|
39
|
+
*
|
|
40
|
+
* const jwtConfig: JWTConfig = {
|
|
41
|
+
* secret: process.env['JWT_SECRET'] ?? '',
|
|
42
|
+
* algorithm: 'HS256',
|
|
43
|
+
* issuer: 'https://auth.example.com',
|
|
44
|
+
* audience: 'weft-api',
|
|
45
|
+
* clockTolerance: 30,
|
|
46
|
+
* };
|
|
47
|
+
* void jwtConfig;
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export type JWTConfig = {
|
|
51
|
+
/** HMAC secret for HS256/HS384/HS512 algorithms. */
|
|
52
|
+
secret?: string;
|
|
53
|
+
/** PEM-encoded public key for RS* or ES* algorithms. */
|
|
54
|
+
publicKey?: string;
|
|
55
|
+
/** Signing algorithm (default: HS256). */
|
|
56
|
+
algorithm?: JWTAlgorithm;
|
|
57
|
+
/** Expected `iss` claim. Rejected if present and mismatched. */
|
|
58
|
+
issuer?: string;
|
|
59
|
+
/** Expected `aud` claim. Rejected if present and mismatched. */
|
|
60
|
+
audience?: string;
|
|
61
|
+
/** Seconds of clock skew tolerance for `exp` and `nbf` checks (default: 60). */
|
|
62
|
+
clockTolerance?: number;
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Mutual TLS configuration passed through to `Bun.serve`'s `tls` option.
|
|
66
|
+
*
|
|
67
|
+
* When present in an {@link AuthConfig}, `serve()` builds a TLS listener that
|
|
68
|
+
* requests a client certificate signed by the configured CA. Bun's fetch
|
|
69
|
+
* handler cannot see the peer certificate, so the authenticator reports
|
|
70
|
+
* `method: 'mtls'` only on positive evidence that one was verified: either
|
|
71
|
+
* `verifyClientCertificate` returns `true`, or `serve()` itself built a
|
|
72
|
+
* listener that refuses unverified clients (`rejectUnauthorized` left `true`).
|
|
73
|
+
* With `rejectUnauthorized: false`, or when TLS terminates outside `serve()`,
|
|
74
|
+
* certificate-less requests are rejected unless `verifyClientCertificate`
|
|
75
|
+
* confirms a verified certificate.
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* ```ts
|
|
79
|
+
* import { type MTLSConfig } from '@lostgradient/backchannel';
|
|
80
|
+
* import { readFileSync } from 'node:fs';
|
|
81
|
+
*
|
|
82
|
+
* const mtlsConfig: MTLSConfig = {
|
|
83
|
+
* ca: readFileSync('./certs/ca.pem', 'utf8'),
|
|
84
|
+
* cert: readFileSync('./certs/server.crt', 'utf8'),
|
|
85
|
+
* key: readFileSync('./certs/server.key', 'utf8'),
|
|
86
|
+
* rejectUnauthorized: true,
|
|
87
|
+
* };
|
|
88
|
+
* void mtlsConfig;
|
|
89
|
+
* ```
|
|
90
|
+
*/
|
|
91
|
+
export type MTLSConfig = {
|
|
92
|
+
/** PEM-encoded CA certificate(s) for client certificate verification. */
|
|
93
|
+
ca: string | string[];
|
|
94
|
+
/** PEM-encoded server certificate. */
|
|
95
|
+
cert: string;
|
|
96
|
+
/** PEM-encoded server private key. */
|
|
97
|
+
key: string;
|
|
98
|
+
/**
|
|
99
|
+
* Reject connections without a valid client certificate (default: true).
|
|
100
|
+
* Setting `false` stops the listener from vouching for client certificates,
|
|
101
|
+
* so mTLS admits a request only when `verifyClientCertificate` returns `true`.
|
|
102
|
+
*/
|
|
103
|
+
rejectUnauthorized?: boolean;
|
|
104
|
+
/**
|
|
105
|
+
* Host-supplied evidence that the request arrived with a verified client
|
|
106
|
+
* certificate — for example, by checking the verification header a
|
|
107
|
+
* TLS-terminating proxy sets. When present, its answer alone decides mTLS
|
|
108
|
+
* admission; a throw counts as unverified. Required for mTLS to admit anyone
|
|
109
|
+
* when `rejectUnauthorized` is `false` or TLS terminates outside `serve()`.
|
|
110
|
+
*/
|
|
111
|
+
verifyClientCertificate?: (request: Request) => boolean | Promise<boolean>;
|
|
112
|
+
};
|
|
113
|
+
/**
|
|
114
|
+
* Top-level authentication configuration for {@link serve}.
|
|
115
|
+
*
|
|
116
|
+
* At least one of `apiKeys`, `resolveApiKeyPrincipal`, `jwt`, or `mtls` must be
|
|
117
|
+
* present — the server rejects the config at startup otherwise. Paths listed in
|
|
118
|
+
* `publicPaths` bypass all authentication (default: health, metrics, and
|
|
119
|
+
* discovery document endpoints).
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```ts
|
|
123
|
+
* import { type AuthConfig } from '@lostgradient/backchannel';
|
|
124
|
+
*
|
|
125
|
+
* const auth: AuthConfig = {
|
|
126
|
+
* apiKeys: [process.env['API_KEY'] ?? ''],
|
|
127
|
+
* defaultApiKeyScopes: ['inventory:read'],
|
|
128
|
+
* jwt: {
|
|
129
|
+
* secret: process.env['JWT_SECRET'] ?? '',
|
|
130
|
+
* issuer: 'https://auth.example.com',
|
|
131
|
+
* },
|
|
132
|
+
* publicPaths: ['/v1/health', '/openapi.json'],
|
|
133
|
+
* };
|
|
134
|
+
* void auth;
|
|
135
|
+
* ```
|
|
136
|
+
*/
|
|
137
|
+
export type AuthConfig = {
|
|
138
|
+
/** Ordered verifiers to use in place of the legacy API-key, JWT and mTLS admission checks. */
|
|
139
|
+
verifiers?: readonly CredentialVerifier[];
|
|
140
|
+
/** Allowed API keys. Checked against `Authorization: Bearer <key>` and `X-API-Key` headers. */
|
|
141
|
+
apiKeys?: string[];
|
|
142
|
+
/** JWT verification configuration. */
|
|
143
|
+
jwt?: JWTConfig;
|
|
144
|
+
/** Mutual TLS configuration. Passed through to Bun.serve's `tls` option. */
|
|
145
|
+
mtls?: MTLSConfig;
|
|
146
|
+
/**
|
|
147
|
+
* Paths that bypass authentication. Defaults to
|
|
148
|
+
* `['/v1/health', '/v1/metrics', '/.well-known/api-catalog', '/.well-known/mcp.json', '/openapi.json', '/openrpc.json', '/asyncapi.json']`.
|
|
149
|
+
*/
|
|
150
|
+
publicPaths?: string[];
|
|
151
|
+
/**
|
|
152
|
+
* Optional resolver that maps a presented API key to a fully-shaped
|
|
153
|
+
* `AuthenticatedPrincipal`. When configured, the resolver is
|
|
154
|
+
* authoritative for the entire API-key space:
|
|
155
|
+
* - returns a principal → admitted with that principal entirely
|
|
156
|
+
* (scopes authoritative; `defaultApiKeyScopes` IGNORED). Its scopes
|
|
157
|
+
* are still narrowed to the handler's vocabulary: built-in scopes and
|
|
158
|
+
* the package scopes listed in `additionalScopes`. Any other scope is
|
|
159
|
+
* dropped, as it would be from a JWT claim.
|
|
160
|
+
* - returns `null` → key rejected; static `apiKeys` is NOT
|
|
161
|
+
* consulted as a fallback.
|
|
162
|
+
* - throws → treated as `null` (rejected); server log records the
|
|
163
|
+
* throw detail, wire error stays generic.
|
|
164
|
+
* When not configured, static `apiKeys` admits and the admitted
|
|
165
|
+
* principal's scopes come from `defaultApiKeyScopes`, which `serve()`
|
|
166
|
+
* requires to be non-empty whenever `apiKeys` is.
|
|
167
|
+
*/
|
|
168
|
+
resolveApiKeyPrincipal?: (key: string) => Promise<AuthenticatedPrincipal | null>;
|
|
169
|
+
/**
|
|
170
|
+
* Scopes granted to principals admitted via static `apiKeys`. Ignored
|
|
171
|
+
* when `resolveApiKeyPrincipal` is configured (the resolver's scopes
|
|
172
|
+
* are authoritative for keys it admits). `serve()` throws before binding
|
|
173
|
+
* when `apiKeys` is non-empty and neither this nor `resolveApiKeyPrincipal`
|
|
174
|
+
* grants a scope: every catalog operation except `weft.system.principal`
|
|
175
|
+
* requires one. A package scope is granted only when the handler lists it
|
|
176
|
+
* in `additionalScopes`; an unlisted one is dropped, as it would be from a
|
|
177
|
+
* JWT claim.
|
|
178
|
+
*/
|
|
179
|
+
defaultApiKeyScopes?: ReadonlyArray<AuthorizationScope>;
|
|
180
|
+
/**
|
|
181
|
+
* Sink for the authentication audit trail. The authenticator emits one
|
|
182
|
+
* structured {@link AuthAuditSink} event per non-public decision (admission
|
|
183
|
+
* or rejection), carrying the authenticated subject, method, and outcome —
|
|
184
|
+
* never the presented credential. Public-path bypasses are not audited.
|
|
185
|
+
* Defaults to a sink that writes one JSON line per event to the console
|
|
186
|
+
* (`console.info` for success, `console.warn` for failure). Set to a custom
|
|
187
|
+
* sink to forward audit records to a SIEM, or to a no-op to disable auditing.
|
|
188
|
+
*/
|
|
189
|
+
auditSink?: AuthAuditSink;
|
|
190
|
+
};
|
|
191
|
+
/**
|
|
192
|
+
* Which authentication path admitted a request.
|
|
193
|
+
*
|
|
194
|
+
* Returned inside an {@link AuthResult} when `authenticated: true`. Use this
|
|
195
|
+
* to distinguish bearer-token callers from mTLS-authenticated services or to
|
|
196
|
+
* log the admission method alongside the request trace. `'unauthenticated-local'`
|
|
197
|
+
* is never returned by an authenticator: `serve()` with no authentication
|
|
198
|
+
* attaches it to every request's {@link AuthContext}, with a principal that
|
|
199
|
+
* holds every built-in scope.
|
|
200
|
+
*
|
|
201
|
+
* @example
|
|
202
|
+
* ```ts
|
|
203
|
+
* import { createAuthenticator, type AuthMethod } from '@lostgradient/backchannel';
|
|
204
|
+
*
|
|
205
|
+
* const authenticate = await createAuthenticator({
|
|
206
|
+
* apiKeys: ['key-1'],
|
|
207
|
+
* defaultApiKeyScopes: ['inventory:read'],
|
|
208
|
+
* });
|
|
209
|
+
* const req = new Request('http://localhost/v1/workflows', {
|
|
210
|
+
* headers: { 'X-API-Key': 'key-1' },
|
|
211
|
+
* });
|
|
212
|
+
* const result = await authenticate(req);
|
|
213
|
+
* if (result.authenticated) {
|
|
214
|
+
* const method = result.method;
|
|
215
|
+
* console.log(method); // 'api-key'
|
|
216
|
+
* }
|
|
217
|
+
* ```
|
|
218
|
+
*/
|
|
219
|
+
export type AuthMethod = 'api-key' | 'jwt' | 'mtls' | 'public' | 'unauthenticated-local';
|
|
220
|
+
/**
|
|
221
|
+
* Shared context carried from the authenticator through the request
|
|
222
|
+
* pipeline. Single source of truth for the `{ method, claims?,
|
|
223
|
+
* principal? }` shape — re-used by `AuthResult`,
|
|
224
|
+
* `HandlerOptions.authContext`, and the handler's internal
|
|
225
|
+
* `AuthenticatedRequestContext`.
|
|
226
|
+
*
|
|
227
|
+
* - `method`: which admission path succeeded.
|
|
228
|
+
* - `claims`: JWT payload when `method === 'jwt'`.
|
|
229
|
+
* - `principal`: fully-shaped principal forwarded from the
|
|
230
|
+
* authenticator (resolver admission, or static API-key admission
|
|
231
|
+
* with `defaultApiKeyScopes`). Downstream pipeline code uses this
|
|
232
|
+
* verbatim; when absent, `authContextToPrincipal` reconstructs a
|
|
233
|
+
* minimal principal from `method` + `claims`. That reconstruction
|
|
234
|
+
* keeps only built-in scopes, so a host that registers package
|
|
235
|
+
* scopes must forward the authenticator's `principal`.
|
|
236
|
+
*/
|
|
237
|
+
export type AuthContext = {
|
|
238
|
+
/** How the caller authenticated. */
|
|
239
|
+
method: AuthMethod | 'browser-session' | 'connector-token';
|
|
240
|
+
/** The verified JWT claims, when the method is `jwt`. */
|
|
241
|
+
claims?: JWTPayload;
|
|
242
|
+
/** The principal the credential resolved to. */
|
|
243
|
+
principal?: AuthenticatedPrincipal;
|
|
244
|
+
};
|
|
245
|
+
/**
|
|
246
|
+
* Discriminated union returned by an {@link Authenticator}.
|
|
247
|
+
*
|
|
248
|
+
* Check `authenticated` first: when `true`, the request was admitted and
|
|
249
|
+
* `method` (plus optional `claims` / `principal`) are populated. When
|
|
250
|
+
* `false`, `error` holds a client-safe rejection message.
|
|
251
|
+
*
|
|
252
|
+
* @example
|
|
253
|
+
* ```ts
|
|
254
|
+
* import { createAuthenticator, type AuthResult } from '@lostgradient/backchannel';
|
|
255
|
+
*
|
|
256
|
+
* const authenticate = await createAuthenticator({
|
|
257
|
+
* apiKeys: ['s3cr3t'],
|
|
258
|
+
* defaultApiKeyScopes: ['inventory:read'],
|
|
259
|
+
* });
|
|
260
|
+
* const req = new Request('http://localhost/v1/workflows');
|
|
261
|
+
* const result: AuthResult = await authenticate(req);
|
|
262
|
+
* if (!result.authenticated) {
|
|
263
|
+
* console.error('Rejected:', result.error);
|
|
264
|
+
* } else {
|
|
265
|
+
* console.log('Admitted via', result.method);
|
|
266
|
+
* }
|
|
267
|
+
* ```
|
|
268
|
+
*/
|
|
269
|
+
export type AuthResult = ({
|
|
270
|
+
authenticated: true;
|
|
271
|
+
} & AuthContext) | {
|
|
272
|
+
authenticated: false;
|
|
273
|
+
error: string;
|
|
274
|
+
};
|
|
275
|
+
/**
|
|
276
|
+
* Decoded JWT claims payload — the JSON object between the JWT header and
|
|
277
|
+
* signature after base64url-decoding.
|
|
278
|
+
*
|
|
279
|
+
* Populated on an {@link AuthResult} when `method === 'jwt'`. Standard claims
|
|
280
|
+
* (`iss`, `sub`, `aud`, `exp`, `nbf`) are validated automatically; any
|
|
281
|
+
* application-specific claims are accessible as `claims['my-claim']`.
|
|
282
|
+
*
|
|
283
|
+
* @example
|
|
284
|
+
* ```ts
|
|
285
|
+
* import { createAuthenticator, type JWTPayload } from '@lostgradient/backchannel';
|
|
286
|
+
*
|
|
287
|
+
* const authenticate = await createAuthenticator({
|
|
288
|
+
* jwt: { secret: 'test-secret' },
|
|
289
|
+
* });
|
|
290
|
+
* const req = new Request('http://localhost/v1/workflows', {
|
|
291
|
+
* headers: { Authorization: 'Bearer <token>' },
|
|
292
|
+
* });
|
|
293
|
+
* const result = await authenticate(req);
|
|
294
|
+
* if (result.authenticated && result.method === 'jwt') {
|
|
295
|
+
* const payload: JWTPayload = result.claims ?? {};
|
|
296
|
+
* console.log(payload['sub']);
|
|
297
|
+
* }
|
|
298
|
+
* ```
|
|
299
|
+
*/
|
|
300
|
+
export type JWTPayload = Record<string, unknown>;
|
|
301
|
+
/**
|
|
302
|
+
* Async function that inspects a `Request` and returns an {@link AuthResult}.
|
|
303
|
+
*
|
|
304
|
+
* Obtain an `Authenticator` by calling `createAuthenticator(config)`. You can
|
|
305
|
+
* also implement this type directly to plug a custom admission strategy into the
|
|
306
|
+
* server handler pipeline.
|
|
307
|
+
*
|
|
308
|
+
* @example
|
|
309
|
+
* ```ts
|
|
310
|
+
* import { createAuthenticator, type Authenticator } from '@lostgradient/backchannel';
|
|
311
|
+
*
|
|
312
|
+
* const authenticate: Authenticator = await createAuthenticator({
|
|
313
|
+
* apiKeys: ['my-key'],
|
|
314
|
+
* defaultApiKeyScopes: ['inventory:read'],
|
|
315
|
+
* });
|
|
316
|
+
*
|
|
317
|
+
* const request = new Request('http://localhost/v1/workflows', {
|
|
318
|
+
* headers: { 'X-API-Key': 'my-key' },
|
|
319
|
+
* });
|
|
320
|
+
* const result = await authenticate(request);
|
|
321
|
+
* console.log(result.authenticated); // true
|
|
322
|
+
* ```
|
|
323
|
+
*/
|
|
324
|
+
export type Authenticator = (request: Request) => Promise<AuthResult>;
|
|
325
|
+
/** Paths the authentication layer answers without a credential by default. */
|
|
326
|
+
export declare const DEFAULT_PUBLIC_PATHS: string[];
|
|
327
|
+
export declare const DEFAULT_CLOCK_TOLERANCE = 60;
|
|
328
|
+
/**
|
|
329
|
+
* Normalize the request pathname for consistent public-path lookup: strip
|
|
330
|
+
* trailing slashes (except bare `/`) so that `/v1/health` and `/v1/health/`
|
|
331
|
+
* resolve to the same key.
|
|
332
|
+
*
|
|
333
|
+
* Used by both the authenticator and the request-gate rate-limiting step so
|
|
334
|
+
* that public-path detection stays consistent across both modules.
|
|
335
|
+
*/
|
|
336
|
+
export declare function normalizeRequestPathname(request: Request): string;
|
|
337
|
+
export {};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Constants
|
|
3
|
+
// ---------------------------------------------------------------------------
|
|
4
|
+
/** Paths the authentication layer answers without a credential by default. */
|
|
5
|
+
export const DEFAULT_PUBLIC_PATHS = [
|
|
6
|
+
'/v1/health',
|
|
7
|
+
'/v1/metrics',
|
|
8
|
+
'/.well-known/api-catalog',
|
|
9
|
+
'/.well-known/mcp.json',
|
|
10
|
+
'/openapi.json',
|
|
11
|
+
'/openrpc.json',
|
|
12
|
+
'/asyncapi.json',
|
|
13
|
+
];
|
|
14
|
+
export const DEFAULT_CLOCK_TOLERANCE = 60;
|
|
15
|
+
/**
|
|
16
|
+
* Normalize the request pathname for consistent public-path lookup: strip
|
|
17
|
+
* trailing slashes (except bare `/`) so that `/v1/health` and `/v1/health/`
|
|
18
|
+
* resolve to the same key.
|
|
19
|
+
*
|
|
20
|
+
* Used by both the authenticator and the request-gate rate-limiting step so
|
|
21
|
+
* that public-path detection stays consistent across both modules.
|
|
22
|
+
*/
|
|
23
|
+
export function normalizeRequestPathname(request) {
|
|
24
|
+
const url = new URL(request.url);
|
|
25
|
+
return url.pathname.length > 1 ? url.pathname.replace(/\/+$/, '') : url.pathname;
|
|
26
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./authentication/index.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./authentication/index.js";
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authorization scope vocabulary — extracted into its own module to avoid a
|
|
3
|
+
* dependency cycle between `principal.ts` and `authorization.ts`.
|
|
4
|
+
*
|
|
5
|
+
* All authorization-scope-related types and runtime helpers live here. Access
|
|
6
|
+
* policies, scope requirements, and the access-check pipeline live in
|
|
7
|
+
* `authorization.ts`.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* A scope another package defines and registers with one handler through
|
|
11
|
+
* `additionalScopes`: a dotted namespace, a colon, and an action, such as
|
|
12
|
+
* `bureau.tasks:read`. The `weft` namespace is reserved. At run time each
|
|
13
|
+
* segment must also match {@link PACKAGE_AUTHORIZATION_SCOPE_PATTERN}.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```ts
|
|
17
|
+
* import { type PackageAuthorizationScope } from '@lostgradient/backchannel';
|
|
18
|
+
*
|
|
19
|
+
* const scope: PackageAuthorizationScope = 'bureau.tasks:read';
|
|
20
|
+
* console.log(scope);
|
|
21
|
+
* ```
|
|
22
|
+
*/
|
|
23
|
+
export type PackageAuthorizationScope = `${string}.${string}:${string}`;
|
|
24
|
+
/** The scopes one host vocabulary and its registered packages can name. */
|
|
25
|
+
export type AuthorizationScope<HostScope extends string = string> = HostScope | PackageAuthorizationScope;
|
|
26
|
+
/** An immutable list of the scopes a host grants to its trusted local principals. */
|
|
27
|
+
export type ScopeVocabulary<HostScope extends string = string> = {
|
|
28
|
+
/** The scopes the host defines directly. */
|
|
29
|
+
readonly scopes: readonly HostScope[];
|
|
30
|
+
/** Returns whether a scope belongs to this host. */
|
|
31
|
+
has(value: string): value is HostScope;
|
|
32
|
+
};
|
|
33
|
+
/** Build a vocabulary from the host's own scope strings. */
|
|
34
|
+
export declare function createScopeVocabulary<const HostScope extends string>(scopes: readonly HostScope[]): ScopeVocabulary<HostScope>;
|
|
35
|
+
export declare const EMPTY_SCOPE_VOCABULARY: ScopeVocabulary;
|
|
36
|
+
/**
|
|
37
|
+
* Run-time shape of a {@link PackageAuthorizationScope}: lowercase segments
|
|
38
|
+
* of letters, digits, `_`, and `-`, each starting with a letter; a namespace
|
|
39
|
+
* and at least one more dot-separated segment; then `:` and an action. Whitespace can
|
|
40
|
+
* never appear, so a registered scope always survives space-delimited JWT
|
|
41
|
+
* `scope` claims intact.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* import { PACKAGE_AUTHORIZATION_SCOPE_PATTERN } from '@lostgradient/backchannel';
|
|
46
|
+
*
|
|
47
|
+
* console.log(PACKAGE_AUTHORIZATION_SCOPE_PATTERN.test('bureau.tasks:read'));
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export declare const PACKAGE_AUTHORIZATION_SCOPE_PATTERN: RegExp;
|
|
51
|
+
/** Whether the host defines this scope in its own vocabulary. */
|
|
52
|
+
export declare function isAuthorizationScope<HostScope extends string>(value: string, vocabulary: ScopeVocabulary<HostScope>): value is HostScope;
|
|
53
|
+
/**
|
|
54
|
+
* Runtime type guard for the shape of a {@link PackageAuthorizationScope}.
|
|
55
|
+
* It checks the shape only; it does not say whether any handler registered
|
|
56
|
+
* the scope, and it accepts the reserved `weft` namespace.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```ts
|
|
60
|
+
* import { isPackageAuthorizationScope } from '@lostgradient/backchannel';
|
|
61
|
+
*
|
|
62
|
+
* console.log(isPackageAuthorizationScope('bureau.tasks:read'));
|
|
63
|
+
* console.log(isPackageAuthorizationScope('inventory:read'));
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
export declare function isPackageAuthorizationScope(value: string): value is PackageAuthorizationScope;
|
|
67
|
+
/**
|
|
68
|
+
* The scopes one handler recognizes beyond the built-in vocabulary. Built by
|
|
69
|
+
* {@link createAdditionalScopeSet}; never shared between handlers.
|
|
70
|
+
*/
|
|
71
|
+
export type AdditionalScopeSet = ReadonlySet<PackageAuthorizationScope>;
|
|
72
|
+
/**
|
|
73
|
+
* Validate a handler's `additionalScopes` option and return the set that
|
|
74
|
+
* handler recognizes. Throws when an entry does not match
|
|
75
|
+
* {@link PACKAGE_AUTHORIZATION_SCOPE_PATTERN} or names the reserved `weft`
|
|
76
|
+
* namespace, so a misregistration fails when the handler is constructed.
|
|
77
|
+
*/
|
|
78
|
+
export declare function createAdditionalScopeSet(additionalScopes: readonly PackageAuthorizationScope[] | undefined): AdditionalScopeSet;
|
|
79
|
+
/**
|
|
80
|
+
* Whether a handler recognizes `value`: a built-in scope, or a package scope
|
|
81
|
+
* that handler registered.
|
|
82
|
+
*/
|
|
83
|
+
export declare function isRecognizedScope(value: string, additionalScopes?: AdditionalScopeSet, vocabulary?: ScopeVocabulary): value is AuthorizationScope;
|
|
84
|
+
/**
|
|
85
|
+
* Keep only the scopes a handler recognizes, dropping unknown and
|
|
86
|
+
* unregistered entries the same way JWT claim parsing does.
|
|
87
|
+
*/
|
|
88
|
+
export declare function filterRecognizedScopes(scopes: ReadonlyArray<AuthorizationScope>, additionalScopes?: AdditionalScopeSet, vocabulary?: ScopeVocabulary): AuthorizationScope[];
|
|
89
|
+
/**
|
|
90
|
+
* Extract the full set of scopes granted by a JWT payload by *merging* every
|
|
91
|
+
* recognized claim source. Real-world tokens commonly carry OIDC scopes (e.g.
|
|
92
|
+
* `openid profile`) in `scope` while application scopes live in `permissions`;
|
|
93
|
+
* a short-circuit on the first present claim would silently drop privileges.
|
|
94
|
+
*
|
|
95
|
+
* Sources merged (all consulted, all unioned):
|
|
96
|
+
* - `scope` — RFC 8693-style space-delimited string
|
|
97
|
+
* - `scp` — alternate space-delimited string used by some IdPs
|
|
98
|
+
* - `permissions` — array of strings
|
|
99
|
+
*
|
|
100
|
+
* Whitespace-only values are treated as absent so they never block fallback to
|
|
101
|
+
* other sources. Unknown scope strings are silently filtered out — the
|
|
102
|
+
* host vocabulary, plus the package scopes the handler
|
|
103
|
+
* registered in `additionalScopes`, is the single source of truth and a
|
|
104
|
+
* misspelled or unregistered scope cannot grant unintended privileges.
|
|
105
|
+
*
|
|
106
|
+
* Credential *validation* (signature verification, expiry, revocation) happens
|
|
107
|
+
* at the transport edge before the claims object reaches this function.
|
|
108
|
+
*/
|
|
109
|
+
export declare function extractScopesFromClaims(claims: Record<string, unknown>, additionalScopes?: AdditionalScopeSet, vocabulary?: ScopeVocabulary): ReadonlySet<AuthorizationScope>;
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authorization scope vocabulary — extracted into its own module to avoid a
|
|
3
|
+
* dependency cycle between `principal.ts` and `authorization.ts`.
|
|
4
|
+
*
|
|
5
|
+
* All authorization-scope-related types and runtime helpers live here. Access
|
|
6
|
+
* policies, scope requirements, and the access-check pipeline live in
|
|
7
|
+
* `authorization.ts`.
|
|
8
|
+
*/
|
|
9
|
+
/** Build a vocabulary from the host's own scope strings. */
|
|
10
|
+
export function createScopeVocabulary(scopes) {
|
|
11
|
+
const names = new Set(scopes);
|
|
12
|
+
return Object.freeze({
|
|
13
|
+
scopes: Object.freeze([...scopes]),
|
|
14
|
+
has(value) {
|
|
15
|
+
return names.has(value);
|
|
16
|
+
},
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
export const EMPTY_SCOPE_VOCABULARY = createScopeVocabulary([]);
|
|
20
|
+
/**
|
|
21
|
+
* Run-time shape of a {@link PackageAuthorizationScope}: lowercase segments
|
|
22
|
+
* of letters, digits, `_`, and `-`, each starting with a letter; a namespace
|
|
23
|
+
* and at least one more dot-separated segment; then `:` and an action. Whitespace can
|
|
24
|
+
* never appear, so a registered scope always survives space-delimited JWT
|
|
25
|
+
* `scope` claims intact.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* import { PACKAGE_AUTHORIZATION_SCOPE_PATTERN } from '@lostgradient/backchannel';
|
|
30
|
+
*
|
|
31
|
+
* console.log(PACKAGE_AUTHORIZATION_SCOPE_PATTERN.test('bureau.tasks:read'));
|
|
32
|
+
* ```
|
|
33
|
+
*/
|
|
34
|
+
export const PACKAGE_AUTHORIZATION_SCOPE_PATTERN = /^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)+:[a-z][a-z0-9_-]*$/;
|
|
35
|
+
/** The namespace no package may register a scope under. */
|
|
36
|
+
const RESERVED_NAMESPACE = 'weft';
|
|
37
|
+
/** Whether the host defines this scope in its own vocabulary. */
|
|
38
|
+
export function isAuthorizationScope(value, vocabulary) {
|
|
39
|
+
return vocabulary.has(value);
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Runtime type guard for the shape of a {@link PackageAuthorizationScope}.
|
|
43
|
+
* It checks the shape only; it does not say whether any handler registered
|
|
44
|
+
* the scope, and it accepts the reserved `weft` namespace.
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```ts
|
|
48
|
+
* import { isPackageAuthorizationScope } from '@lostgradient/backchannel';
|
|
49
|
+
*
|
|
50
|
+
* console.log(isPackageAuthorizationScope('bureau.tasks:read'));
|
|
51
|
+
* console.log(isPackageAuthorizationScope('inventory:read'));
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export function isPackageAuthorizationScope(value) {
|
|
55
|
+
return PACKAGE_AUTHORIZATION_SCOPE_PATTERN.test(value);
|
|
56
|
+
}
|
|
57
|
+
const NO_ADDITIONAL_SCOPES = new Set();
|
|
58
|
+
/**
|
|
59
|
+
* Validate a handler's `additionalScopes` option and return the set that
|
|
60
|
+
* handler recognizes. Throws when an entry does not match
|
|
61
|
+
* {@link PACKAGE_AUTHORIZATION_SCOPE_PATTERN} or names the reserved `weft`
|
|
62
|
+
* namespace, so a misregistration fails when the handler is constructed.
|
|
63
|
+
*/
|
|
64
|
+
export function createAdditionalScopeSet(additionalScopes) {
|
|
65
|
+
if (additionalScopes === undefined || additionalScopes.length === 0)
|
|
66
|
+
return NO_ADDITIONAL_SCOPES;
|
|
67
|
+
const registered = new Set();
|
|
68
|
+
for (const scope of additionalScopes) {
|
|
69
|
+
if (typeof scope !== 'string' || !isPackageAuthorizationScope(scope)) {
|
|
70
|
+
throw new TypeError(`additionalScopes entry ${JSON.stringify(scope)} must look like ` +
|
|
71
|
+
'"<namespace>.<resource>:<action>", for example "bureau.tasks:read"');
|
|
72
|
+
}
|
|
73
|
+
if (scope.slice(0, scope.indexOf('.')) === RESERVED_NAMESPACE) {
|
|
74
|
+
throw new TypeError(`additionalScopes entry "${scope}" uses the reserved "${RESERVED_NAMESPACE}" namespace`);
|
|
75
|
+
}
|
|
76
|
+
registered.add(scope);
|
|
77
|
+
}
|
|
78
|
+
return registered;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Whether a handler recognizes `value`: a built-in scope, or a package scope
|
|
82
|
+
* that handler registered.
|
|
83
|
+
*/
|
|
84
|
+
export function isRecognizedScope(value, additionalScopes = NO_ADDITIONAL_SCOPES, vocabulary = EMPTY_SCOPE_VOCABULARY) {
|
|
85
|
+
return vocabulary.has(value) || additionalScopes.has(value);
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Keep only the scopes a handler recognizes, dropping unknown and
|
|
89
|
+
* unregistered entries the same way JWT claim parsing does.
|
|
90
|
+
*/
|
|
91
|
+
export function filterRecognizedScopes(scopes, additionalScopes = NO_ADDITIONAL_SCOPES, vocabulary = EMPTY_SCOPE_VOCABULARY) {
|
|
92
|
+
return scopes.filter((scope) => isRecognizedScope(scope, additionalScopes, vocabulary));
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Extract the full set of scopes granted by a JWT payload by *merging* every
|
|
96
|
+
* recognized claim source. Real-world tokens commonly carry OIDC scopes (e.g.
|
|
97
|
+
* `openid profile`) in `scope` while application scopes live in `permissions`;
|
|
98
|
+
* a short-circuit on the first present claim would silently drop privileges.
|
|
99
|
+
*
|
|
100
|
+
* Sources merged (all consulted, all unioned):
|
|
101
|
+
* - `scope` — RFC 8693-style space-delimited string
|
|
102
|
+
* - `scp` — alternate space-delimited string used by some IdPs
|
|
103
|
+
* - `permissions` — array of strings
|
|
104
|
+
*
|
|
105
|
+
* Whitespace-only values are treated as absent so they never block fallback to
|
|
106
|
+
* other sources. Unknown scope strings are silently filtered out — the
|
|
107
|
+
* host vocabulary, plus the package scopes the handler
|
|
108
|
+
* registered in `additionalScopes`, is the single source of truth and a
|
|
109
|
+
* misspelled or unregistered scope cannot grant unintended privileges.
|
|
110
|
+
*
|
|
111
|
+
* Credential *validation* (signature verification, expiry, revocation) happens
|
|
112
|
+
* at the transport edge before the claims object reaches this function.
|
|
113
|
+
*/
|
|
114
|
+
export function extractScopesFromClaims(claims, additionalScopes = NO_ADDITIONAL_SCOPES, vocabulary = EMPTY_SCOPE_VOCABULARY) {
|
|
115
|
+
const merged = new Set();
|
|
116
|
+
addStringClaimScopes(claims['scope'], merged, additionalScopes, vocabulary);
|
|
117
|
+
addStringClaimScopes(claims['scp'], merged, additionalScopes, vocabulary);
|
|
118
|
+
const permissions = claims['permissions'];
|
|
119
|
+
if (Array.isArray(permissions)) {
|
|
120
|
+
for (const entry of permissions) {
|
|
121
|
+
if (typeof entry === 'string' && isRecognizedScope(entry, additionalScopes, vocabulary)) {
|
|
122
|
+
merged.add(entry);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return merged;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Add every recognized scope token from a space-delimited claim string into
|
|
130
|
+
* `target`. No-op for non-strings, empty strings, and whitespace-only strings.
|
|
131
|
+
*/
|
|
132
|
+
function addStringClaimScopes(value, target, additionalScopes, vocabulary) {
|
|
133
|
+
if (typeof value !== 'string')
|
|
134
|
+
return;
|
|
135
|
+
if (value.trim().length === 0)
|
|
136
|
+
return;
|
|
137
|
+
for (const token of value.split(/\s+/)) {
|
|
138
|
+
if (token.length === 0)
|
|
139
|
+
continue;
|
|
140
|
+
if (isRecognizedScope(token, additionalScopes, vocabulary)) {
|
|
141
|
+
target.add(token);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport-neutral authorization policy types and the pipeline access check.
|
|
3
|
+
*
|
|
4
|
+
* Hosts the `AccessPolicy` / `ScopeRequirement` discriminated unions and
|
|
5
|
+
* `evaluateAccess`, the function `executeOperation` calls between the
|
|
6
|
+
* authentication step and the operation invocation. The scope vocabulary
|
|
7
|
+
* and JWT claim extraction live in `authorization-scope.ts` — separated to
|
|
8
|
+
* keep `principal.ts` and this file cycle-free. This stable authorization
|
|
9
|
+
* policy model ensures consistent access control across REST and JSON-RPC
|
|
10
|
+
* transports.
|
|
11
|
+
*/
|
|
12
|
+
import { type AuthorizationScope } from "./authorization-scope.js";
|
|
13
|
+
import { type Principal } from "./principal.js";
|
|
14
|
+
/** Non-empty tuple of authorization scopes. Prevents `anyOf([])` / `allOf([])` at the type level. */
|
|
15
|
+
export type ScopeRequirement = {
|
|
16
|
+
kind: 'anyOf';
|
|
17
|
+
scopes: readonly [AuthorizationScope, ...AuthorizationScope[]];
|
|
18
|
+
} | {
|
|
19
|
+
kind: 'allOf';
|
|
20
|
+
scopes: readonly [AuthorizationScope, ...AuthorizationScope[]];
|
|
21
|
+
};
|
|
22
|
+
/** The only representable access policies for an operation. Invalid combinations are unrepresentable. */
|
|
23
|
+
export type AccessPolicy = {
|
|
24
|
+
kind: 'public';
|
|
25
|
+
} | {
|
|
26
|
+
kind: 'authenticated';
|
|
27
|
+
} | {
|
|
28
|
+
kind: 'scoped';
|
|
29
|
+
scopes: ScopeRequirement;
|
|
30
|
+
} | {
|
|
31
|
+
kind: 'scopedAlternatives';
|
|
32
|
+
alternatives: readonly [ScopeRequirement, ...ScopeRequirement[]];
|
|
33
|
+
} | {
|
|
34
|
+
kind: 'optionalAuth';
|
|
35
|
+
authenticatedScopes: ScopeRequirement;
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* Result of a pipeline access check. Denials carry a classification so the
|
|
39
|
+
* caller can emit the correct `Unauthorized` vs `Forbidden` fault.
|
|
40
|
+
*/
|
|
41
|
+
export type AccessCheckResult = {
|
|
42
|
+
allowed: true;
|
|
43
|
+
} | {
|
|
44
|
+
allowed: false;
|
|
45
|
+
classification: 'unauthorized' | 'forbidden';
|
|
46
|
+
reason: string;
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Evaluate an `AccessPolicy` against the caller's principal. This is the
|
|
50
|
+
* pipeline step that translates the declarative policy into a pass/fail
|
|
51
|
+
* decision. Credential *validation* happens at the transport edge, BEFORE
|
|
52
|
+
* this function runs; by the time we're here, the principal shape tells us
|
|
53
|
+
* whether the caller is authenticated.
|
|
54
|
+
*/
|
|
55
|
+
export declare function evaluateAccess(policy: AccessPolicy, principal: Principal): AccessCheckResult;
|