@webpieces/http-routing 0.4.664 → 0.4.666
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 +36 -7
- package/src/AuthConfig.js +41 -8
- package/src/AuthConfig.js.map +1 -1
- package/src/AuthHooks.d.ts +45 -37
- package/src/AuthHooks.js +11 -10
- package/src/AuthHooks.js.map +1 -1
- package/src/AuthHooksCompileAssertions.d.ts +31 -0
- package/src/AuthHooksCompileAssertions.js +85 -0
- package/src/AuthHooksCompileAssertions.js.map +1 -0
- package/src/DefaultJwtHook.d.ts +2 -2
- package/src/DefaultJwtHook.js +1 -1
- package/src/DefaultJwtHook.js.map +1 -1
- package/src/JwtHookCompileAssertions.js +4 -4
- package/src/JwtHookCompileAssertions.js.map +1 -1
- package/src/filters/AuthFilter.d.ts +20 -5
- package/src/filters/AuthFilter.js +41 -21
- package/src/filters/AuthFilter.js.map +1 -1
- package/src/index.d.ts +3 -3
- package/src/index.js +3 -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.666",
|
|
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.666",
|
|
26
|
+
"@webpieces/core-util": "0.4.666",
|
|
27
|
+
"@webpieces/gcp-identity": "0.4.666",
|
|
28
28
|
"inversify": "7.10.4",
|
|
29
29
|
"jsonwebtoken": "9.0.2",
|
|
30
30
|
"minimatch": "10.0.1"
|
package/src/AuthConfig.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ContextTuple } from '@webpieces/core-util';
|
|
1
|
+
import { ContextKey, ContextTuple } from '@webpieces/core-util';
|
|
2
2
|
/**
|
|
3
3
|
* SharedSecrets - the accepted values for ONE `@AuthSharedSecret(name)`. BOTH secret1 AND secret2
|
|
4
4
|
* are accepted — this is what makes zero-downtime ROTATION possible:
|
|
@@ -15,19 +15,48 @@ export declare class SharedSecrets {
|
|
|
15
15
|
constructor(secret1: string, secret2: string);
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
18
|
+
* AuthenticatedCaller - what an authenticator PROVED about the caller of ONE request. Every hook
|
|
19
|
+
* that authenticates resolves to this: {@link JwtHook.parseJwt}, {@link ApiKeyHook.verifyApiKey} and
|
|
20
|
+
* {@link WebhookAuthCallback.verifyWebhook}. Four fields, three jobs:
|
|
21
|
+
*
|
|
22
|
+
* - `userId` — WHO the caller is, as the credential proved it.
|
|
23
|
+
* - `roles` / `claims` — the AUTHORIZATION inputs: `roles` is what the framework's own any-of check
|
|
24
|
+
* reads, `claims` is the raw payload an app's {@link JwtHook.authorizeJwt}
|
|
25
|
+
* override reads for app-defined requirements (inOrg, tenant, ...).
|
|
26
|
+
* - `entries` — the TRUSTED CONTEXT to seed. The framework writes each one with
|
|
27
|
+
* {@link RequestContext.putTrusted}, so return only what THIS authenticator
|
|
28
|
+
* derived from the credential it just verified.
|
|
29
|
+
*
|
|
30
|
+
* NAMING, said out loud so it is not "fixed" back: it is deliberately NOT a `TrustedContextMap`.
|
|
31
|
+
* Three of the four fields are not context, and it is not a Map — it is the authenticated caller,
|
|
32
|
+
* and the context is one thing it carries.
|
|
33
|
+
*
|
|
34
|
+
* Data-only structure (a class, per the guidelines).
|
|
23
35
|
*/
|
|
24
|
-
export declare class
|
|
36
|
+
export declare class AuthenticatedCaller {
|
|
25
37
|
readonly userId: string;
|
|
26
38
|
readonly roles: string[];
|
|
27
39
|
readonly entries: ContextTuple[];
|
|
28
40
|
readonly claims: Record<string, unknown>;
|
|
29
41
|
constructor(userId: string, roles?: string[], entries?: ContextTuple[], claims?: Record<string, unknown>);
|
|
30
42
|
}
|
|
43
|
+
/**
|
|
44
|
+
* The context slot holding the {@link AuthenticatedCaller} the framework {@link AuthFilter} resolved
|
|
45
|
+
* for this request. A real TRUSTED {@link ContextKey}, written with `RequestContext.putTrusted` and
|
|
46
|
+
* read with `RequestContext.getTrusted` — it replaces a raw `'__webpieces_principal__'` string that
|
|
47
|
+
* was the one place in the codebase bypassing the typed context layer.
|
|
48
|
+
*
|
|
49
|
+
* `httpHeader` is deliberately UNDEFINED, so the key is context-only and NEVER travels. Two reasons,
|
|
50
|
+
* and either alone is decisive: the value is an OBJECT, which no HTTP header can carry; and a
|
|
51
|
+
* principal is proof THIS hop's authenticator produced, so forwarding it would hand the next service
|
|
52
|
+
* a "proven" caller nothing on that hop verified. The individual facts a downstream service needs
|
|
53
|
+
* (userId, orgId, roles) already propagate as their own transferred keys in
|
|
54
|
+
* {@link WebpiecesCoreHeaders}, gated by the caller-verified rule.
|
|
55
|
+
*
|
|
56
|
+
* `isLogged` is FALSE: it is an object carrying the raw credential claims, which has no business
|
|
57
|
+
* being serialized into a log line.
|
|
58
|
+
*/
|
|
59
|
+
export declare const AUTHENTICATED_CALLER_KEY: ContextKey<AuthenticatedCaller, "trusted">;
|
|
31
60
|
/**
|
|
32
61
|
* AuthConfig - the app-provided SHARED-SECRET state the framework {@link AuthFilter} reads to
|
|
33
62
|
* enforce `@AuthSharedSecret(name)` endpoints. It holds ONLY the accepted secret values (STATE) —
|
package/src/AuthConfig.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.AUTH_CONFIG = exports.AuthConfig = exports.
|
|
3
|
+
exports.AUTH_CONFIG = exports.AuthConfig = exports.AUTHENTICATED_CALLER_KEY = exports.AuthenticatedCaller = exports.SharedSecrets = void 0;
|
|
4
|
+
const core_util_1 = require("@webpieces/core-util");
|
|
4
5
|
/**
|
|
5
6
|
* SharedSecrets - the accepted values for ONE `@AuthSharedSecret(name)`. BOTH secret1 AND secret2
|
|
6
7
|
* are accepted — this is what makes zero-downtime ROTATION possible:
|
|
@@ -21,13 +22,25 @@ class SharedSecrets {
|
|
|
21
22
|
}
|
|
22
23
|
exports.SharedSecrets = SharedSecrets;
|
|
23
24
|
/**
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
25
|
+
* AuthenticatedCaller - what an authenticator PROVED about the caller of ONE request. Every hook
|
|
26
|
+
* that authenticates resolves to this: {@link JwtHook.parseJwt}, {@link ApiKeyHook.verifyApiKey} and
|
|
27
|
+
* {@link WebhookAuthCallback.verifyWebhook}. Four fields, three jobs:
|
|
28
|
+
*
|
|
29
|
+
* - `userId` — WHO the caller is, as the credential proved it.
|
|
30
|
+
* - `roles` / `claims` — the AUTHORIZATION inputs: `roles` is what the framework's own any-of check
|
|
31
|
+
* reads, `claims` is the raw payload an app's {@link JwtHook.authorizeJwt}
|
|
32
|
+
* override reads for app-defined requirements (inOrg, tenant, ...).
|
|
33
|
+
* - `entries` — the TRUSTED CONTEXT to seed. The framework writes each one with
|
|
34
|
+
* {@link RequestContext.putTrusted}, so return only what THIS authenticator
|
|
35
|
+
* derived from the credential it just verified.
|
|
36
|
+
*
|
|
37
|
+
* NAMING, said out loud so it is not "fixed" back: it is deliberately NOT a `TrustedContextMap`.
|
|
38
|
+
* Three of the four fields are not context, and it is not a Map — it is the authenticated caller,
|
|
39
|
+
* and the context is one thing it carries.
|
|
40
|
+
*
|
|
41
|
+
* Data-only structure (a class, per the guidelines).
|
|
29
42
|
*/
|
|
30
|
-
class
|
|
43
|
+
class AuthenticatedCaller {
|
|
31
44
|
userId;
|
|
32
45
|
roles;
|
|
33
46
|
entries;
|
|
@@ -41,7 +54,27 @@ class AuthValues {
|
|
|
41
54
|
this.claims = claims;
|
|
42
55
|
}
|
|
43
56
|
}
|
|
44
|
-
exports.
|
|
57
|
+
exports.AuthenticatedCaller = AuthenticatedCaller;
|
|
58
|
+
/**
|
|
59
|
+
* The context slot holding the {@link AuthenticatedCaller} the framework {@link AuthFilter} resolved
|
|
60
|
+
* for this request. A real TRUSTED {@link ContextKey}, written with `RequestContext.putTrusted` and
|
|
61
|
+
* read with `RequestContext.getTrusted` — it replaces a raw `'__webpieces_principal__'` string that
|
|
62
|
+
* was the one place in the codebase bypassing the typed context layer.
|
|
63
|
+
*
|
|
64
|
+
* `httpHeader` is deliberately UNDEFINED, so the key is context-only and NEVER travels. Two reasons,
|
|
65
|
+
* and either alone is decisive: the value is an OBJECT, which no HTTP header can carry; and a
|
|
66
|
+
* principal is proof THIS hop's authenticator produced, so forwarding it would hand the next service
|
|
67
|
+
* a "proven" caller nothing on that hop verified. The individual facts a downstream service needs
|
|
68
|
+
* (userId, orgId, roles) already propagate as their own transferred keys in
|
|
69
|
+
* {@link WebpiecesCoreHeaders}, gated by the caller-verified rule.
|
|
70
|
+
*
|
|
71
|
+
* `isLogged` is FALSE: it is an object carrying the raw credential claims, which has no business
|
|
72
|
+
* being serialized into a log line.
|
|
73
|
+
*/
|
|
74
|
+
exports.AUTHENTICATED_CALLER_KEY = core_util_1.ContextKey.trusted('authenticatedCaller', 'resolved by the framework AuthFilter from a credential an app-bound JwtHook, ApiKeyHook or WebhookAuthCallback verified',
|
|
75
|
+
/*httpHeader*/ undefined,
|
|
76
|
+
/*maskInLogs*/ false,
|
|
77
|
+
/*isLogged*/ false);
|
|
45
78
|
/**
|
|
46
79
|
* AuthConfig - the app-provided SHARED-SECRET state the framework {@link AuthFilter} reads to
|
|
47
80
|
* enforce `@AuthSharedSecret(name)` endpoints. It holds ONLY the accepted secret values (STATE) —
|
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":";;;
|
|
1
|
+
{"version":3,"file":"AuthConfig.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthConfig.ts"],"names":[],"mappings":";;;AAAA,oDAAgE;AAEhE;;;;;;;;;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;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,mBAAmB;IAER;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,kDAQC;AAED;;;;;;;;;;;;;;;GAeG;AACU,QAAA,wBAAwB,GAAG,sBAAU,CAAC,OAAO,CACtD,qBAAqB,EACrB,yHAAyH;AACzH,cAAc,CAAC,SAAS;AACxB,cAAc,CAAC,KAAK;AACpB,YAAY,CAAC,KAAK,CACrB,CAAC;AAEF;;;;;;;;;;;;;;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 { ContextKey, 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 * AuthenticatedCaller - what an authenticator PROVED about the caller of ONE request. Every hook\n * that authenticates resolves to this: {@link JwtHook.parseJwt}, {@link ApiKeyHook.verifyApiKey} and\n * {@link WebhookAuthCallback.verifyWebhook}. Four fields, three jobs:\n *\n * - `userId` — WHO the caller is, as the credential proved it.\n * - `roles` / `claims` — the AUTHORIZATION inputs: `roles` is what the framework's own any-of check\n * reads, `claims` is the raw payload an app's {@link JwtHook.authorizeJwt}\n * override reads for app-defined requirements (inOrg, tenant, ...).\n * - `entries` — the TRUSTED CONTEXT to seed. The framework writes each one with\n * {@link RequestContext.putTrusted}, so return only what THIS authenticator\n * derived from the credential it just verified.\n *\n * NAMING, said out loud so it is not \"fixed\" back: it is deliberately NOT a `TrustedContextMap`.\n * Three of the four fields are not context, and it is not a Map — it is the authenticated caller,\n * and the context is one thing it carries.\n *\n * Data-only structure (a class, per the guidelines).\n */\nexport class AuthenticatedCaller {\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 * The context slot holding the {@link AuthenticatedCaller} the framework {@link AuthFilter} resolved\n * for this request. A real TRUSTED {@link ContextKey}, written with `RequestContext.putTrusted` and\n * read with `RequestContext.getTrusted` — it replaces a raw `'__webpieces_principal__'` string that\n * was the one place in the codebase bypassing the typed context layer.\n *\n * `httpHeader` is deliberately UNDEFINED, so the key is context-only and NEVER travels. Two reasons,\n * and either alone is decisive: the value is an OBJECT, which no HTTP header can carry; and a\n * principal is proof THIS hop's authenticator produced, so forwarding it would hand the next service\n * a \"proven\" caller nothing on that hop verified. The individual facts a downstream service needs\n * (userId, orgId, roles) already propagate as their own transferred keys in\n * {@link WebpiecesCoreHeaders}, gated by the caller-verified rule.\n *\n * `isLogged` is FALSE: it is an object carrying the raw credential claims, which has no business\n * being serialized into a log line.\n */\nexport const AUTHENTICATED_CALLER_KEY = ContextKey.trusted<AuthenticatedCaller>(\n 'authenticatedCaller',\n 'resolved by the framework AuthFilter from a credential an app-bound JwtHook, ApiKeyHook or WebhookAuthCallback verified',\n /*httpHeader*/ undefined,\n /*maskInLogs*/ false,\n /*isLogged*/ false,\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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { JwtRequirement } from '@webpieces/core-util';
|
|
2
|
-
import { HttpRequest,
|
|
3
|
-
import {
|
|
2
|
+
import { HttpRequest, RawHttpRequest } from '@webpieces/core-context';
|
|
3
|
+
import { AuthenticatedCaller } from './AuthConfig';
|
|
4
4
|
/**
|
|
5
5
|
* JwtHook - the OPTIONAL user-JWT mechanism. Its DI token is the {@link JWT_HOOK} Symbol injected via
|
|
6
6
|
* `@inject(JWT_HOOK)` (a Symbol, because the app container uses autobind; rebindable in tests). Bind one
|
|
@@ -8,7 +8,7 @@ import { AuthValues } from './AuthConfig';
|
|
|
8
8
|
* {@link AuthFilter} treats every jwt endpoint as "not enabled" and fails fast (401) — there is no
|
|
9
9
|
* default JWT verification because it needs an app secret + payload shape the framework can't guess.
|
|
10
10
|
*
|
|
11
|
-
* - `parseJwt` — AUTHENTICATION: decode/verify a user JWT into {@link
|
|
11
|
+
* - `parseJwt` — AUTHENTICATION: decode/verify a user JWT into {@link AuthenticatedCaller}, or throw. The
|
|
12
12
|
* app owns the strategy (HS256 secret, RS256 + JWKS, a provider SDK, ...).
|
|
13
13
|
* - `authorizeJwt` — AUTHORIZATION: check the authenticated user against the endpoint's
|
|
14
14
|
* {@link JwtRequirement}. The DEFAULT enforces the roles any-of; override for
|
|
@@ -20,7 +20,7 @@ import { AuthValues } from './AuthConfig';
|
|
|
20
20
|
* reaches the network. `parseJwt` may fetch a JWKS or call a provider SDK; `authorizeJwt`'s own
|
|
21
21
|
* motivating example — `@AuthJwt({allRolesAllowed: true, inOrg: true})` — is a membership question a
|
|
22
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.
|
|
23
|
+
* `JwtHook` the last sync hook: {@link OidcHook.verifyOidc}, {@link WebhookAuthCallback.verifyWebhook} and
|
|
24
24
|
* {@link ApiKeyHook.verifyApiKey} all return promises. An implementation that needs no I/O simply has
|
|
25
25
|
* no `await` in its body — {@link DefaultJwtHook} is exactly that and pays nothing for it.
|
|
26
26
|
*/
|
|
@@ -28,14 +28,23 @@ export declare abstract class JwtHook {
|
|
|
28
28
|
/**
|
|
29
29
|
* Parse a user JWT (kind:'jwt') — AUTHENTICATION only. Return who the user is, or throw.
|
|
30
30
|
* ASYNC so an app can reach a JWKS endpoint or a provider SDK; see the class doc.
|
|
31
|
+
*
|
|
32
|
+
* IT TAKES THE TOKEN, NOT THE REQUEST — the one deliberate asymmetry among the four hooks, and
|
|
33
|
+
* NOT an oversight to be "fixed". {@link ApiKeyHook.verifyApiKey} and
|
|
34
|
+
* {@link WebhookAuthCallback.verifyWebhook} take the whole {@link HttpRequest} because their
|
|
35
|
+
* credential regime is the APP's: which headers carry an api key, and how a vendor signs, are
|
|
36
|
+
* things the framework cannot know. A user JWT is different — the framework owns the
|
|
37
|
+
* `Authorization: Bearer` scheme and has already extracted the token from it. Widening this to
|
|
38
|
+
* the request would only invite a JwtHook to authenticate off some OTHER header, which is a
|
|
39
|
+
* second, ungoverned credential path on the mode that guards browser traffic.
|
|
31
40
|
*/
|
|
32
|
-
abstract parseJwt(token: string): Promise<
|
|
41
|
+
abstract parseJwt(token: string): Promise<AuthenticatedCaller>;
|
|
33
42
|
/**
|
|
34
43
|
* DEFAULT authorization: enforce the endpoint's roles (any-of). Override to enforce app-defined
|
|
35
44
|
* requirements. Throw HttpForbiddenError to deny; return to allow. ASYNC so an app-defined
|
|
36
45
|
* requirement can be answered from a datastore; see the class doc.
|
|
37
46
|
*/
|
|
38
|
-
authorizeJwt(
|
|
47
|
+
authorizeJwt(caller: AuthenticatedCaller, requirement: JwtRequirement): Promise<void>;
|
|
39
48
|
}
|
|
40
49
|
/**
|
|
41
50
|
* DI identifier for the optional {@link JwtHook} binding. It is a Symbol (not the class) so the app
|
|
@@ -81,20 +90,32 @@ export declare const OIDC_HOOK: unique symbol;
|
|
|
81
90
|
*
|
|
82
91
|
* ONE hook serves EVERY vendor: `name` selects which, so an app with a Sentry hook and a Twilio hook
|
|
83
92
|
* switches on it rather than binding a token per vendor. What arrives is enough of the raw request to
|
|
84
|
-
* call the vendor's OWN validator —
|
|
85
|
-
* Slack),
|
|
93
|
+
* call the vendor's OWN validator — `request.raw.rawBody` for a body-signing vendor (Sentry, GitHub,
|
|
94
|
+
* Stripe, Slack), `request.raw.absoluteUrl` for one that signs the url instead (Twilio).
|
|
86
95
|
*/
|
|
87
96
|
export declare abstract class WebhookAuthCallback {
|
|
88
97
|
/**
|
|
89
|
-
* Verify ONE inbound request. Return
|
|
98
|
+
* Verify ONE inbound request. Return the {@link AuthenticatedCaller} the vendor's signature
|
|
99
|
+
* proved; throw {@link HttpUnauthorizedError} to deny.
|
|
100
|
+
*
|
|
101
|
+
* IT RETURNS A CALLER, not `void`, for the same reason {@link ApiKeyHook.verifyApiKey} does: once
|
|
102
|
+
* the signature checks out, the payload's vendor account is a PROVEN fact, and a hook that could
|
|
103
|
+
* only return `void` had no way to say so. The framework seeds `entries` with
|
|
104
|
+
* `RequestContext.putTrusted` exactly as it does for a jwt or api-key caller, so a controller
|
|
105
|
+
* reads which vendor account this webhook is for off the context instead of re-deriving it.
|
|
90
106
|
*
|
|
91
|
-
*
|
|
92
|
-
*
|
|
93
|
-
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
107
|
+
* Return only what THIS hook proved from the signature it just verified. `webhook` remains
|
|
108
|
+
* caller-NOT-verified (see `AuthFilter.verifiesCaller`): a vendor is not a peer service, so
|
|
109
|
+
* nothing the vendor merely ASSERTED on the wire is admitted.
|
|
110
|
+
*
|
|
111
|
+
* @param name the string on the contract's `@AuthWebhook(name)` — which vendor this route is.
|
|
112
|
+
* @param request the transport-neutral request, narrowed to {@link RawHttpRequest}: `request.raw`
|
|
113
|
+
* holds the verbatim bytes + absolute url and is PRESENT, never optional.
|
|
114
|
+
* `@AuthWebhook` requires `@Endpoint(..., { rawBody: true })` at wiring time, and
|
|
115
|
+
* AuthFilter 401s rather than calling this hook with nothing to check — so an
|
|
116
|
+
* implementation never writes `raw!` or a guard of its own.
|
|
96
117
|
*/
|
|
97
|
-
abstract
|
|
118
|
+
abstract verifyWebhook(name: string, request: RawHttpRequest): Promise<AuthenticatedCaller>;
|
|
98
119
|
}
|
|
99
120
|
/**
|
|
100
121
|
* DI identifier for the optional {@link WebhookAuthCallback} binding. It is a Symbol (not the class) so the app
|
|
@@ -102,21 +123,6 @@ export declare abstract class WebhookAuthCallback {
|
|
|
102
123
|
* correct — undefined when unbound. The WebhookAuthCallback class stays the TYPE and the impl base.
|
|
103
124
|
*/
|
|
104
125
|
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
126
|
/**
|
|
121
127
|
* ApiKeyHook - the OPTIONAL mechanism behind `@AuthApiKey(name)`: authenticate a CUSTOMER-held api key
|
|
122
128
|
* against the app's own datastore and return the context to seed. Its DI token is the
|
|
@@ -134,19 +140,20 @@ export interface HeaderReader {
|
|
|
134
140
|
* one: the key regime lives in the app's datastore, under the app's hashing scheme, behind the app's
|
|
135
141
|
* choice of header names.
|
|
136
142
|
*
|
|
137
|
-
* THE ONE THING THIS HAS THAT `JwtHook.parseJwt` DOES NOT: it receives
|
|
138
|
-
* pre-extracted token. A real key regime validates the key TOGETHER WITH a second header — the
|
|
143
|
+
* THE ONE THING THIS HAS THAT `JwtHook.parseJwt` DOES NOT: it receives the whole {@link HttpRequest},
|
|
144
|
+
* not one pre-extracted token. A real key regime validates the key TOGETHER WITH a second header — the
|
|
139
145
|
* organization the caller is acting for — and a hook handed one header's value physically cannot do
|
|
140
146
|
* that cross-check. The framework therefore configures no api-key header name: which headers carry the
|
|
141
|
-
* credential is the app's business
|
|
142
|
-
* for the same reason: an
|
|
147
|
+
* credential is the app's business, and `getHeader` / `getHeaderValues` read as many as the regime
|
|
148
|
+
* needs. (Being ASYNC is no longer a difference — every hook here is, and for the same reason: an
|
|
149
|
+
* app's strategy reaches the network.)
|
|
143
150
|
*
|
|
144
151
|
* ONE hook serves EVERY regime: `name` selects which, so a server with a partner-api regime and an
|
|
145
152
|
* internal-tooling regime switches on it rather than binding a token per regime.
|
|
146
153
|
*/
|
|
147
154
|
export declare abstract class ApiKeyHook {
|
|
148
155
|
/**
|
|
149
|
-
* AUTHENTICATE one inbound request. Return who the caller is plus the {@link
|
|
156
|
+
* AUTHENTICATE one inbound request. Return who the caller is plus the {@link AuthenticatedCaller.entries}
|
|
150
157
|
* the framework seeds into `RequestContext` via `putTrusted`, or throw
|
|
151
158
|
* {@link HttpUnauthorizedError} to deny.
|
|
152
159
|
*
|
|
@@ -156,9 +163,10 @@ export declare abstract class ApiKeyHook {
|
|
|
156
163
|
* because a customer is not an internal service.
|
|
157
164
|
*
|
|
158
165
|
* @param name the string on the contract's `@AuthApiKey(name)` — which key regime this route is.
|
|
159
|
-
* @param
|
|
166
|
+
* @param request the inbound request; read as many headers as the regime needs with
|
|
167
|
+
* `getHeader` / `getHeaderValues`, either by raw name or by {@link ContextKey}.
|
|
160
168
|
*/
|
|
161
|
-
abstract verifyApiKey(name: string,
|
|
169
|
+
abstract verifyApiKey(name: string, request: HttpRequest): Promise<AuthenticatedCaller>;
|
|
162
170
|
}
|
|
163
171
|
/**
|
|
164
172
|
* DI identifier for the optional {@link ApiKeyHook} binding. It is a Symbol (not the class) so the app
|
package/src/AuthHooks.js
CHANGED
|
@@ -9,7 +9,7 @@ const core_util_1 = require("@webpieces/core-util");
|
|
|
9
9
|
* {@link AuthFilter} treats every jwt endpoint as "not enabled" and fails fast (401) — there is no
|
|
10
10
|
* default JWT verification because it needs an app secret + payload shape the framework can't guess.
|
|
11
11
|
*
|
|
12
|
-
* - `parseJwt` — AUTHENTICATION: decode/verify a user JWT into {@link
|
|
12
|
+
* - `parseJwt` — AUTHENTICATION: decode/verify a user JWT into {@link AuthenticatedCaller}, or throw. The
|
|
13
13
|
* app owns the strategy (HS256 secret, RS256 + JWKS, a provider SDK, ...).
|
|
14
14
|
* - `authorizeJwt` — AUTHORIZATION: check the authenticated user against the endpoint's
|
|
15
15
|
* {@link JwtRequirement}. The DEFAULT enforces the roles any-of; override for
|
|
@@ -21,7 +21,7 @@ const core_util_1 = require("@webpieces/core-util");
|
|
|
21
21
|
* reaches the network. `parseJwt` may fetch a JWKS or call a provider SDK; `authorizeJwt`'s own
|
|
22
22
|
* motivating example — `@AuthJwt({allRolesAllowed: true, inOrg: true})` — is a membership question a
|
|
23
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.
|
|
24
|
+
* `JwtHook` the last sync hook: {@link OidcHook.verifyOidc}, {@link WebhookAuthCallback.verifyWebhook} and
|
|
25
25
|
* {@link ApiKeyHook.verifyApiKey} all return promises. An implementation that needs no I/O simply has
|
|
26
26
|
* no `await` in its body — {@link DefaultJwtHook} is exactly that and pays nothing for it.
|
|
27
27
|
*/
|
|
@@ -31,11 +31,11 @@ class JwtHook {
|
|
|
31
31
|
* requirements. Throw HttpForbiddenError to deny; return to allow. ASYNC so an app-defined
|
|
32
32
|
* requirement can be answered from a datastore; see the class doc.
|
|
33
33
|
*/
|
|
34
|
-
async authorizeJwt(
|
|
34
|
+
async authorizeJwt(caller, requirement) {
|
|
35
35
|
// rolesRequired is the ONE reader of the JwtRoles union: [] means the endpoint typed
|
|
36
36
|
// `allRolesAllowed: true`, never "the field was missing" — that state no longer compiles.
|
|
37
37
|
const roles = (0, core_util_1.rolesRequired)(requirement);
|
|
38
|
-
if (roles.length > 0 && !roles.some((role) =>
|
|
38
|
+
if (roles.length > 0 && !roles.some((role) => caller.roles.includes(role))) {
|
|
39
39
|
throw new core_util_1.HttpForbiddenError(`Endpoint requires one of roles: ${roles.join(', ')}`);
|
|
40
40
|
}
|
|
41
41
|
}
|
|
@@ -87,8 +87,8 @@ exports.OIDC_HOOK = Symbol.for('OidcHook');
|
|
|
87
87
|
*
|
|
88
88
|
* ONE hook serves EVERY vendor: `name` selects which, so an app with a Sentry hook and a Twilio hook
|
|
89
89
|
* switches on it rather than binding a token per vendor. What arrives is enough of the raw request to
|
|
90
|
-
* call the vendor's OWN validator —
|
|
91
|
-
* Slack),
|
|
90
|
+
* call the vendor's OWN validator — `request.raw.rawBody` for a body-signing vendor (Sentry, GitHub,
|
|
91
|
+
* Stripe, Slack), `request.raw.absoluteUrl` for one that signs the url instead (Twilio).
|
|
92
92
|
*/
|
|
93
93
|
class WebhookAuthCallback {
|
|
94
94
|
}
|
|
@@ -117,12 +117,13 @@ exports.WEBHOOK_AUTH_CALLBACK = Symbol.for('WebhookAuthCallback');
|
|
|
117
117
|
* one: the key regime lives in the app's datastore, under the app's hashing scheme, behind the app's
|
|
118
118
|
* choice of header names.
|
|
119
119
|
*
|
|
120
|
-
* THE ONE THING THIS HAS THAT `JwtHook.parseJwt` DOES NOT: it receives
|
|
121
|
-
* pre-extracted token. A real key regime validates the key TOGETHER WITH a second header — the
|
|
120
|
+
* THE ONE THING THIS HAS THAT `JwtHook.parseJwt` DOES NOT: it receives the whole {@link HttpRequest},
|
|
121
|
+
* not one pre-extracted token. A real key regime validates the key TOGETHER WITH a second header — the
|
|
122
122
|
* organization the caller is acting for — and a hook handed one header's value physically cannot do
|
|
123
123
|
* that cross-check. The framework therefore configures no api-key header name: which headers carry the
|
|
124
|
-
* credential is the app's business
|
|
125
|
-
* for the same reason: an
|
|
124
|
+
* credential is the app's business, and `getHeader` / `getHeaderValues` read as many as the regime
|
|
125
|
+
* needs. (Being ASYNC is no longer a difference — every hook here is, and for the same reason: an
|
|
126
|
+
* app's strategy reaches the network.)
|
|
126
127
|
*
|
|
127
128
|
* ONE hook serves EVERY regime: `name` selects which, so a server with a partner-api regime and an
|
|
128
129
|
* internal-tooling regime switches on it rather than binding a token per regime.
|
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;;;;;;;;;;;;;;;;;;;;;;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"]}
|
|
1
|
+
{"version":3,"file":"AuthHooks.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthHooks.ts"],"names":[],"mappings":";;;AAAA,oDAAyF;AAIzF;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAsB,OAAO;IAgBzB;;;;OAIG;IACH,KAAK,CAAC,YAAY,CAAC,MAA2B,EAAE,WAA2B;QACvE,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;AA7BD,0BA6BC;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;CAuBxC;AAvBD,kDAuBC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,qBAAqB,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAEvE;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,MAAsB,UAAU;CAgB/B;AAhBD,gCAgBC;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, RawHttpRequest } from '@webpieces/core-context';\nimport { AuthenticatedCaller } 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 AuthenticatedCaller}, 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.verifyWebhook} 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 * IT TAKES THE TOKEN, NOT THE REQUEST — the one deliberate asymmetry among the four hooks, and\n * NOT an oversight to be \"fixed\". {@link ApiKeyHook.verifyApiKey} and\n * {@link WebhookAuthCallback.verifyWebhook} take the whole {@link HttpRequest} because their\n * credential regime is the APP's: which headers carry an api key, and how a vendor signs, are\n * things the framework cannot know. A user JWT is different — the framework owns the\n * `Authorization: Bearer` scheme and has already extracted the token from it. Widening this to\n * the request would only invite a JwtHook to authenticate off some OTHER header, which is a\n * second, ungoverned credential path on the mode that guards browser traffic.\n */\n abstract parseJwt(token: string): Promise<AuthenticatedCaller>;\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(caller: AuthenticatedCaller, 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) => caller.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 — `request.raw.rawBody` for a body-signing vendor (Sentry, GitHub,\n * Stripe, Slack), `request.raw.absoluteUrl` for one that signs the url instead (Twilio).\n */\nexport abstract class WebhookAuthCallback {\n /**\n * Verify ONE inbound request. Return the {@link AuthenticatedCaller} the vendor's signature\n * proved; throw {@link HttpUnauthorizedError} to deny.\n *\n * IT RETURNS A CALLER, not `void`, for the same reason {@link ApiKeyHook.verifyApiKey} does: once\n * the signature checks out, the payload's vendor account is a PROVEN fact, and a hook that could\n * only return `void` had no way to say so. The framework seeds `entries` with\n * `RequestContext.putTrusted` exactly as it does for a jwt or api-key caller, so a controller\n * reads which vendor account this webhook is for off the context instead of re-deriving it.\n *\n * Return only what THIS hook proved from the signature it just verified. `webhook` remains\n * caller-NOT-verified (see `AuthFilter.verifiesCaller`): a vendor is not a peer service, so\n * nothing the vendor merely ASSERTED on the wire is admitted.\n *\n * @param name the string on the contract's `@AuthWebhook(name)` — which vendor this route is.\n * @param request the transport-neutral request, narrowed to {@link RawHttpRequest}: `request.raw`\n * holds the verbatim bytes + absolute url and is PRESENT, never optional.\n * `@AuthWebhook` requires `@Endpoint(..., { rawBody: true })` at wiring time, and\n * AuthFilter 401s rather than calling this hook with nothing to check — so an\n * implementation never writes `raw!` or a guard of its own.\n */\n abstract verifyWebhook(name: string, request: RawHttpRequest): Promise<AuthenticatedCaller>;\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 * 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 the whole {@link HttpRequest},\n * not one 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, and `getHeader` / `getHeaderValues` read as many as the regime\n * needs. (Being ASYNC is no longer a difference — every hook here is, and for the same reason: an\n * 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 AuthenticatedCaller.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 request the inbound request; read as many headers as the regime needs with\n * `getHeader` / `getHeaderValues`, either by raw name or by {@link ContextKey}.\n */\n abstract verifyApiKey(name: string, request: HttpRequest): Promise<AuthenticatedCaller>;\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"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* COMPILE-TIME assertions that the four auth hooks share ONE shape, and that every spelling this
|
|
3
|
+
* change deleted has actually stopped compiling. Each `@ts-expect-error` FAILS THE BUILD (TS2578,
|
|
4
|
+
* "unused '@ts-expect-error' directive") the moment the thing it guards starts compiling again.
|
|
5
|
+
*
|
|
6
|
+
* WHY THIS IS NOT A `.spec.ts` FILE — the same reason as {@link JwtHookCompileAssertions}:
|
|
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. This repo ships no backwards-compatibility shims: the compile error IS the
|
|
12
|
+
* migration. An implementor that kept `verify(name, request, raw)` or a `HeaderReader` parameter
|
|
13
|
+
* would otherwise sit there compiling, and an accepted shape is never migrated.
|
|
14
|
+
*/
|
|
15
|
+
export declare class AuthHooksCompileAssertions {
|
|
16
|
+
/**
|
|
17
|
+
* The DELETED type names, kept referenced so the two `@ts-expect-error`s above are load-bearing
|
|
18
|
+
* rather than decorative. Both resolve to `any` under the suppressed error; the assertion is the
|
|
19
|
+
* IMPORT failing, not what these aliases denote.
|
|
20
|
+
*/
|
|
21
|
+
deletedNames(): void;
|
|
22
|
+
/** The ALIGNED spellings must keep compiling; asserted by the ABSENCE of an error. */
|
|
23
|
+
legitimate(): void;
|
|
24
|
+
/** Every spelling this change deleted must now be UNWRITABLE. */
|
|
25
|
+
rejected(): void;
|
|
26
|
+
/**
|
|
27
|
+
* An {@link HttpRequest} whose `raw` is merely OPTIONAL is NOT a {@link RawHttpRequest}. This is
|
|
28
|
+
* the assignment that makes the narrowing real: without it, `RawHttpRequest` would be a comment.
|
|
29
|
+
*/
|
|
30
|
+
rawIsNotOptional(): void;
|
|
31
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AuthHooksCompileAssertions = void 0;
|
|
4
|
+
const core_context_1 = require("@webpieces/core-context");
|
|
5
|
+
const AuthHooks_1 = require("./AuthHooks");
|
|
6
|
+
const AuthConfig_1 = require("./AuthConfig");
|
|
7
|
+
/**
|
|
8
|
+
* COMPILE-TIME assertions that the four auth hooks share ONE shape, and that every spelling this
|
|
9
|
+
* change deleted has actually stopped compiling. Each `@ts-expect-error` FAILS THE BUILD (TS2578,
|
|
10
|
+
* "unused '@ts-expect-error' directive") the moment the thing it guards starts compiling again.
|
|
11
|
+
*
|
|
12
|
+
* WHY THIS IS NOT A `.spec.ts` FILE — the same reason as {@link JwtHookCompileAssertions}:
|
|
13
|
+
* tsconfig.lib.json EXCLUDES specs and vitest strips types with esbuild, so a `@ts-expect-error` in a
|
|
14
|
+
* spec is inert and the suite passes either way. A type-level guarantee has to be asserted in a file
|
|
15
|
+
* the type-checker actually compiles.
|
|
16
|
+
*
|
|
17
|
+
* WHY IT MATTERS HERE. This repo ships no backwards-compatibility shims: the compile error IS the
|
|
18
|
+
* migration. An implementor that kept `verify(name, request, raw)` or a `HeaderReader` parameter
|
|
19
|
+
* would otherwise sit there compiling, and an accepted shape is never migrated.
|
|
20
|
+
*/
|
|
21
|
+
class AuthHooksCompileAssertions {
|
|
22
|
+
/**
|
|
23
|
+
* The DELETED type names, kept referenced so the two `@ts-expect-error`s above are load-bearing
|
|
24
|
+
* rather than decorative. Both resolve to `any` under the suppressed error; the assertion is the
|
|
25
|
+
* IMPORT failing, not what these aliases denote.
|
|
26
|
+
*/
|
|
27
|
+
// webpieces-disable no-any-unknown -- a suppressed import of a deleted symbol resolves to any; the assertion is the import error itself
|
|
28
|
+
deletedNames() {
|
|
29
|
+
const headerReaderIsGone = undefined;
|
|
30
|
+
const authValuesIsGone = undefined;
|
|
31
|
+
void headerReaderIsGone;
|
|
32
|
+
void authValuesIsGone;
|
|
33
|
+
}
|
|
34
|
+
/** The ALIGNED spellings must keep compiling; asserted by the ABSENCE of an error. */
|
|
35
|
+
legitimate() {
|
|
36
|
+
void class extends AuthHooks_1.WebhookAuthCallback {
|
|
37
|
+
async verifyWebhook(_name, request) {
|
|
38
|
+
// No `raw!`, no `if (!raw) throw`: AuthFilter checked once and the TYPE carries it.
|
|
39
|
+
const bytes = request.raw.rawBody;
|
|
40
|
+
return new AuthConfig_1.AuthenticatedCaller(`sentry:${bytes.length}`);
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
void class extends AuthHooks_1.ApiKeyHook {
|
|
44
|
+
async verifyApiKey(_name, request) {
|
|
45
|
+
// Both of these were UNREACHABLE through the deleted one-method HeaderReader.
|
|
46
|
+
const all = request.getHeaderValues('x-api-key');
|
|
47
|
+
return new AuthConfig_1.AuthenticatedCaller(all?.[0] ?? 'anonymous');
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** Every spelling this change deleted must now be UNWRITABLE. */
|
|
52
|
+
rejected() {
|
|
53
|
+
void class extends AuthHooks_1.WebhookAuthCallback {
|
|
54
|
+
async verifyWebhook(_name, _request) {
|
|
55
|
+
return new AuthConfig_1.AuthenticatedCaller('u1');
|
|
56
|
+
}
|
|
57
|
+
// @ts-expect-error `verify` was renamed to `verifyWebhook`: the old name overrides nothing
|
|
58
|
+
async verify(_name, _request, _raw) {
|
|
59
|
+
// the three-parameter, void-returning spelling this change deletes
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
void class extends AuthHooks_1.WebhookAuthCallback {
|
|
63
|
+
// @ts-expect-error verifyWebhook returns the caller it proved: a void override must not compile
|
|
64
|
+
async verifyWebhook(_name, _request) {
|
|
65
|
+
// a hook that verifies and then has no way to say what it proved
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* An {@link HttpRequest} whose `raw` is merely OPTIONAL is NOT a {@link RawHttpRequest}. This is
|
|
71
|
+
* the assignment that makes the narrowing real: without it, `RawHttpRequest` would be a comment.
|
|
72
|
+
*/
|
|
73
|
+
rawIsNotOptional() {
|
|
74
|
+
const maybeRaw = new core_context_1.HttpRequest('POST', '/hook/sentry/issue', new Map());
|
|
75
|
+
// @ts-expect-error HttpRequest.raw is optional, so it is not assignable to RawHttpRequest
|
|
76
|
+
const narrowed = maybeRaw;
|
|
77
|
+
void narrowed;
|
|
78
|
+
// The other direction is free: a RawHttpRequest IS an HttpRequest everywhere one is wanted.
|
|
79
|
+
const proven = new core_context_1.HttpRequest('POST', '/hook/sentry/issue', new Map(), new core_context_1.RawRequest('https://example.com/hook', Buffer.from('{}', 'utf8'), '1.2.3.4'));
|
|
80
|
+
const widened = proven;
|
|
81
|
+
void widened;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
exports.AuthHooksCompileAssertions = AuthHooksCompileAssertions;
|
|
85
|
+
//# sourceMappingURL=AuthHooksCompileAssertions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AuthHooksCompileAssertions.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthHooksCompileAssertions.ts"],"names":[],"mappings":";;;AAAA,0DAAkF;AAMlF,2CAA8D;AAC9D,6CAAmD;AAEnD;;;;;;;;;;;;;GAaG;AACH,MAAa,0BAA0B;IACnC;;;;OAIG;IACH,wIAAwI;IACxI,YAAY;QACR,MAAM,kBAAkB,GAA6B,SAAS,CAAC;QAC/D,MAAM,gBAAgB,GAA2B,SAAS,CAAC;QAC3D,KAAK,kBAAkB,CAAC;QACxB,KAAK,gBAAgB,CAAC;IAC1B,CAAC;IAED,sFAAsF;IACtF,UAAU;QACN,KAAK,KAAM,SAAQ,+BAAmB;YACzB,KAAK,CAAC,aAAa,CAAC,KAAa,EAAE,OAAuB;gBAC/D,oFAAoF;gBACpF,MAAM,KAAK,GAAW,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;gBAC1C,OAAO,IAAI,gCAAmB,CAAC,UAAU,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;YAC7D,CAAC;SACJ,CAAC;QACF,KAAK,KAAM,SAAQ,sBAAU;YAChB,KAAK,CAAC,YAAY,CAAC,KAAa,EAAE,OAAoB;gBAC3D,8EAA8E;gBAC9E,MAAM,GAAG,GAAyB,OAAO,CAAC,eAAe,CAAC,WAAW,CAAC,CAAC;gBACvE,OAAO,IAAI,gCAAmB,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,WAAW,CAAC,CAAC;YAC5D,CAAC;SACJ,CAAC;IACN,CAAC;IAED,iEAAiE;IACjE,QAAQ;QACJ,KAAK,KAAM,SAAQ,+BAAmB;YACzB,KAAK,CAAC,aAAa,CAAC,KAAa,EAAE,QAAwB;gBAChE,OAAO,IAAI,gCAAmB,CAAC,IAAI,CAAC,CAAC;YACzC,CAAC;YAED,2FAA2F;YAClF,KAAK,CAAC,MAAM,CAAC,KAAa,EAAE,QAAqB,EAAE,IAAgB;gBACxE,mEAAmE;YACvE,CAAC;SACJ,CAAC;QACF,KAAK,KAAM,SAAQ,+BAAmB;YAClC,gGAAgG;YACvF,KAAK,CAAC,aAAa,CAAC,KAAa,EAAE,QAAwB;gBAChE,iEAAiE;YACrE,CAAC;SACJ,CAAC;IACN,CAAC;IAED;;;OAGG;IACH,gBAAgB;QACZ,MAAM,QAAQ,GAAG,IAAI,0BAAW,CAAC,MAAM,EAAE,oBAAoB,EAAE,IAAI,GAAG,EAAoB,CAAC,CAAC;QAC5F,0FAA0F;QAC1F,MAAM,QAAQ,GAAmB,QAAQ,CAAC;QAC1C,KAAK,QAAQ,CAAC;QAEd,4FAA4F;QAC5F,MAAM,MAAM,GAAG,IAAI,0BAAW,CAC1B,MAAM,EACN,oBAAoB,EACpB,IAAI,GAAG,EAAoB,EAC3B,IAAI,yBAAU,CAAC,0BAA0B,EAAE,MAAM,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,EAAE,SAAS,CAAC,CACjE,CAAC;QACpB,MAAM,OAAO,GAAgB,MAAM,CAAC;QACpC,KAAK,OAAO,CAAC;IACjB,CAAC;CACJ;AAxED,gEAwEC","sourcesContent":["import { HttpRequest, RawHttpRequest, RawRequest } from '@webpieces/core-context';\n// @ts-expect-error HeaderReader is DELETED — an ApiKeyHook now receives the whole HttpRequest, so it\n// reaches getHeaderValues and the ContextKey overload of getHeader that the narrow reader hid.\nimport type { HeaderReader } from './AuthHooks';\n// @ts-expect-error AuthValues is RENAMED to AuthenticatedCaller — there is no alias, by policy.\nimport type { AuthValues } from './AuthConfig';\nimport { ApiKeyHook, WebhookAuthCallback } from './AuthHooks';\nimport { AuthenticatedCaller } from './AuthConfig';\n\n/**\n * COMPILE-TIME assertions that the four auth hooks share ONE shape, and that every spelling this\n * change deleted has actually stopped compiling. Each `@ts-expect-error` FAILS THE BUILD (TS2578,\n * \"unused '@ts-expect-error' directive\") the moment the thing it guards starts compiling again.\n *\n * WHY THIS IS NOT A `.spec.ts` FILE — the same reason as {@link JwtHookCompileAssertions}:\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. This repo ships no backwards-compatibility shims: the compile error IS the\n * migration. An implementor that kept `verify(name, request, raw)` or a `HeaderReader` parameter\n * would otherwise sit there compiling, and an accepted shape is never migrated.\n */\nexport class AuthHooksCompileAssertions {\n /**\n * The DELETED type names, kept referenced so the two `@ts-expect-error`s above are load-bearing\n * rather than decorative. Both resolve to `any` under the suppressed error; the assertion is the\n * IMPORT failing, not what these aliases denote.\n */\n // webpieces-disable no-any-unknown -- a suppressed import of a deleted symbol resolves to any; the assertion is the import error itself\n deletedNames(): void {\n const headerReaderIsGone: HeaderReader | undefined = undefined;\n const authValuesIsGone: AuthValues | undefined = undefined;\n void headerReaderIsGone;\n void authValuesIsGone;\n }\n\n /** The ALIGNED spellings must keep compiling; asserted by the ABSENCE of an error. */\n legitimate(): void {\n void class extends WebhookAuthCallback {\n override async verifyWebhook(_name: string, request: RawHttpRequest): Promise<AuthenticatedCaller> {\n // No `raw!`, no `if (!raw) throw`: AuthFilter checked once and the TYPE carries it.\n const bytes: Buffer = request.raw.rawBody;\n return new AuthenticatedCaller(`sentry:${bytes.length}`);\n }\n };\n void class extends ApiKeyHook {\n override async verifyApiKey(_name: string, request: HttpRequest): Promise<AuthenticatedCaller> {\n // Both of these were UNREACHABLE through the deleted one-method HeaderReader.\n const all: string[] | undefined = request.getHeaderValues('x-api-key');\n return new AuthenticatedCaller(all?.[0] ?? 'anonymous');\n }\n };\n }\n\n /** Every spelling this change deleted must now be UNWRITABLE. */\n rejected(): void {\n void class extends WebhookAuthCallback {\n override async verifyWebhook(_name: string, _request: RawHttpRequest): Promise<AuthenticatedCaller> {\n return new AuthenticatedCaller('u1');\n }\n\n // @ts-expect-error `verify` was renamed to `verifyWebhook`: the old name overrides nothing\n override async verify(_name: string, _request: HttpRequest, _raw: RawRequest): Promise<void> {\n // the three-parameter, void-returning spelling this change deletes\n }\n };\n void class extends WebhookAuthCallback {\n // @ts-expect-error verifyWebhook returns the caller it proved: a void override must not compile\n override async verifyWebhook(_name: string, _request: RawHttpRequest): Promise<void> {\n // a hook that verifies and then has no way to say what it proved\n }\n };\n }\n\n /**\n * An {@link HttpRequest} whose `raw` is merely OPTIONAL is NOT a {@link RawHttpRequest}. This is\n * the assignment that makes the narrowing real: without it, `RawHttpRequest` would be a comment.\n */\n rawIsNotOptional(): void {\n const maybeRaw = new HttpRequest('POST', '/hook/sentry/issue', new Map<string, string[]>());\n // @ts-expect-error HttpRequest.raw is optional, so it is not assignable to RawHttpRequest\n const narrowed: RawHttpRequest = maybeRaw;\n void narrowed;\n\n // The other direction is free: a RawHttpRequest IS an HttpRequest everywhere one is wanted.\n const proven = new HttpRequest(\n 'POST',\n '/hook/sentry/issue',\n new Map<string, string[]>(),\n new RawRequest('https://example.com/hook', Buffer.from('{}', 'utf8'), '1.2.3.4'),\n ) as RawHttpRequest;\n const widened: HttpRequest = proven;\n void widened;\n }\n}\n"]}
|
package/src/DefaultJwtHook.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { JwtHook } from './AuthHooks';
|
|
2
|
-
import {
|
|
2
|
+
import { AuthenticatedCaller } from './AuthConfig';
|
|
3
3
|
/**
|
|
4
4
|
* DefaultJwtHook - a batteries-included {@link JwtHook} for the common case: HS256 user JWTs signed
|
|
5
5
|
* with ONE shared secret. Construct it with the secret and bind it — `new DefaultJwtHook(secret)` —
|
|
@@ -18,7 +18,7 @@ import { AuthValues } from './AuthConfig';
|
|
|
18
18
|
export declare class DefaultJwtHook extends JwtHook {
|
|
19
19
|
private readonly secret;
|
|
20
20
|
constructor(secret: string);
|
|
21
|
-
parseJwt(token: string): Promise<
|
|
21
|
+
parseJwt(token: string): Promise<AuthenticatedCaller>;
|
|
22
22
|
/** Verify HS256 signature + expiry; translate jsonwebtoken's raw error into a framework 401. */
|
|
23
23
|
private verifyToken;
|
|
24
24
|
private extractRoles;
|
package/src/DefaultJwtHook.js
CHANGED
|
@@ -32,7 +32,7 @@ class DefaultJwtHook extends AuthHooks_1.JwtHook {
|
|
|
32
32
|
if (!userId) {
|
|
33
33
|
throw new core_util_1.HttpUnauthorizedError('JWT is missing the required "sub" (subject) claim');
|
|
34
34
|
}
|
|
35
|
-
return new AuthConfig_1.
|
|
35
|
+
return new AuthConfig_1.AuthenticatedCaller(userId, this.extractRoles(payload), [], payload);
|
|
36
36
|
}
|
|
37
37
|
/** Verify HS256 signature + expiry; translate jsonwebtoken's raw error into a framework 401. */
|
|
38
38
|
verifyToken(token) {
|
|
@@ -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,
|
|
1
|
+
{"version":3,"file":"DefaultJwtHook.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/DefaultJwtHook.ts"],"names":[],"mappings":";;;AAAA,+CAAkD;AAClD,oDAAsE;AACtE,2CAAsC;AACtC,6CAAmD;AAEnD;;;;;;;;;;;;;;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,OAA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CAAC;IACd,CAAC;CACJ;AA1CD,wCA0CC","sourcesContent":["import { verify, JwtPayload } from 'jsonwebtoken';\nimport { HttpUnauthorizedError, toError } from '@webpieces/core-util';\nimport { JwtHook } from './AuthHooks';\nimport { AuthenticatedCaller } 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<AuthenticatedCaller> {\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 AuthenticatedCaller(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"]}
|
|
@@ -24,7 +24,7 @@ class JwtHookCompileAssertions {
|
|
|
24
24
|
legitimate() {
|
|
25
25
|
void class extends AuthHooks_1.JwtHook {
|
|
26
26
|
async parseJwt(_token) {
|
|
27
|
-
return new AuthConfig_1.
|
|
27
|
+
return new AuthConfig_1.AuthenticatedCaller('u1');
|
|
28
28
|
}
|
|
29
29
|
async authorizeJwt(_values, _requirement) {
|
|
30
30
|
// An implementation that needs no I/O simply has no await — that is allowed and free.
|
|
@@ -34,14 +34,14 @@ class JwtHookCompileAssertions {
|
|
|
34
34
|
/** The SYNC spellings — what every implementor wrote before — must now be UNWRITABLE. */
|
|
35
35
|
rejected() {
|
|
36
36
|
void class extends AuthHooks_1.JwtHook {
|
|
37
|
-
// @ts-expect-error parseJwt is async now: returning
|
|
37
|
+
// @ts-expect-error parseJwt is async now: returning AuthenticatedCaller instead of Promise<AuthenticatedCaller> must not compile
|
|
38
38
|
parseJwt(_token) {
|
|
39
|
-
return new AuthConfig_1.
|
|
39
|
+
return new AuthConfig_1.AuthenticatedCaller('u1');
|
|
40
40
|
}
|
|
41
41
|
};
|
|
42
42
|
void class extends AuthHooks_1.JwtHook {
|
|
43
43
|
async parseJwt(_token) {
|
|
44
|
-
return new AuthConfig_1.
|
|
44
|
+
return new AuthConfig_1.AuthenticatedCaller('u1');
|
|
45
45
|
}
|
|
46
46
|
// @ts-expect-error authorizeJwt is async now: a void override must not compile either
|
|
47
47
|
authorizeJwt(_values, _requirement) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JwtHookCompileAssertions.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/JwtHookCompileAssertions.ts"],"names":[],"mappings":";;;AACA,2CAAsC;AACtC,
|
|
1
|
+
{"version":3,"file":"JwtHookCompileAssertions.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/JwtHookCompileAssertions.ts"],"names":[],"mappings":";;;AACA,2CAAsC;AACtC,6CAAmD;AAEnD;;;;;;;;;;;;;;;GAeG;AACH,MAAa,wBAAwB;IACjC,oFAAoF;IACpF,UAAU;QACN,KAAK,KAAM,SAAQ,mBAAO;YACb,KAAK,CAAC,QAAQ,CAAC,MAAc;gBAClC,OAAO,IAAI,gCAAmB,CAAC,IAAI,CAAC,CAAC;YACzC,CAAC;YAEQ,KAAK,CAAC,YAAY,CAAC,OAA4B,EAAE,YAA4B;gBAClF,sFAAsF;YAC1F,CAAC;SACJ,CAAC;IACN,CAAC;IAED,yFAAyF;IACzF,QAAQ;QACJ,KAAK,KAAM,SAAQ,mBAAO;YACtB,iIAAiI;YACxH,QAAQ,CAAC,MAAc;gBAC5B,OAAO,IAAI,gCAAmB,CAAC,IAAI,CAAC,CAAC;YACzC,CAAC;SACJ,CAAC;QACF,KAAK,KAAM,SAAQ,mBAAO;YACb,KAAK,CAAC,QAAQ,CAAC,MAAc;gBAClC,OAAO,IAAI,gCAAmB,CAAC,IAAI,CAAC,CAAC;YACzC,CAAC;YAED,sFAAsF;YAC7E,YAAY,CAAC,OAA4B,EAAE,YAA4B;gBAC5E,wEAAwE;YAC5E,CAAC;SACJ,CAAC;IACN,CAAC;CACJ;AAjCD,4DAiCC","sourcesContent":["import { JwtRequirement } from '@webpieces/core-util';\nimport { JwtHook } from './AuthHooks';\nimport { AuthenticatedCaller } 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<AuthenticatedCaller> {\n return new AuthenticatedCaller('u1');\n }\n\n override async authorizeJwt(_values: AuthenticatedCaller, _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 AuthenticatedCaller instead of Promise<AuthenticatedCaller> must not compile\n override parseJwt(_token: string): AuthenticatedCaller {\n return new AuthenticatedCaller('u1');\n }\n };\n void class extends JwtHook {\n override async parseJwt(_token: string): Promise<AuthenticatedCaller> {\n return new AuthenticatedCaller('u1');\n }\n\n // @ts-expect-error authorizeJwt is async now: a void override must not compile either\n override authorizeJwt(_values: AuthenticatedCaller, _requirement: JwtRequirement): void {\n // an app rule enforced synchronously — the spelling this change deletes\n }\n };\n }\n}\n"]}
|
|
@@ -50,8 +50,19 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
|
|
|
50
50
|
* an in-process caller (a spec) that published an HttpRequest with no {@link RawRequest}. The
|
|
51
51
|
* message says which fix applies rather than leaving a bare 401.
|
|
52
52
|
* 3. The hook threw — the signature did not verify.
|
|
53
|
+
*
|
|
54
|
+
* Case 2 is checked HERE and nowhere else. {@link hasRawBytes} narrows the request to
|
|
55
|
+
* {@link RawHttpRequest} at this one gate, so the hook's signature promises `raw` is present and
|
|
56
|
+
* no vendor implementation ever writes `raw!` or a guard of its own.
|
|
53
57
|
*/
|
|
54
58
|
private enforceWebhook;
|
|
59
|
+
/**
|
|
60
|
+
* The ONE place the framework decides a request carries the verbatim bytes. A TYPE PREDICATE, so
|
|
61
|
+
* the `true` branch hands {@link enforceWebhook} a {@link RawHttpRequest} with no cast and no
|
|
62
|
+
* non-null assertion — the bad state stops being representable past this line rather than being
|
|
63
|
+
* re-thrown about by every hook.
|
|
64
|
+
*/
|
|
65
|
+
private hasRawBytes;
|
|
55
66
|
/**
|
|
56
67
|
* `@AuthApiKey(name)`: hand the app's {@link ApiKeyHook} the regime name and the inbound headers and
|
|
57
68
|
* let it look the CUSTOMER's key up. Three ways to fail, all 401, all before the controller:
|
|
@@ -63,8 +74,8 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
|
|
|
63
74
|
* than leaving a bare 401.
|
|
64
75
|
* 3. The hook threw — the key, or the key/organization pair, did not check out.
|
|
65
76
|
*
|
|
66
|
-
* On success the hook's {@link
|
|
67
|
-
* puts the resolved organization into `RequestContext` for every downstream repository call.
|
|
77
|
+
* On success the hook's {@link AuthenticatedCaller} is stamped exactly as a jwt parse's is, which is
|
|
78
|
+
* what puts the resolved organization into `RequestContext` for every downstream repository call.
|
|
68
79
|
*/
|
|
69
80
|
private enforceApiKey;
|
|
70
81
|
/**
|
|
@@ -119,7 +130,7 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
|
|
|
119
130
|
* else is rejected — see {@link requireVouched}.
|
|
120
131
|
*
|
|
121
132
|
* Runs AFTER the mode enforcement above, because that is what stamps the authenticator's own
|
|
122
|
-
* values (`
|
|
133
|
+
* values (`applyAuthenticatedCaller`); comparing before it ran would compare against nothing.
|
|
123
134
|
*/
|
|
124
135
|
private reconcileWireTrust;
|
|
125
136
|
/**
|
|
@@ -164,8 +175,12 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
|
|
|
164
175
|
private matchesEither;
|
|
165
176
|
/** Parse a JWT if one is present, else do nothing — used on public routes; never throws. */
|
|
166
177
|
private bestEffortJwt;
|
|
167
|
-
/**
|
|
168
|
-
|
|
178
|
+
/**
|
|
179
|
+
* Stamp the authenticated caller's context entries + the caller itself into the RequestContext.
|
|
180
|
+
* ONE path for all three authenticating hooks — jwt, api-key and webhook — so a vendor hook that
|
|
181
|
+
* proved which account a payload belongs to seeds context exactly as a JwtHook does.
|
|
182
|
+
*/
|
|
183
|
+
private applyAuthenticatedCaller;
|
|
169
184
|
/**
|
|
170
185
|
* The credential value IF the header carries the expected scheme, else undefined.
|
|
171
186
|
*
|
|
@@ -31,8 +31,6 @@ const AUTHORIZATION_HEADER = 'authorization';
|
|
|
31
31
|
*/
|
|
32
32
|
const BEARER_SCHEME = 'Bearer';
|
|
33
33
|
const SHARED_SECRET_SCHEME = 'Webpieces';
|
|
34
|
-
/** Reserved context key holding the authenticated {@link AuthValues} (stamped after a jwt parse). */
|
|
35
|
-
const PRINCIPAL_KEY = '__webpieces_principal__';
|
|
36
34
|
/**
|
|
37
35
|
* AuthFilter - the ONE framework auth filter, auto-installed just below the error filter on every
|
|
38
36
|
* route. It is TRANSPORT-NEUTRAL: it reads the raw credential from the {@link HttpRequest} in
|
|
@@ -122,6 +120,10 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
122
120
|
* an in-process caller (a spec) that published an HttpRequest with no {@link RawRequest}. The
|
|
123
121
|
* message says which fix applies rather than leaving a bare 401.
|
|
124
122
|
* 3. The hook threw — the signature did not verify.
|
|
123
|
+
*
|
|
124
|
+
* Case 2 is checked HERE and nowhere else. {@link hasRawBytes} narrows the request to
|
|
125
|
+
* {@link RawHttpRequest} at this one gate, so the hook's signature promises `raw` is present and
|
|
126
|
+
* no vendor implementation ever writes `raw!` or a guard of its own.
|
|
125
127
|
*/
|
|
126
128
|
async enforceWebhook(name, meta) {
|
|
127
129
|
if (!this.webhookAuthCallback) {
|
|
@@ -130,14 +132,25 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
130
132
|
throw new core_util_1.HttpUnauthorizedError('Webhook auth is not enabled on this server');
|
|
131
133
|
}
|
|
132
134
|
const request = core_context_1.RequestContext.getRequest();
|
|
133
|
-
|
|
134
|
-
if (!request || !raw) {
|
|
135
|
+
if (!this.hasRawBytes(request)) {
|
|
135
136
|
log.warn(`Refusing @AuthWebhook('${name}') endpoint ${meta.routeMeta.path}: the inbound request carries ` +
|
|
136
137
|
`no raw bytes. Declare @Endpoint(path, 'external', { calledBy: '${name}', rawBody: true }); a ` +
|
|
137
138
|
`spec driving this route in-process must publish an HttpRequest built with a RawRequest.`);
|
|
138
139
|
throw new core_util_1.HttpUnauthorizedError('Webhook signature cannot be verified: no raw request was retained');
|
|
139
140
|
}
|
|
140
|
-
|
|
141
|
+
// Throws HttpUnauthorizedError to deny. On success the vendor account the signature proved is
|
|
142
|
+
// stamped through the SAME path a jwt or api-key caller takes.
|
|
143
|
+
const caller = await this.webhookAuthCallback.verifyWebhook(name, request);
|
|
144
|
+
this.applyAuthenticatedCaller(caller);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* The ONE place the framework decides a request carries the verbatim bytes. A TYPE PREDICATE, so
|
|
148
|
+
* the `true` branch hands {@link enforceWebhook} a {@link RawHttpRequest} with no cast and no
|
|
149
|
+
* non-null assertion — the bad state stops being representable past this line rather than being
|
|
150
|
+
* re-thrown about by every hook.
|
|
151
|
+
*/
|
|
152
|
+
hasRawBytes(request) {
|
|
153
|
+
return request?.raw !== undefined;
|
|
141
154
|
}
|
|
142
155
|
/**
|
|
143
156
|
* `@AuthApiKey(name)`: hand the app's {@link ApiKeyHook} the regime name and the inbound headers and
|
|
@@ -150,8 +163,8 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
150
163
|
* than leaving a bare 401.
|
|
151
164
|
* 3. The hook threw — the key, or the key/organization pair, did not check out.
|
|
152
165
|
*
|
|
153
|
-
* On success the hook's {@link
|
|
154
|
-
* puts the resolved organization into `RequestContext` for every downstream repository call.
|
|
166
|
+
* On success the hook's {@link AuthenticatedCaller} is stamped exactly as a jwt parse's is, which is
|
|
167
|
+
* what puts the resolved organization into `RequestContext` for every downstream repository call.
|
|
155
168
|
*/
|
|
156
169
|
async enforceApiKey(name, meta) {
|
|
157
170
|
if (!this.apiKeyHook) {
|
|
@@ -166,9 +179,10 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
166
179
|
`publish an HttpRequest carrying the api-key headers.`);
|
|
167
180
|
throw new core_util_1.HttpUnauthorizedError('API key cannot be verified: no inbound request was published');
|
|
168
181
|
}
|
|
169
|
-
// Throws HttpUnauthorizedError to deny.
|
|
170
|
-
|
|
171
|
-
this.
|
|
182
|
+
// Throws HttpUnauthorizedError to deny. The hook gets the WHOLE request so it can cross-check
|
|
183
|
+
// the key against a second header (the organization the customer is acting for).
|
|
184
|
+
const caller = await this.apiKeyHook.verifyApiKey(name, request);
|
|
185
|
+
this.applyAuthenticatedCaller(caller);
|
|
172
186
|
}
|
|
173
187
|
/**
|
|
174
188
|
* A body that failed to parse is held on the {@link RawRequest} and surfaces HERE, after auth, as
|
|
@@ -228,7 +242,7 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
228
242
|
// `apikey` authenticates the SENDER — but the sender is a CUSTOMER's codebase, not a peer
|
|
229
243
|
// service in this repo, so its forwarded trusted context is exactly what must NOT be
|
|
230
244
|
// 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 (
|
|
245
|
+
// The hook's OWN derived entries still land (applyAuthenticatedCaller), and reconcileWireTrust then
|
|
232
246
|
// admits an inbound trusted header only when the hook independently derived the same value.
|
|
233
247
|
case 'apikey':
|
|
234
248
|
case 'local-only':
|
|
@@ -250,7 +264,7 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
250
264
|
* else is rejected — see {@link requireVouched}.
|
|
251
265
|
*
|
|
252
266
|
* Runs AFTER the mode enforcement above, because that is what stamps the authenticator's own
|
|
253
|
-
* values (`
|
|
267
|
+
* values (`applyAuthenticatedCaller`); comparing before it ran would compare against nothing.
|
|
254
268
|
*/
|
|
255
269
|
reconcileWireTrust(callerVerified) {
|
|
256
270
|
const pending = core_context_1.PendingWireTrust.takeAll();
|
|
@@ -325,9 +339,9 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
325
339
|
if (!this.jwtHook) {
|
|
326
340
|
throw new core_util_1.HttpUnauthorizedError('User-JWT auth is not enabled on this server');
|
|
327
341
|
}
|
|
328
|
-
const
|
|
329
|
-
this.
|
|
330
|
-
await this.jwtHook.authorizeJwt(
|
|
342
|
+
const caller = await this.jwtHook.parseJwt(token); // AUTHENTICATE — throws HttpUnauthorizedError if invalid
|
|
343
|
+
this.applyAuthenticatedCaller(caller);
|
|
344
|
+
await this.jwtHook.authorizeJwt(caller, requirement); // AUTHORIZE — app policy; throws HttpForbiddenError to deny
|
|
331
345
|
}
|
|
332
346
|
async enforceOidc(header, callers) {
|
|
333
347
|
const token = this.credential(header, BEARER_SCHEME);
|
|
@@ -362,21 +376,27 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends Filter_1.Filter {
|
|
|
362
376
|
}
|
|
363
377
|
// 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
|
|
364
378
|
try {
|
|
365
|
-
this.
|
|
379
|
+
this.applyAuthenticatedCaller(await this.jwtHook.parseJwt(token));
|
|
366
380
|
}
|
|
367
381
|
catch (err) {
|
|
368
382
|
const error = (0, core_util_1.toError)(err);
|
|
369
383
|
log.debug('Best-effort JWT parse on a public endpoint failed (treating as anonymous): ', error);
|
|
370
384
|
}
|
|
371
385
|
}
|
|
372
|
-
/**
|
|
373
|
-
|
|
374
|
-
|
|
386
|
+
/**
|
|
387
|
+
* Stamp the authenticated caller's context entries + the caller itself into the RequestContext.
|
|
388
|
+
* ONE path for all three authenticating hooks — jwt, api-key and webhook — so a vendor hook that
|
|
389
|
+
* proved which account a payload belongs to seeds context exactly as a JwtHook does.
|
|
390
|
+
*/
|
|
391
|
+
applyAuthenticatedCaller(caller) {
|
|
392
|
+
for (const entry of caller.entries) {
|
|
375
393
|
// ContextTuple.key is a TRUSTED key by type, so this is the one sanctioned write of a
|
|
376
|
-
// proven identity: the app's
|
|
394
|
+
// proven identity: the app's hook derived it from a credential we just verified.
|
|
377
395
|
core_context_1.RequestContext.putTrusted(entry.key, entry.value);
|
|
378
396
|
}
|
|
379
|
-
|
|
397
|
+
// A real TRUSTED ContextKey, not a raw string slot: the caller IS the framework's own proof,
|
|
398
|
+
// so it is written with the same typed verb every other proven value goes through.
|
|
399
|
+
core_context_1.RequestContext.putTrusted(AuthConfig_1.AUTHENTICATED_CALLER_KEY, caller);
|
|
380
400
|
}
|
|
381
401
|
/**
|
|
382
402
|
* The credential value IF the header carries the expected scheme, else undefined.
|
|
@@ -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,4CAA4I;AAC5I,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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,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;AA9XY,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;IAIzC,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,wBAAY,CAAC,CAAA;6CAjB2B,yCAAmB;QAGhB,uBAAU;QAGhB,mBAAO;QAGL,oBAAQ;QAIe,+BAAmB;QAIrC,sBAAU;GArBrE,UAAU,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"]}
|
|
1
|
+
{"version":3,"file":"AuthFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-routing/src/filters/AuthFilter.ts"],"names":[],"mappings":";;;;;AAAA,yCAA6C;AAC7C,mCAAyC;AACzC,0DAAwJ;AACxJ,oDAAyK;AACzK,sCAAwD;AAExD,8CAAsH;AACtH,4CAA4I;AAC5I,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;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGI,IAAM,UAAU,kBAAhB,MAAM,UAAW,SAAQ,eAAuC;IAIjB;IAGI;IAGH;IAGC;IAIY;IAIT;IApBvD,YAGkD,YAAiC,EAG7B,UAAuB,EAG1B,OAAiB,EAGhB,QAAmB,EAIP,mBAAyC,EAIlD,UAAuB;QAE1E,KAAK,EAAE,CAAC;QAnBsC,iBAAY,GAAZ,YAAY,CAAqB;QAG7B,eAAU,GAAV,UAAU,CAAa;QAG1B,YAAO,GAAP,OAAO,CAAU;QAGhB,aAAQ,GAAR,QAAQ,CAAW;QAIP,wBAAmB,GAAnB,mBAAmB,CAAsB;QAIlD,eAAU,GAAV,UAAU,CAAa;IAG9E,CAAC;IAED,iGAAiG;IACxF,KAAK,CAAC,MAAM,CACjB,IAAgB,EAChB,UAAoD;QAEpD,MAAM,IAA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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;IAIzC,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,wBAAY,CAAC,CAAA;6CAjB2B,yCAAmB;QAGhB,uBAAU;QAGhB,mBAAO;QAGL,oBAAQ;QAIe,+BAAmB;QAIrC,sBAAU;GArBrE,UAAU,CAqZtB","sourcesContent":["import { inject, optional } from 'inversify';\nimport { timingSafeEqual } from 'crypto';\nimport { provideFrameworkSingleton, HttpRequest, PendingWireTrust, PendingTrustedValue, RawHttpRequest, 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, AuthenticatedCaller, AUTHENTICATED_CALLER_KEY, 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/**\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 * Case 2 is checked HERE and nowhere else. {@link hasRawBytes} narrows the request to\n * {@link RawHttpRequest} at this one gate, so the hook's signature promises `raw` is present and\n * no vendor implementation ever writes `raw!` or a guard of its own.\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 if (!this.hasRawBytes(request)) {\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 // Throws HttpUnauthorizedError to deny. On success the vendor account the signature proved is\n // stamped through the SAME path a jwt or api-key caller takes.\n const caller = await this.webhookAuthCallback.verifyWebhook(name, request);\n this.applyAuthenticatedCaller(caller);\n }\n\n /**\n * The ONE place the framework decides a request carries the verbatim bytes. A TYPE PREDICATE, so\n * the `true` branch hands {@link enforceWebhook} a {@link RawHttpRequest} with no cast and no\n * non-null assertion — the bad state stops being representable past this line rather than being\n * re-thrown about by every hook.\n */\n private hasRawBytes(request: HttpRequest | undefined): request is RawHttpRequest {\n return request?.raw !== undefined;\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 AuthenticatedCaller} is stamped exactly as a jwt parse's is, which is\n * what 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. The hook gets the WHOLE request so it can cross-check\n // the key against a second header (the organization the customer is acting for).\n const caller = await this.apiKeyHook.verifyApiKey(name, request);\n this.applyAuthenticatedCaller(caller);\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 (applyAuthenticatedCaller), 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 (`applyAuthenticatedCaller`); 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 caller = await this.jwtHook.parseJwt(token); // AUTHENTICATE — throws HttpUnauthorizedError if invalid\n this.applyAuthenticatedCaller(caller);\n await this.jwtHook.authorizeJwt(caller, 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.applyAuthenticatedCaller(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 /**\n * Stamp the authenticated caller's context entries + the caller itself into the RequestContext.\n * ONE path for all three authenticating hooks — jwt, api-key and webhook — so a vendor hook that\n * proved which account a payload belongs to seeds context exactly as a JwtHook does.\n */\n private applyAuthenticatedCaller(caller: AuthenticatedCaller): void {\n for (const entry of caller.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 hook derived it from a credential we just verified.\n RequestContext.putTrusted(entry.key, entry.value);\n }\n // A real TRUSTED ContextKey, not a raw string slot: the caller IS the framework's own proof,\n // so it is written with the same typed verb every other proven value goes through.\n RequestContext.putTrusted(AUTHENTICATED_CALLER_KEY, caller);\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
|
@@ -5,7 +5,7 @@ export { provideSingletonDefaultForApi } from '@webpieces/core-context';
|
|
|
5
5
|
export { provideFrameworkSingleton, provideFrameworkSingletonDefaultForApi, buildFrameworkModule, } from '@webpieces/core-context';
|
|
6
6
|
export { ApiRoutingFactory, ClassType } from './ApiRoutingFactory';
|
|
7
7
|
export { Routes, RouteBuilder, RouteDefinition, FilterDefinition, } from './WebAppMeta';
|
|
8
|
-
export { HttpRequest, RawRequest } from '@webpieces/core-context';
|
|
8
|
+
export { HttpRequest, RawHttpRequest, RawRequest } from '@webpieces/core-context';
|
|
9
9
|
export { Filter, WpResponse, Service } from './Filter';
|
|
10
10
|
export { FilterChain } from './FilterChain';
|
|
11
11
|
export { MethodMeta } from './MethodMeta';
|
|
@@ -15,8 +15,8 @@ export { FilterMatcher, HttpFilter } from './FilterMatcher';
|
|
|
15
15
|
export { AppModules, RouteModule } from './AppModules';
|
|
16
16
|
export { ApiFactory } from './ApiFactory';
|
|
17
17
|
export { ApiClient, ApiClientProxy } from './ApiClient';
|
|
18
|
-
export { AuthConfig, AUTH_CONFIG,
|
|
19
|
-
export { JwtHook, JWT_HOOK, OidcHook, OIDC_HOOK, WebhookAuthCallback, WEBHOOK_AUTH_CALLBACK, ApiKeyHook, API_KEY_HOOK,
|
|
18
|
+
export { AuthConfig, AUTH_CONFIG, AuthenticatedCaller, AUTHENTICATED_CALLER_KEY, SharedSecrets } from './AuthConfig';
|
|
19
|
+
export { JwtHook, JWT_HOOK, OidcHook, OIDC_HOOK, WebhookAuthCallback, WEBHOOK_AUTH_CALLBACK, ApiKeyHook, API_KEY_HOOK, } 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.API_KEY_HOOK = exports.ApiKeyHook = exports.WEBHOOK_AUTH_CALLBACK = exports.WebhookAuthCallback = exports.OIDC_HOOK = exports.OidcHook = exports.JWT_HOOK = exports.JwtHook = exports.SharedSecrets = exports.
|
|
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.AUTHENTICATED_CALLER_KEY = exports.AuthenticatedCaller = 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; } });
|
|
@@ -88,7 +88,8 @@ Object.defineProperty(exports, "ApiClient", { enumerable: true, get: function ()
|
|
|
88
88
|
var AuthConfig_1 = require("./AuthConfig");
|
|
89
89
|
Object.defineProperty(exports, "AuthConfig", { enumerable: true, get: function () { return AuthConfig_1.AuthConfig; } });
|
|
90
90
|
Object.defineProperty(exports, "AUTH_CONFIG", { enumerable: true, get: function () { return AuthConfig_1.AUTH_CONFIG; } });
|
|
91
|
-
Object.defineProperty(exports, "
|
|
91
|
+
Object.defineProperty(exports, "AuthenticatedCaller", { enumerable: true, get: function () { return AuthConfig_1.AuthenticatedCaller; } });
|
|
92
|
+
Object.defineProperty(exports, "AUTHENTICATED_CALLER_KEY", { enumerable: true, get: function () { return AuthConfig_1.AUTHENTICATED_CALLER_KEY; } });
|
|
92
93
|
Object.defineProperty(exports, "SharedSecrets", { enumerable: true, get: function () { return AuthConfig_1.SharedSecrets; } });
|
|
93
94
|
var AuthHooks_1 = require("./AuthHooks");
|
|
94
95
|
Object.defineProperty(exports, "JwtHook", { enumerable: true, get: function () { return AuthHooks_1.JwtHook; } });
|
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,
|
|
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,2CAGs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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, RawHttpRequest, 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, AuthenticatedCaller, AUTHENTICATED_CALLER_KEY, SharedSecrets } from './AuthConfig';\nexport {\n JwtHook, JWT_HOOK,\n OidcHook, OIDC_HOOK,\n WebhookAuthCallback, WEBHOOK_AUTH_CALLBACK,\n ApiKeyHook, API_KEY_HOOK,\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"]}
|