@webpieces/http-routing 0.4.924 → 0.4.925

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/README.md CHANGED
@@ -12,11 +12,14 @@ npm install @webpieces/http-routing
12
12
 
13
13
  ## OIDC on private Cloud Run
14
14
 
15
- `@WpAuth([oidc()])` primarily selects client-side Google ID-token generation. With invocation
16
- authentication and invoker IAM enabled, Cloud Run checks the invocation before it reaches
17
- `AuthFilter`; the framework retains supplementary server validation. No callers means delegate
18
- caller authorization to the edge; explicit callers add an application allow-list. Local tokens
19
- exercise the filter chain without proving deployed IAM or Google signature validation.
15
+ `@WpAuth([oidcSameProject()])` and `@WpAuth([oidcSvcs([...])])` select client-side Google
16
+ ID-token generation. With invocation authentication and invoker IAM enabled, Cloud Run checks the
17
+ invocation before it reaches `AuthFilter`; the framework then checks the caller itself.
18
+ `oidcSameProject()` admits any service account of this service's GCP project (open off GCP, where
19
+ there is no project), and `oidcSvcs([...])` only the listed accounts, which may belong to other
20
+ projects; an endpoint may pair the two, and the token is then verified once against both. A bound
21
+ `OidcHook` receives all of the endpoint's OIDC methods (`OidcAuthMethods`). Local tokens exercise
22
+ the filter chain without proving deployed IAM or Google signature validation.
20
23
  See [the Cloud Run OIDC security boundary](../../../docs/architecture/cloud-run-oidc.md) for the
21
24
  current verifier behavior and the assumptions required for that deployment model.
22
25
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webpieces/http-routing",
3
- "version": "0.4.924",
3
+ "version": "0.4.925",
4
4
  "description": "Decorator-based routing with auto-wiring for WebPieces",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -22,14 +22,14 @@
22
22
  },
23
23
  "dependencies": {
24
24
  "@inversifyjs/binding-decorators": "1.1.5",
25
- "@webpieces/core-context": "0.4.924",
26
- "@webpieces/core-util": "0.4.924",
27
- "@webpieces/gcp-identity": "0.4.924",
25
+ "@webpieces/core-context": "0.4.925",
26
+ "@webpieces/core-util": "0.4.925",
27
+ "@webpieces/gcp-identity": "0.4.925",
28
28
  "inversify": "7.10.4",
29
29
  "jsonwebtoken": "9.0.2",
30
30
  "minimatch": "10.0.1",
31
- "@webpieces/http-client-core": "0.4.924",
32
- "@webpieces/http-client-node": "0.4.924",
33
- "@webpieces/cloudtasks-client": "0.4.924"
31
+ "@webpieces/http-client-core": "0.4.925",
32
+ "@webpieces/http-client-node": "0.4.925",
33
+ "@webpieces/cloudtasks-client": "0.4.925"
34
34
  }
35
35
  }
@@ -1,4 +1,5 @@
1
1
  import { HttpRequest, RawHttpRequest } from '@webpieces/core-context';
2
+ import { OidcAuthMethods } from '@webpieces/core-util';
2
3
  import { AuthenticatedCaller, AuthenticatedMachineIdentity } from './AuthConfig';
3
4
  /** Framework-normalized result from an application-owned JWT mint operation. */
4
5
  export declare class MintedJwt {
@@ -23,12 +24,14 @@ export declare const JWT_HOOK: unique symbol;
23
24
  * autobind; rebindable in tests). Bind one ONLY to customize the caller policy — e.g. an app that reads an
24
25
  * `ALLOWED_OIDC_CALLERS` env var at its composition root and enforces that allow-list. When NO
25
26
  * OidcHook is bound, the framework {@link AuthFilter} runs the built-in {@link DefaultOidcVerifier}
26
- * directly, so a server that wires nothing still verifies Google OIDC against its `oidc(...callers)`
27
- * (else trusts the edge — any Google-signed caller). `verifyOidc` verifies the token against `callers`;
28
- * throw on failure.
27
+ * directly, so a server that wires nothing still verifies Google OIDC against the endpoint's caller
28
+ * scopes. `verifyOidc` receives EVERY OIDC method the endpoint declares ({@link OidcAuthMethods}: one,
29
+ * or one `oidcSameProject()` (`callerScope: 'same-project'`) plus one `oidcSvcs([...])`
30
+ * (`callerScope: 'services'` with its `callers`)), because they are one bearer credential: verify
31
+ * the token once, admit the call when ANY of them admits the caller, and throw otherwise.
29
32
  */
30
33
  export declare abstract class OidcHook {
31
- abstract verifyOidc(token: string, callers: string[]): Promise<AuthenticatedMachineIdentity>;
34
+ abstract verifyOidc(token: string, methods: OidcAuthMethods): Promise<AuthenticatedMachineIdentity>;
32
35
  }
33
36
  /**
34
37
  * DI identifier for the optional {@link OidcHook} binding. It is a Symbol (not the class) so the app
package/src/AuthHooks.js CHANGED
@@ -33,9 +33,11 @@ exports.JWT_HOOK = Symbol.for('JwtHook');
33
33
  * autobind; rebindable in tests). Bind one ONLY to customize the caller policy — e.g. an app that reads an
34
34
  * `ALLOWED_OIDC_CALLERS` env var at its composition root and enforces that allow-list. When NO
35
35
  * OidcHook is bound, the framework {@link AuthFilter} runs the built-in {@link DefaultOidcVerifier}
36
- * directly, so a server that wires nothing still verifies Google OIDC against its `oidc(...callers)`
37
- * (else trusts the edge — any Google-signed caller). `verifyOidc` verifies the token against `callers`;
38
- * throw on failure.
36
+ * directly, so a server that wires nothing still verifies Google OIDC against the endpoint's caller
37
+ * scopes. `verifyOidc` receives EVERY OIDC method the endpoint declares ({@link OidcAuthMethods}: one,
38
+ * or one `oidcSameProject()` (`callerScope: 'same-project'`) plus one `oidcSvcs([...])`
39
+ * (`callerScope: 'services'` with its `callers`)), because they are one bearer credential: verify
40
+ * the token once, admit the call when ANY of them admits the caller, and throw otherwise.
39
41
  */
