@webpieces/http-routing 0.3.305 → 0.3.306

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/http-routing",
3
- "version": "0.3.305",
3
+ "version": "0.3.306",
4
4
  "description": "Decorator-based routing with auto-wiring for WebPieces",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -22,8 +22,8 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@inversifyjs/binding-decorators": "1.1.5",
25
- "@webpieces/core-context": "0.3.305",
26
- "@webpieces/core-util": "0.3.305",
25
+ "@webpieces/core-context": "0.3.306",
26
+ "@webpieces/core-util": "0.3.306",
27
27
  "inversify": "7.10.4",
28
28
  "minimatch": "10.0.1"
29
29
  }
@@ -1,30 +1,48 @@
1
+ import { ContextKey } from '@webpieces/core-util';
1
2
  /**
2
- * Principal - the authenticated caller established by {@link AuthConfig.verifyJwt}.
3
- * Data-only structure (a class, per the webpieces guidelines).
3
+ * ContextValue - one (ContextKey, value) pair the JWT parse plugin wants stamped into the
4
+ * RequestContext (e.g. USER_ID, ORG_ID). Data-only structure (a class, per the guidelines).
4
5
  */
5
- export declare class Principal {
6
+ export declare class ContextValue {
7
+ readonly key: ContextKey;
8
+ readonly value: unknown;
9
+ constructor(key: ContextKey, value: unknown);
10
+ }
11
+ /**
12
+ * AuthValues - what {@link AuthConfig.parseJwt} returns: the authenticated user's id + roles (used
13
+ * by the framework to stamp a principal and enforce @AuthJwt(...roles)) plus any extra context
14
+ * entries the app wants set (orgId, tenant, ...). The framework sets `entries` into RequestContext
15
+ * via {@link RequestContext.putHeader}. Data-only structure (a class, per the guidelines).
16
+ */
17
+ export declare class AuthValues {
6
18
  readonly userId: string;
7
- readonly claims: Record<string, unknown>;
8
- constructor(userId: string, claims?: Record<string, unknown>);
19
+ readonly roles: string[];
20
+ readonly entries: ContextValue[];
21
+ constructor(userId: string, roles?: string[], entries?: ContextValue[]);
9
22
  }
10
23
  /**
11
- * AuthConfig - the app-provided verifiers the framework {@link AuthFilter} injects to enforce
12
- * each endpoint's AuthMode. It is an ABSTRACT CLASS (not a Symbol) so it is injected by type
13
- * (per the webpieces no-symbol-di-tokens guidance) and rebindable in tests.
24
+ * AuthConfig - the ONE app-provided auth binding the framework {@link AuthFilter} injects to enforce
25
+ * each endpoint's AuthMode. It is a single abstract class (injected by type, per no-symbol-di-tokens)
26
+ * bound in the APP container and rebindable in tests. Each mechanism has its RIGHT shape:
14
27
  *
15
- * It is BOUND IN THE APP CONTAINER (appBindings) — remember the two containers: the framework
16
- * AuthFilter is resolved from the app child container, so the app's binding (or a test's
17
- * appOverrides rebind) is what it sees. Keeping the concrete verifiers here (not in http-routing)
18
- * means http-routing needs NO crypto / gcp-identity it stays transport- and provider-neutral.
28
+ * - `sharedSecrets` — STATE: the expected secret VALUE per name (from `@AuthSharedSecret(name)`).
29
+ * Prod fills it from env; a test binds `{ NAME: 'some-test-key' }` and can then
30
+ * exercise the shared-secret path (and a negative test with a wrong key).
31
+ * - `parseJwt` — PLUGIN: decode/verify a user JWT into {@link AuthValues} (userId, roles,
32
+ * context entries). Minting a JWT is a controller concern (login), not here.
33
+ * - `verifyOidc` — PLUGIN: verify a Google OIDC service-to-service token against the endpoint's
34
+ * caller allow-list. Fully generic — the company base wires it to
35
+ * @webpieces/gcp-identity once, so apps never customize OIDC.
19
36
  *
20
- * A public-only server need not bind one (AuthFilter injects it @optional); a non-public route
21
- * with no AuthConfig bound fails fast.
37
+ * Keeping the plugins app-side means http-routing needs NO jsonwebtoken / gcp-identity. AuthFilter
38
+ * injects this `@optional`: a public-only server binds none; a non-public route with no AuthConfig
39
+ * (or no value/plugin for its mode) fails fast.
22
40
  */
23
41
  export declare abstract class AuthConfig {
24
- /** Verify a user JWT (kind:'jwt'); return the principal or throw HttpUnauthorizedError. */
25
- abstract verifyJwt(token: string): Principal;
26
- /** Verify a Google OIDC token from an allowed caller SA (kind:'oidc'); throw on failure. */
42
+ /** Expected shared-secret values keyed by the `@AuthSharedSecret(name)` name. STATE. */
43
+ abstract readonly sharedSecrets: Record<string, string>;
44
+ /** Parse a user JWT (kind:'jwt'); return the auth values or throw HttpUnauthorizedError. */
45
+ abstract parseJwt(token: string): AuthValues;
46
+ /** Verify a Google OIDC token from an allowed caller (kind:'oidc'); throw on failure. */
27
47
  abstract verifyOidc(token: string, callers: string[]): Promise<void>;
28
- /** The expected shared secret for the given env var name (kind:'shared-secret'). */
29
- abstract sharedSecret(secretEnv: string): string | undefined;
30
48
  }
package/src/AuthConfig.js CHANGED
@@ -1,33 +1,55 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AuthConfig = exports.Principal = void 0;
3
+ exports.AuthConfig = exports.AuthValues = exports.ContextValue = void 0;
4
4
  /**
5
- * Principal - the authenticated caller established by {@link AuthConfig.verifyJwt}.
6
- * Data-only structure (a class, per the webpieces guidelines).
5
+ * ContextValue - one (ContextKey, value) pair the JWT parse plugin wants stamped into the
6
+ * RequestContext (e.g. USER_ID, ORG_ID). Data-only structure (a class, per the guidelines).
7
7
  */
8
- class Principal {
8
+ class ContextValue {
9
+ key;
10
+ value;
11
+ constructor(key,
12
+ // webpieces-disable no-any-unknown -- context values are arbitrary app-defined data
13
+ value) {
14
+ this.key = key;
15
+ this.value = value;
16
+ }
17
+ }
18
+ exports.ContextValue = ContextValue;
19
+ /**
20
+ * AuthValues - what {@link AuthConfig.parseJwt} returns: the authenticated user's id + roles (used
21
+ * by the framework to stamp a principal and enforce @AuthJwt(...roles)) plus any extra context
22
+ * entries the app wants set (orgId, tenant, ...). The framework sets `entries` into RequestContext
23
+ * via {@link RequestContext.putHeader}. Data-only structure (a class, per the guidelines).
24
+ */
25
+ class AuthValues {
9
26
  userId;
10
- claims;
11
- constructor(userId,
12
- // webpieces-disable no-any-unknown -- JWT claims are an arbitrary provider-defined bag
13
- claims = {}) {
27
+ roles;
28
+ entries;
29
+ constructor(userId, roles = [], entries = []) {
14
30
  this.userId = userId;
15
- this.claims = claims;
31
+ this.roles = roles;
32
+ this.entries = entries;
16
33
  }
17
34
  }
18
- exports.Principal = Principal;
35
+ exports.AuthValues = AuthValues;
19
36
  /**
20
- * AuthConfig - the app-provided verifiers the framework {@link AuthFilter} injects to enforce
21
- * each endpoint's AuthMode. It is an ABSTRACT CLASS (not a Symbol) so it is injected by type
22
- * (per the webpieces no-symbol-di-tokens guidance) and rebindable in tests.
37
+ * AuthConfig - the ONE app-provided auth binding the framework {@link AuthFilter} injects to enforce
38
+ * each endpoint's AuthMode. It is a single abstract class (injected by type, per no-symbol-di-tokens)
39
+ * bound in the APP container and rebindable in tests. Each mechanism has its RIGHT shape:
23
40
  *
24
- * It is BOUND IN THE APP CONTAINER (appBindings) — remember the two containers: the framework
25
- * AuthFilter is resolved from the app child container, so the app's binding (or a test's
26
- * appOverrides rebind) is what it sees. Keeping the concrete verifiers here (not in http-routing)
27
- * means http-routing needs NO crypto / gcp-identity it stays transport- and provider-neutral.
41
+ * - `sharedSecrets` — STATE: the expected secret VALUE per name (from `@AuthSharedSecret(name)`).
42
+ * Prod fills it from env; a test binds `{ NAME: 'some-test-key' }` and can then
43
+ * exercise the shared-secret path (and a negative test with a wrong key).
44
+ * - `parseJwt` — PLUGIN: decode/verify a user JWT into {@link AuthValues} (userId, roles,
45
+ * context entries). Minting a JWT is a controller concern (login), not here.
46
+ * - `verifyOidc` — PLUGIN: verify a Google OIDC service-to-service token against the endpoint's
47
+ * caller allow-list. Fully generic — the company base wires it to
48
+ * @webpieces/gcp-identity once, so apps never customize OIDC.
28
49
  *
29
- * A public-only server need not bind one (AuthFilter injects it @optional); a non-public route
30
- * with no AuthConfig bound fails fast.
50
+ * Keeping the plugins app-side means http-routing needs NO jsonwebtoken / gcp-identity. AuthFilter
51
+ * injects this `@optional`: a public-only server binds none; a non-public route with no AuthConfig
52
+ * (or no value/plugin for its mode) fails fast.
31
53
  */
32
54
  class AuthConfig {
33
55
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AuthConfig.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthConfig.ts"],"names":[],"mappings":";;;AAAA;;;GAGG;AACH,MAAa,SAAS;IAEE;IAEA;IAHpB,YACoB,MAAc;IAC9B,uFAAuF;IACvE,SAAkC,EAAE;QAFpC,WAAM,GAAN,MAAM,CAAQ;QAEd,WAAM,GAAN,MAAM,CAA8B;IACrD,CAAC;CACP;AAND,8BAMC;AAED;;;;;;;;;;;;GAYG;AACH,MAAsB,UAAU;CAS/B;AATD,gCASC","sourcesContent":["/**\n * Principal - the authenticated caller established by {@link AuthConfig.verifyJwt}.\n * Data-only structure (a class, per the webpieces guidelines).\n */\nexport class Principal {\n constructor(\n public readonly userId: string,\n // webpieces-disable no-any-unknown -- JWT claims are an arbitrary provider-defined bag\n public readonly claims: Record<string, unknown> = {},\n ) {}\n}\n\n/**\n * AuthConfig - the app-provided verifiers the framework {@link AuthFilter} injects to enforce\n * each endpoint's AuthMode. It is an ABSTRACT CLASS (not a Symbol) so it is injected by type\n * (per the webpieces no-symbol-di-tokens guidance) and rebindable in tests.\n *\n * It is BOUND IN THE APP CONTAINER (appBindings) remember the two containers: the framework\n * AuthFilter is resolved from the app child container, so the app's binding (or a test's\n * appOverrides rebind) is what it sees. Keeping the concrete verifiers here (not in http-routing)\n * means http-routing needs NO crypto / gcp-identity it stays transport- and provider-neutral.\n *\n * A public-only server need not bind one (AuthFilter injects it @optional); a non-public route\n * with no AuthConfig bound fails fast.\n */\nexport abstract class AuthConfig {\n /** Verify a user JWT (kind:'jwt'); return the principal or throw HttpUnauthorizedError. */\n abstract verifyJwt(token: string): Principal;\n\n /** Verify a Google OIDC token from an allowed caller SA (kind:'oidc'); throw on failure. */\n abstract verifyOidc(token: string, callers: string[]): Promise<void>;\n\n /** The expected shared secret for the given env var name (kind:'shared-secret'). */\n abstract sharedSecret(secretEnv: string): string | undefined;\n}\n"]}
1
+ {"version":3,"file":"AuthConfig.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthConfig.ts"],"names":[],"mappings":";;;AAEA;;;GAGG;AACH,MAAa,YAAY;IAED;IAEA;IAHpB,YACoB,GAAe;IAC/B,oFAAoF;IACpE,KAAc;QAFd,QAAG,GAAH,GAAG,CAAY;QAEf,UAAK,GAAL,KAAK,CAAS;IAC/B,CAAC;CACP;AAND,oCAMC;AAED;;;;;GAKG;AACH,MAAa,UAAU;IAEC;IACA;IACA;IAHpB,YACoB,MAAc,EACd,QAAkB,EAAE,EACpB,UAA0B,EAAE;QAF5B,WAAM,GAAN,MAAM,CAAQ;QACd,UAAK,GAAL,KAAK,CAAe;QACpB,YAAO,GAAP,OAAO,CAAqB;IAC7C,CAAC;CACP;AAND,gCAMC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAsB,UAAU;CAS/B;AATD,gCASC","sourcesContent":["import { ContextKey } from '@webpieces/core-util';\n\n/**\n * ContextValue - one (ContextKey, value) pair the JWT parse plugin wants stamped into the\n * RequestContext (e.g. USER_ID, ORG_ID). Data-only structure (a class, per the guidelines).\n */\nexport class ContextValue {\n constructor(\n public readonly key: ContextKey,\n // webpieces-disable no-any-unknown -- context values are arbitrary app-defined data\n public readonly value: unknown,\n ) {}\n}\n\n/**\n * AuthValues - what {@link AuthConfig.parseJwt} returns: the authenticated user's id + roles (used\n * by the framework to stamp a principal and enforce @AuthJwt(...roles)) plus any extra context\n * entries the app wants set (orgId, tenant, ...). The framework sets `entries` into RequestContext\n * via {@link RequestContext.putHeader}. Data-only structure (a class, per the guidelines).\n */\nexport class AuthValues {\n constructor(\n public readonly userId: string,\n public readonly roles: string[] = [],\n public readonly entries: ContextValue[] = [],\n ) {}\n}\n\n/**\n * AuthConfig - the ONE app-provided auth binding the framework {@link AuthFilter} injects to enforce\n * each endpoint's AuthMode. It is a single abstract class (injected by type, per no-symbol-di-tokens)\n * bound in the APP container and rebindable in tests. Each mechanism has its RIGHT shape:\n *\n * - `sharedSecrets` — STATE: the expected secret VALUE per name (from `@AuthSharedSecret(name)`).\n * Prod fills it from env; a test binds `{ NAME: 'some-test-key' }` and can then\n * exercise the shared-secret path (and a negative test with a wrong key).\n * - `parseJwt` — PLUGIN: decode/verify a user JWT into {@link AuthValues} (userId, roles,\n * context entries). Minting a JWT is a controller concern (login), not here.\n * - `verifyOidc` — PLUGIN: verify a Google OIDC service-to-service token against the endpoint's\n * caller allow-list. Fully generic the company base wires it to\n * @webpieces/gcp-identity once, so apps never customize OIDC.\n *\n * Keeping the plugins app-side means http-routing needs NO jsonwebtoken / gcp-identity. AuthFilter\n * injects this `@optional`: a public-only server binds none; a non-public route with no AuthConfig\n * (or no value/plugin for its mode) fails fast.\n */\nexport abstract class AuthConfig {\n /** Expected shared-secret values keyed by the `@AuthSharedSecret(name)` name. STATE. */\n abstract readonly sharedSecrets: Record<string, string>;\n\n /** Parse a user JWT (kind:'jwt'); return the auth values or throw HttpUnauthorizedError. */\n abstract parseJwt(token: string): AuthValues;\n\n /** Verify a Google OIDC token from an allowed caller (kind:'oidc'); throw on failure. */\n abstract verifyOidc(token: string, callers: string[]): Promise<void>;\n}\n"]}
@@ -2,14 +2,19 @@ import { Filter, WpResponse, Service } from '../Filter';
2
2
  import { MethodMeta } from '../MethodMeta';
3
3
  import { AuthConfig } from '../AuthConfig';
4
4
  /**
5
- * AuthFilter - the ONE framework auth filter, auto-installed just below the error filter on
6
- * every route. It is TRANSPORT-NEUTRAL: it reads the raw credential from the {@link HttpRequest}
7
- * in RequestContext (never express), so the SAME check runs over HTTP and via createApiClient.
5
+ * AuthFilter - the ONE framework auth filter, auto-installed just below the error filter on every
6
+ * route. It is TRANSPORT-NEUTRAL: it reads the raw credential from the {@link HttpRequest} in
7
+ * RequestContext (never express), so the SAME check runs over HTTP and via createApiClient.
8
8
  *
9
- * It enforces the endpoint's AuthMode (public/jwt/oidc/shared-secret) using the injected
10
- * {@link AuthConfig} the concrete verifiers are app-provided and container-bound (rebindable
11
- * in tests), so http-routing needs no crypto / gcp-identity. Replaces the old app AuthFilter +
12
- * framework ServiceAuthFilter and removes the express/api filter tier.
9
+ * It enforces the endpoint's AuthMode using the injected app-bound {@link AuthConfig}:
10
+ * - shared-secret constant-time compare vs the bound secret VALUE (state).
11
+ * - jwt → `parseJwt` stamp the user's context values + enforce @AuthJwt(...roles).
12
+ * - oidc → `verifyOidc` (delegates to gcp-identity in the company layer).
13
+ * - public → BEST-EFFORT jwt parse: if a token is present, stamp the user's context so a
14
+ * logged-out page still knows who is logged in; never fails.
15
+ *
16
+ * The verifiers/secrets are app-provided (rebindable in tests), so http-routing needs no
17
+ * jsonwebtoken / gcp-identity.
13
18
  */
14
19
  export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>> {
15
20
  private readonly authConfig?;
@@ -19,6 +24,10 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
19
24
  private enforceJwt;
20
25
  private enforceOidc;
21
26
  private enforceSharedSecret;
27
+ /** Parse a JWT if one is present, else do nothing — used on public routes; never throws. */
28
+ private bestEffortJwt;
29
+ /** Stamp the parsed user's context entries + the principal into the RequestContext. */
30
+ private applyAuthValues;
22
31
  private stripBearer;
23
32
  private constantTimeEquals;
24
33
  }
@@ -8,17 +8,23 @@ const core_context_1 = require("@webpieces/core-context");
8
8
  const core_util_1 = require("@webpieces/core-util");
9
9
  const Filter_1 = require("../Filter");
10
10
  const AuthConfig_1 = require("../AuthConfig");
11
- /** Reserved context key holding the authenticated Principal (stamped after a jwt verify). */
11
+ const log = core_util_1.LogManager.getLogger('AuthFilter');
12
+ /** Reserved context key holding the authenticated {@link AuthValues} (stamped after a jwt parse). */
12
13
  const PRINCIPAL_KEY = '__webpieces_principal__';
13
14
  /**
14
- * AuthFilter - the ONE framework auth filter, auto-installed just below the error filter on
15
- * every route. It is TRANSPORT-NEUTRAL: it reads the raw credential from the {@link HttpRequest}
16
- * in RequestContext (never express), so the SAME check runs over HTTP and via createApiClient.
15
+ * AuthFilter - the ONE framework auth filter, auto-installed just below the error filter on every
16
+ * route. It is TRANSPORT-NEUTRAL: it reads the raw credential from the {@link HttpRequest} in
17
+ * RequestContext (never express), so the SAME check runs over HTTP and via createApiClient.
17
18
  *
18
- * It enforces the endpoint's AuthMode (public/jwt/oidc/shared-secret) using the injected
19
- * {@link AuthConfig} the concrete verifiers are app-provided and container-bound (rebindable
20
- * in tests), so http-routing needs no crypto / gcp-identity. Replaces the old app AuthFilter +
21
- * framework ServiceAuthFilter and removes the express/api filter tier.
19
+ * It enforces the endpoint's AuthMode using the injected app-bound {@link AuthConfig}:
20
+ * - shared-secret constant-time compare vs the bound secret VALUE (state).
21
+ * - jwt → `parseJwt` stamp the user's context values + enforce @AuthJwt(...roles).
22
+ * - oidc → `verifyOidc` (delegates to gcp-identity in the company layer).
23
+ * - public → BEST-EFFORT jwt parse: if a token is present, stamp the user's context so a
24
+ * logged-out page still knows who is logged in; never fails.
25
+ *
26
+ * The verifiers/secrets are app-provided (rebindable in tests), so http-routing needs no
27
+ * jsonwebtoken / gcp-identity.
22
28
  */
23
29
  let AuthFilter = class AuthFilter extends Filter_1.Filter {
24
30
  authConfig;
@@ -29,19 +35,21 @@ let AuthFilter = class AuthFilter extends Filter_1.Filter {
29
35
  // webpieces-disable no-any-unknown -- Filter generic params use unknown for response flexibility
30
36
  async filter(meta, nextFilter) {
31
37
  const mode = meta.authMeta?.mode;
38
+ const authHeader = core_context_1.RequestContext.getRequest()?.getHeader(core_util_1.WebpiecesCoreHeaders.AUTHORIZATION);
32
39
  if (!mode || mode.kind === 'public') {
40
+ // Public: best-effort parse so a logged-out page can still know the logged-in user.
41
+ this.bestEffortJwt(authHeader);
33
42
  return nextFilter.invoke(meta);
34
43
  }
35
- const request = core_context_1.RequestContext.getRequest();
36
44
  switch (mode.kind) {
37
45
  case 'jwt':
38
- this.enforceJwt(request?.getHeader(core_util_1.WebpiecesCoreHeaders.AUTHORIZATION));
46
+ this.enforceJwt(authHeader, mode.roles);
39
47
  break;
40
48
  case 'oidc':
41
- await this.enforceOidc(request?.getHeader(core_util_1.WebpiecesCoreHeaders.AUTHORIZATION), mode.callers);
49
+ await this.enforceOidc(authHeader, mode.callers);
42
50
  break;
43
51
  case 'shared-secret':
44
- this.enforceSharedSecret(request?.getHeader(core_util_1.WebpiecesCoreHeaders.SHARED_SECRET), mode.secretEnv);
52
+ this.enforceSharedSecret(core_context_1.RequestContext.getRequest()?.getHeader(core_util_1.WebpiecesCoreHeaders.SHARED_SECRET), mode.secretEnv);
45
53
  break;
46
54
  }
47
55
  return nextFilter.invoke(meta);
@@ -52,13 +60,17 @@ let AuthFilter = class AuthFilter extends Filter_1.Filter {
52
60
  }
53
61
  return this.authConfig;
54
62
  }
55
- enforceJwt(header) {
63
+ enforceJwt(header, roles) {
56
64
  const token = this.stripBearer(header);
57
65
  if (!token) {
58
66
  throw new core_util_1.HttpUnauthorizedError('Authentication required');
59
67
  }
60
- const principal = this.requireAuthConfig().verifyJwt(token);
61
- core_context_1.RequestContext.put(PRINCIPAL_KEY, principal);
68
+ const values = this.requireAuthConfig().parseJwt(token); // throws HttpUnauthorizedError if invalid
69
+ this.applyAuthValues(values);
70
+ // @AuthJwt(...roles): empty = any authenticated user; non-empty = must hold at least one.
71
+ if (roles.length > 0 && !roles.some((role) => values.roles.includes(role))) {
72
+ throw new core_util_1.HttpForbiddenError(`Endpoint requires one of roles: ${roles.join(', ')}`);
73
+ }
62
74
  }
63
75
  async enforceOidc(header, callers) {
64
76
  const token = this.stripBearer(header);
@@ -68,11 +80,33 @@ let AuthFilter = class AuthFilter extends Filter_1.Filter {
68
80
  await this.requireAuthConfig().verifyOidc(token, callers);
69
81
  }
70
82
  enforceSharedSecret(provided, secretEnv) {
71
- const expected = this.requireAuthConfig().sharedSecret(secretEnv);
83
+ const expected = this.requireAuthConfig().sharedSecrets[secretEnv];
72
84
  if (!expected || !provided || !this.constantTimeEquals(provided, expected)) {
73
85
  throw new core_util_1.HttpUnauthorizedError('Invalid shared secret for @AuthSharedSecret endpoint');
74
86
  }
75
87
  }
88
+ /** Parse a JWT if one is present, else do nothing — used on public routes; never throws. */
89
+ bestEffortJwt(header) {
90
+ const token = this.stripBearer(header);
91
+ if (!this.authConfig || !token) {
92
+ return;
93
+ }
94
+ // 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
95
+ try {
96
+ this.applyAuthValues(this.authConfig.parseJwt(token));
97
+ }
98
+ catch (err) {
99
+ const error = (0, core_util_1.toError)(err);
100
+ log.debug('Best-effort JWT parse on a public endpoint failed (treating as anonymous): ', error);
101
+ }
102
+ }
103
+ /** Stamp the parsed user's context entries + the principal into the RequestContext. */
104
+ applyAuthValues(values) {
105
+ for (const entry of values.entries) {
106
+ core_context_1.RequestContext.putHeader(entry.key, entry.value);
107
+ }
108
+ core_context_1.RequestContext.put(PRINCIPAL_KEY, values);
109
+ }
76
110
  stripBearer(header) {
77
111
  if (!header) {
78
112
  return undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"AuthFilter.js","sourceRoot":"","sources":["../../../../../../packages/http/http-routing/src/filters/AuthFilter.ts"],"names":[],"mappings":";;;;AAAA,yCAAyD;AACzD,mCAAyC;AACzC,0DAAoF;AACpF,oDAAmF;AACnF,sCAAwD;AAExD,8CAA2C;AAE3C,6FAA6F;AAC7F,MAAM,aAAa,GAAG,yBAAyB,CAAC;AAEhD;;;;;;;;;GASG;AAII,IAAM,UAAU,GAAhB,MAAM,UAAW,SAAQ,eAAuC;IAId;IAHrD,YAGqD,UAAuB;QAExE,KAAK,EAAE,CAAC;QAFyC,eAAU,GAAV,UAAU,CAAa;IAG5E,CAAC;IAED,iGAAiG;IACxF,KAAK,CAAC,MAAM,CACjB,IAAgB,EAChB,UAAoD;QAEpD,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC;QACjC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ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e,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC;CACJ,CAAA;AAjFY,gCAAU;qBAAV,UAAU;IAHtB,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;IACb,iGAAiG;;IAKxF,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,uBAAU,CAAC,CAAA;6CAA+B,uBAAU;GAJnE,UAAU,CAiFtB","sourcesContent":["import { inject, injectable, optional } from 'inversify';\nimport { timingSafeEqual } from 'crypto';\nimport { provideFrameworkSingleton, RequestContext } from '@webpieces/core-context';\nimport { WebpiecesCoreHeaders, HttpUnauthorizedError } from '@webpieces/core-util';\nimport { Filter, WpResponse, Service } from '../Filter';\nimport { MethodMeta } from '../MethodMeta';\nimport { AuthConfig } from '../AuthConfig';\n\n/** Reserved context key holding the authenticated Principal (stamped after a jwt verify). */\nconst PRINCIPAL_KEY = '__webpieces_principal__';\n\n/**\n * AuthFilter - the ONE framework auth filter, auto-installed just below the error filter on\n * every route. It is TRANSPORT-NEUTRAL: it reads the raw credential from the {@link HttpRequest}\n * in RequestContext (never express), so the SAME check runs over HTTP and via createApiClient.\n *\n * It enforces the endpoint's AuthMode (public/jwt/oidc/shared-secret) using the injected\n * {@link AuthConfig} — the concrete verifiers are app-provided and container-bound (rebindable\n * in tests), so http-routing needs no crypto / gcp-identity. Replaces the old app AuthFilter +\n * framework ServiceAuthFilter and removes the express/api filter tier.\n */\n@provideFrameworkSingleton()\n@injectable()\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 // @optional: a public-only server need not bind an AuthConfig; a non-public route\n // then fails fast in requireAuthConfig().\n @optional() @inject(AuthConfig) private readonly authConfig?: AuthConfig,\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.authMeta?.mode;\n if (!mode || mode.kind === 'public') {\n return nextFilter.invoke(meta);\n }\n\n const request = RequestContext.getRequest();\n switch (mode.kind) {\n case 'jwt':\n this.enforceJwt(request?.getHeader(WebpiecesCoreHeaders.AUTHORIZATION));\n break;\n case 'oidc':\n await this.enforceOidc(request?.getHeader(WebpiecesCoreHeaders.AUTHORIZATION), mode.callers);\n break;\n case 'shared-secret':\n this.enforceSharedSecret(request?.getHeader(WebpiecesCoreHeaders.SHARED_SECRET), mode.secretEnv);\n break;\n }\n return nextFilter.invoke(meta);\n }\n\n private requireAuthConfig(): AuthConfig {\n if (!this.authConfig) {\n throw new HttpUnauthorizedError('No AuthConfig bound — cannot enforce a non-public endpoint');\n }\n return this.authConfig;\n }\n\n private enforceJwt(header: string | undefined): void {\n const token = this.stripBearer(header);\n if (!token) {\n throw new HttpUnauthorizedError('Authentication required');\n }\n const principal = this.requireAuthConfig().verifyJwt(token);\n RequestContext.put(PRINCIPAL_KEY, principal);\n }\n\n private async enforceOidc(header: string | undefined, callers: string[]): Promise<void> {\n const token = this.stripBearer(header);\n if (!token) {\n throw new HttpUnauthorizedError('Missing OIDC bearer token for @AuthOidc endpoint');\n }\n await this.requireAuthConfig().verifyOidc(token, callers);\n }\n\n private enforceSharedSecret(provided: string | undefined, secretEnv: string): void {\n const expected = this.requireAuthConfig().sharedSecret(secretEnv);\n if (!expected || !provided || !this.constantTimeEquals(provided, expected)) {\n throw new HttpUnauthorizedError('Invalid shared secret for @AuthSharedSecret endpoint');\n }\n }\n\n private stripBearer(header: string | undefined): string | undefined {\n if (!header) {\n return undefined;\n }\n const prefix = 'Bearer ';\n return header.startsWith(prefix) ? header.substring(prefix.length) : header;\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,yCAAyD;AACzD,mCAAyC;AACzC,0DAAoF;AACpF,oDAA4H;AAC5H,sCAAwD;AAExD,8CAAuD;AAEvD,MAAM,GAAG,GAAG,sBAAU,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;AAE/C,qGAAqG;AACrG,MAAM,aAAa,GAAG,yBAAyB,CAAC;AAEhD;;;;;;;;;;;;;;GAcG;AAII,IAAM,UAAU,GAAhB,MAAM,UAAW,SAAQ,eAAuC;IAId;IAHrD,YAGqD,UAAuB;QAExE,KAAK,EAAE,CAAC;QAFyC,eAAU,GAAV,UAAU,CAAa;IAG5E,CAAC;IAED,iGAAiG;IACxF,KAAK,CAAC,MAAM,CACjB,IAAgB,EAChB,UAAoD;QAEpD,MAAM,IAAI,GAAG,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC;QACjC,MAAM,UAAU,GAAG,6BAAc,CAAC,UAAU,EAAE,EAAE,SAAS,CAAC,gCAAoB,CAAC,aAAa,CAAC,CAAC;QAE9F,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAClC,oFAAoF;YACpF,IAAI,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;YAC/B,OAAO,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACnC,CAAC;QAED,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;YAChB,KAAK,KAAK;gBACN,IAAI,CAAC,UAAU,CAAC,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;gBACxC,MAAM;YACV,KAAK,MAAM;gBACP,MAAM,IAAI,CAAC,WAAW,CAAC,UAAU,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;gBACjD,MAAM;YACV,KAAK,eAAe;gBAChB,IAAI,CAAC,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C,CAAC;IAEO,WAAW,CAAC,MAA0B;QAC1C,IAAI,CAAC,MAAM,EAAE,CAAC;YACV,OAAO,SAAS,CAAC;QACrB,CAAC;QACD,MAAM,MAAM,GAAG,SAAS,CAAC;QACzB,OAAO,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;IAChF,CAAC;IAEO,kBAAkB,CAAC,CAAS,EAAE,CAAS;QAC3C,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QACpC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC;QACpC,IAAI,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,MAAM,EAAE,CAAC;YAC9B,OAAO,KAAK,CAAC;QACjB,CAAC;QACD,OAAO,IAAA,wBAAe,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACvC,CAAC;CACJ,CAAA;AAlHY,gCAAU;qBAAV,UAAU;IAHtB,IAAA,wCAAyB,GAAE;IAC3B,IAAA,sBAAU,GAAE;IACb,iGAAiG;;IAKxF,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,uBAAU,CAAC,CAAA;6CAA+B,uBAAU;GAJnE,UAAU,CAkHtB","sourcesContent":["import { inject, injectable, optional } from 'inversify';\nimport { timingSafeEqual } from 'crypto';\nimport { provideFrameworkSingleton, RequestContext } from '@webpieces/core-context';\nimport { WebpiecesCoreHeaders, HttpUnauthorizedError, HttpForbiddenError, LogManager, toError } from '@webpieces/core-util';\nimport { Filter, WpResponse, Service } from '../Filter';\nimport { MethodMeta } from '../MethodMeta';\nimport { AuthConfig, AuthValues } from '../AuthConfig';\n\nconst log = LogManager.getLogger('AuthFilter');\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 using the injected app-bound {@link AuthConfig}:\n * - shared-secret → constant-time compare vs the bound secret VALUE (state).\n * - jwt → `parseJwt` → stamp the user's context values + enforce @AuthJwt(...roles).\n * - oidc → `verifyOidc` (delegates to gcp-identity in the company layer).\n * - public → BEST-EFFORT jwt parse: if a token is present, stamp the user's context so a\n * logged-out page still knows who is logged in; never fails.\n *\n * The verifiers/secrets are app-provided (rebindable in tests), so http-routing needs no\n * jsonwebtoken / gcp-identity.\n */\n@provideFrameworkSingleton()\n@injectable()\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 // @optional: a public-only server need not bind an AuthConfig; a non-public route then\n // fails fast in requireAuthConfig().\n @optional() @inject(AuthConfig) private readonly authConfig?: AuthConfig,\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.authMeta?.mode;\n const authHeader = RequestContext.getRequest()?.getHeader(WebpiecesCoreHeaders.AUTHORIZATION);\n\n if (!mode || mode.kind === 'public') {\n // Public: best-effort parse so a logged-out page can still know the logged-in user.\n this.bestEffortJwt(authHeader);\n return nextFilter.invoke(meta);\n }\n\n switch (mode.kind) {\n case 'jwt':\n this.enforceJwt(authHeader, mode.roles);\n break;\n case 'oidc':\n await this.enforceOidc(authHeader, mode.callers);\n break;\n case 'shared-secret':\n this.enforceSharedSecret(\n RequestContext.getRequest()?.getHeader(WebpiecesCoreHeaders.SHARED_SECRET),\n mode.secretEnv,\n );\n break;\n }\n return nextFilter.invoke(meta);\n }\n\n private requireAuthConfig(): AuthConfig {\n if (!this.authConfig) {\n throw new HttpUnauthorizedError('No AuthConfig bound — cannot enforce a non-public endpoint');\n }\n return this.authConfig;\n }\n\n private enforceJwt(header: string | undefined, roles: string[]): void {\n const token = this.stripBearer(header);\n if (!token) {\n throw new HttpUnauthorizedError('Authentication required');\n }\n const values = this.requireAuthConfig().parseJwt(token); // throws HttpUnauthorizedError if invalid\n this.applyAuthValues(values);\n // @AuthJwt(...roles): empty = any authenticated user; non-empty = must hold at least one.\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 private async enforceOidc(header: string | undefined, callers: string[]): Promise<void> {\n const token = this.stripBearer(header);\n if (!token) {\n throw new HttpUnauthorizedError('Missing OIDC bearer token for @AuthOidc endpoint');\n }\n await this.requireAuthConfig().verifyOidc(token, callers);\n }\n\n private enforceSharedSecret(provided: string | undefined, secretEnv: string): void {\n const expected = this.requireAuthConfig().sharedSecrets[secretEnv];\n if (!expected || !provided || !this.constantTimeEquals(provided, expected)) {\n throw new HttpUnauthorizedError('Invalid shared secret for @AuthSharedSecret endpoint');\n }\n }\n\n /** Parse a JWT if one is present, else do nothing — used on public routes; never throws. */\n private bestEffortJwt(header: string | undefined): void {\n const token = this.stripBearer(header);\n if (!this.authConfig || !token) {\n return;\n }\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- best-effort on a public route: a bad/absent token just means \"not logged in\", must not fail the request\n try {\n this.applyAuthValues(this.authConfig.parseJwt(token));\n } catch (err: unknown) {\n const error = toError(err);\n log.debug('Best-effort JWT parse on a public endpoint failed (treating as anonymous): ', error);\n }\n }\n\n /** Stamp the parsed user's context entries + the principal into the RequestContext. */\n private applyAuthValues(values: AuthValues): void {\n for (const entry of values.entries) {\n RequestContext.putHeader(entry.key, entry.value);\n }\n RequestContext.put(PRINCIPAL_KEY, values);\n }\n\n private stripBearer(header: string | undefined): string | undefined {\n if (!header) {\n return undefined;\n }\n const prefix = 'Bearer ';\n return header.startsWith(prefix) ? header.substring(prefix.length) : header;\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
@@ -13,7 +13,7 @@ export { RouteHandler } from './RouteHandler';
13
13
  export { FilterMatcher, HttpFilter } from './FilterMatcher';
14
14
  export { ApiFactory } from './ApiFactory';
15
15
  export { ApiClient, ApiClientProxy } from './ApiClient';
16
- export { AuthConfig, Principal } from './AuthConfig';
16
+ export { AuthConfig, AuthValues, ContextValue } from './AuthConfig';
17
17
  export { fillContext } from './fillContext';
18
18
  export { WebpiecesRouter, WebpiecesRouterFactory, WebpiecesRouterOptions } from './WebpiecesRouter';
19
19
  export { setupRuntime, RuntimeSetupOptions } from './setupRuntime';
package/src/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WebpiecesRouterFactory = exports.WebpiecesRouter = exports.fillContext = exports.Principal = exports.AuthConfig = exports.ApiClient = exports.FilterMatcher = exports.RouteHandler = exports.MethodMeta = exports.FilterChain = exports.WpResponse = exports.Filter = exports.HttpRequest = exports.FilterDefinition = exports.RouteDefinition = exports.ApiRoutingFactory = exports.buildFrameworkModule = exports.provideFrameworkSingletonAs = exports.provideFrameworkSingleton = exports.provideTransient = exports.provideSingletonAs = exports.provideSingleton = 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.getEndpoints = exports.getApiPath = exports.Queue = exports.PubSub = exports.Rpc = exports.AuthSharedSecret = exports.AuthOidc = exports.AuthJwt = exports.Public = exports.AuthenticationConfig = exports.Authentication = exports.Endpoint = exports.ApiPath = void 0;
4
- exports.WEBPIECES_CONFIG_TOKEN = exports.WebpiecesConfig = exports.RequestContextReader = exports.RuntimeSetupOptions = exports.setupRuntime = void 0;
3
+ exports.WebpiecesRouter = exports.fillContext = exports.ContextValue = exports.AuthValues = exports.AuthConfig = exports.ApiClient = exports.FilterMatcher = exports.RouteHandler = exports.MethodMeta = exports.FilterChain = exports.WpResponse = exports.Filter = exports.HttpRequest = exports.FilterDefinition = exports.RouteDefinition = exports.ApiRoutingFactory = exports.buildFrameworkModule = exports.provideFrameworkSingletonAs = exports.provideFrameworkSingleton = exports.provideTransient = exports.provideSingletonAs = exports.provideSingleton = 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.getEndpoints = exports.getApiPath = exports.Queue = exports.PubSub = exports.Rpc = exports.AuthSharedSecret = exports.AuthOidc = exports.AuthJwt = exports.Public = exports.AuthenticationConfig = exports.Authentication = exports.Endpoint = exports.ApiPath = void 0;
4
+ exports.WEBPIECES_CONFIG_TOKEN = exports.WebpiecesConfig = exports.RequestContextReader = exports.RuntimeSetupOptions = exports.setupRuntime = exports.WebpiecesRouterFactory = 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; } });
@@ -73,10 +73,11 @@ var FilterMatcher_1 = require("./FilterMatcher");
73
73
  Object.defineProperty(exports, "FilterMatcher", { enumerable: true, get: function () { return FilterMatcher_1.FilterMatcher; } });
74
74
  var ApiClient_1 = require("./ApiClient");
75
75
  Object.defineProperty(exports, "ApiClient", { enumerable: true, get: function () { return ApiClient_1.ApiClient; } });
76
- // Auth: the app-provided, container-bound verifiers the framework AuthFilter injects.
76
+ // Auth: the app-provided, container-bound AuthConfig the framework AuthFilter injects.
77
77
  var AuthConfig_1 = require("./AuthConfig");
78
78
  Object.defineProperty(exports, "AuthConfig", { enumerable: true, get: function () { return AuthConfig_1.AuthConfig; } });
79
- Object.defineProperty(exports, "Principal", { enumerable: true, get: function () { return AuthConfig_1.Principal; } });
79
+ Object.defineProperty(exports, "AuthValues", { enumerable: true, get: function () { return AuthConfig_1.AuthValues; } });
80
+ Object.defineProperty(exports, "ContextValue", { enumerable: true, get: function () { return AuthConfig_1.ContextValue; } });
80
81
  // Above-boundary context setup shared by every transport adapter.
81
82
  var fillContext_1 = require("./fillContext");
82
83
  Object.defineProperty(exports, "fillContext", { enumerable: true, get: function () { return fillContext_1.fillContext; } });
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,kDA8B8B;AA7B1B,oGAAA,OAAO,OAAA;AACP,qGAAA,QAAQ,OAAA;AACR,2GAAA,cAAc,OAAA;AACd,iHAAA,oBAAoB,OAAA;AACpB,mGAAA,MAAM,OAAA;AACN,oGAAA,OAAO,OAAA;AACP,qGAAA,QAAQ,OAAA;AACR,6GAAA,gBAAgB,OAAA;AAChB,gGAAA,GAAG,OAAA;AACH,mGAAA,MAAM,OAAA;AACN,kGAAA,KAAK,OAAA;AACL,uGAAA,UAAU,OAAA;AACV,yGAAA,YAAY,OAAA;AACZ,sGAAA,SAAS,OAAA;AACT,wGAAA,WAAW,OAAA;AACX,wGAAA,WAAW,OAAA;AACX,2HAAA,8BAA8B,OAAA;AAC9B,uGAAA,U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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,oFAAoF;AACpF,wDAA+D;AAAtD,oHAAA,oBAAoB,OAAA;AAE7B,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 Authentication,\n AuthenticationConfig,\n Public,\n AuthJwt,\n AuthOidc,\n AuthSharedSecret,\n Rpc,\n PubSub,\n Queue,\n getApiPath,\n getEndpoints,\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 } 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 { provideSingleton, provideSingletonAs, provideTransient } from '@webpieces/core-context';\n// Framework-only DI registry (packages/** framework classes use these; see frameworkProvide.ts)\nexport {\n provideFrameworkSingleton,\n provideFrameworkSingletonAs,\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 } 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// 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 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 verifiers the framework AuthFilter injects.\nexport { AuthConfig, Principal } from './AuthConfig';\n\n// Above-boundary context setup shared by every transport adapter.\nexport { fillContext } from './fillContext';\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// Context readers (Node.js only) moved to core-context; re-exported for back-compat\nexport { RequestContextReader } from '@webpieces/core-context';\n\n// Server configuration\nexport { WebpiecesConfig, WEBPIECES_CONFIG_TOKEN } from './WebpiecesConfig';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/index.ts"],"names":[],"mappings":";;;;AAAA,0DAA0D;AAC1D,kDA8B8B;AA7B1B,oGAAA,OAAO,OAAA;AACP,qGAAA,QAAQ,OAAA;AACR,2GAAA,cAAc,OAAA;AACd,iHAAA,oBAAoB,OAAA;AACpB,mGAAA,MAAM,OAAA;AACN,oGAAA,OAAO,OAAA;AACP,qGAAA,QAAQ,OAAA;AACR,6GAAA,gBAAgB,OAAA;AAChB,gGAAA,GAAG,OAA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D;AAAnD,8GAAA,aAAa,OAAA;AAItB,yCAAwD;AAA/C,sGAAA,SAAS,OAAA;AAElB,uFAAuF;AACvF,2CAAoE;AAA3D,wGAAA,UAAU,OAAA;AAAE,wGAAA,UAAU,OAAA;AAAE,0GAAA,YAAY,OAAA;AAE7C,kEAAkE;AAClE,6CAA4C;AAAnC,0GAAA,WAAW,OAAA;AAEpB,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,oFAAoF;AACpF,wDAA+D;AAAtD,oHAAA,oBAAoB,OAAA;AAE7B,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 Authentication,\n AuthenticationConfig,\n Public,\n AuthJwt,\n AuthOidc,\n AuthSharedSecret,\n Rpc,\n PubSub,\n Queue,\n getApiPath,\n getEndpoints,\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 } 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 { provideSingleton, provideSingletonAs, provideTransient } from '@webpieces/core-context';\n// Framework-only DI registry (packages/** framework classes use these; see frameworkProvide.ts)\nexport {\n provideFrameworkSingleton,\n provideFrameworkSingletonAs,\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 } 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// 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 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 AuthConfig the framework AuthFilter injects.\nexport { AuthConfig, AuthValues, ContextValue } from './AuthConfig';\n\n// Above-boundary context setup shared by every transport adapter.\nexport { fillContext } from './fillContext';\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// Context readers (Node.js only) moved to core-context; re-exported for back-compat\nexport { RequestContextReader } from '@webpieces/core-context';\n\n// Server configuration\nexport { WebpiecesConfig, WEBPIECES_CONFIG_TOKEN } from './WebpiecesConfig';\n"]}