@webpieces/http-routing 0.4.663 → 0.4.664
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/package.json +4 -4
- package/src/AuthConfig.d.ts +4 -2
- package/src/AuthConfig.js +4 -2
- package/src/AuthConfig.js.map +1 -1
- package/src/AuthHooks.d.ts +80 -4
- package/src/AuthHooks.js +49 -3
- package/src/AuthHooks.js.map +1 -1
- package/src/DefaultJwtHook.d.ts +6 -1
- package/src/DefaultJwtHook.js +6 -1
- package/src/DefaultJwtHook.js.map +1 -1
- package/src/JwtHookCompileAssertions.d.ts +22 -0
- package/src/JwtHookCompileAssertions.js +54 -0
- package/src/JwtHookCompileAssertions.js.map +1 -0
- package/src/filters/AuthFilter.d.ts +30 -8
- package/src/filters/AuthFilter.js +67 -16
- package/src/filters/AuthFilter.js.map +1 -1
- package/src/index.d.ts +1 -1
- package/src/index.js +5 -2
- package/src/index.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/http-routing",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.664",
|
|
4
4
|
"description": "Decorator-based routing with auto-wiring for WebPieces",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -22,9 +22,9 @@
|
|
|
22
22
|
},
|
|
23
23
|
"dependencies": {
|
|
24
24
|
"@inversifyjs/binding-decorators": "1.1.5",
|
|
25
|
-
"@webpieces/core-context": "0.4.
|
|
26
|
-
"@webpieces/core-util": "0.4.
|
|
27
|
-
"@webpieces/gcp-identity": "0.4.
|
|
25
|
+
"@webpieces/core-context": "0.4.664",
|
|
26
|
+
"@webpieces/core-util": "0.4.664",
|
|
27
|
+
"@webpieces/gcp-identity": "0.4.664",
|
|
28
28
|
"inversify": "7.10.4",
|
|
29
29
|
"jsonwebtoken": "9.0.2",
|
|
30
30
|
"minimatch": "10.0.1"
|
package/src/AuthConfig.d.ts
CHANGED
|
@@ -15,7 +15,8 @@ export declare class SharedSecrets {
|
|
|
15
15
|
constructor(secret1: string, secret2: string);
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
* AuthValues - what {@link JwtHook.parseJwt}
|
|
18
|
+
* AuthValues - what {@link JwtHook.parseJwt} and {@link ApiKeyHook.verifyApiKey} resolve to (both are
|
|
19
|
+
* async): the authenticated caller's id + roles (used
|
|
19
20
|
* by the framework to stamp a principal and enforce @AuthJwt({roles: [...]})) plus any extra context
|
|
20
21
|
* entries the app wants set (orgId, tenant, ...). The framework sets `entries` into RequestContext
|
|
21
22
|
* via {@link RequestContext.putTrusted}. Data-only structure (a class, per the guidelines).
|
|
@@ -33,7 +34,8 @@ export declare class AuthValues {
|
|
|
33
34
|
* there is no verification code here. The verification MECHANISMS are separate optional hooks the
|
|
34
35
|
* app binds when it needs them:
|
|
35
36
|
*
|
|
36
|
-
* - user JWT → bind a {@link JwtHook} (parseJwt + authorizeJwt).
|
|
37
|
+
* - user JWT → bind a {@link JwtHook} (async parseJwt + async authorizeJwt).
|
|
38
|
+
* - api key → bind an {@link ApiKeyHook} (async verifyApiKey over the request's headers).
|
|
37
39
|
* - OIDC → bind an {@link OidcHook} to override the framework's default verifier; a server that
|
|
38
40
|
* binds nothing still verifies Google OIDC via the built-in {@link DefaultOidcVerifier}.
|
|
39
41
|
*
|
package/src/AuthConfig.js
CHANGED
|
@@ -21,7 +21,8 @@ class SharedSecrets {
|
|
|
21
21
|
}
|
|
22
22
|
exports.SharedSecrets = SharedSecrets;
|
|
23
23
|
/**
|
|
24
|
-
* AuthValues - what {@link JwtHook.parseJwt}
|
|
24
|
+
* AuthValues - what {@link JwtHook.parseJwt} and {@link ApiKeyHook.verifyApiKey} resolve to (both are
|
|
25
|
+
* async): the authenticated caller's id + roles (used
|
|
25
26
|
* by the framework to stamp a principal and enforce @AuthJwt({roles: [...]})) plus any extra context
|
|
26
27
|
* entries the app wants set (orgId, tenant, ...). The framework sets `entries` into RequestContext
|
|
27
28
|
* via {@link RequestContext.putTrusted}. Data-only structure (a class, per the guidelines).
|
|
@@ -47,7 +48,8 @@ exports.AuthValues = AuthValues;
|
|
|
47
48
|
* there is no verification code here. The verification MECHANISMS are separate optional hooks the
|
|
48
49
|
* app binds when it needs them:
|
|
49
50
|
*
|
|
50
|
-
* - user JWT → bind a {@link JwtHook} (parseJwt + authorizeJwt).
|
|
51
|
+
* - user JWT → bind a {@link JwtHook} (async parseJwt + async authorizeJwt).
|
|
52
|
+
* - api key → bind an {@link ApiKeyHook} (async verifyApiKey over the request's headers).
|
|
51
53
|
* - OIDC → bind an {@link OidcHook} to override the framework's default verifier; a server that
|
|
52
54
|
* binds nothing still verifies Google OIDC via the built-in {@link DefaultOidcVerifier}.
|
|
53
55
|
*
|
package/src/AuthConfig.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthConfig.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthConfig.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;GASG;AACH,MAAa,aAAa;IAEF;IACA;IAFpB,YACoB,OAAe,EACf,OAAe;QADf,YAAO,GAAP,OAAO,CAAQ;QACf,YAAO,GAAP,OAAO,CAAQ;IAChC,CAAC;CACP;AALD,sCAKC;AAED
|
|
1
|
+
{"version":3,"file":"AuthConfig.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthConfig.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;GASG;AACH,MAAa,aAAa;IAEF;IACA;IAFpB,YACoB,OAAe,EACf,OAAe;QADf,YAAO,GAAP,OAAO,CAAQ;QACf,YAAO,GAAP,OAAO,CAAQ;IAChC,CAAC;CACP;AALD,sCAKC;AAED;;;;;;GAMG;AACH,MAAa,UAAU;IAEC;IACA;IACA;IAEA;IALpB,YACoB,MAAc,EACd,QAAkB,EAAE,EACpB,UAA0B,EAAE;IAC5C,wGAAwG;IACxF,SAAkC,EAAE;QAJpC,WAAM,GAAN,MAAM,CAAQ;QACd,UAAK,GAAL,KAAK,CAAe;QACpB,YAAO,GAAP,OAAO,CAAqB;QAE5B,WAAM,GAAN,MAAM,CAA8B;IACrD,CAAC;CACP;AARD,gCAQC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAa,UAAU;IACnB,wGAAwG;IAC/F,aAAa,CAAgC;IAEtD,YAAY,gBAA+C,EAAE;QACzD,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACvC,CAAC;CACJ;AAPD,gCAOC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,WAAW,GAAG,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC","sourcesContent":["import { ContextTuple } from '@webpieces/core-util';\n\n/**\n * SharedSecrets - the accepted values for ONE `@AuthSharedSecret(name)`. BOTH secret1 AND secret2\n * are accepted — this is what makes zero-downtime ROTATION possible:\n *\n * to rotate: shift secret2 → secret1, and put the NEW secret in secret2. Callers cut over from\n * the old value to the new during the window; once every caller sends the new one, the stale\n * value falls out on the next shift. At all times EITHER key works, so no request is dropped.\n *\n * Data-only structure (a class, per the guidelines). Leave secret2 empty for a single secret.\n */\nexport class SharedSecrets {\n constructor(\n public readonly secret1: string,\n public readonly secret2: string,\n ) {}\n}\n\n/**\n * AuthValues - what {@link JwtHook.parseJwt} and {@link ApiKeyHook.verifyApiKey} resolve to (both are\n * async): the authenticated caller's id + roles (used\n * by the framework to stamp a principal and enforce @AuthJwt({roles: [...]})) plus any extra context\n * entries the app wants set (orgId, tenant, ...). The framework sets `entries` into RequestContext\n * via {@link RequestContext.putTrusted}. Data-only structure (a class, per the guidelines).\n */\nexport class AuthValues {\n constructor(\n public readonly userId: string,\n public readonly roles: string[] = [],\n public readonly entries: ContextTuple[] = [],\n // webpieces-disable no-any-unknown -- raw JWT claims for app-defined authorization (inOrg, tenant, ...)\n public readonly claims: Record<string, unknown> = {},\n ) {}\n}\n\n/**\n * AuthConfig - the app-provided SHARED-SECRET state the framework {@link AuthFilter} reads to\n * enforce `@AuthSharedSecret(name)` endpoints. It holds ONLY the accepted secret values (STATE) —\n * there is no verification code here. The verification MECHANISMS are separate optional hooks the\n * app binds when it needs them:\n *\n * - user JWT → bind a {@link JwtHook} (async parseJwt + async authorizeJwt).\n * - api key → bind an {@link ApiKeyHook} (async verifyApiKey over the request's headers).\n * - OIDC → bind an {@link OidcHook} to override the framework's default verifier; a server that\n * binds nothing still verifies Google OIDC via the built-in {@link DefaultOidcVerifier}.\n *\n * So a zero-wiring server accepts service-to-service OIDC out of the box, and an app only binds the\n * pieces it actually uses. This class is injected `@optional` into AuthFilter (rebindable in tests);\n * when unbound, shared-secret endpoints simply have no accepted secret and fail fast (401).\n */\nexport class AuthConfig {\n /** Accepted shared-secret values keyed by `@AuthSharedSecret(name)`. DEFAULT empty — pass to enable. */\n readonly sharedSecrets: Record<string, SharedSecrets>;\n\n constructor(sharedSecrets: Record<string, SharedSecrets> = {}) {\n this.sharedSecrets = sharedSecrets;\n }\n}\n\n/**\n * DI identifier for the optional {@link AuthConfig} binding. It is a Symbol (not the class) so the app\n * container's inversify autobind never auto-constructs this token, keeping `@optional() @inject(AUTH_CONFIG)`\n * correct — undefined when unbound. The AuthConfig class stays the TYPE and the impl base.\n */\n// webpieces-disable no-symbol-di-tokens -- optional DI token: must be a Symbol so the app container's autobind never auto-constructs this token, keeping @optional() @inject(...) correct (undefined when unbound)\nexport const AUTH_CONFIG = Symbol.for('AuthConfig');\n"]}
|
package/src/AuthHooks.d.ts
CHANGED
|
@@ -15,15 +15,27 @@ import { AuthValues } from './AuthConfig';
|
|
|
15
15
|
* app-defined requirements carried by the SAME decorator, e.g.
|
|
16
16
|
* `@AuthJwt({allRolesAllowed: true, inOrg: true})` →
|
|
17
17
|
* `if (requirement['inOrg'] && !values.claims['orgId']) ...`.
|
|
18
|
+
*
|
|
19
|
+
* BOTH ARE ASYNC, and both for the same reason: the strategy is the app's, and an app's strategy
|
|
20
|
+
* reaches the network. `parseJwt` may fetch a JWKS or call a provider SDK; `authorizeJwt`'s own
|
|
21
|
+
* motivating example — `@AuthJwt({allRolesAllowed: true, inOrg: true})` — is a membership question a
|
|
22
|
+
* real app answers from a datastore. A sync signature makes both of those unwritable, and it made
|
|
23
|
+
* `JwtHook` the last sync hook: {@link OidcHook.verifyOidc}, {@link WebhookAuthCallback.verify} and
|
|
24
|
+
* {@link ApiKeyHook.verifyApiKey} all return promises. An implementation that needs no I/O simply has
|
|
25
|
+
* no `await` in its body — {@link DefaultJwtHook} is exactly that and pays nothing for it.
|
|
18
26
|
*/
|
|
19
27
|
export declare abstract class JwtHook {
|
|
20
|
-
/**
|
|
21
|
-
|
|
28
|
+
/**
|
|
29
|
+
* Parse a user JWT (kind:'jwt') — AUTHENTICATION only. Return who the user is, or throw.
|
|
30
|
+
* ASYNC so an app can reach a JWKS endpoint or a provider SDK; see the class doc.
|
|
31
|
+
*/
|
|
32
|
+
abstract parseJwt(token: string): Promise<AuthValues>;
|
|
22
33
|
/**
|
|
23
34
|
* DEFAULT authorization: enforce the endpoint's roles (any-of). Override to enforce app-defined
|
|
24
|
-
* requirements. Throw HttpForbiddenError to deny; return to allow.
|
|
35
|
+
* requirements. Throw HttpForbiddenError to deny; return to allow. ASYNC so an app-defined
|
|
36
|
+
* requirement can be answered from a datastore; see the class doc.
|
|
25
37
|
*/
|
|
26
|
-
authorizeJwt(values: AuthValues, requirement: JwtRequirement): void
|
|
38
|
+
authorizeJwt(values: AuthValues, requirement: JwtRequirement): Promise<void>;
|
|
27
39
|
}
|
|
28
40
|
/**
|
|
29
41
|
* DI identifier for the optional {@link JwtHook} binding. It is a Symbol (not the class) so the app
|
|
@@ -90,3 +102,67 @@ export declare abstract class WebhookAuthCallback {
|
|
|
90
102
|
* correct — undefined when unbound. The WebhookAuthCallback class stays the TYPE and the impl base.
|
|
91
103
|
*/
|
|
92
104
|
export declare const WEBHOOK_AUTH_CALLBACK: unique symbol;
|
|
105
|
+
/**
|
|
106
|
+
* HeaderReader - read-only access to the inbound request's headers, and the ONLY thing an
|
|
107
|
+
* {@link ApiKeyHook} is handed besides the regime name.
|
|
108
|
+
*
|
|
109
|
+
* It is an INTERFACE, not a class, because it is behaviour rather than data (per the guidelines) —
|
|
110
|
+
* and it is NARROWER than {@link HttpRequest} on purpose. An api-key hook's job is to read the
|
|
111
|
+
* credential headers and look them up; giving it the whole request would also give it the retained
|
|
112
|
+
* raw bytes and the parsed body, none of which it has any business deciding authentication on.
|
|
113
|
+
* `HttpRequest` satisfies this structurally, so the framework passes the live request and a spec can
|
|
114
|
+
* pass a two-line stub.
|
|
115
|
+
*/
|
|
116
|
+
export interface HeaderReader {
|
|
117
|
+
/** First value of the header, by lowercased name, or undefined when absent. */
|
|
118
|
+
getHeader(name: string): string | undefined;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* ApiKeyHook - the OPTIONAL mechanism behind `@AuthApiKey(name)`: authenticate a CUSTOMER-held api key
|
|
122
|
+
* against the app's own datastore and return the context to seed. Its DI token is the
|
|
123
|
+
* {@link API_KEY_HOOK} Symbol injected via `@inject(API_KEY_HOOK)` (a Symbol, because the app container
|
|
124
|
+
* uses autobind; rebindable in tests). The fourth hook, symmetric with {@link JwtHook} /
|
|
125
|
+
* {@link OidcHook} / {@link WebhookAuthCallback}:
|
|
126
|
+
*
|
|
127
|
+
* ```typescript
|
|
128
|
+
* // AppModule.ts, beside the CompanyJwtHook binding
|
|
129
|
+
* options.bind(API_KEY_HOOK).to(OneTabletApiKeyHook);
|
|
130
|
+
* ```
|
|
131
|
+
*
|
|
132
|
+
* When NO ApiKeyHook is bound, the framework {@link AuthFilter} 401s every `@AuthApiKey` endpoint,
|
|
133
|
+
* exactly as it does for an unbound JwtHook. There is no framework default and there never will be
|
|
134
|
+
* one: the key regime lives in the app's datastore, under the app's hashing scheme, behind the app's
|
|
135
|
+
* choice of header names.
|
|
136
|
+
*
|
|
137
|
+
* THE ONE THING THIS HAS THAT `JwtHook.parseJwt` DOES NOT: it receives a {@link HeaderReader}, not one
|
|
138
|
+
* pre-extracted token. A real key regime validates the key TOGETHER WITH a second header — the
|
|
139
|
+
* organization the caller is acting for — and a hook handed one header's value physically cannot do
|
|
140
|
+
* that cross-check. The framework therefore configures no api-key header name: which headers carry the
|
|
141
|
+
* credential is the app's business. (Being ASYNC is no longer a difference — every hook here is, and
|
|
142
|
+
* for the same reason: an app's strategy reaches the network.)
|
|
143
|
+
*
|
|
144
|
+
* ONE hook serves EVERY regime: `name` selects which, so a server with a partner-api regime and an
|
|
145
|
+
* internal-tooling regime switches on it rather than binding a token per regime.
|
|
146
|
+
*/
|
|
147
|
+
export declare abstract class ApiKeyHook {
|
|
148
|
+
/**
|
|
149
|
+
* AUTHENTICATE one inbound request. Return who the caller is plus the {@link AuthValues.entries}
|
|
150
|
+
* the framework seeds into `RequestContext` via `putTrusted`, or throw
|
|
151
|
+
* {@link HttpUnauthorizedError} to deny.
|
|
152
|
+
*
|
|
153
|
+
* NOTE the seeded entries are TRUSTED context keys, so return only what THIS hook proved from the
|
|
154
|
+
* credential it just verified. Anything the caller merely asserted on the wire is not admitted by
|
|
155
|
+
* `@AuthApiKey` — the mode is deliberately caller-NOT-verified (see `AuthFilter.verifiesCaller`),
|
|
156
|
+
* because a customer is not an internal service.
|
|
157
|
+
*
|
|
158
|
+
* @param name the string on the contract's `@AuthApiKey(name)` — which key regime this route is.
|
|
159
|
+
* @param headers the inbound request's headers; read as many as the regime needs.
|
|
160
|
+
*/
|
|
161
|
+
abstract verifyApiKey(name: string, headers: HeaderReader): Promise<AuthValues>;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* DI identifier for the optional {@link ApiKeyHook} binding. It is a Symbol (not the class) so the app
|
|
165
|
+
* container's inversify autobind never auto-constructs this token, keeping `@optional() @inject(API_KEY_HOOK)`
|
|
166
|
+
* correct — undefined when unbound. The ApiKeyHook class stays the TYPE and the impl base.
|
|
167
|
+
*/
|
|
168
|
+
export declare const API_KEY_HOOK: unique symbol;
|
package/src/AuthHooks.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WEBHOOK_AUTH_CALLBACK = exports.WebhookAuthCallback = exports.OIDC_HOOK = exports.OidcHook = exports.JWT_HOOK = exports.JwtHook = void 0;
|
|
3
|
+
exports.API_KEY_HOOK = exports.ApiKeyHook = exports.WEBHOOK_AUTH_CALLBACK = exports.WebhookAuthCallback = exports.OIDC_HOOK = exports.OidcHook = exports.JWT_HOOK = exports.JwtHook = void 0;
|
|
4
4
|
const core_util_1 = require("@webpieces/core-util");
|
|
5
5
|
/**
|
|
6
6
|
* JwtHook - the OPTIONAL user-JWT mechanism. Its DI token is the {@link JWT_HOOK} Symbol injected via
|
|
@@ -16,13 +16,22 @@ const core_util_1 = require("@webpieces/core-util");
|
|
|
16
16
|
* app-defined requirements carried by the SAME decorator, e.g.
|
|
17
17
|
* `@AuthJwt({allRolesAllowed: true, inOrg: true})` →
|
|
18
18
|
* `if (requirement['inOrg'] && !values.claims['orgId']) ...`.
|
|
19
|
+
*
|
|
20
|
+
* BOTH ARE ASYNC, and both for the same reason: the strategy is the app's, and an app's strategy
|
|
21
|
+
* reaches the network. `parseJwt` may fetch a JWKS or call a provider SDK; `authorizeJwt`'s own
|
|
22
|
+
* motivating example — `@AuthJwt({allRolesAllowed: true, inOrg: true})` — is a membership question a
|
|
23
|
+
* real app answers from a datastore. A sync signature makes both of those unwritable, and it made
|
|
24
|
+
* `JwtHook` the last sync hook: {@link OidcHook.verifyOidc}, {@link WebhookAuthCallback.verify} and
|
|
25
|
+
* {@link ApiKeyHook.verifyApiKey} all return promises. An implementation that needs no I/O simply has
|
|
26
|
+
* no `await` in its body — {@link DefaultJwtHook} is exactly that and pays nothing for it.
|
|
19
27
|
*/
|
|
20
28
|
class JwtHook {
|
|
21
29
|
/**
|
|
22
30
|
* DEFAULT authorization: enforce the endpoint's roles (any-of). Override to enforce app-defined
|
|
23
|
-
* requirements. Throw HttpForbiddenError to deny; return to allow.
|
|
31
|
+
* requirements. Throw HttpForbiddenError to deny; return to allow. ASYNC so an app-defined
|
|
32
|
+
* requirement can be answered from a datastore; see the class doc.
|
|
24
33
|
*/
|
|
25
|
-
authorizeJwt(values, requirement) {
|
|
34
|
+
async authorizeJwt(values, requirement) {
|
|
26
35
|
// rolesRequired is the ONE reader of the JwtRoles union: [] means the endpoint typed
|
|
27
36
|
// `allRolesAllowed: true`, never "the field was missing" — that state no longer compiles.
|
|
28
37
|
const roles = (0, core_util_1.rolesRequired)(requirement);
|
|
@@ -91,4 +100,41 @@ exports.WebhookAuthCallback = WebhookAuthCallback;
|
|
|
91
100
|
*/
|
|
92
101
|
// webpieces-disable no-symbol-di-tokens -- optional DI token: must be a Symbol so the app container's autobind never auto-constructs this token, keeping @optional() @inject(...) correct (undefined when unbound)
|
|
93
102
|
exports.WEBHOOK_AUTH_CALLBACK = Symbol.for('WebhookAuthCallback');
|
|
103
|
+
/**
|
|
104
|
+
* ApiKeyHook - the OPTIONAL mechanism behind `@AuthApiKey(name)`: authenticate a CUSTOMER-held api key
|
|
105
|
+
* against the app's own datastore and return the context to seed. Its DI token is the
|
|
106
|
+
* {@link API_KEY_HOOK} Symbol injected via `@inject(API_KEY_HOOK)` (a Symbol, because the app container
|
|
107
|
+
* uses autobind; rebindable in tests). The fourth hook, symmetric with {@link JwtHook} /
|
|
108
|
+
* {@link OidcHook} / {@link WebhookAuthCallback}:
|
|
109
|
+
*
|
|
110
|
+
* ```typescript
|
|
111
|
+
* // AppModule.ts, beside the CompanyJwtHook binding
|
|
112
|
+
* options.bind(API_KEY_HOOK).to(OneTabletApiKeyHook);
|
|
113
|
+
* ```
|
|
114
|
+
*
|
|
115
|
+
* When NO ApiKeyHook is bound, the framework {@link AuthFilter} 401s every `@AuthApiKey` endpoint,
|
|
116
|
+
* exactly as it does for an unbound JwtHook. There is no framework default and there never will be
|
|
117
|
+
* one: the key regime lives in the app's datastore, under the app's hashing scheme, behind the app's
|
|
118
|
+
* choice of header names.
|
|
119
|
+
*
|
|
120
|
+
* THE ONE THING THIS HAS THAT `JwtHook.parseJwt` DOES NOT: it receives a {@link HeaderReader}, not one
|
|
121
|
+
* pre-extracted token. A real key regime validates the key TOGETHER WITH a second header — the
|
|
122
|
+
* organization the caller is acting for — and a hook handed one header's value physically cannot do
|
|
123
|
+
* that cross-check. The framework therefore configures no api-key header name: which headers carry the
|
|
124
|
+
* credential is the app's business. (Being ASYNC is no longer a difference — every hook here is, and
|
|
125
|
+
* for the same reason: an app's strategy reaches the network.)
|
|
126
|
+
*
|
|
127
|
+
* ONE hook serves EVERY regime: `name` selects which, so a server with a partner-api regime and an
|
|
128
|
+
* internal-tooling regime switches on it rather than binding a token per regime.
|
|
129
|
+
*/
|
|
130
|
+
class ApiKeyHook {
|
|
131
|
+
}
|
|
132
|
+
exports.ApiKeyHook = ApiKeyHook;
|
|
133
|
+
/**
|
|
134
|
+
* DI identifier for the optional {@link ApiKeyHook} binding. It is a Symbol (not the class) so the app
|
|
135
|
+
* container's inversify autobind never auto-constructs this token, keeping `@optional() @inject(API_KEY_HOOK)`
|
|
136
|
+
* correct — undefined when unbound. The ApiKeyHook class stays the TYPE and the impl base.
|
|
137
|
+
*/
|
|
138
|
+
// webpieces-disable no-symbol-di-tokens -- optional DI token: must be a Symbol so the app container's autobind never auto-constructs this token, keeping @optional() @inject(...) correct (undefined when unbound)
|
|
139
|
+
exports.API_KEY_HOOK = Symbol.for('ApiKeyHook');
|
|
94
140
|
//# sourceMappingURL=AuthHooks.js.map
|
package/src/AuthHooks.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthHooks.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthHooks.ts"],"names":[],"mappings":";;;AAAA,oDAAyF;AAIzF;;;;;;;;;;;;;;GAcG;AACH,MAAsB,OAAO;IAIzB;;;OAGG;IACH,YAAY,CAAC,MAAkB,EAAE,WAA2B;QACxD,qFAAqF;QACrF,0FAA0F;QAC1F,MAAM,KAAK,GAAG,IAAA,yBAAa,EAAC,WAAW,CAAC,CAAC;QACzC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;YACjF,MAAM,IAAI,8BAAkB,CAAC,mCAAmC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACxF,CAAC;IACL,CAAC;CACJ;AAhBD,0BAgBC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;AAE9C;;;;;;;;;GASG;AACH,MAAsB,QAAQ;CAE7B;AAFD,4BAEC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAsB,mBAAmB;CAWxC;AAXD,kDAWC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,qBAAqB,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC","sourcesContent":["import { JwtRequirement, rolesRequired, HttpForbiddenError } from '@webpieces/core-util';\nimport { HttpRequest, RawRequest } from '@webpieces/core-context';\nimport { AuthValues } from './AuthConfig';\n\n/**\n * JwtHook - the OPTIONAL user-JWT mechanism. Its DI token is the {@link JWT_HOOK} Symbol injected via\n * `@inject(JWT_HOOK)` (a Symbol, because the app container uses autobind; rebindable in tests). Bind one\n * to turn on `@AuthJwt({...})` endpoints. When NO JwtHook is bound, the framework\n * {@link AuthFilter} treats every jwt endpoint as \"not enabled\" and fails fast (401) — there is no\n * default JWT verification because it needs an app secret + payload shape the framework can't guess.\n *\n * - `parseJwt` — AUTHENTICATION: decode/verify a user JWT into {@link AuthValues}, or throw. The\n * app owns the strategy (HS256 secret, RS256 + JWKS, a provider SDK, ...).\n * - `authorizeJwt` — AUTHORIZATION: check the authenticated user against the endpoint's\n * {@link JwtRequirement}. The DEFAULT enforces the roles any-of; override for\n * app-defined requirements carried by the SAME decorator, e.g.\n * `@AuthJwt({allRolesAllowed: true, inOrg: true})` →\n * `if (requirement['inOrg'] && !values.claims['orgId']) ...`.\n */\nexport abstract class JwtHook {\n /** Parse a user JWT (kind:'jwt') — AUTHENTICATION only. Return who the user is, or throw. */\n abstract parseJwt(token: string): AuthValues;\n\n /**\n * DEFAULT authorization: enforce the endpoint's roles (any-of). Override to enforce app-defined\n * requirements. Throw HttpForbiddenError to deny; return to allow.\n */\n authorizeJwt(values: AuthValues, requirement: JwtRequirement): void {\n // rolesRequired is the ONE reader of the JwtRoles union: [] means the endpoint typed\n // `allRolesAllowed: true`, never \"the field was missing\" — that state no longer compiles.\n const roles = rolesRequired(requirement);\n if (roles.length > 0 && !roles.some((role: string) => values.roles.includes(role))) {\n throw new HttpForbiddenError(`Endpoint requires one of roles: ${roles.join(', ')}`);\n }\n }\n}\n\n/**\n * DI identifier for the optional {@link JwtHook} binding. It is a Symbol (not the class) so the app\n * container's inversify autobind never auto-constructs this token, keeping `@optional() @inject(JWT_HOOK)`\n * correct — undefined when unbound. The JwtHook class stays the TYPE and the impl base.\n */\n// webpieces-disable no-symbol-di-tokens -- optional DI token: must be a Symbol so the app container's autobind never auto-constructs this token, keeping @optional() @inject(...) correct (undefined when unbound)\nexport const JWT_HOOK = Symbol.for('JwtHook');\n\n/**\n * OidcHook - the OPTIONAL override for Google OIDC service-to-service verification. Its DI token is the\n * {@link OIDC_HOOK} Symbol injected via `@inject(OIDC_HOOK)` (a Symbol, because the app container uses\n * autobind; rebindable in tests). Bind one ONLY to customize the caller policy — e.g. an app that reads an\n * `ALLOWED_OIDC_CALLERS` env var at its composition root and enforces that allow-list. When NO\n * OidcHook is bound, the framework {@link AuthFilter} runs the built-in {@link DefaultOidcVerifier}\n * directly, so a server that wires nothing still verifies Google OIDC against its `@AuthOidc(...callers)`\n * (else trusts the edge — any Google-signed caller). `verifyOidc` verifies the token against `callers`;\n * throw on failure.\n */\nexport abstract class OidcHook {\n abstract verifyOidc(token: string, callers: string[]): Promise<void>;\n}\n\n/**\n * DI identifier for the optional {@link OidcHook} binding. It is a Symbol (not the class) so the app\n * container's inversify autobind never auto-constructs this token, keeping `@optional() @inject(OIDC_HOOK)`\n * correct — undefined when unbound. The OidcHook class stays the TYPE and the impl base.\n */\n// webpieces-disable no-symbol-di-tokens -- optional DI token: must be a Symbol so the app container's autobind never auto-constructs this token, keeping @optional() @inject(...) correct (undefined when unbound)\nexport const OIDC_HOOK = Symbol.for('OidcHook');\n\n/**\n * WebhookAuthCallback - the OPTIONAL mechanism behind `@AuthWebhook(name)`: prove that an inbound request was\n * really authored by the outside vendor the contract names. Its DI token is the {@link WEBHOOK_AUTH_CALLBACK}\n * Symbol injected via `@inject(WEBHOOK_AUTH_CALLBACK)` (a Symbol, because the app container uses autobind;\n * rebindable in tests). The third hook, symmetric with {@link JwtHook} / {@link OidcHook}:\n *\n * ```typescript\n * // AppModule.ts, beside the CompanyJwtHook binding\n * options.bind(WEBHOOK_AUTH_CALLBACK).to(CompanyWebhookAuthCallback);\n * ```\n *\n * When NO WebhookAuthCallback is bound, the framework {@link AuthFilter} 401s every `@AuthWebhook` endpoint,\n * exactly as it does for an unbound JwtHook. There is no framework default and there never will be\n * one: silently allowing an unverified webhook is the single default that must not exist, and the\n * framework ships no vendor crypto by design (see {@link AuthWebhook} for why reimplementing five\n * vendors' schemes is a losing trade).\n *\n * ONE hook serves EVERY vendor: `name` selects which, so an app with a Sentry hook and a Twilio hook\n * switches on it rather than binding a token per vendor. What arrives is enough of the raw request to\n * call the vendor's OWN validator — the bytes for a body-signing vendor (Sentry, GitHub, Stripe,\n * Slack), the absolute url for one that signs the url instead (Twilio).\n */\nexport abstract class WebhookAuthCallback {\n /**\n * Verify ONE inbound request. Return to allow; throw {@link HttpUnauthorizedError} to deny.\n *\n * @param name the string on the contract's `@AuthWebhook(name)` — which vendor this route is.\n * @param request the transport-neutral request (method, path, headers).\n * @param raw the verbatim bytes + absolute url, guaranteed present: `@AuthWebhook` requires\n * `@Endpoint(..., { rawBody: true })` at wiring time, and AuthFilter 401s rather\n * than calling this hook with nothing to check.\n */\n abstract verify(name: string, request: HttpRequest, raw: RawRequest): Promise<void>;\n}\n\n/**\n * DI identifier for the optional {@link WebhookAuthCallback} binding. It is a Symbol (not the class) so the app\n * container's inversify autobind never auto-constructs this token, keeping `@optional() @inject(WEBHOOK_AUTH_CALLBACK)`\n * correct — undefined when unbound. The WebhookAuthCallback class stays the TYPE and the impl base.\n */\n// webpieces-disable no-symbol-di-tokens -- optional DI token: must be a Symbol so the app container's autobind never auto-constructs this token, keeping @optional() @inject(...) correct (undefined when unbound)\nexport const WEBHOOK_AUTH_CALLBACK = Symbol.for('WebhookAuthCallback');\n"]}
|
|
1
|
+
{"version":3,"file":"AuthHooks.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthHooks.ts"],"names":[],"mappings":";;;AAAA,oDAAyF;AAIzF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAsB,OAAO;IAOzB;;;;OAIG;IACH,KAAK,CAAC,YAAY,CAAC,MAAkB,EAAE,WAA2B;QAC9D,qFAAqF;QACrF,0FAA0F;QAC1F,MAAM,KAAK,GAAG,IAAA,yBAAa,EAAC,WAAW,CAAC,CAAC;QACzC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,EAAE,CAAC;YACjF,MAAM,IAAI,8BAAkB,CAAC,mCAAmC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACxF,CAAC;IACL,CAAC;CACJ;AApBD,0BAoBC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;AAE9C;;;;;;;;;GASG;AACH,MAAsB,QAAQ;CAE7B;AAFD,4BAEC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;AAEhD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAsB,mBAAmB;CAWxC;AAXD,kDAWC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,qBAAqB,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAkBvE;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAsB,UAAU;CAe/B;AAfD,gCAeC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC","sourcesContent":["import { JwtRequirement, rolesRequired, HttpForbiddenError } from '@webpieces/core-util';\nimport { HttpRequest, RawRequest } from '@webpieces/core-context';\nimport { AuthValues } from './AuthConfig';\n\n/**\n * JwtHook - the OPTIONAL user-JWT mechanism. Its DI token is the {@link JWT_HOOK} Symbol injected via\n * `@inject(JWT_HOOK)` (a Symbol, because the app container uses autobind; rebindable in tests). Bind one\n * to turn on `@AuthJwt({...})` endpoints. When NO JwtHook is bound, the framework\n * {@link AuthFilter} treats every jwt endpoint as \"not enabled\" and fails fast (401) — there is no\n * default JWT verification because it needs an app secret + payload shape the framework can't guess.\n *\n * - `parseJwt` — AUTHENTICATION: decode/verify a user JWT into {@link AuthValues}, or throw. The\n * app owns the strategy (HS256 secret, RS256 + JWKS, a provider SDK, ...).\n * - `authorizeJwt` — AUTHORIZATION: check the authenticated user against the endpoint's\n * {@link JwtRequirement}. The DEFAULT enforces the roles any-of; override for\n * app-defined requirements carried by the SAME decorator, e.g.\n * `@AuthJwt({allRolesAllowed: true, inOrg: true})` →\n * `if (requirement['inOrg'] && !values.claims['orgId']) ...`.\n *\n * BOTH ARE ASYNC, and both for the same reason: the strategy is the app's, and an app's strategy\n * reaches the network. `parseJwt` may fetch a JWKS or call a provider SDK; `authorizeJwt`'s own\n * motivating example — `@AuthJwt({allRolesAllowed: true, inOrg: true})` — is a membership question a\n * real app answers from a datastore. A sync signature makes both of those unwritable, and it made\n * `JwtHook` the last sync hook: {@link OidcHook.verifyOidc}, {@link WebhookAuthCallback.verify} and\n * {@link ApiKeyHook.verifyApiKey} all return promises. An implementation that needs no I/O simply has\n * no `await` in its body — {@link DefaultJwtHook} is exactly that and pays nothing for it.\n */\nexport abstract class JwtHook {\n /**\n * Parse a user JWT (kind:'jwt') — AUTHENTICATION only. Return who the user is, or throw.\n * ASYNC so an app can reach a JWKS endpoint or a provider SDK; see the class doc.\n */\n abstract parseJwt(token: string): Promise<AuthValues>;\n\n /**\n * DEFAULT authorization: enforce the endpoint's roles (any-of). Override to enforce app-defined\n * requirements. Throw HttpForbiddenError to deny; return to allow. ASYNC so an app-defined\n * requirement can be answered from a datastore; see the class doc.\n */\n async authorizeJwt(values: AuthValues, requirement: JwtRequirement): Promise<void> {\n // rolesRequired is the ONE reader of the JwtRoles union: [] means the endpoint typed\n // `allRolesAllowed: true`, never \"the field was missing\" — that state no longer compiles.\n const roles = rolesRequired(requirement);\n if (roles.length > 0 && !roles.some((role: string) => values.roles.includes(role))) {\n throw new HttpForbiddenError(`Endpoint requires one of roles: ${roles.join(', ')}`);\n }\n }\n}\n\n/**\n * DI identifier for the optional {@link JwtHook} binding. It is a Symbol (not the class) so the app\n * container's inversify autobind never auto-constructs this token, keeping `@optional() @inject(JWT_HOOK)`\n * correct — undefined when unbound. The JwtHook class stays the TYPE and the impl base.\n */\n// webpieces-disable no-symbol-di-tokens -- optional DI token: must be a Symbol so the app container's autobind never auto-constructs this token, keeping @optional() @inject(...) correct (undefined when unbound)\nexport const JWT_HOOK = Symbol.for('JwtHook');\n\n/**\n * OidcHook - the OPTIONAL override for Google OIDC service-to-service verification. Its DI token is the\n * {@link OIDC_HOOK} Symbol injected via `@inject(OIDC_HOOK)` (a Symbol, because the app container uses\n * autobind; rebindable in tests). Bind one ONLY to customize the caller policy — e.g. an app that reads an\n * `ALLOWED_OIDC_CALLERS` env var at its composition root and enforces that allow-list. When NO\n * OidcHook is bound, the framework {@link AuthFilter} runs the built-in {@link DefaultOidcVerifier}\n * directly, so a server that wires nothing still verifies Google OIDC against its `@AuthOidc(...callers)`\n * (else trusts the edge — any Google-signed caller). `verifyOidc` verifies the token against `callers`;\n * throw on failure.\n */\nexport abstract class OidcHook {\n abstract verifyOidc(token: string, callers: string[]): Promise<void>;\n}\n\n/**\n * DI identifier for the optional {@link OidcHook} binding. It is a Symbol (not the class) so the app\n * container's inversify autobind never auto-constructs this token, keeping `@optional() @inject(OIDC_HOOK)`\n * correct — undefined when unbound. The OidcHook class stays the TYPE and the impl base.\n */\n// webpieces-disable no-symbol-di-tokens -- optional DI token: must be a Symbol so the app container's autobind never auto-constructs this token, keeping @optional() @inject(...) correct (undefined when unbound)\nexport const OIDC_HOOK = Symbol.for('OidcHook');\n\n/**\n * WebhookAuthCallback - the OPTIONAL mechanism behind `@AuthWebhook(name)`: prove that an inbound request was\n * really authored by the outside vendor the contract names. Its DI token is the {@link WEBHOOK_AUTH_CALLBACK}\n * Symbol injected via `@inject(WEBHOOK_AUTH_CALLBACK)` (a Symbol, because the app container uses autobind;\n * rebindable in tests). The third hook, symmetric with {@link JwtHook} / {@link OidcHook}:\n *\n * ```typescript\n * // AppModule.ts, beside the CompanyJwtHook binding\n * options.bind(WEBHOOK_AUTH_CALLBACK).to(CompanyWebhookAuthCallback);\n * ```\n *\n * When NO WebhookAuthCallback is bound, the framework {@link AuthFilter} 401s every `@AuthWebhook` endpoint,\n * exactly as it does for an unbound JwtHook. There is no framework default and there never will be\n * one: silently allowing an unverified webhook is the single default that must not exist, and the\n * framework ships no vendor crypto by design (see {@link AuthWebhook} for why reimplementing five\n * vendors' schemes is a losing trade).\n *\n * ONE hook serves EVERY vendor: `name` selects which, so an app with a Sentry hook and a Twilio hook\n * switches on it rather than binding a token per vendor. What arrives is enough of the raw request to\n * call the vendor's OWN validator — the bytes for a body-signing vendor (Sentry, GitHub, Stripe,\n * Slack), the absolute url for one that signs the url instead (Twilio).\n */\nexport abstract class WebhookAuthCallback {\n /**\n * Verify ONE inbound request. Return to allow; throw {@link HttpUnauthorizedError} to deny.\n *\n * @param name the string on the contract's `@AuthWebhook(name)` — which vendor this route is.\n * @param request the transport-neutral request (method, path, headers).\n * @param raw the verbatim bytes + absolute url, guaranteed present: `@AuthWebhook` requires\n * `@Endpoint(..., { rawBody: true })` at wiring time, and AuthFilter 401s rather\n * than calling this hook with nothing to check.\n */\n abstract verify(name: string, request: HttpRequest, raw: RawRequest): Promise<void>;\n}\n\n/**\n * DI identifier for the optional {@link WebhookAuthCallback} binding. It is a Symbol (not the class) so the app\n * container's inversify autobind never auto-constructs this token, keeping `@optional() @inject(WEBHOOK_AUTH_CALLBACK)`\n * correct — undefined when unbound. The WebhookAuthCallback class stays the TYPE and the impl base.\n */\n// webpieces-disable no-symbol-di-tokens -- optional DI token: must be a Symbol so the app container's autobind never auto-constructs this token, keeping @optional() @inject(...) correct (undefined when unbound)\nexport const WEBHOOK_AUTH_CALLBACK = Symbol.for('WebhookAuthCallback');\n\n/**\n * HeaderReader - read-only access to the inbound request's headers, and the ONLY thing an\n * {@link ApiKeyHook} is handed besides the regime name.\n *\n * It is an INTERFACE, not a class, because it is behaviour rather than data (per the guidelines) —\n * and it is NARROWER than {@link HttpRequest} on purpose. An api-key hook's job is to read the\n * credential headers and look them up; giving it the whole request would also give it the retained\n * raw bytes and the parsed body, none of which it has any business deciding authentication on.\n * `HttpRequest` satisfies this structurally, so the framework passes the live request and a spec can\n * pass a two-line stub.\n */\nexport interface HeaderReader {\n /** First value of the header, by lowercased name, or undefined when absent. */\n getHeader(name: string): string | undefined;\n}\n\n/**\n * ApiKeyHook - the OPTIONAL mechanism behind `@AuthApiKey(name)`: authenticate a CUSTOMER-held api key\n * against the app's own datastore and return the context to seed. Its DI token is the\n * {@link API_KEY_HOOK} Symbol injected via `@inject(API_KEY_HOOK)` (a Symbol, because the app container\n * uses autobind; rebindable in tests). The fourth hook, symmetric with {@link JwtHook} /\n * {@link OidcHook} / {@link WebhookAuthCallback}:\n *\n * ```typescript\n * // AppModule.ts, beside the CompanyJwtHook binding\n * options.bind(API_KEY_HOOK).to(OneTabletApiKeyHook);\n * ```\n *\n * When NO ApiKeyHook is bound, the framework {@link AuthFilter} 401s every `@AuthApiKey` endpoint,\n * exactly as it does for an unbound JwtHook. There is no framework default and there never will be\n * one: the key regime lives in the app's datastore, under the app's hashing scheme, behind the app's\n * choice of header names.\n *\n * THE ONE THING THIS HAS THAT `JwtHook.parseJwt` DOES NOT: it receives a {@link HeaderReader}, not one\n * pre-extracted token. A real key regime validates the key TOGETHER WITH a second header — the\n * organization the caller is acting for — and a hook handed one header's value physically cannot do\n * that cross-check. The framework therefore configures no api-key header name: which headers carry the\n * credential is the app's business. (Being ASYNC is no longer a difference — every hook here is, and\n * for the same reason: an app's strategy reaches the network.)\n *\n * ONE hook serves EVERY regime: `name` selects which, so a server with a partner-api regime and an\n * internal-tooling regime switches on it rather than binding a token per regime.\n */\nexport abstract class ApiKeyHook {\n /**\n * AUTHENTICATE one inbound request. Return who the caller is plus the {@link AuthValues.entries}\n * the framework seeds into `RequestContext` via `putTrusted`, or throw\n * {@link HttpUnauthorizedError} to deny.\n *\n * NOTE the seeded entries are TRUSTED context keys, so return only what THIS hook proved from the\n * credential it just verified. Anything the caller merely asserted on the wire is not admitted by\n * `@AuthApiKey` — the mode is deliberately caller-NOT-verified (see `AuthFilter.verifiesCaller`),\n * because a customer is not an internal service.\n *\n * @param name the string on the contract's `@AuthApiKey(name)` — which key regime this route is.\n * @param headers the inbound request's headers; read as many as the regime needs.\n */\n abstract verifyApiKey(name: string, headers: HeaderReader): Promise<AuthValues>;\n}\n\n/**\n * DI identifier for the optional {@link ApiKeyHook} binding. It is a Symbol (not the class) so the app\n * container's inversify autobind never auto-constructs this token, keeping `@optional() @inject(API_KEY_HOOK)`\n * correct — undefined when unbound. The ApiKeyHook class stays the TYPE and the impl base.\n */\n// webpieces-disable no-symbol-di-tokens -- optional DI token: must be a Symbol so the app container's autobind never auto-constructs this token, keeping @optional() @inject(...) correct (undefined when unbound)\nexport const API_KEY_HOOK = Symbol.for('ApiKeyHook');\n"]}
|
package/src/DefaultJwtHook.d.ts
CHANGED
|
@@ -9,11 +9,16 @@ import { AuthValues } from './AuthConfig';
|
|
|
9
9
|
* `sub` → userId, a string[] `roles` claim → roles, the whole payload → claims. `authorizeJwt`
|
|
10
10
|
* (role enforcement) is inherited from JwtHook. For RS256 + JWKS, a provider SDK, or a non-standard
|
|
11
11
|
* payload, write your own JwtHook subclass instead.
|
|
12
|
+
*
|
|
13
|
+
* It satisfies {@link JwtHook}'s ASYNC signature with a body that awaits NOTHING, and that is the
|
|
14
|
+
* point rather than an oversight: HS256 against a local secret is pure CPU. The signature is async
|
|
15
|
+
* because the hook is the APP's seam and an app's strategy reaches the network — not because this
|
|
16
|
+
* implementation does. No fake await is added to justify it.
|
|
12
17
|
*/
|
|
13
18
|
export declare class DefaultJwtHook extends JwtHook {
|
|
14
19
|
private readonly secret;
|
|
15
20
|
constructor(secret: string);
|
|
16
|
-
parseJwt(token: string): AuthValues
|
|
21
|
+
parseJwt(token: string): Promise<AuthValues>;
|
|
17
22
|
/** Verify HS256 signature + expiry; translate jsonwebtoken's raw error into a framework 401. */
|
|
18
23
|
private verifyToken;
|
|
19
24
|
private extractRoles;
|
package/src/DefaultJwtHook.js
CHANGED
|
@@ -14,6 +14,11 @@ const AuthConfig_1 = require("./AuthConfig");
|
|
|
14
14
|
* `sub` → userId, a string[] `roles` claim → roles, the whole payload → claims. `authorizeJwt`
|
|
15
15
|
* (role enforcement) is inherited from JwtHook. For RS256 + JWKS, a provider SDK, or a non-standard
|
|
16
16
|
* payload, write your own JwtHook subclass instead.
|
|
17
|
+
*
|
|
18
|
+
* It satisfies {@link JwtHook}'s ASYNC signature with a body that awaits NOTHING, and that is the
|
|
19
|
+
* point rather than an oversight: HS256 against a local secret is pure CPU. The signature is async
|
|
20
|
+
* because the hook is the APP's seam and an app's strategy reaches the network — not because this
|
|
21
|
+
* implementation does. No fake await is added to justify it.
|
|
17
22
|
*/
|
|
18
23
|
class DefaultJwtHook extends AuthHooks_1.JwtHook {
|
|
19
24
|
secret;
|
|
@@ -21,7 +26,7 @@ class DefaultJwtHook extends AuthHooks_1.JwtHook {
|
|
|
21
26
|
super();
|
|
22
27
|
this.secret = secret;
|
|
23
28
|
}
|
|
24
|
-
parseJwt(token) {
|
|
29
|
+
async parseJwt(token) {
|
|
25
30
|
const payload = this.verifyToken(token);
|
|
26
31
|
const userId = payload.sub;
|
|
27
32
|
if (!userId) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DefaultJwtHook.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/DefaultJwtHook.ts"],"names":[],"mappings":";;;AAAA,+CAAkD;AAClD,oDAAsE;AACtE,2CAAsC;AACtC,6CAA0C;AAE1C
|
|
1
|
+
{"version":3,"file":"DefaultJwtHook.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/DefaultJwtHook.ts"],"names":[],"mappings":";;;AAAA,+CAAkD;AAClD,oDAAsE;AACtE,2CAAsC;AACtC,6CAA0C;AAE1C;;;;;;;;;;;;;;GAcG;AACH,MAAa,cAAe,SAAQ,mBAAO;IACtB,MAAM,CAAS;IAEhC,YAAY,MAAc;QACtB,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAEQ,KAAK,CAAC,QAAQ,CAAC,KAAa;QACjC,MAAM,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AE,CAAC;IACd,CAAC;CACJ;AA1CD,wCA0CC","sourcesContent":["import { verify, JwtPayload } from 'jsonwebtoken';\nimport { HttpUnauthorizedError, toError } from '@webpieces/core-util';\nimport { JwtHook } from './AuthHooks';\nimport { AuthValues } from './AuthConfig';\n\n/**\n * DefaultJwtHook - a batteries-included {@link JwtHook} for the common case: HS256 user JWTs signed\n * with ONE shared secret. Construct it with the secret and bind it — `new DefaultJwtHook(secret)` —\n * and `@AuthJwt` endpoints work with NO custom verification code.\n *\n * `parseJwt` verifies the signature + expiry (jsonwebtoken, HS256 only) and maps standard claims:\n * `sub` → userId, a string[] `roles` claim → roles, the whole payload → claims. `authorizeJwt`\n * (role enforcement) is inherited from JwtHook. For RS256 + JWKS, a provider SDK, or a non-standard\n * payload, write your own JwtHook subclass instead.\n *\n * It satisfies {@link JwtHook}'s ASYNC signature with a body that awaits NOTHING, and that is the\n * point rather than an oversight: HS256 against a local secret is pure CPU. The signature is async\n * because the hook is the APP's seam and an app's strategy reaches the network — not because this\n * implementation does. No fake await is added to justify it.\n */\nexport class DefaultJwtHook extends JwtHook {\n private readonly secret: string;\n\n constructor(secret: string) {\n super();\n this.secret = secret;\n }\n\n override async parseJwt(token: string): Promise<AuthValues> {\n const payload = this.verifyToken(token);\n const userId = payload.sub;\n if (!userId) {\n throw new HttpUnauthorizedError('JWT is missing the required \"sub\" (subject) claim');\n }\n return new AuthValues(userId, this.extractRoles(payload), [], payload);\n }\n\n /** Verify HS256 signature + expiry; translate jsonwebtoken's raw error into a framework 401. */\n private verifyToken(token: string): JwtPayload {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- AUTH TRANSLATION CHOKEPOINT: jsonwebtoken.verify throws on a bad/expired token; that must surface as a 401 Unauthorized, not bubble to the global handler as a 500. The original error is chained via cause.\n try {\n const decoded = verify(token, this.secret, { algorithms: ['HS256'] });\n if (typeof decoded === 'string') {\n throw new HttpUnauthorizedError('JWT payload must be a JSON object, not a string');\n }\n return decoded;\n } catch (err: unknown) {\n const error = toError(err);\n if (error instanceof HttpUnauthorizedError) {\n throw error;\n }\n throw new HttpUnauthorizedError('JWT verification failed', undefined, error);\n }\n }\n\n private extractRoles(payload: JwtPayload): string[] {\n const roles = payload['roles'];\n if (Array.isArray(roles)) {\n return roles.filter((role: string) => typeof role === 'string');\n }\n return [];\n }\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* COMPILE-TIME assertions that {@link JwtHook} is ASYNC on BOTH halves, and that the old SYNC spelling
|
|
3
|
+
* of either one no longer compiles. Each `@ts-expect-error` below FAILS THE BUILD (TS2578, "unused
|
|
4
|
+
* '@ts-expect-error' directive") if the override it guards ever starts compiling again.
|
|
5
|
+
*
|
|
6
|
+
* WHY THIS IS NOT A `.spec.ts` FILE — the same reason as `core-util`'s `AuthJwtCompileAssertions.ts`:
|
|
7
|
+
* tsconfig.lib.json EXCLUDES specs and vitest strips types with esbuild, so a `@ts-expect-error` in a
|
|
8
|
+
* spec is inert and the suite passes either way. A type-level guarantee has to be asserted in a file
|
|
9
|
+
* the type-checker actually compiles.
|
|
10
|
+
*
|
|
11
|
+
* WHY IT MATTERS HERE SPECIFICALLY. This repo ships no backwards-compatibility shims, so making the
|
|
12
|
+
* hook async means every existing implementor's sync override must STOP COMPILING — the compile error
|
|
13
|
+
* IS the migration. A sync `parseJwt` that kept compiling would be silently awaited to the same value
|
|
14
|
+
* and the break would look optional, which is precisely how an old spelling survives. Pinning both
|
|
15
|
+
* directions here means the async-ness cannot be quietly relaxed later either.
|
|
16
|
+
*/
|
|
17
|
+
export declare class JwtHookCompileAssertions {
|
|
18
|
+
/** The async spellings must keep compiling; asserted by the ABSENCE of an error. */
|
|
19
|
+
legitimate(): void;
|
|
20
|
+
/** The SYNC spellings — what every implementor wrote before — must now be UNWRITABLE. */
|
|
21
|
+
rejected(): void;
|
|
22
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.JwtHookCompileAssertions = void 0;
|
|
4
|
+
const AuthHooks_1 = require("./AuthHooks");
|
|
5
|
+
const AuthConfig_1 = require("./AuthConfig");
|
|
6
|
+
/**
|
|
7
|
+
* COMPILE-TIME assertions that {@link JwtHook} is ASYNC on BOTH halves, and that the old SYNC spelling
|
|
8
|
+
* of either one no longer compiles. Each `@ts-expect-error` below FAILS THE BUILD (TS2578, "unused
|
|
9
|
+
* '@ts-expect-error' directive") if the override it guards ever starts compiling again.
|
|
10
|
+
*
|
|
11
|
+
* WHY THIS IS NOT A `.spec.ts` FILE — the same reason as `core-util`'s `AuthJwtCompileAssertions.ts`:
|
|
12
|
+
* tsconfig.lib.json EXCLUDES specs and vitest strips types with esbuild, so a `@ts-expect-error` in a
|
|
13
|
+
* spec is inert and the suite passes either way. A type-level guarantee has to be asserted in a file
|
|
14
|
+
* the type-checker actually compiles.
|
|
15
|
+
*
|
|
16
|
+
* WHY IT MATTERS HERE SPECIFICALLY. This repo ships no backwards-compatibility shims, so making the
|
|
17
|
+
* hook async means every existing implementor's sync override must STOP COMPILING — the compile error
|
|
18
|
+
* IS the migration. A sync `parseJwt` that kept compiling would be silently awaited to the same value
|
|
19
|
+
* and the break would look optional, which is precisely how an old spelling survives. Pinning both
|
|
20
|
+
* directions here means the async-ness cannot be quietly relaxed later either.
|
|
21
|
+
*/
|
|
22
|
+
class JwtHookCompileAssertions {
|
|
23
|
+
/** The async spellings must keep compiling; asserted by the ABSENCE of an error. */
|
|
24
|
+
legitimate() {
|
|
25
|
+
void class extends AuthHooks_1.JwtHook {
|
|
26
|
+
async parseJwt(_token) {
|
|
27
|
+
return new AuthConfig_1.AuthValues('u1');
|
|
28
|
+
}
|
|
29
|
+
async authorizeJwt(_values, _requirement) {
|
|
30
|
+
// An implementation that needs no I/O simply has no await — that is allowed and free.
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** The SYNC spellings — what every implementor wrote before — must now be UNWRITABLE. */
|
|
35
|
+
rejected() {
|
|
36
|
+
void class extends AuthHooks_1.JwtHook {
|
|
37
|
+
// @ts-expect-error parseJwt is async now: returning AuthValues instead of Promise<AuthValues> must not compile
|
|
38
|
+
parseJwt(_token) {
|
|
39
|
+
return new AuthConfig_1.AuthValues('u1');
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
void class extends AuthHooks_1.JwtHook {
|
|
43
|
+
async parseJwt(_token) {
|
|
44
|
+
return new AuthConfig_1.AuthValues('u1');
|
|
45
|
+
}
|
|
46
|
+
// @ts-expect-error authorizeJwt is async now: a void override must not compile either
|
|
47
|
+
authorizeJwt(_values, _requirement) {
|
|
48
|
+
// an app rule enforced synchronously — the spelling this change deletes
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
exports.JwtHookCompileAssertions = JwtHookCompileAssertions;
|
|
54
|
+
//# sourceMappingURL=JwtHookCompileAssertions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"JwtHookCompileAssertions.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/JwtHookCompileAssertions.ts"],"names":[],"mappings":";;;AACA,2CAAsC;AACtC,6CAA0C;AAE1C;;;;;;;;;;;;;;;GAeG;AACH,MAAa,wBAAwB;IACjC,oFAAoF;IACpF,UAAU;QACN,KAAK,KAAM,SAAQ,mBAAO;YACb,KAAK,CAAC,QAAQ,CAAC,MAAc;gBAClC,OAAO,IAAI,uBAAU,CAAC,IAAI,CAAC,CAAC;YAChC,CAAC;YAEQ,KAAK,CAAC,YAAY,CAAC,OAAmB,EAAE,YAA4B;gBACzE,sFAAsF;YAC1F,CAAC;SACJ,CAAC;IACN,CAAC;IAED,yFAAyF;IACzF,QAAQ;QACJ,KAAK,KAAM,SAAQ,mBAAO;YACtB,+GAA+G;YACtG,QAAQ,CAAC,MAAc;gBAC5B,OAAO,IAAI,uBAAU,CAAC,IAAI,CAAC,CAAC;YAChC,CAAC;SACJ,CAAC;QACF,KAAK,KAAM,SAAQ,mBAAO;YACb,KAAK,CAAC,QAAQ,CAAC,MAAc;gBAClC,OAAO,IAAI,uBAAU,CAAC,IAAI,CAAC,CAAC;YAChC,CAAC;YAED,sFAAsF;YAC7E,YAAY,CAAC,OAAmB,EAAE,YAA4B;gBACnE,wEAAwE;YAC5E,CAAC;SACJ,CAAC;IACN,CAAC;CACJ;AAjCD,4DAiCC","sourcesContent":["import { JwtRequirement } from '@webpieces/core-util';\nimport { JwtHook } from './AuthHooks';\nimport { AuthValues } from './AuthConfig';\n\n/**\n * COMPILE-TIME assertions that {@link JwtHook} is ASYNC on BOTH halves, and that the old SYNC spelling\n * of either one no longer compiles. Each `@ts-expect-error` below FAILS THE BUILD (TS2578, \"unused\n * '@ts-expect-error' directive\") if the override it guards ever starts compiling again.\n *\n * WHY THIS IS NOT A `.spec.ts` FILE — the same reason as `core-util`'s `AuthJwtCompileAssertions.ts`:\n * tsconfig.lib.json EXCLUDES specs and vitest strips types with esbuild, so a `@ts-expect-error` in a\n * spec is inert and the suite passes either way. A type-level guarantee has to be asserted in a file\n * the type-checker actually compiles.\n *\n * WHY IT MATTERS HERE SPECIFICALLY. This repo ships no backwards-compatibility shims, so making the\n * hook async means every existing implementor's sync override must STOP COMPILING — the compile error\n * IS the migration. A sync `parseJwt` that kept compiling would be silently awaited to the same value\n * and the break would look optional, which is precisely how an old spelling survives. Pinning both\n * directions here means the async-ness cannot be quietly relaxed later either.\n */\nexport class JwtHookCompileAssertions {\n /** The async spellings must keep compiling; asserted by the ABSENCE of an error. */\n legitimate(): void {\n void class extends JwtHook {\n override async parseJwt(_token: string): Promise<AuthValues> {\n return new AuthValues('u1');\n }\n\n override async authorizeJwt(_values: AuthValues, _requirement: JwtRequirement): Promise<void> {\n // An implementation that needs no I/O simply has no await — that is allowed and free.\n }\n };\n }\n\n /** The SYNC spellings — what every implementor wrote before — must now be UNWRITABLE. */\n rejected(): void {\n void class extends JwtHook {\n // @ts-expect-error parseJwt is async now: returning AuthValues instead of Promise<AuthValues> must not compile\n override parseJwt(_token: string): AuthValues {\n return new AuthValues('u1');\n }\n };\n void class extends JwtHook {\n override async parseJwt(_token: string): Promise<AuthValues> {\n return new AuthValues('u1');\n }\n\n // @ts-expect-error authorizeJwt is async now: a void override must not compile either\n override authorizeJwt(_values: AuthValues, _requirement: JwtRequirement): void {\n // an app rule enforced synchronously — the spelling this change deletes\n }\n };\n }\n}\n"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Filter, WpResponse, Service } from '../Filter';
|
|
2
2
|
import { MethodMeta } from '../MethodMeta';
|
|
3
3
|
import { AuthConfig } from '../AuthConfig';
|
|
4
|
-
import { JwtHook, OidcHook, WebhookAuthCallback } from '../AuthHooks';
|
|
4
|
+
import { ApiKeyHook, JwtHook, OidcHook, WebhookAuthCallback } from '../AuthHooks';
|
|
5
5
|
import { DefaultOidcVerifier } from '../DefaultOidcVerifier';
|
|
6
6
|
/**
|
|
7
7
|
* AuthFilter - the ONE framework auth filter, auto-installed just below the error filter on every
|
|
@@ -12,13 +12,16 @@ import { DefaultOidcVerifier } from '../DefaultOidcVerifier';
|
|
|
12
12
|
* default:
|
|
13
13
|
* - shared-secret → constant-time compare vs the {@link AuthConfig} secret VALUE (state). No
|
|
14
14
|
* AuthConfig bound → no accepted secret → fail fast (401).
|
|
15
|
-
* - jwt → the bound {@link JwtHook} (`parseJwt` + `authorizeJwt
|
|
16
|
-
*
|
|
15
|
+
* - jwt → the bound {@link JwtHook} (`parseJwt` + `authorizeJwt`, both awaited — an app's
|
|
16
|
+
* strategy may reach a JWKS or a datastore). No JwtHook bound → "not enabled"
|
|
17
|
+
* (401): JWT needs an app secret + payload shape.
|
|
17
18
|
* - oidc → the bound {@link OidcHook} if any, else the framework {@link DefaultOidcVerifier}
|
|
18
19
|
* run DIRECTLY — so a server that wires NOTHING still verifies Google OIDC.
|
|
19
20
|
* - webhook → the bound {@link WebhookAuthCallback} verifies the VENDOR's signature over the retained
|
|
20
21
|
* raw request. No WebhookAuthCallback bound → 401, like jwt: an unverified webhook is
|
|
21
22
|
* never waved through because wiring was forgotten.
|
|
23
|
+
* - apikey → the bound {@link ApiKeyHook} looks the CUSTOMER's key up (async, over the whole
|
|
24
|
+
* header set) and returns the context to seed. No ApiKeyHook bound → 401, like jwt.
|
|
22
25
|
* - public → BEST-EFFORT jwt parse (only if a JwtHook is bound): stamp the user's context so
|
|
23
26
|
* a logged-out page still knows who is logged in; never fails.
|
|
24
27
|
* - local-only → serve only when {@link RuntimeLocality} says this process is a developer's
|
|
@@ -33,7 +36,8 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
|
|
|
33
36
|
private readonly jwtHook?;
|
|
34
37
|
private readonly oidcHook?;
|
|
35
38
|
private readonly webhookAuthCallback?;
|
|
36
|
-
|
|
39
|
+
private readonly apiKeyHook?;
|
|
40
|
+
constructor(oidcVerifier: DefaultOidcVerifier, authConfig?: AuthConfig | undefined, jwtHook?: JwtHook | undefined, oidcHook?: OidcHook | undefined, webhookAuthCallback?: WebhookAuthCallback | undefined, apiKeyHook?: ApiKeyHook | undefined);
|
|
37
41
|
filter(meta: MethodMeta, nextFilter: Service<MethodMeta, WpResponse<unknown>>): Promise<WpResponse<unknown>>;
|
|
38
42
|
/**
|
|
39
43
|
* `@AuthWebhook(name)`: hand the app's {@link WebhookAuthCallback} the verbatim request and let it call the
|
|
@@ -48,6 +52,21 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
|
|
|
48
52
|
* 3. The hook threw — the signature did not verify.
|
|
49
53
|
*/
|
|
50
54
|
private enforceWebhook;
|
|
55
|
+
/**
|
|
56
|
+
* `@AuthApiKey(name)`: hand the app's {@link ApiKeyHook} the regime name and the inbound headers and
|
|
57
|
+
* let it look the CUSTOMER's key up. Three ways to fail, all 401, all before the controller:
|
|
58
|
+
*
|
|
59
|
+
* 1. NO hook bound — the endpoint is not enabled. Matches {@link JwtHook}'s documented behavior; an
|
|
60
|
+
* unverified partner request must never be waved through because wiring was forgotten.
|
|
61
|
+
* 2. NO inbound request in scope — there are no headers to read, so there is nothing to verify. That
|
|
62
|
+
* means a caller drove this route without publishing an HttpRequest; the message says so rather
|
|
63
|
+
* than leaving a bare 401.
|
|
64
|
+
* 3. The hook threw — the key, or the key/organization pair, did not check out.
|
|
65
|
+
*
|
|
66
|
+
* On success the hook's {@link AuthValues} are stamped exactly as a jwt parse's are, which is what
|
|
67
|
+
* puts the resolved organization into `RequestContext` for every downstream repository call.
|
|
68
|
+
*/
|
|
69
|
+
private enforceApiKey;
|
|
51
70
|
/**
|
|
52
71
|
* A body that failed to parse is held on the {@link RawRequest} and surfaces HERE, after auth, as
|
|
53
72
|
* the 400 it always was — never before it.
|
|
@@ -77,7 +96,9 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
|
|
|
77
96
|
* localhost reaches it, and it has no authenticator, so nothing can ever vouch for an inbound
|
|
78
97
|
* trusted header. Any such header therefore rejects the request, which is exactly right.
|
|
79
98
|
*
|
|
80
|
-
*
|
|
99
|
+
* - `apikey` → FALSE. See the comment on that branch: the sender is a CUSTOMER.
|
|
100
|
+
*
|
|
101
|
+
* An exhaustive switch with NO `default`, returning on every branch: a new AuthMode kind is a
|
|
81
102
|
* COMPILE error here (TS7030, no ending return) rather than silently landing on one posture. The
|
|
82
103
|
* boolean expression this replaced defaulted every future mode to "not verified" — the safe
|
|
83
104
|
* answer, but arrived at by accident rather than by decision.
|
|
@@ -87,7 +108,8 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
|
|
|
87
108
|
* Decide what happens to the trusted keys that arrived on the WIRE and were held back by
|
|
88
109
|
* {@link PendingWireTrust} (read that class for why they are held rather than written).
|
|
89
110
|
*
|
|
90
|
-
* `callerVerified` — the endpoint authenticated the SENDER (`@AuthOidc`,
|
|
111
|
+
* `callerVerified` — the endpoint authenticated the SENDER **as a peer service** (`@AuthOidc`,
|
|
112
|
+
* `@AuthSharedSecret`).
|
|
91
113
|
* The sender is a service we trust, this is the service-to-service hop, and its forwarded
|
|
92
114
|
* identity is admitted as-is. This is the case that makes propagating a verified userId across
|
|
93
115
|
* internal services work.
|
|
@@ -111,7 +133,7 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
|
|
|
111
133
|
* credential.
|
|
112
134
|
* - NOTHING vouched for it — nobody derived this key at all, so there is no evidence behind a
|
|
113
135
|
* value a stranger typed. This is the common case, not the exotic one: the framework's
|
|
114
|
-
* {@link DefaultJwtHook} stamps NO entries, and an app hook only stamps the keys it can prove,
|
|
136
|
+
* {@link DefaultJwtHook} stamps NO entries, and an app hook (jwt or api-key) only stamps the keys it can prove,
|
|
115
137
|
* so any other trusted key a caller sends lands here.
|
|
116
138
|
*
|
|
117
139
|
* The pending value is discarded either way — the throw is what leaves the request.
|
|
@@ -142,7 +164,7 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
|
|
|
142
164
|
private matchesEither;
|
|
143
165
|
/** Parse a JWT if one is present, else do nothing — used on public routes; never throws. */
|
|
144
166
|
private bestEffortJwt;
|
|
145
|
-
/** Stamp the
|
|
167
|
+
/** Stamp the authenticated caller's context entries + the principal into the RequestContext. */
|
|
146
168
|
private applyAuthValues;
|
|
147
169
|
/**
|
|
148
170
|
* The credential value IF the header carries the expected scheme, else undefined.
|
|
@@ -42,13 +42,16 @@ const PRINCIPAL_KEY = '__webpieces_principal__';
|
|
|
42
42
|
* default:
|
|
43
43
|
* - shared-secret → constant-time compare vs the {@link AuthConfig} secret VALUE (state). No
|
|
44
44
|
* AuthConfig bound → no accepted secret → fail fast (401).
|
|
45
|
-
* - jwt → the bound {@link JwtHook} (`parseJwt` + `authorizeJwt
|
|
46
|
-
*
|
|
45
|
+
* - jwt → the bound {@link JwtHook} (`parseJwt` + `authorizeJwt`, both awaited — an app's
|
|
46
|
+
* strategy may reach a JWKS or a datastore). No JwtHook bound → "not enabled"
|
|
47
|
+
* (401): JWT needs an app secret + payload shape.
|
|
47
48
|
* - oidc → the bound {@link OidcHook} if any, else the framework {@link DefaultOidcVerifier}
|
|
48
49
|
* run DIRECTLY — so a server that wires NOTHING still verifies Google OIDC.
|
|
49
50
|
* - webhook → the bound {@link WebhookAuthCallback} verifies the VENDOR's signature over the retained
|
|
50
51
|
* raw request. No WebhookAuthCallback bound → 401, like jwt: an unverified webhook is
|
|
51
52
|
* never waved through because wiring was forgotten.
|
|
53
|
+
* - apikey → the bound {@link ApiKeyHook} looks the CUSTOMER's key up (async, over the whole
|
|
54
|
+
* header set) and returns the context to seed. No ApiKeyHook bound → 401, like jwt.
|
|
52
55
|
* - public → BEST-EFFORT jwt parse (only if a JwtHook is bound): stamp the user's context so
|
|
53
56
|
* a logged-out page still knows who is logged in; never fails.
|
|
54
57
|
* - local-only → serve only when {@link RuntimeLocality} says this process is a developer's
|
|
@@ -63,13 +66,15 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
63
66
|
jwtHook;
|
|
64
67
|
oidcHook;
|
|
65
68
|
webhookAuthCallback;
|
|
66
|
-
|
|
69
|
+
apiKeyHook;
|
|
70
|
+
constructor(oidcVerifier, authConfig, jwtHook, oidcHook, webhookAuthCallback, apiKeyHook) {
|
|
67
71
|
super();
|
|
68
72
|
this.oidcVerifier = oidcVerifier;
|
|
69
73
|
this.authConfig = authConfig;
|
|
70
74
|
this.jwtHook = jwtHook;
|
|
71
75
|
this.oidcHook = oidcHook;
|
|
72
76
|
this.webhookAuthCallback = webhookAuthCallback;
|
|
77
|
+
this.apiKeyHook = apiKeyHook;
|
|
73
78
|
}
|
|
74
79
|
// webpieces-disable no-any-unknown -- Filter generic params use unknown for response flexibility
|
|
75
80
|
async filter(meta, nextFilter) {
|
|
@@ -77,14 +82,14 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
77
82
|
const authHeader = core_context_1.RequestContext.getRequest()?.getHeader(AUTHORIZATION_HEADER);
|
|
78
83
|
if (!mode || mode.kind === 'public') {
|
|
79
84
|
// Public: best-effort parse so a logged-out page can still know the logged-in user.
|
|
80
|
-
this.bestEffortJwt(authHeader);
|
|
85
|
+
await this.bestEffortJwt(authHeader);
|
|
81
86
|
this.reconcileWireTrust(/*callerVerified*/ false);
|
|
82
87
|
this.rethrowDeferredBodyError();
|
|
83
88
|
return nextFilter.invoke(meta);
|
|
84
89
|
}
|
|
85
90
|
switch (mode.kind) {
|
|
86
91
|
case 'jwt':
|
|
87
|
-
this.enforceJwt(authHeader, mode.requirement);
|
|
92
|
+
await this.enforceJwt(authHeader, mode.requirement);
|
|
88
93
|
break;
|
|
89
94
|
case 'oidc':
|
|
90
95
|
await this.enforceOidc(authHeader, mode.callers);
|
|
@@ -95,6 +100,9 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
95
100
|
case 'webhook':
|
|
96
101
|
await this.enforceWebhook(mode.name, meta);
|
|
97
102
|
break;
|
|
103
|
+
case 'apikey':
|
|
104
|
+
await this.enforceApiKey(mode.name, meta);
|
|
105
|
+
break;
|
|
98
106
|
case 'local-only':
|
|
99
107
|
this.enforceLocalOnly(meta);
|
|
100
108
|
break;
|
|
@@ -131,6 +139,37 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
131
139
|
}
|
|
132
140
|
await this.webhookAuthCallback.verify(name, request, raw); // throws HttpUnauthorizedError to deny
|
|
133
141
|
}
|
|
142
|
+
/**
|
|
143
|
+
* `@AuthApiKey(name)`: hand the app's {@link ApiKeyHook} the regime name and the inbound headers and
|
|
144
|
+
* let it look the CUSTOMER's key up. Three ways to fail, all 401, all before the controller:
|
|
145
|
+
*
|
|
146
|
+
* 1. NO hook bound — the endpoint is not enabled. Matches {@link JwtHook}'s documented behavior; an
|
|
147
|
+
* unverified partner request must never be waved through because wiring was forgotten.
|
|
148
|
+
* 2. NO inbound request in scope — there are no headers to read, so there is nothing to verify. That
|
|
149
|
+
* means a caller drove this route without publishing an HttpRequest; the message says so rather
|
|
150
|
+
* than leaving a bare 401.
|
|
151
|
+
* 3. The hook threw — the key, or the key/organization pair, did not check out.
|
|
152
|
+
*
|
|
153
|
+
* On success the hook's {@link AuthValues} are stamped exactly as a jwt parse's are, which is what
|
|
154
|
+
* puts the resolved organization into `RequestContext` for every downstream repository call.
|
|
155
|
+
*/
|
|
156
|
+
async enforceApiKey(name, meta) {
|
|
157
|
+
if (!this.apiKeyHook) {
|
|
158
|
+
log.warn(`Refusing @AuthApiKey('${name}') endpoint ${meta.routeMeta.path}: no ApiKeyHook is bound. ` +
|
|
159
|
+
`Bind one (options.bind(API_KEY_HOOK).to(YourApiKeyHook)) to enable api-key verification.`);
|
|
160
|
+
throw new core_util_1.HttpUnauthorizedError('API-key auth is not enabled on this server');
|
|
161
|
+
}
|
|
162
|
+
const request = core_context_1.RequestContext.getRequest();
|
|
163
|
+
if (!request) {
|
|
164
|
+
log.warn(`Refusing @AuthApiKey('${name}') endpoint ${meta.routeMeta.path}: no inbound HttpRequest is ` +
|
|
165
|
+
`in scope, so the hook has no headers to read. A spec driving this route in-process must ` +
|
|
166
|
+
`publish an HttpRequest carrying the api-key headers.`);
|
|
167
|
+
throw new core_util_1.HttpUnauthorizedError('API key cannot be verified: no inbound request was published');
|
|
168
|
+
}
|
|
169
|
+
// Throws HttpUnauthorizedError to deny. HttpRequest satisfies HeaderReader structurally.
|
|
170
|
+
const values = await this.apiKeyHook.verifyApiKey(name, request);
|
|
171
|
+
this.applyAuthValues(values);
|
|
172
|
+
}
|
|
134
173
|
/**
|
|
135
174
|
* A body that failed to parse is held on the {@link RawRequest} and surfaces HERE, after auth, as
|
|
136
175
|
* the 400 it always was — never before it.
|
|
@@ -165,7 +204,9 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
165
204
|
* localhost reaches it, and it has no authenticator, so nothing can ever vouch for an inbound
|
|
166
205
|
* trusted header. Any such header therefore rejects the request, which is exactly right.
|
|
167
206
|
*
|
|
168
|
-
*
|
|
207
|
+
* - `apikey` → FALSE. See the comment on that branch: the sender is a CUSTOMER.
|
|
208
|
+
*
|
|
209
|
+
* An exhaustive switch with NO `default`, returning on every branch: a new AuthMode kind is a
|
|
169
210
|
* COMPILE error here (TS7030, no ending return) rather than silently landing on one posture. The
|
|
170
211
|
* boolean expression this replaced defaulted every future mode to "not verified" — the safe
|
|
171
212
|
* answer, but arrived at by accident rather than by decision.
|
|
@@ -184,6 +225,12 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
184
225
|
// key a vendor's payload could carry. Same answer as the OUTBOUND half
|
|
185
226
|
// (DestinationTrust.forAuthMode), which is the invariant that keeps the two ends agreeing.
|
|
186
227
|
case 'webhook':
|
|
228
|
+
// `apikey` authenticates the SENDER — but the sender is a CUSTOMER's codebase, not a peer
|
|
229
|
+
// service in this repo, so its forwarded trusted context is exactly what must NOT be
|
|
230
|
+
// believed: admitting it would let a partner assert another customer's org id on the wire.
|
|
231
|
+
// The hook's OWN derived entries still land (applyAuthValues), and reconcileWireTrust then
|
|
232
|
+
// admits an inbound trusted header only when the hook independently derived the same value.
|
|
233
|
+
case 'apikey':
|
|
187
234
|
case 'local-only':
|
|
188
235
|
return false;
|
|
189
236
|
}
|
|
@@ -192,7 +239,8 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
192
239
|
* Decide what happens to the trusted keys that arrived on the WIRE and were held back by
|
|
193
240
|
* {@link PendingWireTrust} (read that class for why they are held rather than written).
|
|
194
241
|
*
|
|
195
|
-
* `callerVerified` — the endpoint authenticated the SENDER (`@AuthOidc`,
|
|
242
|
+
* `callerVerified` — the endpoint authenticated the SENDER **as a peer service** (`@AuthOidc`,
|
|
243
|
+
* `@AuthSharedSecret`).
|
|
196
244
|
* The sender is a service we trust, this is the service-to-service hop, and its forwarded
|
|
197
245
|
* identity is admitted as-is. This is the case that makes propagating a verified userId across
|
|
198
246
|
* internal services work.
|
|
@@ -226,7 +274,7 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
226
274
|
* credential.
|
|
227
275
|
* - NOTHING vouched for it — nobody derived this key at all, so there is no evidence behind a
|
|
228
276
|
* value a stranger typed. This is the common case, not the exotic one: the framework's
|
|
229
|
-
* {@link DefaultJwtHook} stamps NO entries, and an app hook only stamps the keys it can prove,
|
|
277
|
+
* {@link DefaultJwtHook} stamps NO entries, and an app hook (jwt or api-key) only stamps the keys it can prove,
|
|
230
278
|
* so any other trusted key a caller sends lands here.
|
|
231
279
|
*
|
|
232
280
|
* The pending value is discarded either way — the throw is what leaves the request.
|
|
@@ -269,7 +317,7 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
269
317
|
// Same shape as an unregistered route — see the method doc for why this is not a 403.
|
|
270
318
|
throw new core_util_1.EndpointNotFoundError(`No endpoint at ${meta.routeMeta.path}`);
|
|
271
319
|
}
|
|
272
|
-
enforceJwt(header, requirement) {
|
|
320
|
+
async enforceJwt(header, requirement) {
|
|
273
321
|
const token = this.credential(header, BEARER_SCHEME);
|
|
274
322
|
if (!token) {
|
|
275
323
|
throw new core_util_1.HttpUnauthorizedError('Authentication required');
|
|
@@ -277,9 +325,9 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
277
325
|
if (!this.jwtHook) {
|
|
278
326
|
throw new core_util_1.HttpUnauthorizedError('User-JWT auth is not enabled on this server');
|
|
279
327
|
}
|
|
280
|
-
const values = this.jwtHook.parseJwt(token); // AUTHENTICATE — throws HttpUnauthorizedError if invalid
|
|
328
|
+
const values = await this.jwtHook.parseJwt(token); // AUTHENTICATE — throws HttpUnauthorizedError if invalid
|
|
281
329
|
this.applyAuthValues(values);
|
|
282
|
-
this.jwtHook.authorizeJwt(values, requirement); // AUTHORIZE — app policy; throws HttpForbiddenError to deny
|
|
330
|
+
await this.jwtHook.authorizeJwt(values, requirement); // AUTHORIZE — app policy; throws HttpForbiddenError to deny
|
|
283
331
|
}
|
|
284
332
|
async enforceOidc(header, callers) {
|
|
285
333
|
const token = this.credential(header, BEARER_SCHEME);
|
|
@@ -307,25 +355,25 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
307
355
|
(accepted.secret2 !== '' && this.constantTimeEquals(provided, accepted.secret2)));
|
|
308
356
|
}
|
|
309
357
|
/** Parse a JWT if one is present, else do nothing — used on public routes; never throws. */
|
|
310
|
-
bestEffortJwt(header) {
|
|
358
|
+
async bestEffortJwt(header) {
|
|
311
359
|
const token = this.credential(header, BEARER_SCHEME);
|
|
312
360
|
if (!this.jwtHook || !token) {
|
|
313
361
|
return;
|
|
314
362
|
}
|
|
315
363
|
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- best-effort on a public route: a bad/absent token just means "not logged in", must not fail the request
|
|
316
364
|
try {
|
|
317
|
-
this.applyAuthValues(this.jwtHook.parseJwt(token));
|
|
365
|
+
this.applyAuthValues(await this.jwtHook.parseJwt(token));
|
|
318
366
|
}
|
|
319
367
|
catch (err) {
|
|
320
368
|
const error = (0, core_util_1.toError)(err);
|
|
321
369
|
log.debug('Best-effort JWT parse on a public endpoint failed (treating as anonymous): ', error);
|
|
322
370
|
}
|
|
323
371
|
}
|
|
324
|
-
/** Stamp the
|
|
372
|
+
/** Stamp the authenticated caller's context entries + the principal into the RequestContext. */
|
|
325
373
|
applyAuthValues(values) {
|
|
326
374
|
for (const entry of values.entries) {
|
|
327
375
|
// ContextTuple.key is a TRUSTED key by type, so this is the one sanctioned write of a
|
|
328
|
-
// proven identity: the app's JwtHook derived it from a credential we just verified.
|
|
376
|
+
// proven identity: the app's JwtHook or ApiKeyHook derived it from a credential we just verified.
|
|
329
377
|
core_context_1.RequestContext.putTrusted(entry.key, entry.value);
|
|
330
378
|
}
|
|
331
379
|
core_context_1.RequestContext.put(PRINCIPAL_KEY, values);
|
|
@@ -366,10 +414,13 @@ exports.AuthFilter = AuthFilter = AuthFilter_1 = tslib_1.__decorate([
|
|
|
366
414
|
tslib_1.__param(3, (0, inversify_1.inject)(AuthHooks_1.OIDC_HOOK)),
|
|
367
415
|
tslib_1.__param(4, (0, inversify_1.optional)()),
|
|
368
416
|
tslib_1.__param(4, (0, inversify_1.inject)(AuthHooks_1.WEBHOOK_AUTH_CALLBACK)),
|
|
417
|
+
tslib_1.__param(5, (0, inversify_1.optional)()),
|
|
418
|
+
tslib_1.__param(5, (0, inversify_1.inject)(AuthHooks_1.API_KEY_HOOK)),
|
|
369
419
|
tslib_1.__metadata("design:paramtypes", [DefaultOidcVerifier_1.DefaultOidcVerifier,
|
|
370
420
|
AuthConfig_1.AuthConfig,
|
|
371
421
|
AuthHooks_1.JwtHook,
|
|
372
422
|
AuthHooks_1.OidcHook,
|
|
373
|
-
AuthHooks_1.WebhookAuthCallback
|
|
423
|
+
AuthHooks_1.WebhookAuthCallback,
|
|
424
|
+
AuthHooks_1.ApiKeyHook])
|
|
374
425
|
], AuthFilter);
|
|
375
426
|
//# sourceMappingURL=AuthFilter.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-routing/src/filters/AuthFilter.ts"],"names":[],"mappings":";;;;;AAAA,yCAA6C;AAC7C,mCAAyC;AACzC,0DAA2H;AAC3H,oDAAyK;AACzK,sCAAwD;AAExD,8CAAmF;AACnF,4CAAkH;AAClH,gEAA6D;AAE7D,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;AAE/C;;;;;;GAMG;AACH,MAAM,oBAAoB,GAAG,eAAe,CAAC;AAE7C;;;;;;;;GAQG;AACH,MAAM,aAAa,GAAG,QAAQ,CAAC;AAC/B,MAAM,oBAAoB,GAAG,WAAW,CAAC;AAEzC,qGAAqG;AACrG,MAAM,aAAa,GA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AAC,CAAC,SAAS,CAAC;IACnF,CAAC;IAEO,kBAAkB,CAAC,CAAS,EAAE,CAAS;QAC3C,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QACpC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QACpC,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,EAAE,CAAC;YAC9B,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,OAAO,IAAA,wBAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC;CACJ,CAAA;AA1UY,gCAAU;qBAAV,UAAU;IAFtB,IAAA,wCAAyB,GAAE;IAC5B,iGAAiG;;IAKxF,mBAAA,IAAA,kBAAM,EAAC,yCAAmB,CAAC,CAAA;IAG3B,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,wBAAW,CAAC,CAAA;IAG/B,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,oBAAQ,CAAC,CAAA;IAG5B,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,qBAAS,CAAC,CAAA;IAI7B,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,iCAAqB,CAAC,CAAA;6CAbkB,yCAAmB;QAGhB,uBAAU;QAGhB,mBAAO;QAGL,oBAAQ;QAIe,+BAAmB;GAjBhG,UAAU,CA0UtB","sourcesContent":["import { inject, optional } from 'inversify';\nimport { timingSafeEqual } from 'crypto';\nimport { provideFrameworkSingleton, PendingWireTrust, PendingTrustedValue, RequestContext } from '@webpieces/core-context';\nimport { AuthMode, EndpointNotFoundError, HttpBadRequestError, HttpUnauthorizedError, JwtRequirement, LogManager, RuntimeLocality, toError } from '@webpieces/core-util';\nimport { Filter, WpResponse, Service } from '../Filter';\nimport { MethodMeta } from '../MethodMeta';\nimport { AuthConfig, AUTH_CONFIG, AuthValues, SharedSecrets } from '../AuthConfig';\nimport { JwtHook, JWT_HOOK, OidcHook, OIDC_HOOK, WebhookAuthCallback, WEBHOOK_AUTH_CALLBACK } from '../AuthHooks';\nimport { DefaultOidcVerifier } from '../DefaultOidcVerifier';\n\nconst log = LogManager.getLogger('AuthFilter');\n\n/**\n * The ONE credential header, read straight off the inbound HttpRequest.\n *\n * Deliberately NOT a ContextKey: a ContextKey with an httpHeader is a TRANSFERRED key, which would\n * put the caller's credential into RequestContext and hence onto every outbound call this service\n * makes, and onto every Cloud Task it enqueues. A credential belongs to ONE request hop.\n */\nconst AUTHORIZATION_HEADER = 'authorization';\n\n/**\n * The scheme (first word of the Authorization value) names WHICH credential follows, so a secret\n * can never be mistaken for a token, nor accepted where the other was expected:\n *\n * Authorization: Bearer <user JWT | service OIDC token>\n * Authorization: Webpieces <@AuthSharedSecret value>\n *\n * The scheme is REQUIRED. A bare value with no scheme is rejected.\n */\nconst BEARER_SCHEME = 'Bearer';\nconst SHARED_SECRET_SCHEME = 'Webpieces';\n\n/** Reserved context key holding the authenticated {@link AuthValues} (stamped after a jwt parse). */\nconst PRINCIPAL_KEY = '__webpieces_principal__';\n\n/**\n * AuthFilter - the ONE framework auth filter, auto-installed just below the error filter on every\n * route. It is TRANSPORT-NEUTRAL: it reads the raw credential from the {@link HttpRequest} in\n * RequestContext (never express), so the SAME check runs over HTTP and via createApiClient.\n *\n * It enforces the endpoint's AuthMode from separately-bound pieces, each OPTIONAL except the OIDC\n * default:\n * - shared-secret → constant-time compare vs the {@link AuthConfig} secret VALUE (state). No\n * AuthConfig bound → no accepted secret → fail fast (401).\n * - jwt → the bound {@link JwtHook} (`parseJwt` + `authorizeJwt`). No JwtHook bound →\n * \"not enabled\" (401): JWT needs an app secret + payload shape.\n * - oidc → the bound {@link OidcHook} if any, else the framework {@link DefaultOidcVerifier}\n * run DIRECTLY — so a server that wires NOTHING still verifies Google OIDC.\n * - webhook → the bound {@link WebhookAuthCallback} verifies the VENDOR's signature over the retained\n * raw request. No WebhookAuthCallback bound → 401, like jwt: an unverified webhook is\n * never waved through because wiring was forgotten.\n * - public → BEST-EFFORT jwt parse (only if a JwtHook is bound): stamp the user's context so\n * a logged-out page still knows who is logged in; never fails.\n * - local-only → serve only when {@link RuntimeLocality} says this process is a developer's\n * machine; otherwise 404, indistinguishable from the route not existing (which,\n * off-local, it does not — `ApiRoutingFactory` never registered it).\n *\n * Zero wiring = OIDC just works; an app only binds the hooks it actually uses.\n */\n@provideFrameworkSingleton()\n// webpieces-disable no-any-unknown -- Filter generic params use unknown for response flexibility\nexport class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>> {\n constructor(\n // Framework default, always available — verifies Google OIDC with zero app wiring.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- AuthFilter is DI-resolved via the esbuild/vitest path, which elides type-only imports (no design:paramtypes), so every param needs its explicit token\n @inject(DefaultOidcVerifier) private readonly oidcVerifier: DefaultOidcVerifier,\n // @optional: only bind an AuthConfig to enable @AuthSharedSecret endpoints.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- see above: explicit token required for DI-resolved param\n @optional() @inject(AUTH_CONFIG) private readonly authConfig?: AuthConfig,\n // @optional: only bind a JwtHook to enable @AuthJwt endpoints.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- see above: explicit token required for DI-resolved param\n @optional() @inject(JWT_HOOK) private readonly jwtHook?: JwtHook,\n // @optional: only bind an OidcHook to OVERRIDE the DefaultOidcVerifier caller policy.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- see above: explicit token required for DI-resolved param\n @optional() @inject(OIDC_HOOK) private readonly oidcHook?: OidcHook,\n // @optional: only bind a WebhookAuthCallback to enable @AuthWebhook endpoints. Unbound = every such\n // endpoint 401s, which is the ONE default that must not be the other way round.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- see above: explicit token required for DI-resolved param\n @optional() @inject(WEBHOOK_AUTH_CALLBACK) private readonly webhookAuthCallback?: WebhookAuthCallback,\n ) {\n super();\n }\n\n // webpieces-disable no-any-unknown -- Filter generic params use unknown for response flexibility\n override async filter(\n meta: MethodMeta,\n nextFilter: Service<MethodMeta, WpResponse<unknown>>,\n ): Promise<WpResponse<unknown>> {\n const mode = meta.routeMeta.authMeta?.mode;\n const authHeader = RequestContext.getRequest()?.getHeader(AUTHORIZATION_HEADER);\n\n if (!mode || mode.kind === 'public') {\n // Public: best-effort parse so a logged-out page can still know the logged-in user.\n this.bestEffortJwt(authHeader);\n this.reconcileWireTrust(/*callerVerified*/ false);\n this.rethrowDeferredBodyError();\n return nextFilter.invoke(meta);\n }\n\n switch (mode.kind) {\n case 'jwt':\n this.enforceJwt(authHeader, mode.requirement);\n break;\n case 'oidc':\n await this.enforceOidc(authHeader, mode.callers);\n break;\n case 'shared-secret':\n this.enforceSharedSecret(this.credential(authHeader, SHARED_SECRET_SCHEME), mode.secretKey);\n break;\n case 'webhook':\n await this.enforceWebhook(mode.name, meta);\n break;\n case 'local-only':\n this.enforceLocalOnly(meta);\n break;\n }\n this.reconcileWireTrust(AuthFilter.verifiesCaller(mode));\n this.rethrowDeferredBodyError();\n return nextFilter.invoke(meta);\n }\n\n /**\n * `@AuthWebhook(name)`: hand the app's {@link WebhookAuthCallback} the verbatim request and let it call the\n * VENDOR's own validator. Three ways to fail, all 401, all before the controller is entered:\n *\n * 1. NO hook bound — the endpoint is not enabled. Matches {@link JwtHook}'s documented behavior;\n * an unverified webhook must never be waved through because wiring was forgotten.\n * 2. NO raw request — the transport kept no bytes. `assertEveryWebhookEndpointRetainsRawBody`\n * normally makes this a startup error, so reaching it means either a hand-registered route or\n * an in-process caller (a spec) that published an HttpRequest with no {@link RawRequest}. The\n * message says which fix applies rather than leaving a bare 401.\n * 3. The hook threw — the signature did not verify.\n */\n private async enforceWebhook(name: string, meta: MethodMeta): Promise<void> {\n if (!this.webhookAuthCallback) {\n log.warn(\n `Refusing @AuthWebhook('${name}') endpoint ${meta.routeMeta.path}: no WebhookAuthCallback is bound. ` +\n `Bind one (options.bind(WEBHOOK_AUTH_CALLBACK).to(YourWebhookAuthCallback)) to enable webhook verification.`,\n );\n throw new HttpUnauthorizedError('Webhook auth is not enabled on this server');\n }\n const request = RequestContext.getRequest();\n const raw = request?.raw;\n if (!request || !raw) {\n log.warn(\n `Refusing @AuthWebhook('${name}') endpoint ${meta.routeMeta.path}: the inbound request carries ` +\n `no raw bytes. Declare @Endpoint(path, 'external', { calledBy: '${name}', rawBody: true }); a ` +\n `spec driving this route in-process must publish an HttpRequest built with a RawRequest.`,\n );\n throw new HttpUnauthorizedError('Webhook signature cannot be verified: no raw request was retained');\n }\n await this.webhookAuthCallback.verify(name, request, raw); // throws HttpUnauthorizedError to deny\n }\n\n /**\n * A body that failed to parse is held on the {@link RawRequest} and surfaces HERE, after auth, as\n * the 400 it always was — never before it.\n *\n * The order is the whole point. A malformed body from an unauthenticated caller must answer 401,\n * because \"your JSON was bad\" also says \"I got past auth\", and on a webhook endpoint — whose url\n * is public by construction — that is a free oracle for anyone probing. Parsing first made the\n * framework hand that out for nothing.\n *\n * Only routes that retain raw bytes can defer at all; every other route still fails at parse time\n * in the transport, exactly as before.\n */\n private rethrowDeferredBodyError(): void {\n const parseError = RequestContext.getRequest()?.raw?.bodyParseError;\n if (parseError) {\n throw new HttpBadRequestError('Request body is not valid JSON', undefined, undefined, parseError);\n }\n }\n\n /**\n * Does this mode authenticate the CALLER ITSELF (as opposed to a user, or nobody)? The INBOUND\n * twin of {@link DestinationTrust.forAuthMode}, and deliberately the same question: the client\n * omits trusted keys for a destination that cannot verify it, and the server rejects trusted keys\n * on a route that cannot verify the sender. One rule, two ends — if they disagreed, every call\n * would fail with a 401 that looks like a framework bug.\n *\n * - `oidc` / `shared-secret` → TRUE. An internal service is on the other end and the trusted\n * context it forwarded may be believed. This is what makes cross-service identity propagation\n * work.\n * - `jwt` / `public` → FALSE. A user JWT proves who the USER is; the SENDER is still whoever\n * holds the token, i.e. a browser.\n * - `local-only` → FALSE. It verifies WHERE WE ARE RUNNING, not who is calling — anything on\n * localhost reaches it, and it has no authenticator, so nothing can ever vouch for an inbound\n * trusted header. Any such header therefore rejects the request, which is exactly right.\n *\n * An exhaustive switch with NO `default`, returning on every branch: a sixth AuthMode kind is a\n * COMPILE error here (TS7030, no ending return) rather than silently landing on one posture. The\n * boolean expression this replaced defaulted every future mode to \"not verified\" — the safe\n * answer, but arrived at by accident rather than by decision.\n */\n // webpieces-disable no-function-outside-class -- static pure mapping from the AuthMode union, kept beside its only caller (mirrors DestinationTrust.forAuthMode)\n private static verifiesCaller(mode: AuthMode): boolean {\n switch (mode.kind) {\n case 'oidc':\n case 'shared-secret':\n return true;\n case 'jwt':\n case 'public':\n // `webhook` DOES authenticate its sender — but the sender is an outside VENDOR, not a\n // peer in this repo, and a vendor neither speaks nor forwards webpieces context headers.\n // So there is no forwarded identity to believe, and admitting one would mean trusting a\n // key a vendor's payload could carry. Same answer as the OUTBOUND half\n // (DestinationTrust.forAuthMode), which is the invariant that keeps the two ends agreeing.\n case 'webhook':\n case 'local-only':\n return false;\n }\n }\n\n /**\n * Decide what happens to the trusted keys that arrived on the WIRE and were held back by\n * {@link PendingWireTrust} (read that class for why they are held rather than written).\n *\n * `callerVerified` — the endpoint authenticated the SENDER (`@AuthOidc`, `@AuthSharedSecret`).\n * The sender is a service we trust, this is the service-to-service hop, and its forwarded\n * identity is admitted as-is. This is the case that makes propagating a verified userId across\n * internal services work.\n *\n * Otherwise the sender is a browser or anyone else with curl, and the ONLY acceptable inbound\n * trusted value is one the authenticator independently derived to the same value. Everything\n * else is rejected — see {@link requireVouched}.\n *\n * Runs AFTER the mode enforcement above, because that is what stamps the authenticator's own\n * values (`applyAuthValues`); comparing before it ran would compare against nothing.\n */\n private reconcileWireTrust(callerVerified: boolean): void {\n const pending = PendingWireTrust.takeAll();\n for (const item of pending) {\n if (callerVerified) {\n RequestContext.putTrusted(item.key, item.value);\n } else {\n this.requireVouched(item);\n }\n }\n }\n\n /**\n * On a browser-reachable route, an inbound trusted header must match what the authenticator\n * itself derived, or the request dies. Both failure shapes are rejections, not repairs:\n *\n * - DIFFERENT value — the caller said `alice`, the credential says `bob`. Silently letting the\n * credential win is not safe, because upstream rate limiters commonly bucket on the header\n * rather than the token: the request was already counted against the wrong principal, so\n * every forged header would be a free rate-limit bypass. No honest caller contradicts its own\n * credential.\n * - NOTHING vouched for it — nobody derived this key at all, so there is no evidence behind a\n * value a stranger typed. This is the common case, not the exotic one: the framework's\n * {@link DefaultJwtHook} stamps NO entries, and an app hook only stamps the keys it can prove,\n * so any other trusted key a caller sends lands here.\n *\n * The pending value is discarded either way — the throw is what leaves the request.\n */\n private requireVouched(item: PendingTrustedValue): void {\n const vouched = RequestContext.getTrusted(item.key);\n if (vouched === item.value) {\n return;\n }\n log.error(\n `Rejecting inbound '${item.key.httpHeader}': it is a TRUSTED context key, this route does ` +\n `not authenticate its caller, and the credential ` +\n (vouched === undefined ? 'vouched for no such value' : 'derived a different value') + '.',\n );\n throw new HttpUnauthorizedError(\n `Header '${item.key.httpHeader}' cannot be supplied by the caller on this endpoint`,\n );\n }\n\n /**\n * `@AuthLocalOnly`: serve only on a developer's machine, and off-local behave EXACTLY as if the\n * endpoint did not exist.\n *\n * WHY 404 AND NOT THE 403 APPS HAND-ROLLED. Off-local the route is not registered at all\n * (`ApiRoutingFactory` skips it), so the ordinary way to reach this path already answers 404. A\n * 403 from here would be a DIFFERENT answer from the same framework for the same endpoint, and\n * the difference is itself the leak: 403 confirms \"this path exists in production, you merely\n * lack permission\", which is a map of the dev-only surface for anyone probing. A local-only\n * endpoint should not admit it exists. Both gates therefore return the same 404, and this one is\n * the backstop for routes registered by hand through `RouteBuilder` rather than by\n * `ApiRoutingFactory`.\n *\n * The log line names WHICH reason applies, because \"you are deployed\" and \"nobody declared a\n * locality\" have completely different fixes and both look like a bare 404 from outside.\n */\n private enforceLocalOnly(meta: MethodMeta): void {\n if (RuntimeLocality.isLocalDevelopment()) {\n return;\n }\n log.warn(\n `Refusing @AuthLocalOnly endpoint ${meta.routeMeta.path}: ` +\n (RuntimeLocality.isDeclared()\n ? 'this process declared itself DEPLOYED.'\n : 'no startup declared a RuntimeLocality, so this process is treated as DEPLOYED. ' +\n 'Pass the locality into RuntimeSetupOptions if this really is a developer machine.'),\n );\n // Same shape as an unregistered route — see the method doc for why this is not a 403.\n throw new EndpointNotFoundError(`No endpoint at ${meta.routeMeta.path}`);\n }\n\n private enforceJwt(header: string | undefined, requirement: JwtRequirement): void {\n const token = this.credential(header, BEARER_SCHEME);\n if (!token) {\n throw new HttpUnauthorizedError('Authentication required');\n }\n if (!this.jwtHook) {\n throw new HttpUnauthorizedError('User-JWT auth is not enabled on this server');\n }\n const values = this.jwtHook.parseJwt(token); // AUTHENTICATE — throws HttpUnauthorizedError if invalid\n this.applyAuthValues(values);\n this.jwtHook.authorizeJwt(values, requirement); // AUTHORIZE — app policy; throws HttpForbiddenError to deny\n }\n\n private async enforceOidc(header: string | undefined, callers: string[]): Promise<void> {\n const token = this.credential(header, BEARER_SCHEME);\n if (!token) {\n throw new HttpUnauthorizedError('Missing OIDC bearer token for @AuthOidc endpoint');\n }\n // App-bound OidcHook overrides the caller policy; otherwise the framework default runs directly.\n if (this.oidcHook) {\n await this.oidcHook.verifyOidc(token, callers);\n } else {\n await this.oidcVerifier.verify(token, callers);\n }\n }\n\n /** `provided` is the Authorization bearer value — the secret itself, same header as a JWT. */\n private enforceSharedSecret(provided: string | undefined, secretKey: string): void {\n const accepted = this.authConfig?.sharedSecrets[secretKey];\n if (!accepted || !provided || !this.matchesEither(provided, accepted)) {\n throw new HttpUnauthorizedError('Invalid shared secret for @AuthSharedSecret endpoint');\n }\n }\n\n /** EITHER secret1 or secret2 passes — the rotation window. Constant-time on each non-empty slot. */\n private matchesEither(provided: string, accepted: SharedSecrets): boolean {\n return (\n (accepted.secret1 !== '' && this.constantTimeEquals(provided, accepted.secret1)) ||\n (accepted.secret2 !== '' && this.constantTimeEquals(provided, accepted.secret2))\n );\n }\n\n /** Parse a JWT if one is present, else do nothing — used on public routes; never throws. */\n private bestEffortJwt(header: string | undefined): void {\n const token = this.credential(header, BEARER_SCHEME);\n if (!this.jwtHook || !token) {\n return;\n }\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- best-effort on a public route: a bad/absent token just means \"not logged in\", must not fail the request\n try {\n this.applyAuthValues(this.jwtHook.parseJwt(token));\n } catch (err: unknown) {\n const error = toError(err);\n log.debug('Best-effort JWT parse on a public endpoint failed (treating as anonymous): ', error);\n }\n }\n\n /** Stamp the parsed user's context entries + the principal into the RequestContext. */\n private applyAuthValues(values: AuthValues): void {\n for (const entry of values.entries) {\n // ContextTuple.key is a TRUSTED key by type, so this is the one sanctioned write of a\n // proven identity: the app's JwtHook derived it from a credential we just verified.\n RequestContext.putTrusted(entry.key, entry.value);\n }\n RequestContext.put(PRINCIPAL_KEY, values);\n }\n\n /**\n * The credential value IF the header carries the expected scheme, else undefined.\n *\n * Strict: a bare value with no scheme, or a value under the WRONG scheme (a shared secret sent\n * where a JWT is expected), yields undefined and the caller 401s.\n */\n private credential(header: string | undefined, scheme: string): string | undefined {\n if (!header) {\n return undefined;\n }\n const prefix = `${scheme} `;\n return header.startsWith(prefix) ? header.substring(prefix.length) : undefined;\n }\n\n private constantTimeEquals(a: string, b: string): boolean {\n const bufA = Buffer.from(a, 'utf8');\n const bufB = Buffer.from(b, 'utf8');\n if (bufA.length !== bufB.length) {\n return false;\n }\n return timingSafeEqual(bufA, bufB);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"AuthFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-routing/src/filters/AuthFilter.ts"],"names":[],"mappings":";;;;;AAAA,yCAA6C;AAC7C,mCAAyC;AACzC,0DAA2H;AAC3H,oDAAyK;AACzK,sCAAwD;AAExD,8CAAmF;AACnF,4CAA4I;AAC5I,gEAA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,CA8XtB","sourcesContent":["import { inject, optional } from 'inversify';\nimport { timingSafeEqual } from 'crypto';\nimport { provideFrameworkSingleton, PendingWireTrust, PendingTrustedValue, RequestContext } from '@webpieces/core-context';\nimport { AuthMode, EndpointNotFoundError, HttpBadRequestError, HttpUnauthorizedError, JwtRequirement, LogManager, RuntimeLocality, toError } from '@webpieces/core-util';\nimport { Filter, WpResponse, Service } from '../Filter';\nimport { MethodMeta } from '../MethodMeta';\nimport { AuthConfig, AUTH_CONFIG, AuthValues, SharedSecrets } from '../AuthConfig';\nimport { ApiKeyHook, API_KEY_HOOK, JwtHook, JWT_HOOK, OidcHook, OIDC_HOOK, WebhookAuthCallback, WEBHOOK_AUTH_CALLBACK } from '../AuthHooks';\nimport { DefaultOidcVerifier } from '../DefaultOidcVerifier';\n\nconst log = LogManager.getLogger('AuthFilter');\n\n/**\n * The ONE credential header, read straight off the inbound HttpRequest.\n *\n * Deliberately NOT a ContextKey: a ContextKey with an httpHeader is a TRANSFERRED key, which would\n * put the caller's credential into RequestContext and hence onto every outbound call this service\n * makes, and onto every Cloud Task it enqueues. A credential belongs to ONE request hop.\n */\nconst AUTHORIZATION_HEADER = 'authorization';\n\n/**\n * The scheme (first word of the Authorization value) names WHICH credential follows, so a secret\n * can never be mistaken for a token, nor accepted where the other was expected:\n *\n * Authorization: Bearer <user JWT | service OIDC token>\n * Authorization: Webpieces <@AuthSharedSecret value>\n *\n * The scheme is REQUIRED. A bare value with no scheme is rejected.\n */\nconst BEARER_SCHEME = 'Bearer';\nconst SHARED_SECRET_SCHEME = 'Webpieces';\n\n/** Reserved context key holding the authenticated {@link AuthValues} (stamped after a jwt parse). */\nconst PRINCIPAL_KEY = '__webpieces_principal__';\n\n/**\n * AuthFilter - the ONE framework auth filter, auto-installed just below the error filter on every\n * route. It is TRANSPORT-NEUTRAL: it reads the raw credential from the {@link HttpRequest} in\n * RequestContext (never express), so the SAME check runs over HTTP and via createApiClient.\n *\n * It enforces the endpoint's AuthMode from separately-bound pieces, each OPTIONAL except the OIDC\n * default:\n * - shared-secret → constant-time compare vs the {@link AuthConfig} secret VALUE (state). No\n * AuthConfig bound → no accepted secret → fail fast (401).\n * - jwt → the bound {@link JwtHook} (`parseJwt` + `authorizeJwt`, both awaited — an app's\n * strategy may reach a JWKS or a datastore). No JwtHook bound → \"not enabled\"\n * (401): JWT needs an app secret + payload shape.\n * - oidc → the bound {@link OidcHook} if any, else the framework {@link DefaultOidcVerifier}\n * run DIRECTLY — so a server that wires NOTHING still verifies Google OIDC.\n * - webhook → the bound {@link WebhookAuthCallback} verifies the VENDOR's signature over the retained\n * raw request. No WebhookAuthCallback bound → 401, like jwt: an unverified webhook is\n * never waved through because wiring was forgotten.\n * - apikey → the bound {@link ApiKeyHook} looks the CUSTOMER's key up (async, over the whole\n * header set) and returns the context to seed. No ApiKeyHook bound → 401, like jwt.\n * - public → BEST-EFFORT jwt parse (only if a JwtHook is bound): stamp the user's context so\n * a logged-out page still knows who is logged in; never fails.\n * - local-only → serve only when {@link RuntimeLocality} says this process is a developer's\n * machine; otherwise 404, indistinguishable from the route not existing (which,\n * off-local, it does not — `ApiRoutingFactory` never registered it).\n *\n * Zero wiring = OIDC just works; an app only binds the hooks it actually uses.\n */\n@provideFrameworkSingleton()\n// webpieces-disable no-any-unknown -- Filter generic params use unknown for response flexibility\nexport class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>> {\n constructor(\n // Framework default, always available — verifies Google OIDC with zero app wiring.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- AuthFilter is DI-resolved via the esbuild/vitest path, which elides type-only imports (no design:paramtypes), so every param needs its explicit token\n @inject(DefaultOidcVerifier) private readonly oidcVerifier: DefaultOidcVerifier,\n // @optional: only bind an AuthConfig to enable @AuthSharedSecret endpoints.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- see above: explicit token required for DI-resolved param\n @optional() @inject(AUTH_CONFIG) private readonly authConfig?: AuthConfig,\n // @optional: only bind a JwtHook to enable @AuthJwt endpoints.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- see above: explicit token required for DI-resolved param\n @optional() @inject(JWT_HOOK) private readonly jwtHook?: JwtHook,\n // @optional: only bind an OidcHook to OVERRIDE the DefaultOidcVerifier caller policy.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- see above: explicit token required for DI-resolved param\n @optional() @inject(OIDC_HOOK) private readonly oidcHook?: OidcHook,\n // @optional: only bind a WebhookAuthCallback to enable @AuthWebhook endpoints. Unbound = every such\n // endpoint 401s, which is the ONE default that must not be the other way round.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- see above: explicit token required for DI-resolved param\n @optional() @inject(WEBHOOK_AUTH_CALLBACK) private readonly webhookAuthCallback?: WebhookAuthCallback,\n // @optional: only bind an ApiKeyHook to enable @AuthApiKey endpoints. Unbound = every such\n // endpoint 401s, for the same reason as the webhook hook above.\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- see above: explicit token required for DI-resolved param\n @optional() @inject(API_KEY_HOOK) private readonly apiKeyHook?: ApiKeyHook,\n ) {\n super();\n }\n\n // webpieces-disable no-any-unknown -- Filter generic params use unknown for response flexibility\n override async filter(\n meta: MethodMeta,\n nextFilter: Service<MethodMeta, WpResponse<unknown>>,\n ): Promise<WpResponse<unknown>> {\n const mode = meta.routeMeta.authMeta?.mode;\n const authHeader = RequestContext.getRequest()?.getHeader(AUTHORIZATION_HEADER);\n\n if (!mode || mode.kind === 'public') {\n // Public: best-effort parse so a logged-out page can still know the logged-in user.\n await this.bestEffortJwt(authHeader);\n this.reconcileWireTrust(/*callerVerified*/ false);\n this.rethrowDeferredBodyError();\n return nextFilter.invoke(meta);\n }\n\n switch (mode.kind) {\n case 'jwt':\n await this.enforceJwt(authHeader, mode.requirement);\n break;\n case 'oidc':\n await this.enforceOidc(authHeader, mode.callers);\n break;\n case 'shared-secret':\n this.enforceSharedSecret(this.credential(authHeader, SHARED_SECRET_SCHEME), mode.secretKey);\n break;\n case 'webhook':\n await this.enforceWebhook(mode.name, meta);\n break;\n case 'apikey':\n await this.enforceApiKey(mode.name, meta);\n break;\n case 'local-only':\n this.enforceLocalOnly(meta);\n break;\n }\n this.reconcileWireTrust(AuthFilter.verifiesCaller(mode));\n this.rethrowDeferredBodyError();\n return nextFilter.invoke(meta);\n }\n\n /**\n * `@AuthWebhook(name)`: hand the app's {@link WebhookAuthCallback} the verbatim request and let it call the\n * VENDOR's own validator. Three ways to fail, all 401, all before the controller is entered:\n *\n * 1. NO hook bound — the endpoint is not enabled. Matches {@link JwtHook}'s documented behavior;\n * an unverified webhook must never be waved through because wiring was forgotten.\n * 2. NO raw request — the transport kept no bytes. `assertEveryWebhookEndpointRetainsRawBody`\n * normally makes this a startup error, so reaching it means either a hand-registered route or\n * an in-process caller (a spec) that published an HttpRequest with no {@link RawRequest}. The\n * message says which fix applies rather than leaving a bare 401.\n * 3. The hook threw — the signature did not verify.\n */\n private async enforceWebhook(name: string, meta: MethodMeta): Promise<void> {\n if (!this.webhookAuthCallback) {\n log.warn(\n `Refusing @AuthWebhook('${name}') endpoint ${meta.routeMeta.path}: no WebhookAuthCallback is bound. ` +\n `Bind one (options.bind(WEBHOOK_AUTH_CALLBACK).to(YourWebhookAuthCallback)) to enable webhook verification.`,\n );\n throw new HttpUnauthorizedError('Webhook auth is not enabled on this server');\n }\n const request = RequestContext.getRequest();\n const raw = request?.raw;\n if (!request || !raw) {\n log.warn(\n `Refusing @AuthWebhook('${name}') endpoint ${meta.routeMeta.path}: the inbound request carries ` +\n `no raw bytes. Declare @Endpoint(path, 'external', { calledBy: '${name}', rawBody: true }); a ` +\n `spec driving this route in-process must publish an HttpRequest built with a RawRequest.`,\n );\n throw new HttpUnauthorizedError('Webhook signature cannot be verified: no raw request was retained');\n }\n await this.webhookAuthCallback.verify(name, request, raw); // throws HttpUnauthorizedError to deny\n }\n\n /**\n * `@AuthApiKey(name)`: hand the app's {@link ApiKeyHook} the regime name and the inbound headers and\n * let it look the CUSTOMER's key up. Three ways to fail, all 401, all before the controller:\n *\n * 1. NO hook bound — the endpoint is not enabled. Matches {@link JwtHook}'s documented behavior; an\n * unverified partner request must never be waved through because wiring was forgotten.\n * 2. NO inbound request in scope — there are no headers to read, so there is nothing to verify. That\n * means a caller drove this route without publishing an HttpRequest; the message says so rather\n * than leaving a bare 401.\n * 3. The hook threw — the key, or the key/organization pair, did not check out.\n *\n * On success the hook's {@link AuthValues} are stamped exactly as a jwt parse's are, which is what\n * puts the resolved organization into `RequestContext` for every downstream repository call.\n */\n private async enforceApiKey(name: string, meta: MethodMeta): Promise<void> {\n if (!this.apiKeyHook) {\n log.warn(\n `Refusing @AuthApiKey('${name}') endpoint ${meta.routeMeta.path}: no ApiKeyHook is bound. ` +\n `Bind one (options.bind(API_KEY_HOOK).to(YourApiKeyHook)) to enable api-key verification.`,\n );\n throw new HttpUnauthorizedError('API-key auth is not enabled on this server');\n }\n const request = RequestContext.getRequest();\n if (!request) {\n log.warn(\n `Refusing @AuthApiKey('${name}') endpoint ${meta.routeMeta.path}: no inbound HttpRequest is ` +\n `in scope, so the hook has no headers to read. A spec driving this route in-process must ` +\n `publish an HttpRequest carrying the api-key headers.`,\n );\n throw new HttpUnauthorizedError('API key cannot be verified: no inbound request was published');\n }\n // Throws HttpUnauthorizedError to deny. HttpRequest satisfies HeaderReader structurally.\n const values = await this.apiKeyHook.verifyApiKey(name, request);\n this.applyAuthValues(values);\n }\n\n /**\n * A body that failed to parse is held on the {@link RawRequest} and surfaces HERE, after auth, as\n * the 400 it always was — never before it.\n *\n * The order is the whole point. A malformed body from an unauthenticated caller must answer 401,\n * because \"your JSON was bad\" also says \"I got past auth\", and on a webhook endpoint — whose url\n * is public by construction — that is a free oracle for anyone probing. Parsing first made the\n * framework hand that out for nothing.\n *\n * Only routes that retain raw bytes can defer at all; every other route still fails at parse time\n * in the transport, exactly as before.\n */\n private rethrowDeferredBodyError(): void {\n const parseError = RequestContext.getRequest()?.raw?.bodyParseError;\n if (parseError) {\n throw new HttpBadRequestError('Request body is not valid JSON', undefined, undefined, parseError);\n }\n }\n\n /**\n * Does this mode authenticate the CALLER ITSELF (as opposed to a user, or nobody)? The INBOUND\n * twin of {@link DestinationTrust.forAuthMode}, and deliberately the same question: the client\n * omits trusted keys for a destination that cannot verify it, and the server rejects trusted keys\n * on a route that cannot verify the sender. One rule, two ends — if they disagreed, every call\n * would fail with a 401 that looks like a framework bug.\n *\n * - `oidc` / `shared-secret` → TRUE. An internal service is on the other end and the trusted\n * context it forwarded may be believed. This is what makes cross-service identity propagation\n * work.\n * - `jwt` / `public` → FALSE. A user JWT proves who the USER is; the SENDER is still whoever\n * holds the token, i.e. a browser.\n * - `local-only` → FALSE. It verifies WHERE WE ARE RUNNING, not who is calling — anything on\n * localhost reaches it, and it has no authenticator, so nothing can ever vouch for an inbound\n * trusted header. Any such header therefore rejects the request, which is exactly right.\n *\n * - `apikey` → FALSE. See the comment on that branch: the sender is a CUSTOMER.\n *\n * An exhaustive switch with NO `default`, returning on every branch: a new AuthMode kind is a\n * COMPILE error here (TS7030, no ending return) rather than silently landing on one posture. The\n * boolean expression this replaced defaulted every future mode to \"not verified\" — the safe\n * answer, but arrived at by accident rather than by decision.\n */\n // webpieces-disable no-function-outside-class -- static pure mapping from the AuthMode union, kept beside its only caller (mirrors DestinationTrust.forAuthMode)\n private static verifiesCaller(mode: AuthMode): boolean {\n switch (mode.kind) {\n case 'oidc':\n case 'shared-secret':\n return true;\n case 'jwt':\n case 'public':\n // `webhook` DOES authenticate its sender — but the sender is an outside VENDOR, not a\n // peer in this repo, and a vendor neither speaks nor forwards webpieces context headers.\n // So there is no forwarded identity to believe, and admitting one would mean trusting a\n // key a vendor's payload could carry. Same answer as the OUTBOUND half\n // (DestinationTrust.forAuthMode), which is the invariant that keeps the two ends agreeing.\n case 'webhook':\n // `apikey` authenticates the SENDER — but the sender is a CUSTOMER's codebase, not a peer\n // service in this repo, so its forwarded trusted context is exactly what must NOT be\n // believed: admitting it would let a partner assert another customer's org id on the wire.\n // The hook's OWN derived entries still land (applyAuthValues), and reconcileWireTrust then\n // admits an inbound trusted header only when the hook independently derived the same value.\n case 'apikey':\n case 'local-only':\n return false;\n }\n }\n\n /**\n * Decide what happens to the trusted keys that arrived on the WIRE and were held back by\n * {@link PendingWireTrust} (read that class for why they are held rather than written).\n *\n * `callerVerified` — the endpoint authenticated the SENDER **as a peer service** (`@AuthOidc`,\n * `@AuthSharedSecret`).\n * The sender is a service we trust, this is the service-to-service hop, and its forwarded\n * identity is admitted as-is. This is the case that makes propagating a verified userId across\n * internal services work.\n *\n * Otherwise the sender is a browser or anyone else with curl, and the ONLY acceptable inbound\n * trusted value is one the authenticator independently derived to the same value. Everything\n * else is rejected — see {@link requireVouched}.\n *\n * Runs AFTER the mode enforcement above, because that is what stamps the authenticator's own\n * values (`applyAuthValues`); comparing before it ran would compare against nothing.\n */\n private reconcileWireTrust(callerVerified: boolean): void {\n const pending = PendingWireTrust.takeAll();\n for (const item of pending) {\n if (callerVerified) {\n RequestContext.putTrusted(item.key, item.value);\n } else {\n this.requireVouched(item);\n }\n }\n }\n\n /**\n * On a browser-reachable route, an inbound trusted header must match what the authenticator\n * itself derived, or the request dies. Both failure shapes are rejections, not repairs:\n *\n * - DIFFERENT value — the caller said `alice`, the credential says `bob`. Silently letting the\n * credential win is not safe, because upstream rate limiters commonly bucket on the header\n * rather than the token: the request was already counted against the wrong principal, so\n * every forged header would be a free rate-limit bypass. No honest caller contradicts its own\n * credential.\n * - NOTHING vouched for it — nobody derived this key at all, so there is no evidence behind a\n * value a stranger typed. This is the common case, not the exotic one: the framework's\n * {@link DefaultJwtHook} stamps NO entries, and an app hook (jwt or api-key) only stamps the keys it can prove,\n * so any other trusted key a caller sends lands here.\n *\n * The pending value is discarded either way — the throw is what leaves the request.\n */\n private requireVouched(item: PendingTrustedValue): void {\n const vouched = RequestContext.getTrusted(item.key);\n if (vouched === item.value) {\n return;\n }\n log.error(\n `Rejecting inbound '${item.key.httpHeader}': it is a TRUSTED context key, this route does ` +\n `not authenticate its caller, and the credential ` +\n (vouched === undefined ? 'vouched for no such value' : 'derived a different value') + '.',\n );\n throw new HttpUnauthorizedError(\n `Header '${item.key.httpHeader}' cannot be supplied by the caller on this endpoint`,\n );\n }\n\n /**\n * `@AuthLocalOnly`: serve only on a developer's machine, and off-local behave EXACTLY as if the\n * endpoint did not exist.\n *\n * WHY 404 AND NOT THE 403 APPS HAND-ROLLED. Off-local the route is not registered at all\n * (`ApiRoutingFactory` skips it), so the ordinary way to reach this path already answers 404. A\n * 403 from here would be a DIFFERENT answer from the same framework for the same endpoint, and\n * the difference is itself the leak: 403 confirms \"this path exists in production, you merely\n * lack permission\", which is a map of the dev-only surface for anyone probing. A local-only\n * endpoint should not admit it exists. Both gates therefore return the same 404, and this one is\n * the backstop for routes registered by hand through `RouteBuilder` rather than by\n * `ApiRoutingFactory`.\n *\n * The log line names WHICH reason applies, because \"you are deployed\" and \"nobody declared a\n * locality\" have completely different fixes and both look like a bare 404 from outside.\n */\n private enforceLocalOnly(meta: MethodMeta): void {\n if (RuntimeLocality.isLocalDevelopment()) {\n return;\n }\n log.warn(\n `Refusing @AuthLocalOnly endpoint ${meta.routeMeta.path}: ` +\n (RuntimeLocality.isDeclared()\n ? 'this process declared itself DEPLOYED.'\n : 'no startup declared a RuntimeLocality, so this process is treated as DEPLOYED. ' +\n 'Pass the locality into RuntimeSetupOptions if this really is a developer machine.'),\n );\n // Same shape as an unregistered route — see the method doc for why this is not a 403.\n throw new EndpointNotFoundError(`No endpoint at ${meta.routeMeta.path}`);\n }\n\n private async enforceJwt(header: string | undefined, requirement: JwtRequirement): Promise<void> {\n const token = this.credential(header, BEARER_SCHEME);\n if (!token) {\n throw new HttpUnauthorizedError('Authentication required');\n }\n if (!this.jwtHook) {\n throw new HttpUnauthorizedError('User-JWT auth is not enabled on this server');\n }\n const values = await this.jwtHook.parseJwt(token); // AUTHENTICATE — throws HttpUnauthorizedError if invalid\n this.applyAuthValues(values);\n await this.jwtHook.authorizeJwt(values, requirement); // AUTHORIZE — app policy; throws HttpForbiddenError to deny\n }\n\n private async enforceOidc(header: string | undefined, callers: string[]): Promise<void> {\n const token = this.credential(header, BEARER_SCHEME);\n if (!token) {\n throw new HttpUnauthorizedError('Missing OIDC bearer token for @AuthOidc endpoint');\n }\n // App-bound OidcHook overrides the caller policy; otherwise the framework default runs directly.\n if (this.oidcHook) {\n await this.oidcHook.verifyOidc(token, callers);\n } else {\n await this.oidcVerifier.verify(token, callers);\n }\n }\n\n /** `provided` is the Authorization bearer value — the secret itself, same header as a JWT. */\n private enforceSharedSecret(provided: string | undefined, secretKey: string): void {\n const accepted = this.authConfig?.sharedSecrets[secretKey];\n if (!accepted || !provided || !this.matchesEither(provided, accepted)) {\n throw new HttpUnauthorizedError('Invalid shared secret for @AuthSharedSecret endpoint');\n }\n }\n\n /** EITHER secret1 or secret2 passes — the rotation window. Constant-time on each non-empty slot. */\n private matchesEither(provided: string, accepted: SharedSecrets): boolean {\n return (\n (accepted.secret1 !== '' && this.constantTimeEquals(provided, accepted.secret1)) ||\n (accepted.secret2 !== '' && this.constantTimeEquals(provided, accepted.secret2))\n );\n }\n\n /** Parse a JWT if one is present, else do nothing — used on public routes; never throws. */\n private async bestEffortJwt(header: string | undefined): Promise<void> {\n const token = this.credential(header, BEARER_SCHEME);\n if (!this.jwtHook || !token) {\n return;\n }\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- best-effort on a public route: a bad/absent token just means \"not logged in\", must not fail the request\n try {\n this.applyAuthValues(await this.jwtHook.parseJwt(token));\n } catch (err: unknown) {\n const error = toError(err);\n log.debug('Best-effort JWT parse on a public endpoint failed (treating as anonymous): ', error);\n }\n }\n\n /** Stamp the authenticated caller's context entries + the principal into the RequestContext. */\n private applyAuthValues(values: AuthValues): void {\n for (const entry of values.entries) {\n // ContextTuple.key is a TRUSTED key by type, so this is the one sanctioned write of a\n // proven identity: the app's JwtHook or ApiKeyHook derived it from a credential we just verified.\n RequestContext.putTrusted(entry.key, entry.value);\n }\n RequestContext.put(PRINCIPAL_KEY, values);\n }\n\n /**\n * The credential value IF the header carries the expected scheme, else undefined.\n *\n * Strict: a bare value with no scheme, or a value under the WRONG scheme (a shared secret sent\n * where a JWT is expected), yields undefined and the caller 401s.\n */\n private credential(header: string | undefined, scheme: string): string | undefined {\n if (!header) {\n return undefined;\n }\n const prefix = `${scheme} `;\n return header.startsWith(prefix) ? header.substring(prefix.length) : undefined;\n }\n\n private constantTimeEquals(a: string, b: string): boolean {\n const bufA = Buffer.from(a, 'utf8');\n const bufB = Buffer.from(b, 'utf8');\n if (bufA.length !== bufB.length) {\n return false;\n }\n return timingSafeEqual(bufA, bufB);\n }\n}\n"]}
|
package/src/index.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export { AppModules, RouteModule } from './AppModules';
|
|
|
16
16
|
export { ApiFactory } from './ApiFactory';
|
|
17
17
|
export { ApiClient, ApiClientProxy } from './ApiClient';
|
|
18
18
|
export { AuthConfig, AUTH_CONFIG, AuthValues, SharedSecrets } from './AuthConfig';
|
|
19
|
-
export { JwtHook, JWT_HOOK, OidcHook, OIDC_HOOK, WebhookAuthCallback, WEBHOOK_AUTH_CALLBACK } from './AuthHooks';
|
|
19
|
+
export { JwtHook, JWT_HOOK, OidcHook, OIDC_HOOK, WebhookAuthCallback, WEBHOOK_AUTH_CALLBACK, ApiKeyHook, API_KEY_HOOK, HeaderReader, } from './AuthHooks';
|
|
20
20
|
export { DefaultOidcVerifier } from './DefaultOidcVerifier';
|
|
21
21
|
export { DefaultJwtHook } from './DefaultJwtHook';
|
|
22
22
|
export { WebpiecesRouter, WebpiecesRouterFactory, WebpiecesRouterOptions } from './WebpiecesRouter';
|
package/src/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.AuthConfig = exports.ApiClient = exports.FilterMatcher = exports.LogApiFilter = exports.RouteHandler = exports.MethodMeta = exports.FilterChain = exports.WpResponse = exports.Filter = exports.RawRequest = exports.HttpRequest = exports.FilterDefinition = exports.RouteDefinition = exports.ApiRoutingFactory = exports.buildFrameworkModule = exports.provideFrameworkSingletonDefaultForApi = exports.provideFrameworkSingleton = exports.provideSingletonDefaultForApi = exports.ROUTING_METADATA_KEYS = exports.SourceFile = exports.isDocumentDesign = exports.DocumentDesign = exports.METADATA_KEYS = exports.RouteMetadata = exports.AuthMeta = exports.getQueueName = exports.assertPubSubConventions = exports.assertApiKind = exports.getApiKind = exports.assertEveryEndpointHasAuthMode = exports.getAuthMode = exports.getAuthMeta = exports.isApiPath = exports.isRawBody = exports.isFormPost = exports.getEndpointOptions = exports.getEndpoints = exports.getApiPath = exports.Queue = exports.PubSub = exports.Rpc = exports.AuthLocalOnly = exports.AuthWebhook = exports.AuthSharedSecret = exports.AuthOidc = exports.rolesRequired = exports.AuthJwt = exports.Public = exports.Endpoint = exports.ApiPath = void 0;
|
|
4
|
-
exports.WEBPIECES_CONFIG_TOKEN = exports.WebpiecesConfig = exports.RuntimeSetupOptions = exports.setupRuntime = exports.WebpiecesRouterFactory = exports.WebpiecesRouter = exports.DefaultJwtHook = exports.DefaultOidcVerifier = exports.WEBHOOK_AUTH_CALLBACK = exports.WebhookAuthCallback = exports.OIDC_HOOK = exports.OidcHook = exports.JWT_HOOK = exports.JwtHook = exports.SharedSecrets = exports.AuthValues = exports.AUTH_CONFIG = void 0;
|
|
4
|
+
exports.WEBPIECES_CONFIG_TOKEN = exports.WebpiecesConfig = exports.RuntimeSetupOptions = exports.setupRuntime = exports.WebpiecesRouterFactory = exports.WebpiecesRouter = exports.DefaultJwtHook = exports.DefaultOidcVerifier = exports.API_KEY_HOOK = exports.ApiKeyHook = exports.WEBHOOK_AUTH_CALLBACK = exports.WebhookAuthCallback = exports.OIDC_HOOK = exports.OidcHook = exports.JWT_HOOK = exports.JwtHook = exports.SharedSecrets = exports.AuthValues = exports.AUTH_CONFIG = void 0;
|
|
5
5
|
// Re-export API decorators from core-util for convenience
|
|
6
6
|
var core_util_1 = require("@webpieces/core-util");
|
|
7
7
|
Object.defineProperty(exports, "ApiPath", { enumerable: true, get: function () { return core_util_1.ApiPath; } });
|
|
@@ -82,7 +82,8 @@ var ApiClient_1 = require("./ApiClient");
|
|
|
82
82
|
Object.defineProperty(exports, "ApiClient", { enumerable: true, get: function () { return ApiClient_1.ApiClient; } });
|
|
83
83
|
// Auth: the app-provided, container-bound pieces the framework AuthFilter injects.
|
|
84
84
|
// - AuthConfig: shared-secret STATE (@AuthSharedSecret values).
|
|
85
|
-
// - JwtHook / OidcHook: OPTIONAL verification mechanisms
|
|
85
|
+
// - JwtHook / OidcHook / WebhookAuthCallback / ApiKeyHook: OPTIONAL verification mechanisms
|
|
86
|
+
// (bind only what you use; unbound means the matching endpoints 401, never open).
|
|
86
87
|
// - DefaultOidcVerifier: the built-in Google OIDC verifier used when no OidcHook is bound.
|
|
87
88
|
var AuthConfig_1 = require("./AuthConfig");
|
|
88
89
|
Object.defineProperty(exports, "AuthConfig", { enumerable: true, get: function () { return AuthConfig_1.AuthConfig; } });
|
|
@@ -96,6 +97,8 @@ Object.defineProperty(exports, "OidcHook", { enumerable: true, get: function ()
|
|
|
96
97
|
Object.defineProperty(exports, "OIDC_HOOK", { enumerable: true, get: function () { return AuthHooks_1.OIDC_HOOK; } });
|
|
97
98
|
Object.defineProperty(exports, "WebhookAuthCallback", { enumerable: true, get: function () { return AuthHooks_1.WebhookAuthCallback; } });
|
|
98
99
|
Object.defineProperty(exports, "WEBHOOK_AUTH_CALLBACK", { enumerable: true, get: function () { return AuthHooks_1.WEBHOOK_AUTH_CALLBACK; } });
|
|
100
|
+
Object.defineProperty(exports, "ApiKeyHook", { enumerable: true, get: function () { return AuthHooks_1.ApiKeyHook; } });
|
|
101
|
+
Object.defineProperty(exports, "API_KEY_HOOK", { enumerable: true, get: function () { return AuthHooks_1.API_KEY_HOOK; } });
|
|
99
102
|
var DefaultOidcVerifier_1 = require("./DefaultOidcVerifier");
|
|
100
103
|
Object.defineProperty(exports, "DefaultOidcVerifier", { enumerable: true, get: function () { return DefaultOidcVerifier_1.DefaultOidcVerifier; } });
|
|
101
104
|
// DefaultJwtHook: batteries-included HS256 JwtHook — `new DefaultJwtHook(secret)` and go.
|
package/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/index.ts"],"names":[],"mappings":";;;;AAAA,0DAA0D;AAC1D,kDAkC8B;AAjC1B,oGAAA,OAAO,OAAA;AACP,qGAAA,QAAQ,OAAA;AACR,mGAAA,MAAM,OAAA;AACN,oGAAA,OAAO,OAAA;AACP,0GAAA,aAAa,OAAA;AACb,qGAAA,QAAQ,OAAA;AACR,6GAAA,gBAAgB,OAAA;AAChB,wGAAA,WAAW,OAAA;AACX,0GAAA,aAAa,OAAA;AACb,gGAAA,GAAG,OAAA;AACH,mGAAA,MAAM,OAAA;AACN,kGAAA,KAAK,OAAA;AACL,uGAAA,UAAU,OAAA;AACV,yGAAA,YAAY,OAAA;AACZ,+GAAA,kBAAkB,OAAA;AAClB,uGAAA,UAAU,OAAA;AACV,sGAAA,SAAS,OAAA;AACT,sGAAA,SAAS,OAAA;AACT,wGAAA,WAAW,OAAA;AACX,wGAAA,WAAW,OAAA;AACX,2HAAA,8BAA8B,OAAA;AAC9B,uGAAA,UAAU,OAAA;AACV,0GAAA,aAAa,OAAA;AACb,oHAAA,uBAAuB,OAAA;AACvB,yGAAA,YAAY,OAAA;AACZ,qGAAA,QAAQ,OAAA;AACR,0GAAA,aAAa,OAAA;AACb,0GAAA,aAAa,OAAA;AAEb,2EAA2E;AAC3E,oCAAoC;AACpC,2GAAA,cAAc,OAAA;AACd,6GAAA,gBAAgB,OAAA;AAIpB,+CAA+C;AAC/C,2CAGsB;AAFlB,wGAAA,UAAU,OAAA;AACV,mHAAA,qBAAqB,OAAA;AAGzB,iFAAiF;AACjF,wDAAwE;AAA/D,6HAAA,6BAA6B,OAAA;AACtC,gGAAgG;AAChG,wDAIiC;AAH7B,yHAAA,yBAAyB,OAAA;AACzB,sIAAA,sCAAsC,OAAA;AACtC,oHAAA,oBAAoB,OAAA;AAGxB,yDAAmE;AAA1D,sHAAA,iBAAiB,OAAA;AAE1B,qBAAqB;AACrB,2CAKsB;AAFlB,6GAAA,eAAe,OAAA;AACf,8GAAA,gBAAgB,OAAA;AAGpB,sFAAsF;AACtF,+FAA+F;AAC/F,wDAAkE;AAAzD,2GAAA,WAAW,OAAA;AAAE,0GAAA,UAAU,OAAA;AAEhC,qFAAqF;AACrF,mCAAuD;AAA9C,gGAAA,MAAM,OAAA;AAAE,oGAAA,UAAU,OAAA;AAC3B,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AACpB,2CAA0C;AAAjC,wGAAA,UAAU,OAAA;AACnB,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AAErB,wFAAwF;AACxF,0FAA0F;AAC1F,uDAAsD;AAA7C,4GAAA,YAAY,OAAA;AAErB,oFAAoF;AACpF,sFAAsF;AAEtF,kBAAkB;AAClB,iDAA4D;AAAnD,8GAAA,aAAa,OAAA;AAOtB,yCAAwD;AAA/C,sGAAA,SAAS,OAAA;AAElB,mFAAmF;AACnF,iEAAiE;AACjE,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/index.ts"],"names":[],"mappings":";;;;AAAA,0DAA0D;AAC1D,kDAkC8B;AAjC1B,oGAAA,OAAO,OAAA;AACP,qGAAA,QAAQ,OAAA;AACR,mGAAA,MAAM,OAAA;AACN,oGAAA,OAAO,OAAA;AACP,0GAAA,aAAa,OAAA;AACb,qGAAA,QAAQ,OAAA;AACR,6GAAA,gBAAgB,OAAA;AAChB,wGAAA,WAAW,OAAA;AACX,0GAAA,aAAa,OAAA;AACb,gGAAA,GAAG,OAAA;AACH,mGAAA,MAAM,OAAA;AACN,kGAAA,KAAK,OAAA;AACL,uGAAA,UAAU,OAAA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ACpF,sFAAsF;AAEtF,kBAAkB;AAClB,iDAA4D;AAAnD,8GAAA,aAAa,OAAA;AAOtB,yCAAwD;AAA/C,sGAAA,SAAS,OAAA;AAElB,mFAAmF;AACnF,iEAAiE;AACjE,6FAA6F;AAC7F,qFAAqF;AACrF,4FAA4F;AAC5F,2CAAkF;AAAzE,wGAAA,UAAU,OAAA;AAAE,yGAAA,WAAW,OAAA;AAAE,wGAAA,UAAU,OAAA;AAAE,2GAAA,aAAa,OAAA;AAC3D,yCAKqB;AAJjB,oGAAA,OAAO,OAAA;AAAE,qGAAA,QAAQ,OAAA;AACjB,qGAAA,QAAQ,OAAA;AAAE,sGAAA,SAAS,OAAA;AACnB,gHAAA,mBAAmB,OAAA;AAAE,kHAAA,qBAAqB,OAAA;AAC1C,uGAAA,UAAU,OAAA;AAAE,yGAAA,YAAY,OAAA;AAE5B,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,0FAA0F;AAC1F,mDAAkD;AAAzC,gHAAA,cAAc,OAAA;AAEvB,kEAAkE;AAElE,0FAA0F;AAC1F,qDAAoG;AAA3F,kHAAA,eAAe,OAAA;AAAE,yHAAA,sBAAsB,OAAA;AAEhD,8FAA8F;AAC9F,kGAAkG;AAClG,+CAAmE;AAA1D,4GAAA,YAAY,OAAA;AAAE,mHAAA,mBAAmB,OAAA;AAE1C,uBAAuB;AACvB,qDAA4E;AAAnE,kHAAA,eAAe,OAAA;AAAE,yHAAA,sBAAsB,OAAA","sourcesContent":["// Re-export API decorators from core-util for convenience\nexport {\n ApiPath,\n Endpoint,\n Public,\n AuthJwt,\n rolesRequired,\n AuthOidc,\n AuthSharedSecret,\n AuthWebhook,\n AuthLocalOnly,\n Rpc,\n PubSub,\n Queue,\n getApiPath,\n getEndpoints,\n getEndpointOptions,\n isFormPost,\n isRawBody,\n isApiPath,\n getAuthMeta,\n getAuthMode,\n assertEveryEndpointHasAuthMode,\n getApiKind,\n assertApiKind,\n assertPubSubConventions,\n getQueueName,\n AuthMeta,\n RouteMetadata,\n METADATA_KEYS,\n ValidateImplementation,\n // @DocumentDesign moved to core-util (design-root marker, browser + Node);\n // re-exported here for back-compat.\n DocumentDesign,\n isDocumentDesign,\n} from '@webpieces/core-util';\nexport type { AuthMode, ApiKind, EndpointOptions } from '@webpieces/core-util';\n\n// Server-side routing decorators and utilities\nexport {\n SourceFile,\n ROUTING_METADATA_KEYS,\n} from './decorators';\n\n// DI provider decorators moved to core-context; re-exported here for back-compat\nexport { provideSingletonDefaultForApi } from '@webpieces/core-context';\n// Framework-only DI registry (packages/** framework classes use these; see frameworkProvide.ts)\nexport {\n provideFrameworkSingleton,\n provideFrameworkSingletonDefaultForApi,\n buildFrameworkModule,\n} from '@webpieces/core-context';\n\nexport { ApiRoutingFactory, ClassType } from './ApiRoutingFactory';\n\n// Core routing types\nexport {\n Routes,\n RouteBuilder,\n RouteDefinition,\n FilterDefinition,\n} from './WebAppMeta';\n\n// The transport-neutral request type (defined in core-context; this is http-routing's\n// public request — a transport adapter builds one and the chain reads it from RequestContext).\nexport { HttpRequest, RawRequest } from '@webpieces/core-context';\n\n// Filter-chain primitives (absorbed from the former @webpieces/http-filters package)\nexport { Filter, WpResponse, Service } from './Filter';\nexport { FilterChain } from './FilterChain';\nexport { MethodMeta } from './MethodMeta';\nexport { RouteHandler } from './RouteHandler';\n\n// LogApiFilter: the fixed OUTERMOST framework filter (auto-installed at 1,000,000 above\n// AuthFilter). Exported for reference/testing only — apps must NOT install it themselves.\nexport { LogApiFilter } from './filters/LogApiFilter';\n\n// RouteBuilderImpl (the route table + chain composer) is now INTERNAL — it is never\n// handed to upper layers. The express layer consumes ApiFactory.apiClients() instead.\n\n// Filter matching\nexport { FilterMatcher, HttpFilter } from './FilterMatcher';\n\n// The app's server-surface declaration: DI binding modules + route groups + headers.\nexport { AppModules, RouteModule } from './AppModules';\n\n// The public API-surface abstraction: declare routes/filters, get them back as ApiClient[].\nexport { ApiFactory } from './ApiFactory';\nexport { ApiClient, ApiClientProxy } from './ApiClient';\n\n// Auth: the app-provided, container-bound pieces the framework AuthFilter injects.\n// - AuthConfig: shared-secret STATE (@AuthSharedSecret values).\n// - JwtHook / OidcHook / WebhookAuthCallback / ApiKeyHook: OPTIONAL verification mechanisms\n// (bind only what you use; unbound means the matching endpoints 401, never open).\n// - DefaultOidcVerifier: the built-in Google OIDC verifier used when no OidcHook is bound.\nexport { AuthConfig, AUTH_CONFIG, AuthValues, SharedSecrets } from './AuthConfig';\nexport {\n JwtHook, JWT_HOOK,\n OidcHook, OIDC_HOOK,\n WebhookAuthCallback, WEBHOOK_AUTH_CALLBACK,\n ApiKeyHook, API_KEY_HOOK, HeaderReader,\n} from './AuthHooks';\nexport { DefaultOidcVerifier } from './DefaultOidcVerifier';\n// DefaultJwtHook: batteries-included HS256 JwtHook — `new DefaultJwtHook(secret)` and go.\nexport { DefaultJwtHook } from './DefaultJwtHook';\n\n// Above-boundary context setup shared by every transport adapter.\n\n// Node-only router (the express-free heart: container + filter chain + in-process client)\nexport { WebpiecesRouter, WebpiecesRouterFactory, WebpiecesRouterOptions } from './WebpiecesRouter';\n\n// The ONE transport-free startup sequence (headers → logging → router → routes) → ApiFactory.\n// Reusable by any company/app and any framework adapter; a company wraps it with its own headers.\nexport { setupRuntime, RuntimeSetupOptions } from './setupRuntime';\n\n// Server configuration\nexport { WebpiecesConfig, WEBPIECES_CONFIG_TOKEN } from './WebpiecesConfig';\n"]}
|