40
42
  class OidcHook {
41
43
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AuthHooks.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthHooks.ts"],"names":[],"mappings":";;;AAGA,gFAAgF;AAChF,MAAa,SAAS;IAEE;IACA;IAFpB,YACoB,KAAa,EACb,qBAA6B;QAD7B,UAAK,GAAL,KAAK,CAAQ;QACb,0BAAqB,GAArB,qBAAqB,CAAQ;QAE7C,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;QAChF,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,qBAAqB,CAAC,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;CACJ;AAVD,8BAUC;AAED,+FAA+F;AAC/F,MAAsB,OAAO;CAG5B;AAHD,0BAGC;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAsB,UAAU;CAiB/B;AAjBD,gCAiBC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC","sourcesContent":["import { HttpRequest, RawHttpRequest } from '@webpieces/core-context';\nimport { AuthenticatedCaller, AuthenticatedMachineIdentity } from './AuthConfig';\n\n/** Framework-normalized result from an application-owned JWT mint operation. */\nexport class MintedJwt {\n constructor(\n public readonly token: string,\n public readonly expiresAtEpochSeconds: number,\n ) {\n if (token.trim() === '') throw new Error('Minted JWT token must be non-empty.');\n if (!Number.isFinite(expiresAtEpochSeconds)) {\n throw new Error('Minted JWT expiry must be a finite epoch-second value.');\n }\n }\n}\n\n/** Optional application JWT credential authority. Authorization lives in AuthorizationHook. */\nexport abstract class JwtHook<TMintRequest> {\n abstract mint(request: TMintRequest): Promise<MintedJwt>;\n abstract parseJwt(token: string): Promise<AuthenticatedCaller>;\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 `oidc(...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<AuthenticatedMachineIdentity>;\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 `webhook(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 `webhook(...)` 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 webhook} 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 ApiUnauthorizedError} 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 `webhook(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 * `webhook(...)` 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 `apiKey(regime, credentials)`: authenticate a\n * 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 `apiKey(...)` 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 EXTRACTS no api-key header: which headers carry the\n * credential is the app's business, and `getHeader` / `getHeaderValues` read as many as the regime\n * needs. The contract's `credentials` list DECLARES those header names for readers and spec\n * generators — it is documentation of the regime, never an instruction to this hook, so the hook\n * stays the single place the pair is actually validated. (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: `regime` 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 ApiUnauthorizedError} 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 * `apiKey(...)` — the mode is deliberately caller-NOT-verified (see `AuthFilter.verifiesCaller`),\n * because a customer is not an internal service.\n *\n * @param regime the first argument of the contract's `apiKey(regime, credentials)` — which key\n * regime this route belongs to.\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(regime: 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"]}
1
+ {"version":3,"file":"AuthHooks.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthHooks.ts"],"names":[],"mappings":";;;AAIA,gFAAgF;AAChF,MAAa,SAAS;IAEE;IACA;IAFpB,YACoB,KAAa,EACb,qBAA6B;QAD7B,UAAK,GAAL,KAAK,CAAQ;QACb,0BAAqB,GAArB,qBAAqB,CAAQ;QAE7C,IAAI,KAAK,CAAC,IAAI,EAAE,KAAK,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,qCAAqC,CAAC,CAAC;QAChF,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,qBAAqB,CAAC,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;CACJ;AAVD,8BAUC;AAED,+FAA+F;AAC/F,MAAsB,OAAO;CAG5B;AAHD,0BAGC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;AAE9C;;;;;;;;;;;GAWG;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAsB,UAAU;CAiB/B;AAjBD,gCAiBC;AAED;;;;GAIG;AACH,mNAAmN;AACtM,QAAA,YAAY,GAAG,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC","sourcesContent":["import { HttpRequest, RawHttpRequest } from '@webpieces/core-context';\nimport { OidcAuthMethods } from '@webpieces/core-util';\nimport { AuthenticatedCaller, AuthenticatedMachineIdentity } from './AuthConfig';\n\n/** Framework-normalized result from an application-owned JWT mint operation. */\nexport class MintedJwt {\n constructor(\n public readonly token: string,\n public readonly expiresAtEpochSeconds: number,\n ) {\n if (token.trim() === '') throw new Error('Minted JWT token must be non-empty.');\n if (!Number.isFinite(expiresAtEpochSeconds)) {\n throw new Error('Minted JWT expiry must be a finite epoch-second value.');\n }\n }\n}\n\n/** Optional application JWT credential authority. Authorization lives in AuthorizationHook. */\nexport abstract class JwtHook<TMintRequest> {\n abstract mint(request: TMintRequest): Promise<MintedJwt>;\n abstract parseJwt(token: string): Promise<AuthenticatedCaller>;\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 the endpoint's caller\n * scopes. `verifyOidc` receives EVERY OIDC method the endpoint declares ({@link OidcAuthMethods}: one,\n * or one `oidcSameProject()` (`callerScope: 'same-project'`) plus one `oidcSvcs([...])`\n * (`callerScope: 'services'` with its `callers`)), because they are one bearer credential: verify\n * the token once, admit the call when ANY of them admits the caller, and throw otherwise.\n */\nexport abstract class OidcHook {\n abstract verifyOidc(token: string, methods: OidcAuthMethods): Promise<AuthenticatedMachineIdentity>;\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 `webhook(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 `webhook(...)` 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 webhook} 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 ApiUnauthorizedError} 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 `webhook(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 * `webhook(...)` 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 `apiKey(regime, credentials)`: authenticate a\n * 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 `apiKey(...)` 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 EXTRACTS no api-key header: which headers carry the\n * credential is the app's business, and `getHeader` / `getHeaderValues` read as many as the regime\n * needs. The contract's `credentials` list DECLARES those header names for readers and spec\n * generators — it is documentation of the regime, never an instruction to this hook, so the hook\n * stays the single place the pair is actually validated. (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: `regime` 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 ApiUnauthorizedError} 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 * `apiKey(...)` — the mode is deliberately caller-NOT-verified (see `AuthFilter.verifiesCaller`),\n * because a customer is not an internal service.\n *\n * @param regime the first argument of the contract's `apiKey(regime, credentials)` — which key\n * regime this route belongs to.\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(regime: 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"]}
@@ -23,6 +23,14 @@ export declare class AuthHooksCompileAssertions {
23
23
  legitimate(): void;
24
24
  /** Every spelling this change deleted must now be UNWRITABLE. */
25
25
  rejected(): void;
26
+ /**
27
+ * {@link OidcHook.verifyOidc} receives EVERY OIDC method the endpoint declares ({@link OidcAuthMethods}),
28
+ * so a hook verifies the token once and can tell `oidcSameProject()` from `oidcSvcs([...])`. The
29
+ * caller-list override this change deletes (`callers: string[]`, where an EMPTY list meant "any
30
+ * Google-signed caller") and a one-method override, which could not see the other scope of a pair,
31
+ * must not compile.
32
+ */
33
+ oidcHookTakesTheMethods(): void;
26
34
  /**
27
35
  * An {@link HttpRequest} whose `raw` is merely OPTIONAL is NOT a {@link RawHttpRequest}. This is
28
36
  * the assignment that makes the narrowing real: without it, `RawHttpRequest` would be a comment.
@@ -66,6 +66,34 @@ class AuthHooksCompileAssertions {
66
66
  }
67
67
  };
68
68
  }
69
+ /**
70
+ * {@link OidcHook.verifyOidc} receives EVERY OIDC method the endpoint declares ({@link OidcAuthMethods}),
71
+ * so a hook verifies the token once and can tell `oidcSameProject()` from `oidcSvcs([...])`. The
72
+ * caller-list override this change deletes (`callers: string[]`, where an EMPTY list meant "any
73
+ * Google-signed caller") and a one-method override, which could not see the other scope of a pair,
74
+ * must not compile.
75
+ */
76
+ oidcHookTakesTheMethods() {
77
+ void class extends AuthHooks_1.OidcHook {
78
+ async verifyOidc(_token, methods) {
79
+ const first = methods[0];
80
+ const named = first.callerScope === 'services' ? first.callers[0] : 'same-project';
81
+ return new AuthConfig_1.AuthenticatedMachineIdentity('oidc', named);
82
+ }
83
+ };
84
+ void class extends AuthHooks_1.OidcHook {
85
+ // @ts-expect-error verifyOidc takes the endpoint's OidcAuthMethods; the deleted caller-list override must not compile
86
+ async verifyOidc(_token, _callers) {
87
+ return new AuthConfig_1.AuthenticatedMachineIdentity('oidc', 'caller@example.test');
88
+ }
89
+ };
90
+ void class extends AuthHooks_1.OidcHook {
91
+ // @ts-expect-error verifyOidc takes every OIDC method of the endpoint, not one, so a pair is verified once
92
+ async verifyOidc(_token, _method) {
93
+ return new AuthConfig_1.AuthenticatedMachineIdentity('oidc', 'caller@example.test');
94
+ }
95
+ };
96
+ }
69
97
  /**
70
98
  * An {@link HttpRequest} whose `raw` is merely OPTIONAL is NOT a {@link RawHttpRequest}. This is
71
99
  * the assignment that makes the narrowing real: without it, `RawHttpRequest` would be a comment.
@@ -1 +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"]}
1
+ {"version":3,"file":"AuthHooksCompileAssertions.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/AuthHooksCompileAssertions.ts"],"names":[],"mappings":";;;AAAA,0DAAkF;AAOlF,2CAAwE;AACxE,6CAAiF;AAEjF;;;;;;;;;;;;;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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CAAC,CAAC;YAC3D,CAAC;SACJ,CAAC;QACF,KAAK,KAAM,SAAQ,oBAAQ;YACvB,sHAAsH;YAC7G,KAAK,CAAC,UAAU,CAAC,MAAc,EAAE,QAAkB;gBACxD,OAAO,IAAI,yCAA4B,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAC;YAC3E,CAAC;SACJ,CAAC;QACF,KAAK,KAAM,SAAQ,oBAAQ;YACvB,2GAA2G;YAClG,KAAK,CAAC,UAAU,CAAC,MAAc,EAAE,OAAuB;gBAC7D,OAAO,IAAI,yCAA4B,CAAC,MAAM,EAAE,qBAAqB,CAAC,CAAC;YAC3E,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;AArGD,gEAqGC","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 { OidcAuthMethod, OidcAuthMethods } from '@webpieces/core-util';\nimport { ApiKeyHook, OidcHook, WebhookAuthCallback } from './AuthHooks';\nimport { AuthenticatedCaller, AuthenticatedMachineIdentity } 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 * {@link OidcHook.verifyOidc} receives EVERY OIDC method the endpoint declares ({@link OidcAuthMethods}),\n * so a hook verifies the token once and can tell `oidcSameProject()` from `oidcSvcs([...])`. The\n * caller-list override this change deletes (`callers: string[]`, where an EMPTY list meant \"any\n * Google-signed caller\") and a one-method override, which could not see the other scope of a pair,\n * must not compile.\n */\n oidcHookTakesTheMethods(): void {\n void class extends OidcHook {\n override async verifyOidc(_token: string, methods: OidcAuthMethods): Promise<AuthenticatedMachineIdentity> {\n const first = methods[0];\n const named = first.callerScope === 'services' ? first.callers[0] : 'same-project';\n return new AuthenticatedMachineIdentity('oidc', named);\n }\n };\n void class extends OidcHook {\n // @ts-expect-error verifyOidc takes the endpoint's OidcAuthMethods; the deleted caller-list override must not compile\n override async verifyOidc(_token: string, _callers: string[]): Promise<AuthenticatedMachineIdentity> {\n return new AuthenticatedMachineIdentity('oidc', 'caller@example.test');\n }\n };\n void class extends OidcHook {\n // @ts-expect-error verifyOidc takes every OIDC method of the endpoint, not one, so a pair is verified once\n override async verifyOidc(_token: string, _method: OidcAuthMethod): Promise<AuthenticatedMachineIdentity> {\n return new AuthenticatedMachineIdentity('oidc', 'caller@example.test');\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"]}
@@ -1,3 +1,4 @@
1
+ import { OidcAuthMethods } from '@webpieces/core-util';
1
2
  import { AuthenticatedMachineIdentity } from './AuthConfig';
2
3
  import { GcpOidc } from '@webpieces/gcp-identity';
3
4
  /**
@@ -6,17 +7,20 @@ import { GcpOidc } from '@webpieces/gcp-identity';
6
7
  * OIDC "just work" with ZERO wiring: http-routing depends on @webpieces/gcp-identity ON PURPOSE so a
7
8
  * server that binds nothing still verifies service-to-service OIDC.
8
9
  *
9
- * `verify` honors the endpoint's `oidc(...callers)` contract exactly: EMPTY (a bare `@WpAuth([oidc()])`)
10
- * = TRUST THE EDGE — verify the token is genuinely Google-signed and let the deployment's `run.invoker`
11
- * IAM restrict WHO (gcp-identity warns loudly, once, if the service is actually public and thus the
12
- * edge is NOT the gate). A non-empty list (`oidc('svc-a')`) enforces that explicit app-level
13
- * allow-list as defense-in-depth. Off-GCP, gcp-identity mints + accepts a dev token so local dev needs
14
- * no GCP. Framework code reads NO process.env — an app that wants an env-driven allow-list binds an
10
+ * `verify` honors the endpoint's caller scopes exactly, through `GcpOidc.verify`, which checks the
11
+ * token's signature ONCE and admits the call when ANY declared scope admits the caller:
12
+ * - `oidcSameProject()` (`callerScope: 'same-project'`) — a service account of THIS GCP project. Off
13
+ * GCP there is no project, so it is open.
14
+ * - `oidcSvcs([...])` (`callerScope: 'services'`) — one of the listed service accounts, which may live
15
+ * in other projects.
16
+ *
17
+ * Off-GCP, gcp-identity mints + accepts a dev token so local dev needs no GCP; on GCP it refuses one.
18
+ * Framework code reads NO process.env — an app that wants an env-driven allow-list binds an
15
19
  * {@link OidcHook} instead (env read at its composition root), keeping this default env-free and tests
16
20
  * parallel-safe.
17
21
  */
18
22
  export declare class DefaultOidcVerifier {
19
23
  private readonly gcpOidc;
20
24
  constructor(gcpOidc: GcpOidc);
21
- verify(token: string, callers: string[]): Promise<AuthenticatedMachineIdentity>;
25
+ verify(token: string, methods: OidcAuthMethods): Promise<AuthenticatedMachineIdentity>;
22
26
  }
@@ -13,12 +13,15 @@ const gcp_identity_1 = require("@webpieces/gcp-identity");
13
13
  * OIDC "just work" with ZERO wiring: http-routing depends on @webpieces/gcp-identity ON PURPOSE so a
14
14
  * server that binds nothing still verifies service-to-service OIDC.
15
15
  *
16
- * `verify` honors the endpoint's `oidc(...callers)` contract exactly: EMPTY (a bare `@WpAuth([oidc()])`)
17
- * = TRUST THE EDGE — verify the token is genuinely Google-signed and let the deployment's `run.invoker`
18
- * IAM restrict WHO (gcp-identity warns loudly, once, if the service is actually public and thus the
19
- * edge is NOT the gate). A non-empty list (`oidc('svc-a')`) enforces that explicit app-level
20
- * allow-list as defense-in-depth. Off-GCP, gcp-identity mints + accepts a dev token so local dev needs
21
- * no GCP. Framework code reads NO process.env — an app that wants an env-driven allow-list binds an
16
+ * `verify` honors the endpoint's caller scopes exactly, through `GcpOidc.verify`, which checks the
17
+ * token's signature ONCE and admits the call when ANY declared scope admits the caller:
18
+ * - `oidcSameProject()` (`callerScope: 'same-project'`) — a service account of THIS GCP project. Off
19
+ * GCP there is no project, so it is open.
20
+ * - `oidcSvcs([...])` (`callerScope: 'services'`) — one of the listed service accounts, which may live
21
+ * in other projects.
22
+ *
23
+ * Off-GCP, gcp-identity mints + accepts a dev token so local dev needs no GCP; on GCP it refuses one.
24
+ * Framework code reads NO process.env — an app that wants an env-driven allow-list binds an
22
25
  * {@link OidcHook} instead (env read at its composition root), keeping this default env-free and tests
23
26
  * parallel-safe.
24
27
  */
@@ -27,11 +30,8 @@ let DefaultOidcVerifier = class DefaultOidcVerifier {
27
30
  constructor(gcpOidc) {
28
31
  this.gcpOidc = gcpOidc;
29
32
  }
30
- async verify(token, callers) {
31
- // callers pass straight through: EMPTY (@WpAuth([oidc()]) with no callers) = TRUST THE EDGE, a
32
- // non-empty list enforces the explicit allow-list. Do NOT inject a ['self'] default — that
33
- // would reject a legitimate cross-SA caller the edge already admitted.
34
- const result = await this.gcpOidc.verifyFromCallers(token, callers);
33
+ async verify(token, methods) {
34
+ const result = await this.gcpOidc.verify(token, methods);
35
35
  if (!result.ok || !result.email) {
36
36
  throw new core_util_1.ApiUnauthorizedError(`OIDC rejected: ${result.reason ?? 'not an allowed caller'}`);
37
37
  }
@@ -1 +1 @@
1
- {"version":3,"file":"DefaultOidcVerifier.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/DefaultOidcVerifier.ts"],"names":[],"mappings":";;;;AAAA,yCAAmC;AACnC,0DAAoE;AACpE,oDAA4D;AAC5D,6CAA4D;AAC5D,0DAAkD;AAElD;;;;;;;;;;;;;;GAcG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAGU;IAFtC,YAEsC,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;IACnD,CAAC;IAEJ,KAAK,CAAC,MAAM,CAAC,KAAa,EAAE,OAAiB;QACzC,+FAA+F;QAC/F,2FAA2F;QAC3F,uEAAuE;QACvE,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YAC9B,MAAM,IAAI,gCAAoB,CAC1B,kBAAkB,MAAM,CAAC,MAAM,IAAI,uBAAuB,EAAE,CAC/D,CAAC;QACN,CAAC;QACD,OAAO,IAAI,yCAA4B,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;IAClE,CAAC;CACJ,CAAA;AAlBY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,wCAAyB,GAAE;IAInB,mBAAA,IAAA,kBAAM,EAAC,sBAAO,CAAC,CAAA;6CAA2B,sBAAO;GAH7C,mBAAmB,CAkB/B","sourcesContent":["import { inject } from 'inversify';\nimport { provideFrameworkSingleton } from '@webpieces/core-context';\nimport { ApiUnauthorizedError } from '@webpieces/core-util';\nimport { AuthenticatedMachineIdentity } from './AuthConfig';\nimport { GcpOidc } from '@webpieces/gcp-identity';\n\n/**\n * DefaultOidcVerifier - the framework's built-in Google OIDC verifier, injected into\n * {@link AuthFilter} and run directly whenever no app {@link OidcHook} is bound. It is what makes\n * OIDC \"just work\" with ZERO wiring: http-routing depends on @webpieces/gcp-identity ON PURPOSE so a\n * server that binds nothing still verifies service-to-service OIDC.\n *\n * `verify` honors the endpoint's `oidc(...callers)` contract exactly: EMPTY (a bare `@WpAuth([oidc()])`)\n * = TRUST THE EDGE — verify the token is genuinely Google-signed and let the deployment's `run.invoker`\n * IAM restrict WHO (gcp-identity warns loudly, once, if the service is actually public and thus the\n * edge is NOT the gate). A non-empty list (`oidc('svc-a')`) enforces that explicit app-level\n * allow-list as defense-in-depth. Off-GCP, gcp-identity mints + accepts a dev token so local dev needs\n * no GCP. Framework code reads NO process.env — an app that wants an env-driven allow-list binds an\n * {@link OidcHook} instead (env read at its composition root), keeping this default env-free and tests\n * parallel-safe.\n */\n@provideFrameworkSingleton()\nexport class DefaultOidcVerifier {\n constructor(\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- DI-resolved param; the esbuild/vitest path elides type-only imports (no design:paramtypes), so the explicit token is required\n @inject(GcpOidc) private readonly gcpOidc: GcpOidc,\n ) {}\n\n async verify(token: string, callers: string[]): Promise<AuthenticatedMachineIdentity> {\n // callers pass straight through: EMPTY (@WpAuth([oidc()]) with no callers) = TRUST THE EDGE, a\n // non-empty list enforces the explicit allow-list. Do NOT inject a ['self'] default — that\n // would reject a legitimate cross-SA caller the edge already admitted.\n const result = await this.gcpOidc.verifyFromCallers(token, callers);\n if (!result.ok || !result.email) {\n throw new ApiUnauthorizedError(\n `OIDC rejected: ${result.reason ?? 'not an allowed caller'}`,\n );\n }\n return new AuthenticatedMachineIdentity('oidc', result.email);\n }\n}\n"]}
1
+ {"version":3,"file":"DefaultOidcVerifier.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/DefaultOidcVerifier.ts"],"names":[],"mappings":";;;;AAAA,yCAAmC;AACnC,0DAAoE;AACpE,oDAA6E;AAC7E,6CAA4D;AAC5D,0DAAkD;AAElD;;;;;;;;;;;;;;;;;GAiBG;AAEI,IAAM,mBAAmB,GAAzB,MAAM,mBAAmB;IAGU;IAFtC,YAEsC,OAAgB;QAAhB,YAAO,GAAP,OAAO,CAAS;IACnD,CAAC;IAEJ,KAAK,CAAC,MAAM,CAAC,KAAa,EAAE,OAAwB;QAChD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;QACzD,IAAI,CAAC,MAAM,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YAC9B,MAAM,IAAI,gCAAoB,CAC1B,kBAAkB,MAAM,CAAC,MAAM,IAAI,uBAAuB,EAAE,CAC/D,CAAC;QACN,CAAC;QACD,OAAO,IAAI,yCAA4B,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;IAClE,CAAC;CACJ,CAAA;AAfY,kDAAmB;8BAAnB,mBAAmB;IAD/B,IAAA,wCAAyB,GAAE;IAInB,mBAAA,IAAA,kBAAM,EAAC,sBAAO,CAAC,CAAA;6CAA2B,sBAAO;GAH7C,mBAAmB,CAe/B","sourcesContent":["import { inject } from 'inversify';\nimport { provideFrameworkSingleton } from '@webpieces/core-context';\nimport { ApiUnauthorizedError, OidcAuthMethods } from '@webpieces/core-util';\nimport { AuthenticatedMachineIdentity } from './AuthConfig';\nimport { GcpOidc } from '@webpieces/gcp-identity';\n\n/**\n * DefaultOidcVerifier - the framework's built-in Google OIDC verifier, injected into\n * {@link AuthFilter} and run directly whenever no app {@link OidcHook} is bound. It is what makes\n * OIDC \"just work\" with ZERO wiring: http-routing depends on @webpieces/gcp-identity ON PURPOSE so a\n * server that binds nothing still verifies service-to-service OIDC.\n *\n * `verify` honors the endpoint's caller scopes exactly, through `GcpOidc.verify`, which checks the\n * token's signature ONCE and admits the call when ANY declared scope admits the caller:\n * - `oidcSameProject()` (`callerScope: 'same-project'`) — a service account of THIS GCP project. Off\n * GCP there is no project, so it is open.\n * - `oidcSvcs([...])` (`callerScope: 'services'`) — one of the listed service accounts, which may live\n * in other projects.\n *\n * Off-GCP, gcp-identity mints + accepts a dev token so local dev needs no GCP; on GCP it refuses one.\n * Framework code reads NO process.env — an app that wants an env-driven allow-list binds an\n * {@link OidcHook} instead (env read at its composition root), keeping this default env-free and tests\n * parallel-safe.\n */\n@provideFrameworkSingleton()\nexport class DefaultOidcVerifier {\n constructor(\n // webpieces-disable inject-annotation-not-needed-for-concrete-class -- DI-resolved param; the esbuild/vitest path elides type-only imports (no design:paramtypes), so the explicit token is required\n @inject(GcpOidc) private readonly gcpOidc: GcpOidc,\n ) {}\n\n async verify(token: string, methods: OidcAuthMethods): Promise<AuthenticatedMachineIdentity> {\n const result = await this.gcpOidc.verify(token, methods);\n if (!result.ok || !result.email) {\n throw new ApiUnauthorizedError(\n `OIDC rejected: ${result.reason ?? 'not an allowed caller'}`,\n );\n }\n return new AuthenticatedMachineIdentity('oidc', result.email);\n }\n}\n"]}
@@ -17,7 +17,8 @@ import { DefaultOidcVerifier } from '../DefaultOidcVerifier';
17
17
  * strategy may reach a JWKS or a datastore). No JwtHook bound → "not enabled"
18
18
  * (401): JWT needs an app secret + payload shape.
19
19
  * - oidc → the bound {@link OidcHook} if any, else the framework {@link DefaultOidcVerifier}
20
- * run DIRECTLY — so a server that wires NOTHING still verifies Google OIDC.
20
+ * run DIRECTLY — so a server that wires NOTHING still verifies Google OIDC against
21
+ * the endpoint's caller scope (`oidcSameProject()` or `oidcSvcs([...])`).
21
22
  * - webhook → the bound {@link WebhookAuthCallback} verifies the VENDOR's signature over the retained
22
23
  * raw request. No WebhookAuthCallback bound → 401, like jwt: an unverified webhook is
23
24
  * never waved through because wiring was forgotten.
@@ -41,7 +42,14 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
41
42
  private readonly callerContext;
42
43
  constructor(oidcVerifier: DefaultOidcVerifier, authConfig?: AuthConfig | undefined, jwtHook?: JwtHook<never> | undefined, oidcHook?: OidcHook | undefined, webhookAuthCallback?: WebhookAuthCallback | undefined, apiKeyHook?: ApiKeyHook | undefined);
43
44
  filter(meta: MethodMeta, nextFilter: Service<MethodMeta, WpResponse<unknown>>): Promise<WpResponse<unknown>>;
45
+ /**
46
+ * Try each declared credential in order. The endpoint's OIDC methods (one `oidcSameProject()` and
47
+ * one `oidcSvcs([...])` may pair) are ONE bearer credential, so they are ONE alternative, tried at
48
+ * the position of the first: the token is verified once against all of them.
49
+ */
44
50
  private authenticateAlternatives;
51
+ /** The endpoint's OIDC methods in declaration order, or undefined when it declares none. */
52
+ private static oidcMethodsOf;
45
53
  private authenticateMethod;
46
54
  /**
47
55
  * Stamp WHICH KIND OF CALLER this is, from the auth mode that matched — `jwt()` is a browser
@@ -54,7 +62,7 @@ export declare class AuthFilter extends Filter<MethodMeta, WpResponse<unknown>>
54
62
  * - the MCP bridge, which stamps `llm` before invoking a `@WpAuthorization` tool through `ApiFactory`
55
63
  * — that in-process hop still runs this filter, and its HTTP auth mode says nothing about the
56
64
  * model on the other end;
57
- * - a `oidc(...)` service-to-service hop, whose caller's surface arrived on the wire. OIDC is an
65
+ * - an OIDC (`oidcSameProject()` / `oidcSvcs(...)`) service-to-service hop, whose caller's surface arrived on the wire. OIDC is an
58
66
  * internal hop, NOT a surface of its own, so it deliberately maps to `undefined` below and the
59
67
  * propagated value survives.
60
68
  *
@@ -46,7 +46,8 @@ const SHARED_SECRET_SCHEME = 'Webpieces';
46
46
  * strategy may reach a JWKS or a datastore). No JwtHook bound → "not enabled"
47
47
  * (401): JWT needs an app secret + payload shape.
48
48
  * - oidc → the bound {@link OidcHook} if any, else the framework {@link DefaultOidcVerifier}
49
- * run DIRECTLY — so a server that wires NOTHING still verifies Google OIDC.
49
+ * run DIRECTLY — so a server that wires NOTHING still verifies Google OIDC against
50
+ * the endpoint's caller scope (`oidcSameProject()` or `oidcSvcs([...])`).
50
51
  * - webhook → the bound {@link WebhookAuthCallback} verifies the VENDOR's signature over the retained
51
52
  * raw request. No WebhookAuthCallback bound → 401, like jwt: an unverified webhook is
52
53
  * never waved through because wiring was forgotten.
@@ -99,28 +100,42 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends core_util_2.Filter {
99
100
  this.callerContext.reconcileWireTrust(AuthFilter_1.verifiesCaller(selected));
100
101
  return nextFilter.invoke(meta);
101
102
  }
103
+ /**
104
+ * Try each declared credential in order. The endpoint's OIDC methods (one `oidcSameProject()` and
105
+ * one `oidcSvcs([...])` may pair) are ONE bearer credential, so they are ONE alternative, tried at
106
+ * the position of the first: the token is verified once against all of them.
107
+ */
102
108
  async authenticateAlternatives(methods, header, meta) {
103
- for (const method of methods) {
109
+ const oidc = AuthFilter_1.oidcMethodsOf(methods);
110
+ const alternatives = methods.filter((method) => method.kind !== 'oidc' || method === oidc?.[0]);
111
+ for (const method of alternatives) {
104
112
  // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- failed credentials may try another declared authenticator; invariants propagate
105
113
  try {
106
- await this.authenticateMethod(method, header, meta);
114
+ await this.authenticateMethod(method, header, meta, oidc);
107
115
  return method;
108
116
  }
109
117
  catch (err) { // webpieces-disable no-any-unknown -- structured credential rejection at the boundary
110
118
  const error = (0, core_util_1.toError)(err);
111
- if (!(error instanceof core_util_1.ApiUnauthorizedError) || methods.length === 1)
119
+ if (!(error instanceof core_util_1.ApiUnauthorizedError) || alternatives.length === 1)
112
120
  throw error;
113
121
  }
114
122
  }
115
123
  throw new core_util_1.ApiUnauthorizedError('No declared credential mechanism authenticated this request.');
116
124
  }
117
- async authenticateMethod(mode, header, meta) {
125
+ /** The endpoint's OIDC methods in declaration order, or undefined when it declares none. */
126
+ // webpieces-disable no-function-outside-class -- static pure reader of the AuthMode list, kept beside its only caller
127
+ static oidcMethodsOf(methods) {
128
+ const oidc = methods.filter((method) => method.kind === 'oidc');
129
+ const first = oidc[0];
130
+ return first === undefined ? undefined : [first, ...oidc.slice(1)];
131
+ }
132
+ async authenticateMethod(mode, header, meta, oidc) {
118
133
  switch (mode.kind) {
119
134
  case 'jwt':
120
135
  await this.enforceJwt(header);
121
136
  return;
122
137
  case 'oidc':
123
- await this.enforceOidc(header, mode.callers);
138
+ await this.enforceOidc(header, oidc ?? [mode]);
124
139
  return;
125
140
  case 'shared-secret':
126
141
  this.enforceSharedSecret(this.credential(header, SHARED_SECRET_SCHEME), mode.secretKey);
@@ -146,7 +161,7 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends core_util_2.Filter {
146
161
  * - the MCP bridge, which stamps `llm` before invoking a `@WpAuthorization` tool through `ApiFactory`
147
162
  * — that in-process hop still runs this filter, and its HTTP auth mode says nothing about the
148
163
  * model on the other end;
149
- * - a `oidc(...)` service-to-service hop, whose caller's surface arrived on the wire. OIDC is an
164
+ * - an OIDC (`oidcSameProject()` / `oidcSvcs(...)`) service-to-service hop, whose caller's surface arrived on the wire. OIDC is an
150
165
  * internal hop, NOT a surface of its own, so it deliberately maps to `undefined` below and the
151
166
  * propagated value survives.
152
167
  *
@@ -348,13 +363,13 @@ let AuthFilter = AuthFilter_1 = class AuthFilter extends core_util_2.Filter {
348
363
  throw new core_util_1.ApiUnauthorizedError('User-JWT auth is not enabled on this server');
349
364
  this.callerContext.publish(await this.jwtHook.parseJwt(token));
350
365
  }
351
- async enforceOidc(header, callers) {
366
+ async enforceOidc(header, methods) {
352
367
  const token = this.credential(header, BEARER_SCHEME);
353
368
  if (!token)
354
369
  throw new core_util_1.ApiUnauthorizedError('Missing OIDC bearer token');
355
370
  const identity = this.oidcHook
356
- ? await this.oidcHook.verifyOidc(token, [...callers])
357
- : await this.oidcVerifier.verify(token, [...callers]);
371
+ ? await this.oidcHook.verifyOidc(token, methods)
372
+ : await this.oidcVerifier.verify(token, methods);
358
373
  if (!identity)
359
374
  throw new core_util_1.ApiImplementationError('OIDC verifier must return its verified machine identity.');
360
375
  core_context_1.RequestContext.putTrusted(AuthorizationHook_1.VERIFIED_MACHINE_CALLER, new AuthorizationHook_1.VerifiedMachineCaller(identity.mechanism, identity.identity));
@@ -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,0DAKiC;AACjC,oDAU8B;AAC9B,oDAAuD;AAGvD,8CAAuE;AACvE,4CASsB;AACtB,8EAA2E;AAC3E,4DAAsF;AACtF,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,kBAAuC;IAMjB;IAGI;IAGH;IAGC;IAM/B;IAIkC;IAxBtC,aAAa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AS,CAAC,CAAA;IAI7B,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IACV,mBAAA,IAAA,kBAAM,EAAC,iCAAqB,CAAC,CAAA;IAK7B,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,wBAAY,CAAC,CAAA;6CAnB2B,yCAAmB;QAGhB,uBAAU;QAGhB,mBAAO;QAGL,oBAAQ;QAM5B,+BAAmB;QAIM,sBAAU;GAzBrE,UAAU,CAgYtB","sourcesContent":["import { inject, optional } from 'inversify';\nimport { timingSafeEqual } from 'crypto';\nimport {\n provideFrameworkSingleton,\n HttpRequest,\n RawHttpRequest,\n RequestContext,\n} from '@webpieces/core-context';\nimport {\n AuthMode,\n ApiEndpointNotFoundError,\n ApiUnauthorizedError,\n ApiImplementationError,\n LogManager,\n RuntimeLocality,\n Surface,\n toError,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nimport { Filter, Service } from '@webpieces/core-util';\nimport { WpResponse } from '../WpResponse';\nimport { MethodMeta } from '../MethodMeta';\nimport { AuthConfig, AUTH_CONFIG, SharedSecrets } from '../AuthConfig';\nimport {\n ApiKeyHook,\n API_KEY_HOOK,\n JwtHook,\n JWT_HOOK,\n OidcHook,\n OIDC_HOOK,\n WebhookAuthCallback,\n WEBHOOK_AUTH_CALLBACK,\n} from '../AuthHooks';\nimport { AuthenticatedCallerContext } from '../AuthenticatedCallerContext';\nimport { VERIFIED_MACHINE_CALLER, VerifiedMachineCaller } from '../AuthorizationHook';\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 <sharedSecret(...) 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`, 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 private readonly callerContext = new AuthenticatedCallerContext();\n\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 sharedSecret(...) 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 jwt() 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<never>,\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 webhook(...) 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()\n @inject(WEBHOOK_AUTH_CALLBACK)\n private readonly webhookAuthCallback?: WebhookAuthCallback,\n // @optional: only bind an ApiKeyHook to enable apiKey(...) 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 auth = meta.routeMeta.authMeta;\n if (!auth) throw new ApiImplementationError('Every endpoint requires @WpAuth or @WpAuthPublic.');\n if (meta.routeMeta.localOnly) this.enforceLocalOnly(meta);\n if (meta.invocationAuthentication) {\n meta.invocationAuthentication.assertTarget(meta.routeMeta);\n return nextFilter.invoke(meta);\n }\n const header = RequestContext.getRequest()?.getHeader(AUTHORIZATION_HEADER);\n if (auth.methods[0].kind === 'public') {\n await this.bestEffortJwt(header);\n this.callerContext.reconcileWireTrust(false);\n return nextFilter.invoke(meta);\n }\n const selected = await this.authenticateAlternatives(auth.methods, header, meta);\n this.applySurface(selected);\n this.callerContext.reconcileWireTrust(AuthFilter.verifiesCaller(selected));\n return nextFilter.invoke(meta);\n }\n\n private async authenticateAlternatives(methods: readonly AuthMode[], header: string | undefined, meta: MethodMeta): Promise<AuthMode> {\n for (const method of methods) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- failed credentials may try another declared authenticator; invariants propagate\n try {\n await this.authenticateMethod(method, header, meta);\n return method;\n } catch (err: unknown) { // webpieces-disable no-any-unknown -- structured credential rejection at the boundary\n const error = toError(err);\n if (!(error instanceof ApiUnauthorizedError) || methods.length === 1) throw error;\n }\n }\n throw new ApiUnauthorizedError('No declared credential mechanism authenticated this request.');\n }\n\n private async authenticateMethod(mode: AuthMode, header: string | undefined, meta: MethodMeta): Promise<void> {\n switch (mode.kind) {\n case 'jwt': await this.enforceJwt(header); return;\n case 'oidc': await this.enforceOidc(header, mode.callers); return;\n case 'shared-secret':\n this.enforceSharedSecret(this.credential(header, SHARED_SECRET_SCHEME), mode.secretKey);\n RequestContext.putTrusted(VERIFIED_MACHINE_CALLER, new VerifiedMachineCaller('shared-secret', mode.secretKey));\n return;\n case 'webhook': await this.enforceWebhook(mode.name, meta); return;\n case 'apikey': await this.enforceApiKey(mode.regime, meta); return;\n case 'public': throw new ApiImplementationError('Public is not a protected auth alternative.');\n }\n }\n\n /**\n * Stamp WHICH KIND OF CALLER this is, from the auth mode that matched — `jwt()` is a browser\n * GUI, `apiKey(...)` is an external partner. See {@link Surface}.\n *\n * SET AT THE EDGE ONLY. The surface belongs to the ORIGINAL caller, so a hop that already has one\n * INHERITS it unchanged and this returns immediately. Two different callers put a value there\n * before this runs, and neither may be overwritten:\n *\n * - the MCP bridge, which stamps `llm` before invoking a `@WpAuthorization` tool through `ApiFactory`\n * — that in-process hop still runs this filter, and its HTTP auth mode says nothing about the\n * model on the other end;\n * - a `oidc(...)` service-to-service hop, whose caller's surface arrived on the wire. OIDC is an\n * internal hop, NOT a surface of its own, so it deliberately maps to `undefined` below and the\n * propagated value survives.\n *\n * Running BEFORE {@link reconcileWireTrust} is what makes the trusted-header rule work for this\n * key: on a `jwt()` edge a caller who also SENDS `x-wp-surface` must match the value the\n * framework just derived, and on a public route nothing vouches for it at all, so it is a 401.\n */\n private applySurface(mode: AuthMode): void {\n if (RequestContext.getTrusted(WebpiecesCoreHeaders.SURFACE) !== undefined) {\n return;\n }\n const surface = AuthFilter.surfaceFor(mode);\n if (surface !== undefined) {\n RequestContext.putTrusted(WebpiecesCoreHeaders.SURFACE, surface);\n }\n }\n\n /**\n * The auth mode -> {@link Surface} table, and the ONE place it is written down.\n *\n * `undefined` means \"this mode is not a surface\", which is a different statement from \"unknown\":\n * `oidc` and `shared-secret` are internal hops that RELAY somebody else's surface, `webhook`'s\n * sender is a vendor with no webpieces surface at all, and `local-only` is a developer's own box.\n *\n * An exhaustive switch with NO `default`, like {@link verifiesCaller} and\n * `DestinationTrust.forAuthMode`: a new AuthMode kind must fail to compile here rather than\n * silently landing on `gui` (which would publish 266 to a partner) or on `public-api` (which would\n * publish a real 4xx to a GUI).\n */\n // webpieces-disable no-function-outside-class -- static pure mapping from the AuthMode union, kept beside its only caller (mirrors verifiesCaller)\n private static surfaceFor(mode: AuthMode): Surface | undefined {\n switch (mode.kind) {\n case 'jwt':\n return 'gui';\n case 'apikey':\n return 'public-api';\n case 'oidc':\n case 'shared-secret':\n case 'webhook':\n case 'public':\n return undefined;\n }\n }\n\n /**\n * `webhook(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 webhook('${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 ApiUnauthorizedError('Webhook auth is not enabled on this server');\n }\n const request = RequestContext.getRequest();\n if (!this.hasRawBytes(request)) {\n log.warn(\n `Refusing webhook('${name}') endpoint ${meta.routeMeta.path}: the inbound request carries ` +\n `no raw bytes. Declare @Endpoint(POST, path, WRITE, 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 ApiUnauthorizedError(\n 'Webhook signature cannot be verified: no raw request was retained',\n );\n }\n // Throws ApiUnauthorizedError 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.callerContext.publish(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 * `apiKey(regime, credentials)`: hand the app's {@link ApiKeyHook} the regime name and the inbound\n * headers and let it look the CUSTOMER's key up. The declared `credentials` are NOT read here — they\n * describe the contract for generators; the hook owns extraction. Three ways to fail, all 401, all\n * 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(regime: string, meta: MethodMeta): Promise<void> {\n if (!this.apiKeyHook) {\n log.warn(\n `Refusing apiKey('${regime}') 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 ApiUnauthorizedError('API-key auth is not enabled on this server');\n }\n const request = RequestContext.getRequest();\n if (!request) {\n log.warn(\n `Refusing apiKey('${regime}') 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 ApiUnauthorizedError(\n 'API key cannot be verified: no inbound request was published',\n );\n }\n // Throws ApiUnauthorizedError 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(regime, request);\n this.callerContext.publish(caller);\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 return false;\n }\n }\n\n /**\n * `@WpLocalOnly`: 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 @WpLocalOnly 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 ApiEndpointNotFoundError(`No endpoint at ${meta.routeMeta.path}`);\n }\n\n private async enforceJwt(header: string | undefined): Promise<void> {\n const token = this.credential(header, BEARER_SCHEME);\n if (!token) throw new ApiUnauthorizedError('Authentication required');\n if (!this.jwtHook) throw new ApiUnauthorizedError('User-JWT auth is not enabled on this server');\n this.callerContext.publish(await this.jwtHook.parseJwt(token));\n }\n\n private async enforceOidc(header: string | undefined, callers: readonly string[]): Promise<void> {\n const token = this.credential(header, BEARER_SCHEME);\n if (!token) throw new ApiUnauthorizedError('Missing OIDC bearer token');\n const identity = this.oidcHook\n ? await this.oidcHook.verifyOidc(token, [...callers])\n : await this.oidcVerifier.verify(token, [...callers]);\n if (!identity) throw new ApiImplementationError('OIDC verifier must return its verified machine identity.');\n RequestContext.putTrusted(VERIFIED_MACHINE_CALLER, new VerifiedMachineCaller(identity.mechanism, identity.identity));\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 ApiUnauthorizedError(\n 'Invalid shared secret for sharedSecret(...) endpoint',\n );\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.callerContext.publish(await this.jwtHook.parseJwt(token));\n } catch (err: unknown) {\n const error = toError(err);\n if (!(error instanceof ApiUnauthorizedError)) throw error;\n log.debug(\n 'Best-effort JWT parse on a public endpoint failed (treating as anonymous): ',\n error,\n );\n }\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,0DAKiC;AACjC,oDAY8B;AAC9B,oDAAuD;AAGvD,8CAAuE;AACvE,4CASsB;AACtB,8EAA2E;AAC3E,4DAAsF;AACtF,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;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAGI,IAAM,UAAU,kBAAhB,MAAM,UAAW,SAAQ,kBAAuC;IAMjB;IAGI;IAGH;IAGC;IAM/B;IAIkC;IAxBtC,aAAa,GAAG,IAAI,uDAA0B,EAAE,CAAC;IAElE,YAGkD,YAAiC,EAG7B,UAAuB,EAG1B,OAAwB,EAGvB,QAAmB,EAMlD,mBAAyC,EAIP,UAAuB;QAE1E,KAAK,EAAE,CAAC;QArBsC,iBAAY,GAAZ,YAAY,CAAqB;QAG7B,eAAU,GAAV,UAAU,CAAa;QAG1B,YAAO,GAAP,OAAO,CAAiB;QAGvB,aAAQ,GAAR,QAAQ,CAAW;QAMlD,wBAAmB,GAAnB,mBAAmB,CAAsB;QAIP,eAAU,GAAV,UAAU,CAAa;IAG9E,CAAC;IAED,iGAAiG;IACxF,KAAK,CAAC,MAAM,CACjB,IAAgB,EAChB,UAAoD;QAEpD,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC;QACrC,IAAI,CAAC,IAAI;YAAE,MAAM,IAAI,kCAAsB,CAAC,mDAAmD,CAAC,CA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CAAC,CAAA;IAG5B,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,qBAAS,CAAC,CAAA;IAI7B,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IACV,mBAAA,IAAA,kBAAM,EAAC,iCAAqB,CAAC,CAAA;IAK7B,mBAAA,IAAA,oBAAQ,GAAE,CAAA;IAAE,mBAAA,IAAA,kBAAM,EAAC,wBAAY,CAAC,CAAA;6CAnB2B,yCAAmB;QAGhB,uBAAU;QAGhB,mBAAO;QAGL,oBAAQ;QAM5B,+BAAmB;QAIM,sBAAU;GAzBrE,UAAU,CA+YtB","sourcesContent":["import { inject, optional } from 'inversify';\nimport { timingSafeEqual } from 'crypto';\nimport {\n provideFrameworkSingleton,\n HttpRequest,\n RawHttpRequest,\n RequestContext,\n} from '@webpieces/core-context';\nimport {\n AuthMode,\n OidcAuthMethod,\n OidcAuthMethods,\n ApiEndpointNotFoundError,\n ApiUnauthorizedError,\n ApiImplementationError,\n LogManager,\n RuntimeLocality,\n Surface,\n toError,\n WebpiecesCoreHeaders,\n} from '@webpieces/core-util';\nimport { Filter, Service } from '@webpieces/core-util';\nimport { WpResponse } from '../WpResponse';\nimport { MethodMeta } from '../MethodMeta';\nimport { AuthConfig, AUTH_CONFIG, SharedSecrets } from '../AuthConfig';\nimport {\n ApiKeyHook,\n API_KEY_HOOK,\n JwtHook,\n JWT_HOOK,\n OidcHook,\n OIDC_HOOK,\n WebhookAuthCallback,\n WEBHOOK_AUTH_CALLBACK,\n} from '../AuthHooks';\nimport { AuthenticatedCallerContext } from '../AuthenticatedCallerContext';\nimport { VERIFIED_MACHINE_CALLER, VerifiedMachineCaller } from '../AuthorizationHook';\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 <sharedSecret(...) 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`, 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 against\n * the endpoint's caller scope (`oidcSameProject()` or `oidcSvcs([...])`).\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 private readonly callerContext = new AuthenticatedCallerContext();\n\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 sharedSecret(...) 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 jwt() 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<never>,\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 webhook(...) 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()\n @inject(WEBHOOK_AUTH_CALLBACK)\n private readonly webhookAuthCallback?: WebhookAuthCallback,\n // @optional: only bind an ApiKeyHook to enable apiKey(...) 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 auth = meta.routeMeta.authMeta;\n if (!auth) throw new ApiImplementationError('Every endpoint requires @WpAuth or @WpAuthPublic.');\n if (meta.routeMeta.localOnly) this.enforceLocalOnly(meta);\n if (meta.invocationAuthentication) {\n meta.invocationAuthentication.assertTarget(meta.routeMeta);\n return nextFilter.invoke(meta);\n }\n const header = RequestContext.getRequest()?.getHeader(AUTHORIZATION_HEADER);\n if (auth.methods[0].kind === 'public') {\n await this.bestEffortJwt(header);\n this.callerContext.reconcileWireTrust(false);\n return nextFilter.invoke(meta);\n }\n const selected = await this.authenticateAlternatives(auth.methods, header, meta);\n this.applySurface(selected);\n this.callerContext.reconcileWireTrust(AuthFilter.verifiesCaller(selected));\n return nextFilter.invoke(meta);\n }\n\n /**\n * Try each declared credential in order. The endpoint's OIDC methods (one `oidcSameProject()` and\n * one `oidcSvcs([...])` may pair) are ONE bearer credential, so they are ONE alternative, tried at\n * the position of the first: the token is verified once against all of them.\n */\n private async authenticateAlternatives(methods: readonly AuthMode[], header: string | undefined, meta: MethodMeta): Promise<AuthMode> {\n const oidc = AuthFilter.oidcMethodsOf(methods);\n const alternatives = methods.filter((method: AuthMode) => method.kind !== 'oidc' || method === oidc?.[0]);\n for (const method of alternatives) {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- failed credentials may try another declared authenticator; invariants propagate\n try {\n await this.authenticateMethod(method, header, meta, oidc);\n return method;\n } catch (err: unknown) { // webpieces-disable no-any-unknown -- structured credential rejection at the boundary\n const error = toError(err);\n if (!(error instanceof ApiUnauthorizedError) || alternatives.length === 1) throw error;\n }\n }\n throw new ApiUnauthorizedError('No declared credential mechanism authenticated this request.');\n }\n\n /** The endpoint's OIDC methods in declaration order, or undefined when it declares none. */\n // webpieces-disable no-function-outside-class -- static pure reader of the AuthMode list, kept beside its only caller\n private static oidcMethodsOf(methods: readonly AuthMode[]): OidcAuthMethods | undefined {\n const oidc = methods.filter((method: AuthMode): method is OidcAuthMethod => method.kind === 'oidc');\n const first = oidc[0];\n return first === undefined ? undefined : [first, ...oidc.slice(1)];\n }\n\n private async authenticateMethod(mode: AuthMode, header: string | undefined, meta: MethodMeta, oidc: OidcAuthMethods | undefined): Promise<void> {\n switch (mode.kind) {\n case 'jwt': await this.enforceJwt(header); return;\n case 'oidc': await this.enforceOidc(header, oidc ?? [mode]); return;\n case 'shared-secret':\n this.enforceSharedSecret(this.credential(header, SHARED_SECRET_SCHEME), mode.secretKey);\n RequestContext.putTrusted(VERIFIED_MACHINE_CALLER, new VerifiedMachineCaller('shared-secret', mode.secretKey));\n return;\n case 'webhook': await this.enforceWebhook(mode.name, meta); return;\n case 'apikey': await this.enforceApiKey(mode.regime, meta); return;\n case 'public': throw new ApiImplementationError('Public is not a protected auth alternative.');\n }\n }\n\n /**\n * Stamp WHICH KIND OF CALLER this is, from the auth mode that matched — `jwt()` is a browser\n * GUI, `apiKey(...)` is an external partner. See {@link Surface}.\n *\n * SET AT THE EDGE ONLY. The surface belongs to the ORIGINAL caller, so a hop that already has one\n * INHERITS it unchanged and this returns immediately. Two different callers put a value there\n * before this runs, and neither may be overwritten:\n *\n * - the MCP bridge, which stamps `llm` before invoking a `@WpAuthorization` tool through `ApiFactory`\n * — that in-process hop still runs this filter, and its HTTP auth mode says nothing about the\n * model on the other end;\n * - an OIDC (`oidcSameProject()` / `oidcSvcs(...)`) service-to-service hop, whose caller's surface arrived on the wire. OIDC is an\n * internal hop, NOT a surface of its own, so it deliberately maps to `undefined` below and the\n * propagated value survives.\n *\n * Running BEFORE {@link reconcileWireTrust} is what makes the trusted-header rule work for this\n * key: on a `jwt()` edge a caller who also SENDS `x-wp-surface` must match the value the\n * framework just derived, and on a public route nothing vouches for it at all, so it is a 401.\n */\n private applySurface(mode: AuthMode): void {\n if (RequestContext.getTrusted(WebpiecesCoreHeaders.SURFACE) !== undefined) {\n return;\n }\n const surface = AuthFilter.surfaceFor(mode);\n if (surface !== undefined) {\n RequestContext.putTrusted(WebpiecesCoreHeaders.SURFACE, surface);\n }\n }\n\n /**\n * The auth mode -> {@link Surface} table, and the ONE place it is written down.\n *\n * `undefined` means \"this mode is not a surface\", which is a different statement from \"unknown\":\n * `oidc` and `shared-secret` are internal hops that RELAY somebody else's surface, `webhook`'s\n * sender is a vendor with no webpieces surface at all, and `local-only` is a developer's own box.\n *\n * An exhaustive switch with NO `default`, like {@link verifiesCaller} and\n * `DestinationTrust.forAuthMode`: a new AuthMode kind must fail to compile here rather than\n * silently landing on `gui` (which would publish 266 to a partner) or on `public-api` (which would\n * publish a real 4xx to a GUI).\n */\n // webpieces-disable no-function-outside-class -- static pure mapping from the AuthMode union, kept beside its only caller (mirrors verifiesCaller)\n private static surfaceFor(mode: AuthMode): Surface | undefined {\n switch (mode.kind) {\n case 'jwt':\n return 'gui';\n case 'apikey':\n return 'public-api';\n case 'oidc':\n case 'shared-secret':\n case 'webhook':\n case 'public':\n return undefined;\n }\n }\n\n /**\n * `webhook(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 webhook('${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 ApiUnauthorizedError('Webhook auth is not enabled on this server');\n }\n const request = RequestContext.getRequest();\n if (!this.hasRawBytes(request)) {\n log.warn(\n `Refusing webhook('${name}') endpoint ${meta.routeMeta.path}: the inbound request carries ` +\n `no raw bytes. Declare @Endpoint(POST, path, WRITE, 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 ApiUnauthorizedError(\n 'Webhook signature cannot be verified: no raw request was retained',\n );\n }\n // Throws ApiUnauthorizedError 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.callerContext.publish(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 * `apiKey(regime, credentials)`: hand the app's {@link ApiKeyHook} the regime name and the inbound\n * headers and let it look the CUSTOMER's key up. The declared `credentials` are NOT read here — they\n * describe the contract for generators; the hook owns extraction. Three ways to fail, all 401, all\n * 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(regime: string, meta: MethodMeta): Promise<void> {\n if (!this.apiKeyHook) {\n log.warn(\n `Refusing apiKey('${regime}') 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 ApiUnauthorizedError('API-key auth is not enabled on this server');\n }\n const request = RequestContext.getRequest();\n if (!request) {\n log.warn(\n `Refusing apiKey('${regime}') 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 ApiUnauthorizedError(\n 'API key cannot be verified: no inbound request was published',\n );\n }\n // Throws ApiUnauthorizedError 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(regime, request);\n this.callerContext.publish(caller);\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 return false;\n }\n }\n\n /**\n * `@WpLocalOnly`: 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 @WpLocalOnly 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 ApiEndpointNotFoundError(`No endpoint at ${meta.routeMeta.path}`);\n }\n\n private async enforceJwt(header: string | undefined): Promise<void> {\n const token = this.credential(header, BEARER_SCHEME);\n if (!token) throw new ApiUnauthorizedError('Authentication required');\n if (!this.jwtHook) throw new ApiUnauthorizedError('User-JWT auth is not enabled on this server');\n this.callerContext.publish(await this.jwtHook.parseJwt(token));\n }\n\n private async enforceOidc(header: string | undefined, methods: OidcAuthMethods): Promise<void> {\n const token = this.credential(header, BEARER_SCHEME);\n if (!token) throw new ApiUnauthorizedError('Missing OIDC bearer token');\n const identity = this.oidcHook\n ? await this.oidcHook.verifyOidc(token, methods)\n : await this.oidcVerifier.verify(token, methods);\n if (!identity) throw new ApiImplementationError('OIDC verifier must return its verified machine identity.');\n RequestContext.putTrusted(VERIFIED_MACHINE_CALLER, new VerifiedMachineCaller(identity.mechanism, identity.identity));\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 ApiUnauthorizedError(\n 'Invalid shared secret for sharedSecret(...) endpoint',\n );\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.callerContext.publish(await this.jwtHook.parseJwt(token));\n } catch (err: unknown) {\n const error = toError(err);\n if (!(error instanceof ApiUnauthorizedError)) throw error;\n log.debug(\n 'Best-effort JWT parse on a public endpoint failed (treating as anonymous): ',\n error,\n );\n }\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
@@ -1,4 +1,4 @@
1
- export { ApiPath, Endpoint, PathParam, QueryParam, WpAuthPublic, WpAuth, WpLocalOnly, isLocalOnly, jwt, oidc, sharedSecret, webhook, apiKey, WpAuthorization, AuthorizationType, getAuthorization, Rpc, PubSub, Queue, getApiPath, getEndpoints, getEndpointOptions, getEndpointHttpMethod, getEndpointOperation, getHttpParameterDeclarations, isFormPost, isRawBody, isApiPath, getAuthMeta, assertEveryEndpointHasAuthMode, getApiKind, assertApiKind, assertPubSubConventions, getQueueName, AuthMeta, RouteMetadata, RouteMetadataFactory, HttpContractMapper, METADATA_KEYS, ValidateImplementation, GET, POST, READ, WRITE_IDEMPOTENT, WRITE, RPC, CLOUDTASKS, CRON, EXTERNAL, DocumentDesign, isDocumentDesign, } from '@webpieces/core-util';
1
+ export { ApiPath, Endpoint, PathParam, QueryParam, WpAuthPublic, WpAuth, WpLocalOnly, isLocalOnly, jwt, oidcSameProject, oidcSvcs, sharedSecret, webhook, apiKey, WpAuthorization, AuthorizationType, getAuthorization, Rpc, PubSub, Queue, getApiPath, getEndpoints, getEndpointOptions, getEndpointHttpMethod, getEndpointOperation, getHttpParameterDeclarations, isFormPost, isRawBody, isApiPath, getAuthMeta, assertEveryEndpointHasAuthMode, getApiKind, assertApiKind, assertPubSubConventions, getQueueName, AuthMeta, RouteMetadata, RouteMetadataFactory, HttpContractMapper, METADATA_KEYS, ValidateImplementation, GET, POST, READ, WRITE_IDEMPOTENT, WRITE, RPC, CLOUDTASKS, CRON, EXTERNAL, DocumentDesign, isDocumentDesign, } from '@webpieces/core-util';
2
2
  export type { AuthMode, ApiKind, HttpMethod, EndpointOperation, EndpointKind, EndpointOptions, EndpointResponseType, } from '@webpieces/core-util';
3
3
  export { SourceFile, ROUTING_METADATA_KEYS } from './decorators';
4
4
  export { provideSingletonDefaultForApi } from '@webpieces/core-context';
package/src/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isDocumentDesign = exports.DocumentDesign = exports.EXTERNAL = exports.CRON = exports.CLOUDTASKS = exports.RPC = exports.WRITE = exports.WRITE_IDEMPOTENT = exports.READ = exports.POST = exports.GET = exports.METADATA_KEYS = exports.HttpContractMapper = exports.RouteMetadataFactory = exports.RouteMetadata = exports.AuthMeta = exports.getQueueName = exports.assertPubSubConventions = exports.assertApiKind = exports.getApiKind = exports.assertEveryEndpointHasAuthMode = exports.getAuthMeta = exports.isApiPath = exports.isRawBody = exports.isFormPost = exports.getHttpParameterDeclarations = exports.getEndpointOperation = exports.getEndpointHttpMethod = exports.getEndpointOptions = exports.getEndpoints = exports.getApiPath = exports.Queue = exports.PubSub = exports.Rpc = exports.getAuthorization = exports.AuthorizationType = exports.WpAuthorization = exports.apiKey = exports.webhook = exports.sharedSecret = exports.oidc = exports.jwt = exports.isLocalOnly = exports.WpLocalOnly = exports.WpAuth = exports.WpAuthPublic = exports.QueryParam = exports.PathParam = exports.Endpoint = exports.ApiPath = void 0;
4
- exports.CanonicalUserRoles = exports.AuthorizationService = exports.AuthorizationHook = exports.WEBPIECES_CONFIG_TOKEN = exports.WebpiecesConfig = exports.RuntimeSetupOptions = exports.setupRuntime = exports.WebpiecesRouterFactory = exports.WebpiecesRouter = exports.DefaultJwtMintRequest = 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.MintedJwt = exports.JwtHook = exports.SharedSecrets = exports.AUTHENTICATED_CALLER_KEY = exports.AuthenticatedMachineIdentity = exports.AuthenticatedCaller = exports.AUTH_CONFIG = exports.AuthConfig = exports.ApiClient = exports.PubSubBindOptions = exports.ClientBindOptions = exports.ContainerBinder = exports.NodeWiringModules = exports.FilterMatcher = exports.LogApiFilter = exports.RouteHandler = exports.MethodMeta = exports.InvocationAuthentication = exports.AuthenticatedCallerContext = exports.WpResponse = exports.RawRequest = exports.HttpRequest = exports.FilterDefinition = exports.RouteDefinition = exports.ApiRoutingFactory = exports.buildFrameworkModule = exports.provideFrameworkSingletonDefaultForApi = exports.provideFrameworkSingleton = exports.provideSingletonDefaultForApi = exports.ROUTING_METADATA_KEYS = exports.SourceFile = void 0;
5
- exports.WiringPolicy = exports.AuthorizedApiDocument = exports.VerifiedMachineCaller = exports.VERIFIED_MACHINE_CALLER = exports.AUTHORIZATION_HOOK = void 0;
3
+ exports.DocumentDesign = exports.EXTERNAL = exports.CRON = exports.CLOUDTASKS = exports.RPC = exports.WRITE = exports.WRITE_IDEMPOTENT = exports.READ = exports.POST = exports.GET = exports.METADATA_KEYS = exports.HttpContractMapper = exports.RouteMetadataFactory = exports.RouteMetadata = exports.AuthMeta = exports.getQueueName = exports.assertPubSubConventions = exports.assertApiKind = exports.getApiKind = exports.assertEveryEndpointHasAuthMode = exports.getAuthMeta = exports.isApiPath = exports.isRawBody = exports.isFormPost = exports.getHttpParameterDeclarations = exports.getEndpointOperation = exports.getEndpointHttpMethod = exports.getEndpointOptions = exports.getEndpoints = exports.getApiPath = exports.Queue = exports.PubSub = exports.Rpc = exports.getAuthorization = exports.AuthorizationType = exports.WpAuthorization = exports.apiKey = exports.webhook = exports.sharedSecret = exports.oidcSvcs = exports.oidcSameProject = exports.jwt = exports.isLocalOnly = exports.WpLocalOnly = exports.WpAuth = exports.WpAuthPublic = exports.QueryParam = exports.PathParam = exports.Endpoint = exports.ApiPath = void 0;
4
+ exports.AuthorizationService = exports.AuthorizationHook = exports.WEBPIECES_CONFIG_TOKEN = exports.WebpiecesConfig = exports.RuntimeSetupOptions = exports.setupRuntime = exports.WebpiecesRouterFactory = exports.WebpiecesRouter = exports.DefaultJwtMintRequest = 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.MintedJwt = exports.JwtHook = exports.SharedSecrets = exports.AUTHENTICATED_CALLER_KEY = exports.AuthenticatedMachineIdentity = exports.AuthenticatedCaller = exports.AUTH_CONFIG = exports.AuthConfig = exports.ApiClient = exports.PubSubBindOptions = exports.ClientBindOptions = exports.ContainerBinder = exports.NodeWiringModules = exports.FilterMatcher = exports.LogApiFilter = exports.RouteHandler = exports.MethodMeta = exports.InvocationAuthentication = exports.AuthenticatedCallerContext = exports.WpResponse = 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 = void 0;
5
+ exports.WiringPolicy = exports.AuthorizedApiDocument = exports.VerifiedMachineCaller = exports.VERIFIED_MACHINE_CALLER = exports.AUTHORIZATION_HOOK = exports.CanonicalUserRoles = void 0;
6
6
  // Re-export API decorators from core-util for convenience
7
7
  var core_util_1 = require("@webpieces/core-util");
8
8
  Object.defineProperty(exports, "ApiPath", { enumerable: true, get: function () { return core_util_1.ApiPath; } });
@@ -14,7 +14,8 @@ Object.defineProperty(exports, "WpAuth", { enumerable: true, get: function () {
14
14
  Object.defineProperty(exports, "WpLocalOnly", { enumerable: true, get: function () { return core_util_1.WpLocalOnly; } });
15
15
  Object.defineProperty(exports, "isLocalOnly", { enumerable: true, get: function () { return core_util_1.isLocalOnly; } });
16
16
  Object.defineProperty(exports, "jwt", { enumerable: true, get: function () { return core_util_1.jwt; } });
17
- Object.defineProperty(exports, "oidc", { enumerable: true, get: function () { return core_util_1.oidc; } });
17
+ Object.defineProperty(exports, "oidcSameProject", { enumerable: true, get: function () { return core_util_1.oidcSameProject; } });
18
+ Object.defineProperty(exports, "oidcSvcs", { enumerable: true, get: function () { return core_util_1.oidcSvcs; } });
18
19
  Object.defineProperty(exports, "sharedSecret", { enumerable: true, get: function () { return core_util_1.sharedSecret; } });
19
20
  Object.defineProperty(exports, "webhook", { enumerable: true, get: function () { return core_util_1.webhook; } });
20
21
  Object.defineProperty(exports, "apiKey", { enumerable: true, get: function () { return core_util_1.apiKey; } });
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,kDA6C8B;AA5C1B,oGAAA,OAAO,OAAA;AACP,qGAAA,QAAQ,OAAA;AACR,sGAAA,SAAS,OAAA;AACT,uGAAA,UAAU,OAAA;AACV,yGAAA,YAAY,OAAA;AACZ,mGAAA,MAAM,OAAA;AAAE,wGAAA,WAAW,OAAA;AAAE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AATjB,oGAAA,OAAO,OAAA;AACP,sGAAA,SAAS,OAAA;AACT,qGAAA,QAAQ,OAAA;AACR,qGAAA,QAAQ,OAAA;AACR,sGAAA,SAAS,OAAA;AACT,gHAAA,mBAAmB,OAAA;AACnB,kHAAA,qBAAqB,OAAA;AACrB,uGAAA,UAAU,OAAA;AACV,yGAAA,YAAY,OAAA;AAEhB,6DAA4D;AAAnD,0HAAA,mBAAmB,OAAA;AAC5B,0FAA0F;AAC1F,mDAAyE;AAAhE,gHAAA,cAAc,OAAA;AAAE,uHAAA,qBAAqB,OAAA;AAE9C,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;AAGhD,yDAAsK;AAA7J,sHAAA,iBAAiB,OAAA;AAAE,yHAAA,oBAAoB,OAAA;AAAE,uHAAA,kBAAkB,OAAA;AAAE,uHAAA,kBAAkB,OAAA;AAAE,4HAAA,uBAAuB,OAAA;AAAE,0HAAA,qBAAqB,OAAA;AACxI,iEAAgE;AAAvD,8HAAA,qBAAqB,OAAA;AAG9B,gEAA2D;AAAlD,gHAAA,YAAY,OAAA","sourcesContent":["// Re-export API decorators from core-util for convenience\nexport {\n ApiPath,\n Endpoint,\n PathParam,\n QueryParam,\n WpAuthPublic,\n WpAuth, WpLocalOnly, isLocalOnly, jwt, oidc, sharedSecret, webhook, apiKey,\n WpAuthorization, AuthorizationType, getAuthorization,\n Rpc,\n PubSub,\n Queue,\n getApiPath,\n getEndpoints,\n getEndpointOptions,\n getEndpointHttpMethod,\n getEndpointOperation,\n getHttpParameterDeclarations,\n isFormPost,\n isRawBody,\n isApiPath,\n getAuthMeta,\n assertEveryEndpointHasAuthMode,\n getApiKind,\n assertApiKind,\n assertPubSubConventions,\n getQueueName,\n AuthMeta,\n RouteMetadata,\n RouteMetadataFactory,\n HttpContractMapper,\n METADATA_KEYS,\n ValidateImplementation,\n GET,\n POST,\n READ,\n WRITE_IDEMPOTENT,\n WRITE,\n RPC,\n CLOUDTASKS,\n CRON,\n EXTERNAL,\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 {\n AuthMode,\n ApiKind,\n HttpMethod,\n EndpointOperation,\n EndpointKind,\n EndpointOptions,\n EndpointResponseType,\n} from '@webpieces/core-util';\n\n// Server-side routing decorators and utilities\nexport { SourceFile, ROUTING_METADATA_KEYS } 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 { Routes, RouteBuilder, RouteDefinition, FilterDefinition } 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// The INBOUND chain's response type. `Filter`, `Service` and `FilterChain` are NOT re-exported\n// here: they moved to @webpieces/core-util so the outbound client chain is the SAME abstraction\n// rather than a second spelling of it. Import them from '@webpieces/core-util'.\nexport { WpResponse } from './WpResponse';\nexport { AuthenticatedCallerContext } from './AuthenticatedCallerContext';\nexport { InvocationAuthentication } from './InvocationAuthentication';\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 bind modules + route groups + headers.\nexport type { Wiring, AppWiring, BindModule, RouteModule } from './Wiring';\nexport { NodeWiringModules } from './Wiring';\n// The Node binder every BindModule.configure receives.\nexport type { Binder } from './Binder';\nexport { ContainerBinder, ClientBindOptions, PubSubBindOptions } from './Binder';\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 (sharedSecret(...) 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 {\n AuthConfig,\n AUTH_CONFIG,\n AuthenticatedCaller,\n AuthenticatedMachineIdentity,\n AUTHENTICATED_CALLER_KEY,\n SharedSecrets,\n} from './AuthConfig';\nexport {\n JwtHook,\n MintedJwt,\n JWT_HOOK,\n OidcHook,\n OIDC_HOOK,\n WebhookAuthCallback,\n WEBHOOK_AUTH_CALLBACK,\n ApiKeyHook,\n API_KEY_HOOK,\n} from './AuthHooks';\nexport { DefaultOidcVerifier } from './DefaultOidcVerifier';\n// DefaultJwtHook: batteries-included HS256 JwtHook — `new DefaultJwtHook(secret)` and go.\nexport { DefaultJwtHook, DefaultJwtMintRequest } 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\n\nexport { AuthorizationHook, AuthorizationService, CanonicalUserRoles, AUTHORIZATION_HOOK, VERIFIED_MACHINE_CALLER, VerifiedMachineCaller } from './AuthorizationHook';\nexport { AuthorizedApiDocument } from './AuthorizedApiDocument';\nexport type { ApiDocumentObject, ApiDocumentValue } from './AuthorizedApiDocument';\n\nexport { WiringPolicy } from '@webpieces/http-client-core';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/http/http-routing/src/index.ts"],"names":[],"mappings":";;;;;AAAA,0DAA0D;AAC1D,kDA6C8B;AA5C1B,oGAAA,OAAO,OAAA;AACP,qGAAA,QAAQ,OAAA;AACR,sGAAA,SAAS,OAAA;AACT,uGAAA,UAAU,OAAA;AACV,yGAAA,YAAY,OAAA;AACZ,mGAAA,MAAM,OAAA;AAAE,wGAAA,WAAW,OAAA;AAAE,wGAAA,WAAW,OAAA;AAAE,gGAAA,GAAG,OAAA;AAAE,4GAAA,eAAe,OAAA;AAAE,qGAAA,QAAQ,OAAA;AAAE,yGAAA,YAAY,OAAA;AAAE,oGAAA,OAAO,OAAA;AAAE,mGAAA,MAAM,OAAA;AAC/F,4GAAA,eAAe,OAAA;AAAE,8GAAA,iBAAiB,OAAA;AAAE,6GAAA,gBAAgB,OAAA;AACpD,gGAAA,GAAG,OAAA;AACH,mGAAA,MAAM,OAAA;AACN,kGAAA,KAAK,OAAA;AACL,uGAAA,UAAU,OAAA;AACV,yGAAA,YAAY,OAAA;AACZ,+GAAA,kBAAkB,OAAA;AAClB,kHAAA,qBAAqB,OAAA;AACrB,iHAAA,oBAAoB,OAAA;AACpB,yHA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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;AAGhD,yDAAsK;AAA7J,sHAAA,iBAAiB,OAAA;AAAE,yHAAA,oBAAoB,OAAA;AAAE,uHAAA,kBAAkB,OAAA;AAAE,uHAAA,kBAAkB,OAAA;AAAE,4HAAA,uBAAuB,OAAA;AAAE,0HAAA,qBAAqB,OAAA;AACxI,iEAAgE;AAAvD,8HAAA,qBAAqB,OAAA;AAG9B,gEAA2D;AAAlD,gHAAA,YAAY,OAAA","sourcesContent":["// Re-export API decorators from core-util for convenience\nexport {\n ApiPath,\n Endpoint,\n PathParam,\n QueryParam,\n WpAuthPublic,\n WpAuth, WpLocalOnly, isLocalOnly, jwt, oidcSameProject, oidcSvcs, sharedSecret, webhook, apiKey,\n WpAuthorization, AuthorizationType, getAuthorization,\n Rpc,\n PubSub,\n Queue,\n getApiPath,\n getEndpoints,\n getEndpointOptions,\n getEndpointHttpMethod,\n getEndpointOperation,\n getHttpParameterDeclarations,\n isFormPost,\n isRawBody,\n isApiPath,\n getAuthMeta,\n assertEveryEndpointHasAuthMode,\n getApiKind,\n assertApiKind,\n assertPubSubConventions,\n getQueueName,\n AuthMeta,\n RouteMetadata,\n RouteMetadataFactory,\n HttpContractMapper,\n METADATA_KEYS,\n ValidateImplementation,\n GET,\n POST,\n READ,\n WRITE_IDEMPOTENT,\n WRITE,\n RPC,\n CLOUDTASKS,\n CRON,\n EXTERNAL,\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 {\n AuthMode,\n ApiKind,\n HttpMethod,\n EndpointOperation,\n EndpointKind,\n EndpointOptions,\n EndpointResponseType,\n} from '@webpieces/core-util';\n\n// Server-side routing decorators and utilities\nexport { SourceFile, ROUTING_METADATA_KEYS } 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 { Routes, RouteBuilder, RouteDefinition, FilterDefinition } 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// The INBOUND chain's response type. `Filter`, `Service` and `FilterChain` are NOT re-exported\n// here: they moved to @webpieces/core-util so the outbound client chain is the SAME abstraction\n// rather than a second spelling of it. Import them from '@webpieces/core-util'.\nexport { WpResponse } from './WpResponse';\nexport { AuthenticatedCallerContext } from './AuthenticatedCallerContext';\nexport { InvocationAuthentication } from './InvocationAuthentication';\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 bind modules + route groups + headers.\nexport type { Wiring, AppWiring, BindModule, RouteModule } from './Wiring';\nexport { NodeWiringModules } from './Wiring';\n// The Node binder every BindModule.configure receives.\nexport type { Binder } from './Binder';\nexport { ContainerBinder, ClientBindOptions, PubSubBindOptions } from './Binder';\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 (sharedSecret(...) 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 {\n AuthConfig,\n AUTH_CONFIG,\n AuthenticatedCaller,\n AuthenticatedMachineIdentity,\n AUTHENTICATED_CALLER_KEY,\n SharedSecrets,\n} from './AuthConfig';\nexport {\n JwtHook,\n MintedJwt,\n JWT_HOOK,\n OidcHook,\n OIDC_HOOK,\n WebhookAuthCallback,\n WEBHOOK_AUTH_CALLBACK,\n ApiKeyHook,\n API_KEY_HOOK,\n} from './AuthHooks';\nexport { DefaultOidcVerifier } from './DefaultOidcVerifier';\n// DefaultJwtHook: batteries-included HS256 JwtHook — `new DefaultJwtHook(secret)` and go.\nexport { DefaultJwtHook, DefaultJwtMintRequest } 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\n\nexport { AuthorizationHook, AuthorizationService, CanonicalUserRoles, AUTHORIZATION_HOOK, VERIFIED_MACHINE_CALLER, VerifiedMachineCaller } from './AuthorizationHook';\nexport { AuthorizedApiDocument } from './AuthorizedApiDocument';\nexport type { ApiDocumentObject, ApiDocumentValue } from './AuthorizedApiDocument';\n\nexport { WiringPolicy } from '@webpieces/http-client-core';\n"]}