@webpieces/core-util 0.4.680 → 0.4.682
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/http/AuthApiKeyCompileAssertions.d.ts +30 -8
- package/src/http/AuthApiKeyCompileAssertions.js +66 -12
- package/src/http/AuthApiKeyCompileAssertions.js.map +1 -1
- package/src/http/DestinationTrust.d.ts +1 -1
- package/src/http/DestinationTrust.js +3 -2
- package/src/http/DestinationTrust.js.map +1 -1
- package/src/http/RouteMetadata.d.ts +1 -1
- package/src/http/RouteMetadata.js.map +1 -1
- package/src/http/auth-mode.d.ts +156 -0
- package/src/http/auth-mode.js +33 -0
- package/src/http/auth-mode.js.map +1 -0
- package/src/http/decorators.d.ts +29 -105
- package/src/http/decorators.js +35 -32
- package/src/http/decorators.js.map +1 -1
- package/src/index.d.ts +4 -2
- package/src/index.js +4 -2
- package/src/index.js.map +1 -1
package/package.json
CHANGED
|
@@ -1,17 +1,29 @@
|
|
|
1
|
-
import { AuthMode } from './
|
|
1
|
+
import { ApiKeyCredential, AuthMode } from './auth-mode';
|
|
2
2
|
/**
|
|
3
|
-
* COMPILE-TIME assertions for the `apikey` member of the {@link AuthMode} union
|
|
4
|
-
* `@ts-expect-error` below FAILS THE BUILD (TS2578, "unused
|
|
5
|
-
* it guards ever starts compiling.
|
|
3
|
+
* COMPILE-TIME assertions for the `apikey` member of the {@link AuthMode} union and for the
|
|
4
|
+
* {@link AuthApiKey} signature. Each `@ts-expect-error` below FAILS THE BUILD (TS2578, "unused
|
|
5
|
+
* '@ts-expect-error' directive") if the line it guards ever starts compiling.
|
|
6
6
|
*
|
|
7
7
|
* WHY THIS IS NOT A `.spec.ts` FILE — same reason as its sibling `AuthJwtCompileAssertions.ts`:
|
|
8
8
|
* tsconfig.lib.json EXCLUDES specs and vitest strips types with esbuild, so a `@ts-expect-error` in a
|
|
9
9
|
* spec is inert and the suite passes whether or not the guarded line really errors.
|
|
10
10
|
*
|
|
11
|
-
* WHAT IT PINS.
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* WHAT IT PINS.
|
|
12
|
+
*
|
|
13
|
+
* 1. The union member is `{ kind: 'apikey'; regime: string; credentials: [...] }` and nothing looser.
|
|
14
|
+
* `regime` is the lookup key selecting WHICH key regime a route belongs to, so a mode with no
|
|
15
|
+
* regime — or spelled `api-key`, which is what a reader guesses from the decorator — must not
|
|
16
|
+
* type-check its way into a switch that would then silently miss it.
|
|
17
|
+
* 2. `credentials` is NON-EMPTY. A regime that names no credential generates a published document
|
|
18
|
+
* with no security block, which is precisely the silent failure the argument exists to remove, so
|
|
19
|
+
* `[]` is a compile error rather than a runtime throw (shim shape #4).
|
|
20
|
+
* 3. {@link ApiKeyCredential} makes the two OpenAPI schemes MUTUALLY exclusive: a header credential
|
|
21
|
+
* must carry its header name, and a bearer credential must NOT — its location IS `Authorization`,
|
|
22
|
+
* so a `name` beside it would be a lie a generator has to guess about.
|
|
23
|
+
* 4. The ONE-ARGUMENT `@AuthApiKey('regime')` form is GONE. It could declare a key regime while
|
|
24
|
+
* saying nothing about where the credential rides, which is the whole defect; per the
|
|
25
|
+
* no-backwards-compatibility rule there is no overload and no optional second parameter left
|
|
26
|
+
* behind, and this directive is what proves it.
|
|
15
27
|
*
|
|
16
28
|
* The EXHAUSTIVENESS half needs no directive: `apiKeyIsCoveredExhaustively` below returns on every
|
|
17
29
|
* branch with no `default`, so dropping the `apikey` case makes tsc fail with TS7030 (not all code
|
|
@@ -21,8 +33,18 @@ import { AuthMode } from './decorators';
|
|
|
21
33
|
export declare class AuthApiKeyCompileAssertions {
|
|
22
34
|
/** The one legitimate spelling must keep compiling; asserted by the ABSENCE of an error. */
|
|
23
35
|
legitimate(): AuthMode;
|
|
36
|
+
/** The bearer branch, likewise asserted by the ABSENCE of an error. */
|
|
37
|
+
legitimateBearer(): ApiKeyCredential;
|
|
38
|
+
/** The decorator's TWO-argument form is the only one; asserted by the ABSENCE of an error. */
|
|
39
|
+
legitimateDecorator(): ClassDecorator & MethodDecorator;
|
|
24
40
|
/** Every one of these must be UNWRITABLE. A directive going unused here fails the build. */
|
|
25
41
|
rejected(): void;
|
|
42
|
+
/**
|
|
43
|
+
* The DELETED one-argument form. `@AuthApiKey('onetablet-partner')` used to compile and is now a
|
|
44
|
+
* compile error naming the missing `credentials` argument — the delivery mechanism for the
|
|
45
|
+
* migration, and the reason no `@deprecated` overload survives.
|
|
46
|
+
*/
|
|
47
|
+
oneArgumentFormIsGone(): void;
|
|
26
48
|
/**
|
|
27
49
|
* Exhaustiveness, stated as code: NO `default`, a return on every branch. Deleting the `apikey`
|
|
28
50
|
* case turns this into TS7030 — the compile error that forces a DECISION about a new mode's trust
|
|
@@ -1,19 +1,32 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.AuthApiKeyCompileAssertions = void 0;
|
|
4
|
+
const decorators_1 = require("./decorators");
|
|
4
5
|
/**
|
|
5
|
-
* COMPILE-TIME assertions for the `apikey` member of the {@link AuthMode} union
|
|
6
|
-
* `@ts-expect-error` below FAILS THE BUILD (TS2578, "unused
|
|
7
|
-
* it guards ever starts compiling.
|
|
6
|
+
* COMPILE-TIME assertions for the `apikey` member of the {@link AuthMode} union and for the
|
|
7
|
+
* {@link AuthApiKey} signature. Each `@ts-expect-error` below FAILS THE BUILD (TS2578, "unused
|
|
8
|
+
* '@ts-expect-error' directive") if the line it guards ever starts compiling.
|
|
8
9
|
*
|
|
9
10
|
* WHY THIS IS NOT A `.spec.ts` FILE — same reason as its sibling `AuthJwtCompileAssertions.ts`:
|
|
10
11
|
* tsconfig.lib.json EXCLUDES specs and vitest strips types with esbuild, so a `@ts-expect-error` in a
|
|
11
12
|
* spec is inert and the suite passes whether or not the guarded line really errors.
|
|
12
13
|
*
|
|
13
|
-
* WHAT IT PINS.
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
14
|
+
* WHAT IT PINS.
|
|
15
|
+
*
|
|
16
|
+
* 1. The union member is `{ kind: 'apikey'; regime: string; credentials: [...] }` and nothing looser.
|
|
17
|
+
* `regime` is the lookup key selecting WHICH key regime a route belongs to, so a mode with no
|
|
18
|
+
* regime — or spelled `api-key`, which is what a reader guesses from the decorator — must not
|
|
19
|
+
* type-check its way into a switch that would then silently miss it.
|
|
20
|
+
* 2. `credentials` is NON-EMPTY. A regime that names no credential generates a published document
|
|
21
|
+
* with no security block, which is precisely the silent failure the argument exists to remove, so
|
|
22
|
+
* `[]` is a compile error rather than a runtime throw (shim shape #4).
|
|
23
|
+
* 3. {@link ApiKeyCredential} makes the two OpenAPI schemes MUTUALLY exclusive: a header credential
|
|
24
|
+
* must carry its header name, and a bearer credential must NOT — its location IS `Authorization`,
|
|
25
|
+
* so a `name` beside it would be a lie a generator has to guess about.
|
|
26
|
+
* 4. The ONE-ARGUMENT `@AuthApiKey('regime')` form is GONE. It could declare a key regime while
|
|
27
|
+
* saying nothing about where the credential rides, which is the whole defect; per the
|
|
28
|
+
* no-backwards-compatibility rule there is no overload and no optional second parameter left
|
|
29
|
+
* behind, and this directive is what proves it.
|
|
17
30
|
*
|
|
18
31
|
* The EXHAUSTIVENESS half needs no directive: `apiKeyIsCoveredExhaustively` below returns on every
|
|
19
32
|
* branch with no `default`, so dropping the `apikey` case makes tsc fail with TS7030 (not all code
|
|
@@ -23,17 +36,58 @@ exports.AuthApiKeyCompileAssertions = void 0;
|
|
|
23
36
|
class AuthApiKeyCompileAssertions {
|
|
24
37
|
/** The one legitimate spelling must keep compiling; asserted by the ABSENCE of an error. */
|
|
25
38
|
legitimate() {
|
|
26
|
-
const mode = {
|
|
39
|
+
const mode = {
|
|
40
|
+
kind: 'apikey',
|
|
41
|
+
regime: 'onetablet-partner',
|
|
42
|
+
credentials: [
|
|
43
|
+
{ in: 'header', name: 'x-api-key', description: 'The key issued to your integration.' },
|
|
44
|
+
{ in: 'header', name: 'x-organization-id' },
|
|
45
|
+
],
|
|
46
|
+
};
|
|
27
47
|
return mode;
|
|
28
48
|
}
|
|
49
|
+
/** The bearer branch, likewise asserted by the ABSENCE of an error. */
|
|
50
|
+
legitimateBearer() {
|
|
51
|
+
const credential = { in: 'bearer', description: 'Send the key as a bearer token.' };
|
|
52
|
+
return credential;
|
|
53
|
+
}
|
|
54
|
+
/** The decorator's TWO-argument form is the only one; asserted by the ABSENCE of an error. */
|
|
55
|
+
legitimateDecorator() {
|
|
56
|
+
return (0, decorators_1.AuthApiKey)('onetablet-partner', [{ in: 'header', name: 'x-api-key' }]);
|
|
57
|
+
}
|
|
29
58
|
/** Every one of these must be UNWRITABLE. A directive going unused here fails the build. */
|
|
30
59
|
rejected() {
|
|
31
|
-
// @ts-expect-error `
|
|
32
|
-
const
|
|
33
|
-
void
|
|
60
|
+
// @ts-expect-error `regime` is REQUIRED — it selects which key regime, so it cannot be omitted
|
|
61
|
+
const noRegime = { kind: 'apikey', credentials: [{ in: 'header', name: 'x-api-key' }] };
|
|
62
|
+
void noRegime;
|
|
63
|
+
// @ts-expect-error `credentials` is REQUIRED — a regime that declares no location is the defect
|
|
64
|
+
const noCredentials = { kind: 'apikey', regime: 'onetablet-partner' };
|
|
65
|
+
void noCredentials;
|
|
66
|
+
// @ts-expect-error EMPTY is not a widening — it would emit a document with no security block
|
|
67
|
+
const empty = { kind: 'apikey', regime: 'onetablet-partner', credentials: [] };
|
|
68
|
+
void empty;
|
|
34
69
|
// @ts-expect-error the discriminant is 'apikey'; 'api-key' is not a member of the union
|
|
35
|
-
const misspelled = { kind: 'api-key',
|
|
70
|
+
const misspelled = { kind: 'api-key', regime: 'onetablet-partner', credentials: [] };
|
|
36
71
|
void misspelled;
|
|
72
|
+
// @ts-expect-error bearer's location IS `Authorization`; a header name beside it is a lie
|
|
73
|
+
const bearerWithName = { in: 'bearer', name: 'x-api-key' };
|
|
74
|
+
void bearerWithName;
|
|
75
|
+
// @ts-expect-error a header credential with no header name cannot become a securityScheme
|
|
76
|
+
const headerWithNoName = { in: 'header' };
|
|
77
|
+
void headerWithNoName;
|
|
78
|
+
// @ts-expect-error 'query' is not reachable — the framework declares only these two locations
|
|
79
|
+
const unknownLocation = { in: 'query', name: 'api_key' };
|
|
80
|
+
void unknownLocation;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The DELETED one-argument form. `@AuthApiKey('onetablet-partner')` used to compile and is now a
|
|
84
|
+
* compile error naming the missing `credentials` argument — the delivery mechanism for the
|
|
85
|
+
* migration, and the reason no `@deprecated` overload survives.
|
|
86
|
+
*/
|
|
87
|
+
oneArgumentFormIsGone() {
|
|
88
|
+
// @ts-expect-error the one-argument form is DELETED; pass the credential list as well
|
|
89
|
+
const legacy = (0, decorators_1.AuthApiKey)('onetablet-partner');
|
|
90
|
+
void legacy;
|
|
37
91
|
}
|
|
38
92
|
/**
|
|
39
93
|
* Exhaustiveness, stated as code: NO `default`, a return on every branch. Deleting the `apikey`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthApiKeyCompileAssertions.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/AuthApiKeyCompileAssertions.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"AuthApiKeyCompileAssertions.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/AuthApiKeyCompileAssertions.ts"],"names":[],"mappings":";;;AACA,6CAA0C;AAE1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAa,2BAA2B;IACpC,4FAA4F;IAC5F,UAAU;QACN,MAAM,IAAI,GAAa;YACnB,IAAI,EAAE,QAAQ;YACd,MAAM,EAAE,mBAAmB;YAC3B,WAAW,EAAE;gBACT,EAAE,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,EAAE,qCAAqC,EAAE;gBACvF,EAAE,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,mBAAmB,EAAE;aAC9C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AAgB,CAAC;QACtB,8FAA8F;QAC9F,MAAM,eAAe,GAAqB,EAAE,EAAE,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;QAC3E,KAAK,eAAe,CAAC;IACzB,CAAC;IAED;;;;OAIG;IACH,qBAAqB;QACjB,sFAAsF;QACtF,MAAM,MAAM,GAAG,IAAA,uBAAU,EAAC,mBAAmB,CAAC,CAAC;QAC/C,KAAK,MAAM,CAAC;IAChB,CAAC;IAED;;;;OAIG;IACH,2BAA2B,CAAC,IAAc;QACtC,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;YAChB,KAAK,QAAQ;gBACT,OAAO,QAAQ,CAAC;YACpB,KAAK,KAAK;gBACN,OAAO,KAAK,CAAC;YACjB,KAAK,MAAM;gBACP,OAAO,MAAM,CAAC;YAClB,KAAK,eAAe;gBAChB,OAAO,eAAe,CAAC;YAC3B,KAAK,SAAS;gBACV,OAAO,SAAS,CAAC;YACrB,KAAK,QAAQ;gBACT,OAAO,QAAQ,CAAC;YACpB,KAAK,YAAY;gBACb,OAAO,YAAY,CAAC;QAC5B,CAAC;IACL,CAAC;CACJ;AApFD,kEAoFC","sourcesContent":["import { ApiKeyCredential, AuthMode } from './auth-mode';\nimport { AuthApiKey } from './decorators';\n\n/**\n * COMPILE-TIME assertions for the `apikey` member of the {@link AuthMode} union and for the\n * {@link AuthApiKey} signature. Each `@ts-expect-error` below FAILS THE BUILD (TS2578, \"unused\n * '@ts-expect-error' directive\") if the line it guards ever starts compiling.\n *\n * WHY THIS IS NOT A `.spec.ts` FILE — same reason as its sibling `AuthJwtCompileAssertions.ts`:\n * tsconfig.lib.json EXCLUDES specs and vitest strips types with esbuild, so a `@ts-expect-error` in a\n * spec is inert and the suite passes whether or not the guarded line really errors.\n *\n * WHAT IT PINS.\n *\n * 1. The union member is `{ kind: 'apikey'; regime: string; credentials: [...] }` and nothing looser.\n * `regime` is the lookup key selecting WHICH key regime a route belongs to, so a mode with no\n * regime — or spelled `api-key`, which is what a reader guesses from the decorator — must not\n * type-check its way into a switch that would then silently miss it.\n * 2. `credentials` is NON-EMPTY. A regime that names no credential generates a published document\n * with no security block, which is precisely the silent failure the argument exists to remove, so\n * `[]` is a compile error rather than a runtime throw (shim shape #4).\n * 3. {@link ApiKeyCredential} makes the two OpenAPI schemes MUTUALLY exclusive: a header credential\n * must carry its header name, and a bearer credential must NOT — its location IS `Authorization`,\n * so a `name` beside it would be a lie a generator has to guess about.\n * 4. The ONE-ARGUMENT `@AuthApiKey('regime')` form is GONE. It could declare a key regime while\n * saying nothing about where the credential rides, which is the whole defect; per the\n * no-backwards-compatibility rule there is no overload and no optional second parameter left\n * behind, and this directive is what proves it.\n *\n * The EXHAUSTIVENESS half needs no directive: `apiKeyIsCoveredExhaustively` below returns on every\n * branch with no `default`, so dropping the `apikey` case makes tsc fail with TS7030 (not all code\n * paths return a value). That is the same property `AuthFilter.verifiesCaller` and\n * `DestinationTrust.forAuthMode` rely on, asserted here where it cannot be edited away by accident.\n */\nexport class AuthApiKeyCompileAssertions {\n /** The one legitimate spelling must keep compiling; asserted by the ABSENCE of an error. */\n legitimate(): AuthMode {\n const mode: AuthMode = {\n kind: 'apikey',\n regime: 'onetablet-partner',\n credentials: [\n { in: 'header', name: 'x-api-key', description: 'The key issued to your integration.' },\n { in: 'header', name: 'x-organization-id' },\n ],\n };\n return mode;\n }\n\n /** The bearer branch, likewise asserted by the ABSENCE of an error. */\n legitimateBearer(): ApiKeyCredential {\n const credential: ApiKeyCredential = { in: 'bearer', description: 'Send the key as a bearer token.' };\n return credential;\n }\n\n /** The decorator's TWO-argument form is the only one; asserted by the ABSENCE of an error. */\n legitimateDecorator(): ClassDecorator & MethodDecorator {\n return AuthApiKey('onetablet-partner', [{ in: 'header', name: 'x-api-key' }]);\n }\n\n /** Every one of these must be UNWRITABLE. A directive going unused here fails the build. */\n rejected(): void {\n // @ts-expect-error `regime` is REQUIRED — it selects which key regime, so it cannot be omitted\n const noRegime: AuthMode = { kind: 'apikey', credentials: [{ in: 'header', name: 'x-api-key' }] };\n void noRegime;\n // @ts-expect-error `credentials` is REQUIRED — a regime that declares no location is the defect\n const noCredentials: AuthMode = { kind: 'apikey', regime: 'onetablet-partner' };\n void noCredentials;\n // @ts-expect-error EMPTY is not a widening — it would emit a document with no security block\n const empty: AuthMode = { kind: 'apikey', regime: 'onetablet-partner', credentials: [] };\n void empty;\n // @ts-expect-error the discriminant is 'apikey'; 'api-key' is not a member of the union\n const misspelled: AuthMode = { kind: 'api-key', regime: 'onetablet-partner', credentials: [] };\n void misspelled;\n // @ts-expect-error bearer's location IS `Authorization`; a header name beside it is a lie\n const bearerWithName: ApiKeyCredential = { in: 'bearer', name: 'x-api-key' };\n void bearerWithName;\n // @ts-expect-error a header credential with no header name cannot become a securityScheme\n const headerWithNoName: ApiKeyCredential = { in: 'header' };\n void headerWithNoName;\n // @ts-expect-error 'query' is not reachable — the framework declares only these two locations\n const unknownLocation: ApiKeyCredential = { in: 'query', name: 'api_key' };\n void unknownLocation;\n }\n\n /**\n * The DELETED one-argument form. `@AuthApiKey('onetablet-partner')` used to compile and is now a\n * compile error naming the missing `credentials` argument — the delivery mechanism for the\n * migration, and the reason no `@deprecated` overload survives.\n */\n oneArgumentFormIsGone(): void {\n // @ts-expect-error the one-argument form is DELETED; pass the credential list as well\n const legacy = AuthApiKey('onetablet-partner');\n void legacy;\n }\n\n /**\n * Exhaustiveness, stated as code: NO `default`, a return on every branch. Deleting the `apikey`\n * case turns this into TS7030 — the compile error that forces a DECISION about a new mode's trust\n * posture rather than letting it land on one by accident.\n */\n apiKeyIsCoveredExhaustively(mode: AuthMode): string {\n switch (mode.kind) {\n case 'public':\n return 'public';\n case 'jwt':\n return 'jwt';\n case 'oidc':\n return 'oidc';\n case 'shared-secret':\n return 'shared-secret';\n case 'webhook':\n return 'webhook';\n case 'apikey':\n return 'apikey';\n case 'local-only':\n return 'local-only';\n }\n }\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { AnyContextKey } from '../ContextKey';
|
|
2
|
-
import { AuthMode } from './
|
|
2
|
+
import { AuthMode } from './auth-mode';
|
|
3
3
|
/**
|
|
4
4
|
* DestinationTrust - the OUTBOUND half of the trust model: may a TRUSTED context key
|
|
5
5
|
* ({@link ContextKey.trusted}) ride to the endpoint we are about to call?
|
|
@@ -71,8 +71,9 @@ class DestinationTrust {
|
|
|
71
71
|
case 'webhook':
|
|
72
72
|
// @AuthApiKey authenticates a CUSTOMER, not a peer service. The holder of the key is
|
|
73
73
|
// another company's codebase, so nothing it forwards may be believed, and no webpieces
|
|
74
|
-
// client can call it anyway (the framework
|
|
75
|
-
// owns which headers carry the credential
|
|
74
|
+
// client can call it anyway (the framework extracts no api-key header — the app's hook
|
|
75
|
+
// owns which headers carry the credential; the contract's `credentials` list only DESCRIBES
|
|
76
|
+
// them). Trusted keys stay home.
|
|
76
77
|
case 'apikey':
|
|
77
78
|
// @AuthLocalOnly authenticates NOBODY — it gates on the environment, not on a
|
|
78
79
|
// credential — so a browser with curl on the same laptop is indistinguishable from us.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DestinationTrust.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/DestinationTrust.ts"],"names":[],"mappings":";;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAa,gBAAgB;IAeY;IAdrC;;;;OAIG;IACK,MAAM,CAAU,eAAe,GAAG,IAAI,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAErE;;;;OAIG;IACK,MAAM,CAAU,oBAAoB,GAAG,IAAI,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAE3E,YAAqC,cAAuB;QAAvB,mBAAc,GAAd,cAAc,CAAS;IAAG,CAAC;IAEhE;;;;OAIG;IACH,qSAAqS;IACrS,MAAM,CAAC,WAAW,CAAC,IAA0B;QACzC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACrB,OAAO,gBAAgB,CAAC,oBAAoB,CAAC;QACjD,CAAC;QACD,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;YAChB,KAAK,MAAM,CAAC;YACZ,KAAK,eAAe;gBAChB,OAAO,gBAAgB,CAAC,eAAe,CAAC;YAC5C,KAAK,KAAK,CAAC;YACX,KAAK,QAAQ,CAAC;YACd,+EAA+E;YAC/E,oFAAoF;YACpF,mFAAmF;YACnF,yFAAyF;YACzF,mDAAmD;YACnD,KAAK,SAAS,CAAC;YACf,qFAAqF;YACrF,uFAAuF;YACvF,
|
|
1
|
+
{"version":3,"file":"DestinationTrust.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/DestinationTrust.ts"],"names":[],"mappings":";;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAa,gBAAgB;IAeY;IAdrC;;;;OAIG;IACK,MAAM,CAAU,eAAe,GAAG,IAAI,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAErE;;;;OAIG;IACK,MAAM,CAAU,oBAAoB,GAAG,IAAI,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAE3E,YAAqC,cAAuB;QAAvB,mBAAc,GAAd,cAAc,CAAS;IAAG,CAAC;IAEhE;;;;OAIG;IACH,qSAAqS;IACrS,MAAM,CAAC,WAAW,CAAC,IAA0B;QACzC,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACrB,OAAO,gBAAgB,CAAC,oBAAoB,CAAC;QACjD,CAAC;QACD,QAAQ,IAAI,CAAC,IAAI,EAAE,CAAC;YAChB,KAAK,MAAM,CAAC;YACZ,KAAK,eAAe;gBAChB,OAAO,gBAAgB,CAAC,eAAe,CAAC;YAC5C,KAAK,KAAK,CAAC;YACX,KAAK,QAAQ,CAAC;YACd,+EAA+E;YAC/E,oFAAoF;YACpF,mFAAmF;YACnF,yFAAyF;YACzF,mDAAmD;YACnD,KAAK,SAAS,CAAC;YACf,qFAAqF;YACrF,uFAAuF;YACvF,uFAAuF;YACvF,4FAA4F;YAC5F,iCAAiC;YACjC,KAAK,QAAQ,CAAC;YACd,8EAA8E;YAC9E,uFAAuF;YACvF,wFAAwF;YACxF,iFAAiF;YACjF,KAAK,YAAY;gBACb,OAAO,gBAAgB,CAAC,oBAAoB,CAAC;QACrD,CAAC;IACL,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,GAAkB;QACrB,OAAO,IAAI,CAAC,cAAc,IAAI,CAAC,GAAG,CAAC,SAAS,EAAE,CAAC;IACnD,CAAC;;AA7DL,4CA8DC","sourcesContent":["import { AnyContextKey } from '../ContextKey';\nimport { AuthMode } from './auth-mode';\n\n/**\n * DestinationTrust - the OUTBOUND half of the trust model: may a TRUSTED context key\n * ({@link ContextKey.trusted}) ride to the endpoint we are about to call?\n *\n * ## Why the client has to answer this at all\n *\n * The server already decided (see `PendingWireTrust`): an inbound `x-user-id` is admitted only on a\n * route that verified WHO called it — `@AuthOidc` / `@AuthSharedSecret`. On a `@AuthJwt` or `@Public`\n * route the same header must match what the authenticator independently derived, or the request is\n * REJECTED with a 401.\n *\n * That rule is correct, and it means a client that ships `x-user-id` to a `@Public` endpoint is\n * building a request the callee is obliged to reject. Before this class the outbound builders\n * forwarded EVERY transferred key with no idea what the destination was, so an internal service\n * calling another service's public or JWT endpoint 401'd itself. The fix belongs on the producing\n * side: don't send what cannot possibly be believed.\n *\n * ## Why it is a class with a private constructor and no boolean parameter\n *\n * `buildOutboundHeaders(sendTrusted = true)` would have been three characters of work and exactly the\n * \"widening that is an ABSENCE rather than a token\" CLAUDE.md rejects — the permissive answer would be\n * what you get by not typing anything. There is no way to build a DestinationTrust except from the\n * destination endpoint's own {@link AuthMode}, so the caller cannot assert a posture the route does\n * not actually have, and `grep -rn DestinationTrust.forAuthMode` lists every place the question is\n * asked. The two instances are PRIVATE for the same reason: exposing them would be a second spelling\n * that skips the derivation.\n *\n * Per CLAUDE.md: data-only structure, so a class rather than an interface or a bare boolean.\n */\nexport class DestinationTrust {\n /**\n * The destination authenticates its CALLER (@AuthOidc / @AuthSharedSecret), so it is entitled to\n * believe context WE vouch for — this is the service-to-service identity propagation that trusted\n * keys keep an `httpHeader` for.\n */\n private static readonly VERIFIES_CALLER = new DestinationTrust(true);\n\n /**\n * The destination cannot tell us from a browser with curl (@AuthJwt / @Public / @AuthWebhook /\n * @AuthApiKey / @AuthLocalOnly / an endpoint with no declared mode), so trusted keys are omitted.\n * Untrusted keys still travel.\n */\n private static readonly CANNOT_VERIFY_CALLER = new DestinationTrust(false);\n\n private constructor(private readonly verifiesCaller: boolean) {}\n\n /**\n * The ONLY way to obtain one: state the destination endpoint's auth mode. `undefined` (an\n * endpoint that declared no mode) is treated as un-verifying, i.e. the SAFE answer — an absent\n * declaration must never be the widest one.\n */\n // webpieces-disable no-function-outside-class -- static factory replacing the (now private) constructor, exactly as ContextKey.trusted/untrusted do: the destination's auth mode must be part of the CALL, and a DI-injected instance method would let a caller hold one without ever naming a route\n static forAuthMode(mode: AuthMode | undefined): DestinationTrust {\n if (mode === undefined) {\n return DestinationTrust.CANNOT_VERIFY_CALLER;\n }\n switch (mode.kind) {\n case 'oidc':\n case 'shared-secret':\n return DestinationTrust.VERIFIES_CALLER;\n case 'jwt':\n case 'public':\n // @AuthWebhook authenticates an OUTSIDE VENDOR, which is not the same thing as\n // authenticating a peer in this repo. The vendor knows nothing of webpieces context\n // headers and would never send one, so there is no identity to propagate in either\n // direction — and a webpieces client cannot call such an endpoint anyway (it cannot mint\n // the vendor's signature). Trusted keys stay home.\n case 'webhook':\n // @AuthApiKey authenticates a CUSTOMER, not a peer service. The holder of the key is\n // another company's codebase, so nothing it forwards may be believed, and no webpieces\n // client can call it anyway (the framework extracts no api-key header — the app's hook\n // owns which headers carry the credential; the contract's `credentials` list only DESCRIBES\n // them). Trusted keys stay home.\n case 'apikey':\n // @AuthLocalOnly authenticates NOBODY — it gates on the environment, not on a\n // credential — so a browser with curl on the same laptop is indistinguishable from us.\n // Same bucket as public/jwt. (This switch has NO `default` on purpose: adding a kind to\n // AuthMode is a compile error here rather than a silent permissive fallthrough.)\n case 'local-only':\n return DestinationTrust.CANNOT_VERIFY_CALLER;\n }\n }\n\n /**\n * May this key go on the wire to this destination? Untrusted keys always may — nobody was ever\n * going to make a security decision on them. A trusted key may only when the destination will\n * authenticate US, because that is the only case its `AuthFilter` will admit it.\n */\n allows(key: AnyContextKey): boolean {\n return this.verifiesCaller || !key.isTrusted();\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"RouteMetadata.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/RouteMetadata.ts"],"names":[],"mappings":";;;AAGA;;;;;;;;GAQG;AACH,MAAa,aAAa;IACtB,UAAU,CAAS;IACnB,IAAI,CAAS;IACb,UAAU,CAAS;IACnB,mBAAmB,CAAU;IAC7B,QAAQ,CAAY;IACpB,wFAAwF;IACxF,OAAO,CAAU;IACjB;;;;OAIG;IACM,QAAQ,CAAU;IAC3B;;;;OAIG;IACM,IAAI,CAAY;IACzB;;;;;OAKG;IACM,OAAO,CAAU;IAE1B,YACI,UAAkB,EAClB,IAAY,EACZ,UAAkB,EAClB,mBAA4B,EAC5B,QAAmB,EACnB,OAAgB,EAChB,WAAoB,KAAK,EACzB,IAAe,EACf,UAAmB,KAAK;QAExB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;QAC/C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AAjDD,sCAiDC","sourcesContent":["import { MaskSpec } from './LogFieldMask';\nimport { AuthMeta } from './
|
|
1
|
+
{"version":3,"file":"RouteMetadata.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/RouteMetadata.ts"],"names":[],"mappings":";;;AAGA;;;;;;;;GAQG;AACH,MAAa,aAAa;IACtB,UAAU,CAAS;IACnB,IAAI,CAAS;IACb,UAAU,CAAS;IACnB,mBAAmB,CAAU;IAC7B,QAAQ,CAAY;IACpB,wFAAwF;IACxF,OAAO,CAAU;IACjB;;;;OAIG;IACM,QAAQ,CAAU;IAC3B;;;;OAIG;IACM,IAAI,CAAY;IACzB;;;;;OAKG;IACM,OAAO,CAAU;IAE1B,YACI,UAAkB,EAClB,IAAY,EACZ,UAAkB,EAClB,mBAA4B,EAC5B,QAAmB,EACnB,OAAgB,EAChB,WAAoB,KAAK,EACzB,IAAe,EACf,UAAmB,KAAK;QAExB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;QAC/C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IAC3B,CAAC;CACJ;AAjDD,sCAiDC","sourcesContent":["import { MaskSpec } from './LogFieldMask';\nimport { AuthMeta } from './auth-mode';\n\n/**\n * Route metadata stored per-method at runtime.\n * Used internally by http-routing and http-client as the runtime representation\n * of a route. Constructed from @ApiPath + @Endpoint metadata by ProxyClient\n * and ApiRoutingFactory.\n *\n * Lives in its own file (one class per file) purely for file size, exactly as `api-kind.ts` and\n * `external-caller.ts` were split off `decorators.ts` before it. Nothing about its role changed.\n */\nexport class RouteMetadata {\n httpMethod: string;\n path: string;\n methodName: string;\n controllerClassName?: string;\n authMeta?: AuthMeta;\n /** The API contract class name (e.g. 'SaveApi') — distinct from the controller name. */\n apiName?: string;\n /**\n * True when @Endpoint(..., { formPost: true }): the body is application/x-www-form-urlencoded\n * (flat key→value), not JSON. Rides the route metadata so the per-route body parse can branch\n * without knowing the apiClass/methodName. Default false = JSON.\n */\n readonly formPost: boolean;\n /**\n * The @MaskLog field-mask spec for this route, or undefined when the method declared none. Read\n * ONCE here at route-build time and handed to {@link LogApiCall} via ApiMethodInfo, so the per-call\n * log path pays for masking only on routes that opted in (the rest stay on plain JSON.stringify).\n */\n readonly mask?: MaskSpec;\n /**\n * True when @Endpoint(..., { rawBody: true }): the transport must retain the verbatim bytes +\n * absolute url for the `@AuthWebhook` hook to verify a vendor signature over. Rides the route\n * metadata for the same reason {@link formPost} does — the transport adapter decides how to read\n * the body from the ROUTE, without knowing the apiClass/methodName.\n */\n readonly rawBody: boolean;\n\n constructor(\n httpMethod: string,\n path: string,\n methodName: string,\n controllerClassName?: string,\n authMeta?: AuthMeta,\n apiName?: string,\n formPost: boolean = false,\n mask?: MaskSpec,\n rawBody: boolean = false,\n ) {\n this.httpMethod = httpMethod;\n this.path = path;\n this.methodName = methodName;\n this.controllerClassName = controllerClassName;\n this.authMeta = authMeta;\n this.apiName = apiName;\n this.formPost = formPost;\n this.mask = mask;\n this.rawBody = rawBody;\n }\n}\n"]}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The TYPE layer of the auth surface: what an endpoint's credential posture IS, with no decorator and
|
|
3
|
+
* no reflect-metadata. `decorators.ts` (which attaches these) imports FROM here, never the other way,
|
|
4
|
+
* so a reader that only needs to switch on a mode — `DestinationTrust`, `RouteMetadata`, a spec
|
|
5
|
+
* generator — does not drag the whole decorator surface in with it.
|
|
6
|
+
*
|
|
7
|
+
* Split out of `decorators.ts` purely for file size, exactly as `api-kind.ts`, `external-caller.ts` and
|
|
8
|
+
* `RouteMetadata.ts` were before it. Nothing about these types' role changed in the move, and the
|
|
9
|
+
* barrel keeps the package surface identical.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* The role decision for a JWT endpoint, as a union the COMPILER enforces — one spelling per decision,
|
|
13
|
+
* every broken combination a compile error:
|
|
14
|
+
*
|
|
15
|
+
* ```typescript
|
|
16
|
+
* @AuthJwt({ roles: ['admin'] }) // ✅ role-gated (any-of)
|
|
17
|
+
* @AuthJwt({ allRolesAllowed: true }) // ✅ every authenticated user, said out loud
|
|
18
|
+
* @AuthJwt({}) // ❌ pick a branch
|
|
19
|
+
* @AuthJwt({ roles: [] }) // ❌ needs at least one role
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* `allRolesAllowed` exists ONLY on the wide branch (the dangerous half must be a greppable token, and
|
|
23
|
+
* the narrow branch rejects it as a redundant second spelling); `roles` is a NON-EMPTY tuple so
|
|
24
|
+
* "declared roles, passed none" — the old optional `string[]`'s silent widest grant — cannot be written.
|
|
25
|
+
* All six bad cases are pinned in `AuthJwtCompileAssertions.ts` — a COMPILED file, not a spec: tsc
|
|
26
|
+
* fails the build (TS2578) if any starts compiling. A spec cannot do this (see that file's header).
|
|
27
|
+
*
|
|
28
|
+
* WHY a type rather than the runtime `throw` this replaced: `.claude/review/backwards-compatibility.md`
|
|
29
|
+
* shim shapes #4 and #5. Not restated here — three copies of one rationale is three things to drift.
|
|
30
|
+
*/
|
|
31
|
+
export type JwtRoles = {
|
|
32
|
+
allRolesAllowed: true;
|
|
33
|
+
roles?: never;
|
|
34
|
+
} | {
|
|
35
|
+
roles: readonly [string, ...string[]];
|
|
36
|
+
allRolesAllowed?: never;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* JwtRequirement - the {@link JwtRoles} decision PLUS any app-defined authorization fields, e.g.
|
|
40
|
+
* `@AuthJwt({ allRolesAllowed: true, inOrg: true })`. The framework authenticates (JwtHook.parseJwt)
|
|
41
|
+
* and enforces the roles any-of; the app overrides JwtHook.authorizeJwt to enforce its own fields.
|
|
42
|
+
* Both hook methods are ASYNC, so an app field like `inOrg` may be answered from a datastore.
|
|
43
|
+
*
|
|
44
|
+
* This was a SECOND decorator (`@Auth`) whose `roles` was optional — so `@Auth({})` reached the exact
|
|
45
|
+
* widest grant that {@link JwtRoles} exists to make un-typeable. Folding it in leaves one decorator per
|
|
46
|
+
* credential kind and closes that route by construction.
|
|
47
|
+
*/
|
|
48
|
+
export type JwtRequirement = JwtRoles & {
|
|
49
|
+
[field: string]: unknown;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* WHERE ONE api-key credential rides on the wire, as a union the COMPILER enforces — the DECLARATION
|
|
53
|
+
* a spec generator turns into an OpenAPI `securityScheme`:
|
|
54
|
+
*
|
|
55
|
+
* ```typescript
|
|
56
|
+
* { in: 'header', name: 'x-api-key' } // ✅ → {type: apiKey, in: header, name: x-api-key}
|
|
57
|
+
* { in: 'bearer' } // ✅ → {type: http, scheme: bearer}
|
|
58
|
+
* { in: 'bearer', name: 'x-api-key' } // ❌ bearer's location IS `Authorization`; a name is a lie
|
|
59
|
+
* { in: 'header' } // ❌ a header credential with no header name is unusable
|
|
60
|
+
* ```
|
|
61
|
+
*
|
|
62
|
+
* WHY A UNION AND NOT ONE OPTIONAL `headerName`. The two OpenAPI schemes reachable from "an api key"
|
|
63
|
+
* are structurally DIFFERENT documents (`type: apiKey` + `in` + `name` vs `type: http` + `scheme`).
|
|
64
|
+
* A single optional field makes the contradictory combination REPRESENTABLE, and a generator handed
|
|
65
|
+
* `{in: 'bearer', name: 'x-api-key'}` has to either guess or emit a silently-wrong published contract.
|
|
66
|
+
* `name?: never` on the bearer branch is what deletes that state — the same device {@link JwtRoles}
|
|
67
|
+
* uses, pinned the same way in `AuthApiKeyCompileAssertions.ts` (a COMPILED file, not a spec).
|
|
68
|
+
*
|
|
69
|
+
* THIS IS DESCRIPTION, NOT HANDLING. The framework reads no header from this; `ApiKeyHook` still gets
|
|
70
|
+
* the whole request and still owns the cross-check. Declaring the location cannot regress running auth
|
|
71
|
+
* — it exists so the location stops living ONLY in a hand-written spec fragment that drifts silently
|
|
72
|
+
* from the hook's own header constants.
|
|
73
|
+
*
|
|
74
|
+
* `description` is carried because it is what a docs site renders on its authorization card, and that
|
|
75
|
+
* prose belongs beside the declaration rather than in a hand-maintained JSON file.
|
|
76
|
+
*/
|
|
77
|
+
export type ApiKeyCredential = {
|
|
78
|
+
in: 'header';
|
|
79
|
+
name: string;
|
|
80
|
+
description?: string;
|
|
81
|
+
} | {
|
|
82
|
+
in: 'bearer';
|
|
83
|
+
name?: never;
|
|
84
|
+
description?: string;
|
|
85
|
+
};
|
|
86
|
+
/**
|
|
87
|
+
* EVERY credential one api-key regime requires, in the order they appear in the published document.
|
|
88
|
+
*
|
|
89
|
+
* A NON-EMPTY tuple, for the same reason {@link JwtRoles}'s `roles` is one: a regime that declares no
|
|
90
|
+
* credential would generate a document with no security block — the exact silent failure the
|
|
91
|
+
* declaration exists to remove — so `[]` is a COMPILE error rather than a runtime throw (shim shape
|
|
92
|
+
* #4). More than one entry is the normal case, not an exotic one: a real regime authenticates a PAIR,
|
|
93
|
+
* and every entry here must be presented TOGETHER (an AND, i.e. ONE OpenAPI security-requirement
|
|
94
|
+
* object holding every scheme, never a LIST of one-key objects, which would mean "either suffices").
|
|
95
|
+
*/
|
|
96
|
+
export type ApiKeyCredentials = readonly [ApiKeyCredential, ...ApiKeyCredential[]];
|
|
97
|
+
/**
|
|
98
|
+
* The service-to-service / user auth mode of an endpoint. Discriminated union so a filter can
|
|
99
|
+
* `switch (mode.kind)` and get the data it needs, exhaustively.
|
|
100
|
+
*
|
|
101
|
+
* - `public` → no auth check
|
|
102
|
+
* - `jwt` → user JWT; `requirement` carries the compiler-enforced role decision
|
|
103
|
+
* ({@link JwtRoles}) plus any app-defined authorization fields
|
|
104
|
+
* - `oidc` → Google OIDC service-to-service (Cloud Tasks delivery / cross-service RPC);
|
|
105
|
+
* `callers` is the allow-list of caller SAs ('self' = this service's SA)
|
|
106
|
+
* - `shared-secret` → constant-time compare of a header against the secret bound for `secretKey`
|
|
107
|
+
* - `webhook` → an OUTSIDE vendor signed this request its own way; the app's bound `WebhookAuthCallback`
|
|
108
|
+
* verifies it, selected by `name`. The framework ships NO vendor crypto (see
|
|
109
|
+
* {@link AuthWebhook}).
|
|
110
|
+
* - `apikey` → a CUSTOMER holds the credential; the app's bound `ApiKeyHook` looks it up
|
|
111
|
+
* (async, over the whole header set) and returns the context to seed, selected
|
|
112
|
+
* by `regime`. `credentials` DECLARES where the credential rides — an ORDERED,
|
|
113
|
+
* non-empty list, because a real regime authenticates a PAIR (a key AND the
|
|
114
|
+
* organization id it acts for) that must be presented TOGETHER. NOT a peer
|
|
115
|
+
* service — see {@link AuthApiKey}.
|
|
116
|
+
* - `local-only` → exists ONLY on a developer's machine; not registered and never served when
|
|
117
|
+
* {@link RuntimeLocality} says this process is deployed. Authenticates NOBODY —
|
|
118
|
+
* it is a deployment gate, not a credential.
|
|
119
|
+
*/
|
|
120
|
+
export type AuthMode = {
|
|
121
|
+
kind: 'public';
|
|
122
|
+
} | {
|
|
123
|
+
kind: 'jwt';
|
|
124
|
+
requirement: JwtRequirement;
|
|
125
|
+
} | {
|
|
126
|
+
kind: 'oidc';
|
|
127
|
+
callers: string[];
|
|
128
|
+
} | {
|
|
129
|
+
kind: 'shared-secret';
|
|
130
|
+
secretKey: string;
|
|
131
|
+
} | {
|
|
132
|
+
kind: 'webhook';
|
|
133
|
+
name: string;
|
|
134
|
+
} | {
|
|
135
|
+
kind: 'apikey';
|
|
136
|
+
regime: string;
|
|
137
|
+
credentials: ApiKeyCredentials;
|
|
138
|
+
} | {
|
|
139
|
+
kind: 'local-only';
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* Auth metadata attached to a class or method via one of the auth decorators
|
|
143
|
+
* (@Public / @AuthJwt / @AuthOidc / @AuthSharedSecret / @AuthWebhook / @AuthApiKey / @AuthLocalOnly) —
|
|
144
|
+
* one per credential kind.
|
|
145
|
+
*
|
|
146
|
+
* Carries a discriminated {@link AuthMode} and nothing else. It USED to also expose
|
|
147
|
+
* `authenticated`/`roles` getters "for back-compat with readers that only understand the user-JWT
|
|
148
|
+
* model" — deleted, because nothing read them: every reader (AuthFilter, BrowserProxyClient,
|
|
149
|
+
* ProxyClient) switches on `mode.kind`, which is the whole point of the discriminated union. A
|
|
150
|
+
* flattened view of a union is a second spelling of it, and the flattened one silently answers
|
|
151
|
+
* `authenticated: true` for oidc and shared-secret too.
|
|
152
|
+
*/
|
|
153
|
+
export declare class AuthMeta {
|
|
154
|
+
mode: AuthMode;
|
|
155
|
+
constructor(mode: AuthMode);
|
|
156
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The TYPE layer of the auth surface: what an endpoint's credential posture IS, with no decorator and
|
|
4
|
+
* no reflect-metadata. `decorators.ts` (which attaches these) imports FROM here, never the other way,
|
|
5
|
+
* so a reader that only needs to switch on a mode — `DestinationTrust`, `RouteMetadata`, a spec
|
|
6
|
+
* generator — does not drag the whole decorator surface in with it.
|
|
7
|
+
*
|
|
8
|
+
* Split out of `decorators.ts` purely for file size, exactly as `api-kind.ts`, `external-caller.ts` and
|
|
9
|
+
* `RouteMetadata.ts` were before it. Nothing about these types' role changed in the move, and the
|
|
10
|
+
* barrel keeps the package surface identical.
|
|
11
|
+
*/
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.AuthMeta = void 0;
|
|
14
|
+
/**
|
|
15
|
+
* Auth metadata attached to a class or method via one of the auth decorators
|
|
16
|
+
* (@Public / @AuthJwt / @AuthOidc / @AuthSharedSecret / @AuthWebhook / @AuthApiKey / @AuthLocalOnly) —
|
|
17
|
+
* one per credential kind.
|
|
18
|
+
*
|
|
19
|
+
* Carries a discriminated {@link AuthMode} and nothing else. It USED to also expose
|
|
20
|
+
* `authenticated`/`roles` getters "for back-compat with readers that only understand the user-JWT
|
|
21
|
+
* model" — deleted, because nothing read them: every reader (AuthFilter, BrowserProxyClient,
|
|
22
|
+
* ProxyClient) switches on `mode.kind`, which is the whole point of the discriminated union. A
|
|
23
|
+
* flattened view of a union is a second spelling of it, and the flattened one silently answers
|
|
24
|
+
* `authenticated: true` for oidc and shared-secret too.
|
|
25
|
+
*/
|
|
26
|
+
class AuthMeta {
|
|
27
|
+
mode;
|
|
28
|
+
constructor(mode) {
|
|
29
|
+
this.mode = mode;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
exports.AuthMeta = AuthMeta;
|
|
33
|
+
//# sourceMappingURL=auth-mode.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-mode.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/auth-mode.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG;;;AAiHH;;;;;;;;;;;GAWG;AACH,MAAa,QAAQ;IACjB,IAAI,CAAW;IAEf,YAAY,IAAc;QACtB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACrB,CAAC;CACJ;AAND,4BAMC","sourcesContent":["/**\n * The TYPE layer of the auth surface: what an endpoint's credential posture IS, with no decorator and\n * no reflect-metadata. `decorators.ts` (which attaches these) imports FROM here, never the other way,\n * so a reader that only needs to switch on a mode — `DestinationTrust`, `RouteMetadata`, a spec\n * generator — does not drag the whole decorator surface in with it.\n *\n * Split out of `decorators.ts` purely for file size, exactly as `api-kind.ts`, `external-caller.ts` and\n * `RouteMetadata.ts` were before it. Nothing about these types' role changed in the move, and the\n * barrel keeps the package surface identical.\n */\n\n/**\n * The role decision for a JWT endpoint, as a union the COMPILER enforces — one spelling per decision,\n * every broken combination a compile error:\n *\n * ```typescript\n * @AuthJwt({ roles: ['admin'] }) // ✅ role-gated (any-of)\n * @AuthJwt({ allRolesAllowed: true }) // ✅ every authenticated user, said out loud\n * @AuthJwt({}) // ❌ pick a branch\n * @AuthJwt({ roles: [] }) // ❌ needs at least one role\n * ```\n *\n * `allRolesAllowed` exists ONLY on the wide branch (the dangerous half must be a greppable token, and\n * the narrow branch rejects it as a redundant second spelling); `roles` is a NON-EMPTY tuple so\n * \"declared roles, passed none\" — the old optional `string[]`'s silent widest grant — cannot be written.\n * All six bad cases are pinned in `AuthJwtCompileAssertions.ts` — a COMPILED file, not a spec: tsc\n * fails the build (TS2578) if any starts compiling. A spec cannot do this (see that file's header).\n *\n * WHY a type rather than the runtime `throw` this replaced: `.claude/review/backwards-compatibility.md`\n * shim shapes #4 and #5. Not restated here — three copies of one rationale is three things to drift.\n */\nexport type JwtRoles =\n | { allRolesAllowed: true; roles?: never }\n | { roles: readonly [string, ...string[]]; allRolesAllowed?: never };\n\n/**\n * JwtRequirement - the {@link JwtRoles} decision PLUS any app-defined authorization fields, e.g.\n * `@AuthJwt({ allRolesAllowed: true, inOrg: true })`. The framework authenticates (JwtHook.parseJwt)\n * and enforces the roles any-of; the app overrides JwtHook.authorizeJwt to enforce its own fields.\n * Both hook methods are ASYNC, so an app field like `inOrg` may be answered from a datastore.\n *\n * This was a SECOND decorator (`@Auth`) whose `roles` was optional — so `@Auth({})` reached the exact\n * widest grant that {@link JwtRoles} exists to make un-typeable. Folding it in leaves one decorator per\n * credential kind and closes that route by construction.\n */\n// webpieces-disable no-any-unknown -- app-defined authorization fields (inOrg, tenant, ...)\nexport type JwtRequirement = JwtRoles & { [field: string]: unknown };\n\n/**\n * WHERE ONE api-key credential rides on the wire, as a union the COMPILER enforces — the DECLARATION\n * a spec generator turns into an OpenAPI `securityScheme`:\n *\n * ```typescript\n * { in: 'header', name: 'x-api-key' } // ✅ → {type: apiKey, in: header, name: x-api-key}\n * { in: 'bearer' } // ✅ → {type: http, scheme: bearer}\n * { in: 'bearer', name: 'x-api-key' } // ❌ bearer's location IS `Authorization`; a name is a lie\n * { in: 'header' } // ❌ a header credential with no header name is unusable\n * ```\n *\n * WHY A UNION AND NOT ONE OPTIONAL `headerName`. The two OpenAPI schemes reachable from \"an api key\"\n * are structurally DIFFERENT documents (`type: apiKey` + `in` + `name` vs `type: http` + `scheme`).\n * A single optional field makes the contradictory combination REPRESENTABLE, and a generator handed\n * `{in: 'bearer', name: 'x-api-key'}` has to either guess or emit a silently-wrong published contract.\n * `name?: never` on the bearer branch is what deletes that state — the same device {@link JwtRoles}\n * uses, pinned the same way in `AuthApiKeyCompileAssertions.ts` (a COMPILED file, not a spec).\n *\n * THIS IS DESCRIPTION, NOT HANDLING. The framework reads no header from this; `ApiKeyHook` still gets\n * the whole request and still owns the cross-check. Declaring the location cannot regress running auth\n * — it exists so the location stops living ONLY in a hand-written spec fragment that drifts silently\n * from the hook's own header constants.\n *\n * `description` is carried because it is what a docs site renders on its authorization card, and that\n * prose belongs beside the declaration rather than in a hand-maintained JSON file.\n */\nexport type ApiKeyCredential =\n | { in: 'header'; name: string; description?: string }\n | { in: 'bearer'; name?: never; description?: string };\n\n/**\n * EVERY credential one api-key regime requires, in the order they appear in the published document.\n *\n * A NON-EMPTY tuple, for the same reason {@link JwtRoles}'s `roles` is one: a regime that declares no\n * credential would generate a document with no security block — the exact silent failure the\n * declaration exists to remove — so `[]` is a COMPILE error rather than a runtime throw (shim shape\n * #4). More than one entry is the normal case, not an exotic one: a real regime authenticates a PAIR,\n * and every entry here must be presented TOGETHER (an AND, i.e. ONE OpenAPI security-requirement\n * object holding every scheme, never a LIST of one-key objects, which would mean \"either suffices\").\n */\nexport type ApiKeyCredentials = readonly [ApiKeyCredential, ...ApiKeyCredential[]];\n\n/**\n * The service-to-service / user auth mode of an endpoint. Discriminated union so a filter can\n * `switch (mode.kind)` and get the data it needs, exhaustively.\n *\n * - `public` → no auth check\n * - `jwt` → user JWT; `requirement` carries the compiler-enforced role decision\n * ({@link JwtRoles}) plus any app-defined authorization fields\n * - `oidc` → Google OIDC service-to-service (Cloud Tasks delivery / cross-service RPC);\n * `callers` is the allow-list of caller SAs ('self' = this service's SA)\n * - `shared-secret` → constant-time compare of a header against the secret bound for `secretKey`\n * - `webhook` → an OUTSIDE vendor signed this request its own way; the app's bound `WebhookAuthCallback`\n * verifies it, selected by `name`. The framework ships NO vendor crypto (see\n * {@link AuthWebhook}).\n * - `apikey` → a CUSTOMER holds the credential; the app's bound `ApiKeyHook` looks it up\n * (async, over the whole header set) and returns the context to seed, selected\n * by `regime`. `credentials` DECLARES where the credential rides — an ORDERED,\n * non-empty list, because a real regime authenticates a PAIR (a key AND the\n * organization id it acts for) that must be presented TOGETHER. NOT a peer\n * service — see {@link AuthApiKey}.\n * - `local-only` → exists ONLY on a developer's machine; not registered and never served when\n * {@link RuntimeLocality} says this process is deployed. Authenticates NOBODY —\n * it is a deployment gate, not a credential.\n */\nexport type AuthMode =\n | { kind: 'public' }\n | { kind: 'jwt'; requirement: JwtRequirement }\n | { kind: 'oidc'; callers: string[] }\n | { kind: 'shared-secret'; secretKey: string }\n | { kind: 'webhook'; name: string }\n | { kind: 'apikey'; regime: string; credentials: ApiKeyCredentials }\n | { kind: 'local-only' };\n\n/**\n * Auth metadata attached to a class or method via one of the auth decorators\n * (@Public / @AuthJwt / @AuthOidc / @AuthSharedSecret / @AuthWebhook / @AuthApiKey / @AuthLocalOnly) —\n * one per credential kind.\n *\n * Carries a discriminated {@link AuthMode} and nothing else. It USED to also expose\n * `authenticated`/`roles` getters \"for back-compat with readers that only understand the user-JWT\n * model\" — deleted, because nothing read them: every reader (AuthFilter, BrowserProxyClient,\n * ProxyClient) switches on `mode.kind`, which is the whole point of the discriminated union. A\n * flattened view of a union is a second spelling of it, and the flattened one silently answers\n * `authenticated: true` for oidc and shared-secret too.\n */\nexport class AuthMeta {\n mode: AuthMode;\n\n constructor(mode: AuthMode) {\n this.mode = mode;\n }\n}\n"]}
|
package/src/http/decorators.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import 'reflect-metadata';
|
|
2
2
|
import { MaskSpec, MaskMode } from './LogFieldMask';
|
|
3
3
|
import { ExternalSystemKind } from './external-caller';
|
|
4
|
+
import { ApiKeyCredentials, AuthMeta, AuthMode, JwtRequirement } from './auth-mode';
|
|
4
5
|
/**
|
|
5
6
|
* Metadata keys for storing API routing information.
|
|
6
7
|
* These keys are used by both server-side (routing) and client-side (client generation).
|
|
@@ -79,102 +80,6 @@ export interface ExternalEndpointOptions extends EndpointOptions {
|
|
|
79
80
|
/** What that caller IS; picks the node's shape. Defaults to `'saas'` (see DEFAULT_CALLER_KIND). */
|
|
80
81
|
callerKind?: ExternalSystemKind;
|
|
81
82
|
}
|
|
82
|
-
/**
|
|
83
|
-
* The role decision for a JWT endpoint, as a union the COMPILER enforces — one spelling per decision,
|
|
84
|
-
* every broken combination a compile error:
|
|
85
|
-
*
|
|
86
|
-
* ```typescript
|
|
87
|
-
* @AuthJwt({ roles: ['admin'] }) // ✅ role-gated (any-of)
|
|
88
|
-
* @AuthJwt({ allRolesAllowed: true }) // ✅ every authenticated user, said out loud
|
|
89
|
-
* @AuthJwt({}) // ❌ pick a branch
|
|
90
|
-
* @AuthJwt({ roles: [] }) // ❌ needs at least one role
|
|
91
|
-
* ```
|
|
92
|
-
*
|
|
93
|
-
* `allRolesAllowed` exists ONLY on the wide branch (the dangerous half must be a greppable token, and
|
|
94
|
-
* the narrow branch rejects it as a redundant second spelling); `roles` is a NON-EMPTY tuple so
|
|
95
|
-
* "declared roles, passed none" — the old optional `string[]`'s silent widest grant — cannot be written.
|
|
96
|
-
* All six bad cases are pinned in `AuthJwtCompileAssertions.ts` — a COMPILED file, not a spec: tsc
|
|
97
|
-
* fails the build (TS2578) if any starts compiling. A spec cannot do this (see that file's header).
|
|
98
|
-
*
|
|
99
|
-
* WHY a type rather than the runtime `throw` this replaced: `.claude/review/backwards-compatibility.md`
|
|
100
|
-
* shim shapes #4 and #5. Not restated here — three copies of one rationale is three things to drift.
|
|
101
|
-
*/
|
|
102
|
-
export type JwtRoles = {
|
|
103
|
-
allRolesAllowed: true;
|
|
104
|
-
roles?: never;
|
|
105
|
-
} | {
|
|
106
|
-
roles: readonly [string, ...string[]];
|
|
107
|
-
allRolesAllowed?: never;
|
|
108
|
-
};
|
|
109
|
-
/**
|
|
110
|
-
* JwtRequirement - the {@link JwtRoles} decision PLUS any app-defined authorization fields, e.g.
|
|
111
|
-
* `@AuthJwt({ allRolesAllowed: true, inOrg: true })`. The framework authenticates (JwtHook.parseJwt)
|
|
112
|
-
* and enforces the roles any-of; the app overrides JwtHook.authorizeJwt to enforce its own fields.
|
|
113
|
-
* Both hook methods are ASYNC, so an app field like `inOrg` may be answered from a datastore.
|
|
114
|
-
*
|
|
115
|
-
* This was a SECOND decorator (`@Auth`) whose `roles` was optional — so `@Auth({})` reached the exact
|
|
116
|
-
* widest grant that {@link JwtRoles} exists to make un-typeable. Folding it in leaves one decorator per
|
|
117
|
-
* credential kind and closes that route by construction.
|
|
118
|
-
*/
|
|
119
|
-
export type JwtRequirement = JwtRoles & {
|
|
120
|
-
[field: string]: unknown;
|
|
121
|
-
};
|
|
122
|
-
/**
|
|
123
|
-
* The service-to-service / user auth mode of an endpoint. Discriminated union so a filter can
|
|
124
|
-
* `switch (mode.kind)` and get the data it needs, exhaustively.
|
|
125
|
-
*
|
|
126
|
-
* - `public` → no auth check
|
|
127
|
-
* - `jwt` → user JWT; `requirement` carries the compiler-enforced role decision
|
|
128
|
-
* ({@link JwtRoles}) plus any app-defined authorization fields
|
|
129
|
-
* - `oidc` → Google OIDC service-to-service (Cloud Tasks delivery / cross-service RPC);
|
|
130
|
-
* `callers` is the allow-list of caller SAs ('self' = this service's SA)
|
|
131
|
-
* - `shared-secret` → constant-time compare of a header against the secret bound for `secretKey`
|
|
132
|
-
* - `webhook` → an OUTSIDE vendor signed this request its own way; the app's bound `WebhookAuthCallback`
|
|
133
|
-
* verifies it, selected by `name`. The framework ships NO vendor crypto (see
|
|
134
|
-
* {@link AuthWebhook}).
|
|
135
|
-
* - `apikey` → a CUSTOMER holds the credential; the app's bound `ApiKeyHook` looks it up
|
|
136
|
-
* (async, over the whole header set) and returns the context to seed, selected
|
|
137
|
-
* by `name`. NOT a peer service — see {@link AuthApiKey}.
|
|
138
|
-
* - `local-only` → exists ONLY on a developer's machine; not registered and never served when
|
|
139
|
-
* {@link RuntimeLocality} says this process is deployed. Authenticates NOBODY —
|
|
140
|
-
* it is a deployment gate, not a credential.
|
|
141
|
-
*/
|
|
142
|
-
export type AuthMode = {
|
|
143
|
-
kind: 'public';
|
|
144
|
-
} | {
|
|
145
|
-
kind: 'jwt';
|
|
146
|
-
requirement: JwtRequirement;
|
|
147
|
-
} | {
|
|
148
|
-
kind: 'oidc';
|
|
149
|
-
callers: string[];
|
|
150
|
-
} | {
|
|
151
|
-
kind: 'shared-secret';
|
|
152
|
-
secretKey: string;
|
|
153
|
-
} | {
|
|
154
|
-
kind: 'webhook';
|
|
155
|
-
name: string;
|
|
156
|
-
} | {
|
|
157
|
-
kind: 'apikey';
|
|
158
|
-
name: string;
|
|
159
|
-
} | {
|
|
160
|
-
kind: 'local-only';
|
|
161
|
-
};
|
|
162
|
-
/**
|
|
163
|
-
* Auth metadata attached to a class or method via one of the auth decorators
|
|
164
|
-
* (@Public / @AuthJwt / @AuthOidc / @AuthSharedSecret / @AuthWebhook / @AuthApiKey / @AuthLocalOnly) —
|
|
165
|
-
* one per credential kind.
|
|
166
|
-
*
|
|
167
|
-
* Carries a discriminated {@link AuthMode} and nothing else. It USED to also expose
|
|
168
|
-
* `authenticated`/`roles` getters "for back-compat with readers that only understand the user-JWT
|
|
169
|
-
* model" — deleted, because nothing read them: every reader (AuthFilter, BrowserProxyClient,
|
|
170
|
-
* ProxyClient) switches on `mode.kind`, which is the whole point of the discriminated union. A
|
|
171
|
-
* flattened view of a union is a second spelling of it, and the flattened one silently answers
|
|
172
|
-
* `authenticated: true` for oidc and shared-secret too.
|
|
173
|
-
*/
|
|
174
|
-
export declare class AuthMeta {
|
|
175
|
-
mode: AuthMode;
|
|
176
|
-
constructor(mode: AuthMode);
|
|
177
|
-
}
|
|
178
83
|
/**
|
|
179
84
|
* @ApiPath(basePath) - Class decorator that marks a class as an API definition
|
|
180
85
|
* and sets the base path for all endpoints.
|
|
@@ -327,21 +232,39 @@ export declare function AuthSharedSecret(key: string): ClassDecorator & MethodDe
|
|
|
327
232
|
*/
|
|
328
233
|
export declare function AuthWebhook(name: string): ClassDecorator & MethodDecorator;
|
|
329
234
|
/**
|
|
330
|
-
* @AuthApiKey(
|
|
331
|
-
* inbound request against its own datastore and returns the `ContextTuple` entries
|
|
332
|
-
* seeds into `RequestContext`. THE mode for a partner-facing contract consumed by other
|
|
333
|
-
* codebases (POS vendors, back-office platforms, ETL pipelines).
|
|
235
|
+
* @AuthApiKey(regime, credentials) - a CUSTOMER holds the credential. The app's bound `ApiKeyHook`
|
|
236
|
+
* authenticates the inbound request against its own datastore and returns the `ContextTuple` entries
|
|
237
|
+
* the framework seeds into `RequestContext`. THE mode for a partner-facing contract consumed by other
|
|
238
|
+
* companies' codebases (POS vendors, back-office platforms, ETL pipelines).
|
|
334
239
|
*
|
|
335
240
|
* ```typescript
|
|
336
|
-
* @AuthApiKey('onetablet-partner'
|
|
241
|
+
* @AuthApiKey('onetablet-partner', [
|
|
242
|
+
* { in: 'header', name: 'x-api-key', description: 'The key issued to your integration.' },
|
|
243
|
+
* { in: 'header', name: 'x-organization-id', description: 'Which of your organizations to act on.' },
|
|
244
|
+
* ])
|
|
337
245
|
* @ApiPath('/management/v1')
|
|
338
246
|
* abstract class ManagementApi { ... }
|
|
339
247
|
* ```
|
|
340
248
|
*
|
|
341
|
-
* `
|
|
249
|
+
* `regime` is a bare STRING selecting WHICH key regime this route belongs to, exactly as
|
|
342
250
|
* `@AuthSharedSecret(key)` and `@AuthWebhook(vendor)` already are — one hook serves several regimes,
|
|
343
251
|
* and an api contract is level 0, so it never references a verifier directly.
|
|
344
252
|
*
|
|
253
|
+
* `credentials` DECLARES where the credential rides ({@link ApiKeyCredential}), so a spec generator
|
|
254
|
+
* reading route auth metadata can emit `components.securitySchemes` instead of a human hand-writing
|
|
255
|
+
* them into a manifest. It is a NON-EMPTY, ORDERED list rather than one credential because a real
|
|
256
|
+
* regime authenticates a PAIR — the key names a customer, a second header names which of that
|
|
257
|
+
* customer's organizations the request acts on, and a mismatch is a 401. Its OpenAPI form is two
|
|
258
|
+
* schemes plus ONE security-requirement object holding BOTH keys (an AND); a LIST of two objects
|
|
259
|
+
* would mean "either alone suffices", which is a load-bearing difference a single-credential shape
|
|
260
|
+
* cannot even express. ORDER IS SIGNIFICANT and preserved: it is the order the credentials are
|
|
261
|
+
* presented in the published document.
|
|
262
|
+
*
|
|
263
|
+
* The list can never be EMPTY — a contract that declares a key regime and then names no credential
|
|
264
|
+
* would generate a document with no security block, which is the exact silent failure this argument
|
|
265
|
+
* exists to remove. That is a compile error, not a runtime throw (see {@link JwtRoles}'s non-empty
|
|
266
|
+
* tuple, the same device for the same reason).
|
|
267
|
+
*
|
|
345
268
|
* WHY IT IS NOT `@AuthSharedSecret`. Shared-secret declares that AN INTERNAL SERVICE is on the other
|
|
346
269
|
* end, so the framework BELIEVES the trusted context headers that caller forwarded (see
|
|
347
270
|
* `DestinationTrust.forAuthMode` and `AuthFilter.verifiesCaller`). A customer is not an internal
|
|
@@ -352,14 +275,15 @@ export declare function AuthWebhook(name: string): ClassDecorator & MethodDecora
|
|
|
352
275
|
*
|
|
353
276
|
* WHY THE HOOK SEES THE REQUEST, NOT ONE TOKEN. A real key regime checks the key TOGETHER WITH a
|
|
354
277
|
* second header (the organization it is acting for), and `JwtHook.parseJwt` — handed one pre-extracted
|
|
355
|
-
* token from one header — physically cannot. `ApiKeyHook.verifyApiKey(
|
|
278
|
+
* token from one header — physically cannot. `ApiKeyHook.verifyApiKey(regime, request)` gets the whole
|
|
356
279
|
* inbound request instead, so the app owns which headers carry the credential and validates them as a
|
|
357
|
-
* PAIR.
|
|
280
|
+
* PAIR. `credentials` does NOT change that: the framework reads no header from it and performs no
|
|
281
|
+
* extraction. It is DECLARATION for readers of the contract, and enforcement stays entirely the hook's.
|
|
358
282
|
*
|
|
359
283
|
* FAILS CLOSED: with no `ApiKeyHook` bound, every `@AuthApiKey` endpoint 401s, matching `JwtHook` and
|
|
360
284
|
* `WebhookAuthCallback`.
|
|
361
285
|
*/
|
|
362
|
-
export declare function AuthApiKey(
|
|
286
|
+
export declare function AuthApiKey(regime: string, credentials: ApiKeyCredentials): ClassDecorator & MethodDecorator;
|
|
363
287
|
/**
|
|
364
288
|
* @AuthLocalOnly() - this endpoint exists ONLY on a developer's machine. Off-local it is not
|
|
365
289
|
* registered as a route at all, and if it is somehow reached it 404s. Class- or method-level.
|
package/src/http/decorators.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MISSING_AUTH_DECORATOR_FIX = exports.
|
|
3
|
+
exports.MISSING_AUTH_DECORATOR_FIX = exports.METADATA_KEYS = void 0;
|
|
4
4
|
exports.ApiPath = ApiPath;
|
|
5
5
|
exports.Endpoint = Endpoint;
|
|
6
6
|
exports.MaskLog = MaskLog;
|
|
@@ -30,6 +30,8 @@ exports.validateNoConflictingDecorators = validateNoConflictingDecorators;
|
|
|
30
30
|
require("reflect-metadata");
|
|
31
31
|
const LogFieldMask_1 = require("./LogFieldMask");
|
|
32
32
|
const external_caller_1 = require("./external-caller");
|
|
33
|
+
// The TYPE layer these decorators attach — split out for file size only (see auth-mode.ts).
|
|
34
|
+
const auth_mode_1 = require("./auth-mode");
|
|
33
35
|
/**
|
|
34
36
|
* Metadata keys for storing API routing information.
|
|
35
37
|
* These keys are used by both server-side (routing) and client-side (client generation).
|
|
@@ -51,25 +53,6 @@ exports.METADATA_KEYS = {
|
|
|
51
53
|
/** Per-method @MaskLog spec (which DTO fields the LogApiCall path masks). */
|
|
52
54
|
MASK_LOG: 'webpieces:mask-log',
|
|
53
55
|
};
|
|
54
|
-
/**
|
|
55
|
-
* Auth metadata attached to a class or method via one of the auth decorators
|
|
56
|
-
* (@Public / @AuthJwt / @AuthOidc / @AuthSharedSecret / @AuthWebhook / @AuthApiKey / @AuthLocalOnly) —
|
|
57
|
-
* one per credential kind.
|
|
58
|
-
*
|
|
59
|
-
* Carries a discriminated {@link AuthMode} and nothing else. It USED to also expose
|
|
60
|
-
* `authenticated`/`roles` getters "for back-compat with readers that only understand the user-JWT
|
|
61
|
-
* model" — deleted, because nothing read them: every reader (AuthFilter, BrowserProxyClient,
|
|
62
|
-
* ProxyClient) switches on `mode.kind`, which is the whole point of the discriminated union. A
|
|
63
|
-
* flattened view of a union is a second spelling of it, and the flattened one silently answers
|
|
64
|
-
* `authenticated: true` for oidc and shared-secret too.
|
|
65
|
-
*/
|
|
66
|
-
class AuthMeta {
|
|
67
|
-
mode;
|
|
68
|
-
constructor(mode) {
|
|
69
|
-
this.mode = mode;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
exports.AuthMeta = AuthMeta;
|
|
73
56
|
/**
|
|
74
57
|
* @ApiPath(basePath) - Class decorator that marks a class as an API definition
|
|
75
58
|
* and sets the base path for all endpoints.
|
|
@@ -161,7 +144,7 @@ function getMaskSpec(apiClass, methodName) {
|
|
|
161
144
|
* decorator on the same target.
|
|
162
145
|
*/
|
|
163
146
|
function defineAuthMode(mode) {
|
|
164
|
-
const authMeta = new AuthMeta(mode);
|
|
147
|
+
const authMeta = new auth_mode_1.AuthMeta(mode);
|
|
165
148
|
// webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any
|
|
166
149
|
return (target, propertyKey, _descriptor) => {
|
|
167
150
|
if (propertyKey !== undefined) {
|
|
@@ -265,21 +248,39 @@ function AuthWebhook(name) {
|
|
|
265
248
|
return defineAuthMode({ kind: 'webhook', name });
|
|
266
249
|
}
|
|
267
250
|
/**
|
|
268
|
-
* @AuthApiKey(
|
|
269
|
-
* inbound request against its own datastore and returns the `ContextTuple` entries
|
|
270
|
-
* seeds into `RequestContext`. THE mode for a partner-facing contract consumed by other
|
|
271
|
-
* codebases (POS vendors, back-office platforms, ETL pipelines).
|
|
251
|
+
* @AuthApiKey(regime, credentials) - a CUSTOMER holds the credential. The app's bound `ApiKeyHook`
|
|
252
|
+
* authenticates the inbound request against its own datastore and returns the `ContextTuple` entries
|
|
253
|
+
* the framework seeds into `RequestContext`. THE mode for a partner-facing contract consumed by other
|
|
254
|
+
* companies' codebases (POS vendors, back-office platforms, ETL pipelines).
|
|
272
255
|
*
|
|
273
256
|
* ```typescript
|
|
274
|
-
* @AuthApiKey('onetablet-partner'
|
|
257
|
+
* @AuthApiKey('onetablet-partner', [
|
|
258
|
+
* { in: 'header', name: 'x-api-key', description: 'The key issued to your integration.' },
|
|
259
|
+
* { in: 'header', name: 'x-organization-id', description: 'Which of your organizations to act on.' },
|
|
260
|
+
* ])
|
|
275
261
|
* @ApiPath('/management/v1')
|
|
276
262
|
* abstract class ManagementApi { ... }
|
|
277
263
|
* ```
|
|
278
264
|
*
|
|
279
|
-
* `
|
|
265
|
+
* `regime` is a bare STRING selecting WHICH key regime this route belongs to, exactly as
|
|
280
266
|
* `@AuthSharedSecret(key)` and `@AuthWebhook(vendor)` already are — one hook serves several regimes,
|
|
281
267
|
* and an api contract is level 0, so it never references a verifier directly.
|
|
282
268
|
*
|
|
269
|
+
* `credentials` DECLARES where the credential rides ({@link ApiKeyCredential}), so a spec generator
|
|
270
|
+
* reading route auth metadata can emit `components.securitySchemes` instead of a human hand-writing
|
|
271
|
+
* them into a manifest. It is a NON-EMPTY, ORDERED list rather than one credential because a real
|
|
272
|
+
* regime authenticates a PAIR — the key names a customer, a second header names which of that
|
|
273
|
+
* customer's organizations the request acts on, and a mismatch is a 401. Its OpenAPI form is two
|
|
274
|
+
* schemes plus ONE security-requirement object holding BOTH keys (an AND); a LIST of two objects
|
|
275
|
+
* would mean "either alone suffices", which is a load-bearing difference a single-credential shape
|
|
276
|
+
* cannot even express. ORDER IS SIGNIFICANT and preserved: it is the order the credentials are
|
|
277
|
+
* presented in the published document.
|
|
278
|
+
*
|
|
279
|
+
* The list can never be EMPTY — a contract that declares a key regime and then names no credential
|
|
280
|
+
* would generate a document with no security block, which is the exact silent failure this argument
|
|
281
|
+
* exists to remove. That is a compile error, not a runtime throw (see {@link JwtRoles}'s non-empty
|
|
282
|
+
* tuple, the same device for the same reason).
|
|
283
|
+
*
|
|
283
284
|
* WHY IT IS NOT `@AuthSharedSecret`. Shared-secret declares that AN INTERNAL SERVICE is on the other
|
|
284
285
|
* end, so the framework BELIEVES the trusted context headers that caller forwarded (see
|
|
285
286
|
* `DestinationTrust.forAuthMode` and `AuthFilter.verifiesCaller`). A customer is not an internal
|
|
@@ -290,16 +291,17 @@ function AuthWebhook(name) {
|
|
|
290
291
|
*
|
|
291
292
|
* WHY THE HOOK SEES THE REQUEST, NOT ONE TOKEN. A real key regime checks the key TOGETHER WITH a
|
|
292
293
|
* second header (the organization it is acting for), and `JwtHook.parseJwt` — handed one pre-extracted
|
|
293
|
-
* token from one header — physically cannot. `ApiKeyHook.verifyApiKey(
|
|
294
|
+
* token from one header — physically cannot. `ApiKeyHook.verifyApiKey(regime, request)` gets the whole
|
|
294
295
|
* inbound request instead, so the app owns which headers carry the credential and validates them as a
|
|
295
|
-
* PAIR.
|
|
296
|
+
* PAIR. `credentials` does NOT change that: the framework reads no header from it and performs no
|
|
297
|
+
* extraction. It is DECLARATION for readers of the contract, and enforcement stays entirely the hook's.
|
|
296
298
|
*
|
|
297
299
|
* FAILS CLOSED: with no `ApiKeyHook` bound, every `@AuthApiKey` endpoint 401s, matching `JwtHook` and
|
|
298
300
|
* `WebhookAuthCallback`.
|
|
299
301
|
*/
|
|
300
302
|
// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope
|
|
301
|
-
function AuthApiKey(
|
|
302
|
-
return defineAuthMode({ kind: 'apikey',
|
|
303
|
+
function AuthApiKey(regime, credentials) {
|
|
304
|
+
return defineAuthMode({ kind: 'apikey', regime, credentials });
|
|
303
305
|
}
|
|
304
306
|
/**
|
|
305
307
|
* @AuthLocalOnly() - this endpoint exists ONLY on a developer's machine. Off-local it is not
|
|
@@ -468,7 +470,8 @@ function getAuthMode(apiClass, methodName) {
|
|
|
468
470
|
* the first thing offered should not be the widest grant.
|
|
469
471
|
*/
|
|
470
472
|
exports.MISSING_AUTH_DECORATOR_FIX = "Add one of @AuthJwt({roles: ['admin']}) / @AuthJwt({allRolesAllowed: true}) / @Public() / " +
|
|
471
|
-
|
|
473
|
+
'@AuthOidc(...callers) / @AuthSharedSecret(key) / ' +
|
|
474
|
+
"@AuthWebhook('vendor') / @AuthApiKey('regime', [{in: 'header', name: 'x-api-key'}]) / " +
|
|
472
475
|
'@AuthLocalOnly() to ' +
|
|
473
476
|
'the class or method.';
|
|
474
477
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decorators.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/decorators.ts"],"names":[],"mappings":";;;AA2LA,0BAUC;AA8CD,4BA8BC;AAoBD,0BAUC;AAOD,kCAIC;AA4BD,wBAEC;AAgBD,0BAEC;AAQD,sCAEC;AAYD,4BAEC;AAQD,4CAEC;AAgCD,kCAEC;AAoCD,gCAEC;AA6BD,sCAEC;AASD,gCAEC;AAMD,oCAEC;AAOD,4CAEC;AAWD,0CAEC;AAMD,gDAIC;AASD,8FAUC;AAOD,gCAEC;AAOD,8BAEC;AAeD,4FAWC;AAKD,8BAEC;AAMD,kCAWC;AAMD,kCAEC;AAqBD,wEAWC;AAMD,0EAcC;AAzrBD,4BAA0B;AAC1B,iDAAoD;AACpD,uDAAoI;AAEpI;;;GAGG;AACU,QAAA,aAAa,GAAG;IACzB,QAAQ,EAAE,oBAAoB;IAC9B,SAAS,EAAE,qBAAqB;IAChC,SAAS,EAAE,qBAAqB;IAChC,uFAAuF;IACvF,QAAQ,EAAE,oBAAoB;IAC9B,mEAAmE;IACnE,cAAc,EAAE,0BAA0B;IAC1C,2EAA2E;IAC3E,gBAAgB,EAAE,4B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AU;QACvB,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,qBAAa,CAAC,SAAS,EAAE,QAAQ,EAAE,UAAU,CAAC;QACpE,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,qBAAa,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IAE7D,IAAI,QAAQ,EAAE,CAAC;QACX,MAAM,UAAU,GAAG,QAAQ,CAAC,IAAI,IAAI,SAAS,CAAC;QAC9C,MAAM,QAAQ,GAAG,UAAU,CAAC,CAAC,CAAC,WAAW,UAAU,QAAQ,UAAU,EAAE,CAAC,CAAC,CAAC,SAAS,UAAU,EAAE,CAAC;QAChG,MAAM,IAAI,KAAK,CACX,iCAAiC,QAAQ,IAAI;YAC7C,sFAAsF;YACtF,gFAAgF,CACnF,CAAC;IACN,CAAC;AACL,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { MaskSpec, MaskMode } from './LogFieldMask';\nimport { DEFAULT_CALLER_KIND, ENDPOINT_CALLER_KEY, ExternalCaller, ExternalSystemKind, getEndpointCaller } from './external-caller';\n\n/**\n * Metadata keys for storing API routing information.\n * These keys are used by both server-side (routing) and client-side (client generation).\n */\nexport const METADATA_KEYS = {\n API_PATH: 'webpieces:api-path',\n ENDPOINTS: 'webpieces:endpoints',\n AUTH_META: 'webpieces:auth-meta',\n /** 'rpc' (default, sync request/response) vs 'pubsub' (fire-and-forget cloud task). */\n API_KIND: 'webpieces:api-kind',\n /** Per-method Cloud Tasks queue-name override (set via @Queue). */\n QUEUE_OVERRIDE: 'webpieces:queue-override',\n /** Per-method @Endpoint options (e.g. formPost), parallel to ENDPOINTS. */\n ENDPOINT_OPTIONS: 'webpieces:endpoint-options',\n /** Per-method @Endpoint trigger kind (rpc | cloudtasks | cron | external), parallel to ENDPOINTS. */\n ENDPOINT_KIND: 'webpieces:endpoint-kind',\n /** Per-method declared external CALLER (only for kind 'external'), parallel to ENDPOINTS. */\n ENDPOINT_CALLER: ENDPOINT_CALLER_KEY,\n /** Per-method @MaskLog spec (which DTO fields the LogApiCall path masks). */\n MASK_LOG: 'webpieces:mask-log',\n};\n\n/**\n * WHAT TRIGGERS an endpoint at runtime — the single fact that decides how the runtime architecture\n * graph draws it, and which Terraform resource must exist for it to ever fire:\n *\n * - `rpc` — a caller in this repo (or a browser) calls it synchronously. A direct arrow.\n * - `cloudtasks` — a producer ENQUEUES it; Cloud Tasks delivers it later. Drawn producer → queue →\n * consumer, one queue node per METHOD (see {@link Queue}). Producer and consumer\n * being the SAME service is legal and common — the queue decouples them.\n * - `cron` — a scheduler fires it on a clock. Nothing in-repo calls it; drawn hanging off a\n * clock symbol. Backed by a Cloud Scheduler job.\n * - `external` — a system OUTSIDE this repo drives it (a GCP Pub/Sub push subscription, a Twilio\n * or Gmail webhook). Drawn as an inbound dashed arrow from that system.\n *\n * Declared PER METHOD, because one api class routinely mixes them: an admin contract can have\n * caller-driven endpoints AND a nightly cron sweep. A class-level marker cannot express that, which\n * is exactly why the graph could not tell these apart before.\n */\nexport type EndpointKind = 'rpc' | 'cloudtasks' | 'cron' | 'external';\n\n/**\n * Options for a single @Endpoint. Kept in a metadata map PARALLEL to ENDPOINTS so the existing\n * `Record<methodName, path>` shape every consumer iterates stays unchanged.\n */\nexport interface EndpointOptions {\n /**\n * Parse the request body as application/x-www-form-urlencoded (flat key→value) instead of JSON.\n * For EXTERNAL webhooks (e.g. Twilio) that post form-encoded. The request DTO must be FLAT —\n * urlencoded has no nesting (unlike JSON). Default false = JSON.\n */\n formPost?: boolean;\n\n /**\n * RETAIN the verbatim request bytes + the absolute url the sender addressed, so an\n * {@link AuthWebhook} hook can verify a vendor signature over them (see `RawRequest`).\n *\n * Opt-in PER ENDPOINT, sitting beside `formPost` and for the same reason: the cost lands on the\n * handful of webhook routes rather than on every request in the process. It is retention, not\n * new buffering — the express adapter already accumulates the whole body, it simply threw it\n * away once it had parsed a DTO.\n *\n * REQUIRED by `@AuthWebhook`, checked at wiring time (see\n * {@link assertEveryWebhookEndpointRetainsRawBody}) rather than left to fail as a 401 in\n * production: a hook with nothing to verify is a misconfiguration, not a bad request.\n *\n * Combines with `formPost` — `{ formPost: true, rawBody: true }` is the Twilio case, where the\n * hook needs the bytes and the url while the controller still wants the flat parsed DTO.\n */\n rawBody?: boolean;\n}\n\n/**\n * Options for an `external` @Endpoint: everything {@link EndpointOptions} carries, PLUS a REQUIRED\n * declaration of WHO is calling. See {@link Endpoint} for why, `external-caller.ts` for identity.\n */\nexport interface ExternalEndpointOptions extends EndpointOptions {\n /** The outside system that posts here (`'twilio'`) — the graph node IDENTITY, not display text. */\n calledBy: string;\n /** What that caller IS; picks the node's shape. Defaults to `'saas'` (see DEFAULT_CALLER_KIND). */\n callerKind?: ExternalSystemKind;\n}\n\n/**\n * The role decision for a JWT endpoint, as a union the COMPILER enforces — one spelling per decision,\n * every broken combination a compile error:\n *\n * ```typescript\n * @AuthJwt({ roles: ['admin'] }) // ✅ role-gated (any-of)\n * @AuthJwt({ allRolesAllowed: true }) // ✅ every authenticated user, said out loud\n * @AuthJwt({}) // ❌ pick a branch\n * @AuthJwt({ roles: [] }) // ❌ needs at least one role\n * ```\n *\n * `allRolesAllowed` exists ONLY on the wide branch (the dangerous half must be a greppable token, and\n * the narrow branch rejects it as a redundant second spelling); `roles` is a NON-EMPTY tuple so\n * \"declared roles, passed none\" — the old optional `string[]`'s silent widest grant — cannot be written.\n * All six bad cases are pinned in `AuthJwtCompileAssertions.ts` — a COMPILED file, not a spec: tsc\n * fails the build (TS2578) if any starts compiling. A spec cannot do this (see that file's header).\n *\n * WHY a type rather than the runtime `throw` this replaced: `.claude/review/backwards-compatibility.md`\n * shim shapes #4 and #5. Not restated here — three copies of one rationale is three things to drift.\n */\nexport type JwtRoles =\n | { allRolesAllowed: true; roles?: never }\n | { roles: readonly [string, ...string[]]; allRolesAllowed?: never };\n\n/**\n * JwtRequirement - the {@link JwtRoles} decision PLUS any app-defined authorization fields, e.g.\n * `@AuthJwt({ allRolesAllowed: true, inOrg: true })`. The framework authenticates (JwtHook.parseJwt)\n * and enforces the roles any-of; the app overrides JwtHook.authorizeJwt to enforce its own fields.\n * Both hook methods are ASYNC, so an app field like `inOrg` may be answered from a datastore.\n *\n * This was a SECOND decorator (`@Auth`) whose `roles` was optional — so `@Auth({})` reached the exact\n * widest grant that {@link JwtRoles} exists to make un-typeable. Folding it in leaves one decorator per\n * credential kind and closes that route by construction.\n */\n// webpieces-disable no-any-unknown -- app-defined authorization fields (inOrg, tenant, ...)\nexport type JwtRequirement = JwtRoles & { [field: string]: unknown };\n\n/**\n * The service-to-service / user auth mode of an endpoint. Discriminated union so a filter can\n * `switch (mode.kind)` and get the data it needs, exhaustively.\n *\n * - `public` → no auth check\n * - `jwt` → user JWT; `requirement` carries the compiler-enforced role decision\n * ({@link JwtRoles}) plus any app-defined authorization fields\n * - `oidc` → Google OIDC service-to-service (Cloud Tasks delivery / cross-service RPC);\n * `callers` is the allow-list of caller SAs ('self' = this service's SA)\n * - `shared-secret` → constant-time compare of a header against the secret bound for `secretKey`\n * - `webhook` → an OUTSIDE vendor signed this request its own way; the app's bound `WebhookAuthCallback`\n * verifies it, selected by `name`. The framework ships NO vendor crypto (see\n * {@link AuthWebhook}).\n * - `apikey` → a CUSTOMER holds the credential; the app's bound `ApiKeyHook` looks it up\n * (async, over the whole header set) and returns the context to seed, selected\n * by `name`. NOT a peer service — see {@link AuthApiKey}.\n * - `local-only` → exists ONLY on a developer's machine; not registered and never served when\n * {@link RuntimeLocality} says this process is deployed. Authenticates NOBODY —\n * it is a deployment gate, not a credential.\n */\nexport type AuthMode =\n | { kind: 'public' }\n | { kind: 'jwt'; requirement: JwtRequirement }\n | { kind: 'oidc'; callers: string[] }\n | { kind: 'shared-secret'; secretKey: string }\n | { kind: 'webhook'; name: string }\n | { kind: 'apikey'; name: string }\n | { kind: 'local-only' };\n\n/**\n * Auth metadata attached to a class or method via one of the auth decorators\n * (@Public / @AuthJwt / @AuthOidc / @AuthSharedSecret / @AuthWebhook / @AuthApiKey / @AuthLocalOnly) —\n * one per credential kind.\n *\n * Carries a discriminated {@link AuthMode} and nothing else. It USED to also expose\n * `authenticated`/`roles` getters \"for back-compat with readers that only understand the user-JWT\n * model\" — deleted, because nothing read them: every reader (AuthFilter, BrowserProxyClient,\n * ProxyClient) switches on `mode.kind`, which is the whole point of the discriminated union. A\n * flattened view of a union is a second spelling of it, and the flattened one silently answers\n * `authenticated: true` for oidc and shared-secret too.\n */\nexport class AuthMeta {\n mode: AuthMode;\n\n constructor(mode: AuthMode) {\n this.mode = mode;\n }\n}\n\n/**\n * @ApiPath(basePath) - Class decorator that marks a class as an API definition\n * and sets the base path for all endpoints.\n *\n * Usage:\n * ```typescript\n * @AuthJwt({ roles: ['admin'] })\n * @ApiPath('/api/save')\n * abstract class SaveApi {\n * @Endpoint('/item', 'rpc')\n * save(request: SaveRequest): Promise<SaveResponse> { ... }\n * }\n * ```\n */\nexport function ApiPath(basePath: string): ClassDecorator {\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any) => {\n Reflect.defineMetadata(METADATA_KEYS.API_PATH, basePath, target);\n\n // Initialize endpoints map if not exists\n if (!Reflect.hasMetadata(METADATA_KEYS.ENDPOINTS, target)) {\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINTS, {}, target);\n }\n };\n}\n\n/**\n * @Endpoint(path, kind, options?) - Method decorator that registers a POST endpoint at the given\n * path and declares WHAT TRIGGERS it.\n *\n * All endpoints are POST-only (matching gRPC/thrift style).\n *\n * Usage:\n * ```typescript\n * @Endpoint('/item', 'rpc')\n * save(request: SaveRequest): Promise<SaveResponse> { ... }\n *\n * // enqueued by a producer, delivered later by Cloud Tasks:\n * @Endpoint('/send', 'cloudtasks')\n * send(request: SendRequest): Promise<void> { ... }\n *\n * // fired by Cloud Scheduler on a clock, called by nobody in this repo:\n * @Endpoint('/nightly', 'cron')\n * nightly(request: NightlyRequest): Promise<void> { ... }\n *\n * // EXTERNAL webhook posting application/x-www-form-urlencoded (e.g. Twilio):\n * @Endpoint('/hook', 'external', { formPost: true, calledBy: 'twilio' })\n * inbound(request: InboundRequest): Promise<InboundResponse> { ... }\n * ```\n *\n * `kind` is REQUIRED and deliberately positional: it makes every pre-existing single-argument\n * `@Endpoint('/x')` a COMPILE error rather than something a lint rule has to chase, so no endpoint\n * can slip into the runtime architecture graph with its trigger left to guesswork. See\n * {@link EndpointKind} for what each value draws and which Terraform resource backs it.\n *\n * `calledBy` is REQUIRED for `external` FOR EXACTLY THE SAME REASON, enforced by the overloads below:\n * the one box on the runtime graph whose whole job is to say who calls us from outside could only\n * restate OUR OWN contract name, because nothing in the source ever said who the caller was. This is\n * BREAKING for published consumers, intentionally — an existing `@Endpoint(p, 'external', {...})`\n * stops compiling until it names its caller. Migration is one property; see the migration note in\n * `external-caller.ts`. Non-`external` endpoints are completely unaffected.\n *\n * The path write to ENDPOINTS is UNCHANGED (every consumer iterates `[methodName, path]`); kind,\n * options and caller ride PARALLEL ENDPOINT_KIND / ENDPOINT_OPTIONS / ENDPOINT_CALLER maps.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(path: string, kind: 'external', options: ExternalEndpointOptions): MethodDecorator;\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(path: string, kind: Exclude<EndpointKind, 'external'>, options?: EndpointOptions): MethodDecorator;\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(path: string, kind: EndpointKind, options: EndpointOptions = {}): MethodDecorator {\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey: string | symbol, _descriptor: PropertyDescriptor) => {\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n\n const endpoints: Record<string, string> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINTS, metadataTarget) || {};\n\n endpoints[propertyKey as string] = path;\n\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINTS, endpoints, metadataTarget);\n\n const kinds: Record<string, EndpointKind> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_KIND, metadataTarget) || {};\n kinds[propertyKey as string] = kind;\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_KIND, kinds, metadataTarget);\n\n const opts: Record<string, EndpointOptions> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, metadataTarget) || {};\n opts[propertyKey as string] = options;\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, opts, metadataTarget);\n\n // ONLY for 'external', mirroring how a queue name is recorded only for the kinds that HAVE\n // a queue: a caller on an rpc endpoint would be a fact about nothing.\n const declared = options as ExternalEndpointOptions;\n if (kind !== 'external' || typeof declared.calledBy !== 'string' || declared.calledBy === '') return;\n const callers: Record<string, ExternalCaller> = Reflect.getMetadata(METADATA_KEYS.ENDPOINT_CALLER, metadataTarget) || {};\n callers[propertyKey as string] = new ExternalCaller(declared.callerKind ?? DEFAULT_CALLER_KIND, declared.calledBy);\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_CALLER, callers, metadataTarget);\n };\n}\n\n/**\n * @MaskLog(fields) - declare which fields of THIS method's request/response DTOs the\n * {@link LogApiCall} logging path must mask, so a secret riding on a DTO (an OAuth refresh token, an\n * id-token JWT) is never written to the logs in cleartext. The REAL value still travels on the wire\n * untouched — masking lives in the logging path only.\n *\n * ```typescript\n * @Endpoint('/account', 'rpc')\n * @MaskLog({ refreshToken: 'full', accessToken: 'last4', credential: 'full' })\n * getEmailAccount(request: GetEmailAccountRequest): Promise<GetEmailAccountResponse> { ... }\n * ```\n *\n * Matching is by field NAME at any depth (nested objects + array elements), so\n * `response.account.refreshToken` is masked. Declared on the SHARED api contract, so BOTH the client\n * `[API-client-*]` and server `[API-server-*]` lines mask it. The spec is read ONCE at route-build\n * time and rides {@link RouteMetadata.mask}, so an unmasked method pays nothing at call time.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function MaskLog(fields: Record<string, MaskMode>): MethodDecorator {\n const spec = new MaskSpec(fields);\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey: string | symbol, _descriptor: PropertyDescriptor) => {\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n const specs: Record<string, MaskSpec> =\n Reflect.getMetadata(METADATA_KEYS.MASK_LOG, metadataTarget) || {};\n specs[propertyKey as string] = spec;\n Reflect.defineMetadata(METADATA_KEYS.MASK_LOG, specs, metadataTarget);\n };\n}\n\n/**\n * The @MaskLog spec for one method, or undefined if the method declared none (the common case — the\n * caller then logs the DTO verbatim on the plain JSON.stringify fast path).\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpointOptions\nexport function getMaskSpec(apiClass: Function, methodName: string): MaskSpec | undefined {\n const specs: Record<string, MaskSpec> =\n Reflect.getMetadata(METADATA_KEYS.MASK_LOG, apiClass) || {};\n return specs[methodName];\n}\n\n/**\n * Shared implementation for every auth decorator: stores an {@link AuthMeta} for\n * the given {@link AuthMode} at class- or method-level, rejecting a second auth\n * decorator on the same target.\n */\nfunction defineAuthMode(mode: AuthMode): ClassDecorator & MethodDecorator {\n const authMeta = new AuthMeta(mode);\n\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey?: string | symbol, _descriptor?: PropertyDescriptor) => {\n if (propertyKey !== undefined) {\n // Method decorator\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n validateNoConflictingDecorators(metadataTarget, propertyKey as string);\n Reflect.defineMetadata(METADATA_KEYS.AUTH_META, authMeta, metadataTarget, propertyKey);\n } else {\n // Class decorator\n validateNoConflictingDecorators(target, undefined);\n Reflect.defineMetadata(METADATA_KEYS.AUTH_META, authMeta, target);\n }\n };\n}\n\n/**\n * @Public() - endpoint requires no authentication. Class- or method-level.\n */\nexport function Public(): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'public' });\n}\n\n/**\n * @AuthJwt(requirement) - THE user-facing JWT decorator, covering the whole user-JWT axis: the\n * compiler-enforced role decision ({@link JwtRoles}) plus app-defined fields ({@link JwtRequirement}).\n *\n * ```typescript\n * @AuthJwt({ roles: ['admin', 'editor'] }) // any-of\n * @AuthJwt({ allRolesAllowed: true, inOrg: true }) // wide + an app rule enforced by authorizeJwt\n * ```\n *\n * It absorbed the former `@Auth(requirement)` — same argument, same AuthMode, so two spellings of one\n * decision. One decorator per credential kind now: `@Public` / `@AuthJwt` / `@AuthOidc` /\n * `@AuthSharedSecret` / `@AuthLocalOnly`.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function AuthJwt(requirement: JwtRequirement): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'jwt', requirement });\n}\n\n/**\n * The roles an endpoint accepts, or [] when it accepts every authenticated user. The ONE reader of\n * the {@link JwtRoles} union, so no caller has to re-derive \"does absent mean wide?\" — a question\n * whose two plausible answers is how the widest grant kept hiding behind an absent field.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getAuthMode\nexport function rolesRequired(requirement: JwtRequirement): readonly string[] {\n return requirement.allRolesAllowed === true ? [] : requirement.roles;\n}\n\n/**\n * @AuthOidc(...callers) - Google OIDC service-to-service auth (Cloud Tasks delivery / cross-service\n * RPC). `callers` is an OPTIONAL app-level allow-list of caller service accounts.\n *\n * NO args = TRUST THE EDGE: accept any genuine Google-signed OIDC caller, because a PRIVATE Cloud\n * Run service's edge already gates WHO via `run.invoker` IAM (managed in terraform — one source of\n * truth, no hand-synced list in code). If the service is actually PUBLIC, the verifier logs a loud\n * warning (it can't be the gate then). Pass explicit SAs (`@AuthOidc('svc-a')`) only when you want\n * an additional app-level allow-list as defense-in-depth.\n */\nexport function AuthOidc(...callers: string[]): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'oidc', callers });\n}\n\n/**\n * @AuthSharedSecret(key) - constant-time compare of an inbound header against the secret bound for\n * `key`. `key` is a LOOKUP KEY (not an env var): the server looks up its accepted {@link SharedSecrets}\n * by this key, and each client looks up the value it sends by the SAME key (see {@link Secrets}).\n * For internal callers that cannot mint OIDC tokens.\n */\nexport function AuthSharedSecret(key: string): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'shared-secret', secretKey: key });\n}\n\n/**\n * @AuthWebhook(name) - an OUTSIDE vendor signed this request in its OWN scheme; the app's bound\n * `WebhookAuthCallback` proves it. THE mode for every signed inbound webhook — Sentry, GitHub, Stripe, Slack,\n * Twilio — none of which fits the other kinds: no vendor mints Google OIDC tokens, and none sends its\n * secret (they all send a DERIVATION over the request), so `@Public` was the only reachable posture\n * and `calledBy: 'sentry'` stayed a claim rather than a fact.\n *\n * ```typescript\n * @AuthWebhook('sentry')\n * @Endpoint('/hook/sentry/issue', 'external', { calledBy: 'sentry', rawBody: true })\n * abstract notify(request: SentryIssueHook): Promise<HookAck>;\n * ```\n *\n * `name` is a bare STRING resolved through DI in the server's container, exactly as\n * `@AuthOidc('gmail-push')` already is — never a function reference. An api contract is level 0: a\n * direct reference to a verifier would invert the dependency graph and drag a vendor SDK into the\n * browser bundle that imports the same contract.\n *\n * THE FRAMEWORK IMPLEMENTS NO VENDOR CRYPTO, deliberately. Every vendor ships an official validator\n * (`twilio.validateRequest`, `stripe.webhooks.constructEvent`, `@octokit/webhooks-methods`) and every\n * vendor revises its scheme (Twilio added `bodySHA256` for JSON bodies; Stripe versions its header).\n * Reimplementing five of those is signing up to track five security changelogs forever and to be\n * wrong at the moment being wrong matters. The framework hands the hook enough of the raw request to\n * call the vendor's own library — hence the REQUIRED `{ rawBody: true }` (see\n * {@link EndpointOptions.rawBody}), which is checked at wiring time.\n *\n * FAILS CLOSED: with no `WebhookAuthCallback` bound, every `@AuthWebhook` endpoint 401s, matching `JwtHook`.\n * Silently allowing an unverified webhook is the one default that must not exist.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function AuthWebhook(name: string): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'webhook', name });\n}\n\n/**\n * @AuthApiKey(name) - a CUSTOMER holds the credential. The app's bound `ApiKeyHook` authenticates the\n * inbound request against its own datastore and returns the `ContextTuple` entries the framework\n * seeds into `RequestContext`. THE mode for a partner-facing contract consumed by other companies'\n * codebases (POS vendors, back-office platforms, ETL pipelines).\n *\n * ```typescript\n * @AuthApiKey('onetablet-partner')\n * @ApiPath('/management/v1')\n * abstract class ManagementApi { ... }\n * ```\n *\n * `name` is a bare STRING selecting WHICH key regime this route belongs to, exactly as\n * `@AuthSharedSecret(key)` and `@AuthWebhook(vendor)` already are — one hook serves several regimes,\n * and an api contract is level 0, so it never references a verifier directly.\n *\n * WHY IT IS NOT `@AuthSharedSecret`. Shared-secret declares that AN INTERNAL SERVICE is on the other\n * end, so the framework BELIEVES the trusted context headers that caller forwarded (see\n * `DestinationTrust.forAuthMode` and `AuthFilter.verifiesCaller`). A customer is not an internal\n * service: declaring a partner endpoint `@AuthSharedSecret` would let that partner assert someone\n * else's org id on the wire and have it admitted — a privilege escalation. `apikey` therefore sits\n * with `jwt` on the caller-NOT-verified side, where an inbound trusted header is admitted only when\n * the hook independently derived the SAME value.\n *\n * WHY THE HOOK SEES THE REQUEST, NOT ONE TOKEN. A real key regime checks the key TOGETHER WITH a\n * second header (the organization it is acting for), and `JwtHook.parseJwt` — handed one pre-extracted\n * token from one header — physically cannot. `ApiKeyHook.verifyApiKey(name, request)` gets the whole\n * inbound request instead, so the app owns which headers carry the credential and validates them as a\n * PAIR. The framework deliberately configures no header name: that cross-check is the entire point.\n *\n * FAILS CLOSED: with no `ApiKeyHook` bound, every `@AuthApiKey` endpoint 401s, matching `JwtHook` and\n * `WebhookAuthCallback`.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function AuthApiKey(name: string): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'apikey', name });\n}\n\n/**\n * @AuthLocalOnly() - this endpoint exists ONLY on a developer's machine. Off-local it is not\n * registered as a route at all, and if it is somehow reached it 404s. Class- or method-level.\n *\n * ```typescript\n * @AuthLocalOnly()\n * @Endpoint('/logs', 'rpc')\n * sendBatch(request: SendLogBatchRequest): Promise<SendLogBatchResponse> { ... }\n * ```\n *\n * WHY IT IS AN AUTH MODE AND NOT A ROUTE-MODULE `if`. Apps hand-rolled this in TWO places kept in\n * sync by a comment: a route module that registered the route only locally, PLUS a\n * `if (env !== 'local') throw new HttpForbiddenError(...)` at the top of the handler. Neither half\n * was visible on the CONTRACT, so nothing reading the api — a human, a generated client, or an\n * agent — could tell this endpoint from a `@Public` one. Both halves are the framework's job now,\n * driven by this ONE declaration on the contract, which is where every other \"who may call this\"\n * fact already lives.\n *\n * It is DELIBERATELY a peer of @Public / @AuthJwt / @AuthOidc / @AuthSharedSecret / @AuthApiKey rather than an\n * option on one of them: one decorator per credential kind, and \"local-only\" is a different kind of\n * gate — it authenticates nobody, it excludes an entire environment.\n *\n * HOW \"local\" IS DECIDED: {@link RuntimeLocality}, declared once at startup (a REQUIRED input to\n * `RuntimeSetupOptions`). Undeclared means DEPLOYED, so a forgotten wiring call refuses the endpoint\n * rather than exposing it.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function AuthLocalOnly(): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'local-only' });\n}\n\n// ============================================================\n// Helper functions\n// ============================================================\n\n/**\n * Get the base path from @ApiPath decorator.\n */\nexport function getApiPath(apiClass: Function): string | undefined {\n return Reflect.getMetadata(METADATA_KEYS.API_PATH, apiClass);\n}\n\n/**\n * Get all endpoints from @Endpoint decorators.\n * Returns a record of methodName -> endpoint path.\n */\nexport function getEndpoints(apiClass: Function): Record<string, string> | undefined {\n return Reflect.getMetadata(METADATA_KEYS.ENDPOINTS, apiClass);\n}\n\n/**\n * Every method's declared trigger kind, as `methodName -> kind`. Parallel to {@link getEndpoints}.\n * Empty for a class carrying no @Endpoint at all.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointKinds(apiClass: Function): Record<string, EndpointKind> {\n return Reflect.getMetadata(METADATA_KEYS.ENDPOINT_KIND, apiClass) || {};\n}\n\n/**\n * What triggers ONE method, or undefined when the method carries no @Endpoint.\n *\n * Defaults to nothing rather than to 'rpc': `kind` is a required argument, so a missing entry means\n * \"this is not an endpoint\", never \"an endpoint that forgot to say\". Silently defaulting here would\n * put an undeclared cron or webhook back into the graph as a normal rpc call — the exact blindness\n * the required argument exists to remove.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointKind(apiClass: Function, methodName: string): EndpointKind | undefined {\n return getEndpointKinds(apiClass)[methodName];\n}\n\n/**\n * Get the @Endpoint options for one method (empty object if the method had no options).\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointOptions(apiClass: Function, methodName: string): EndpointOptions {\n const opts: Record<string, EndpointOptions> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, apiClass) || {};\n return opts[methodName] ?? {};\n}\n\n/**\n * Fail-fast at wiring time when an `external` endpoint declared no caller. The {@link Endpoint}\n * overloads already make that a COMPILE error; this is the backstop for the ways TS is bypassed —\n * a JS caller, an `as any` options object, a hand-rolled Reflect.defineMetadata.\n * @throws Error naming the first external endpoint with no `calledBy`.\n */\n// webpieces-disable no-function-outside-class -- wiring-time assert, sibling of assertEveryEndpointHasAuthMode\nexport function assertEveryExternalEndpointDeclaresCaller(apiClass: Function): void {\n const kinds = getEndpointKinds(apiClass);\n for (const methodName of Object.keys(kinds)) {\n if (kinds[methodName] !== 'external' || getEndpointCaller(apiClass, methodName) !== undefined) continue;\n throw new Error(\n `External endpoint '${methodName}' in ${apiClass.name || 'Unknown'} declares no caller. Say WHO ` +\n `posts to it: @Endpoint(path, 'external', { calledBy: '<vendor>' }) — the runtime architecture ` +\n `graph cannot name an inbound caller it was never told about.`,\n );\n }\n}\n\n/**\n * True when the method's @Endpoint declared `{ formPost: true }` — its body is\n * application/x-www-form-urlencoded (flat), not JSON.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function isFormPost(apiClass: Function, methodName: string): boolean {\n return getEndpointOptions(apiClass, methodName).formPost === true;\n}\n\n/**\n * True when the method's @Endpoint declared `{ rawBody: true }` — the transport must retain the\n * verbatim bytes + absolute url for an {@link AuthWebhook} hook to verify.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of isFormPost\nexport function isRawBody(apiClass: Function, methodName: string): boolean {\n return getEndpointOptions(apiClass, methodName).rawBody === true;\n}\n\n/**\n * Fail-fast at wiring time when an `@AuthWebhook` endpoint did not ask the transport to keep the\n * bytes it is supposed to verify. A hook with nothing to verify is a MISCONFIGURATION, and it must\n * surface at startup, naming the fix — not as a 401 in production on exactly the traffic the endpoint\n * exists for.\n *\n * This pairing is a runtime assert rather than a type because the two halves live on DIFFERENT\n * decorators (`@AuthWebhook` and `@Endpoint`), and no union over one decorator's argument can say\n * anything about the other's.\n *\n * @throws Error naming the first `@AuthWebhook` endpoint missing `{ rawBody: true }`.\n */\n// webpieces-disable no-function-outside-class -- wiring-time assert, sibling of assertEveryEndpointHasAuthMode\nexport function assertEveryWebhookEndpointRetainsRawBody(apiClass: Function): void {\n const endpoints = getEndpoints(apiClass) || {};\n for (const methodName of Object.keys(endpoints)) {\n if (getAuthMode(apiClass, methodName)?.kind !== 'webhook' || isRawBody(apiClass, methodName)) continue;\n throw new Error(\n `Endpoint '${methodName}' in ${apiClass.name || 'Unknown'} is @AuthWebhook but its @Endpoint ` +\n `does not declare { rawBody: true }. A webhook hook verifies a signature over the bytes and ` +\n `the url the SENDER transmitted, and without that option the transport parses the body and ` +\n `throws them away — leaving the hook nothing to check.`,\n );\n }\n}\n\n/**\n * Check if a class has @ApiPath decorator.\n */\nexport function isApiPath(apiClass: Function): boolean {\n return Reflect.hasMetadata(METADATA_KEYS.API_PATH, apiClass);\n}\n\n/**\n * Get auth metadata for a specific method, falling back to class-level auth.\n * Method-level auth takes precedence over class-level auth.\n */\nexport function getAuthMeta(apiClass: Function, methodName?: string): AuthMeta | undefined {\n // Check method-level first\n if (methodName) {\n const methodAuth = Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass, methodName);\n if (methodAuth) {\n return methodAuth;\n }\n }\n\n // Fall back to class-level\n return Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass);\n}\n\n/**\n * Get the auth mode for a method (falling back to class-level), or undefined.\n * Convenience wrapper over getAuthMeta for callers that only want the mode.\n */\nexport function getAuthMode(apiClass: Function, methodName?: string): AuthMode | undefined {\n return getAuthMeta(apiClass, methodName)?.mode;\n}\n\n/**\n * The ONE prescription for \"this endpoint declares no auth\", shared by the two places that raise it\n * (here and http-routing's ApiRoutingFactory) because they had drifted into teaching different menus.\n * A message teaching an incomplete API is the same defect as an API with two spellings: whichever menu\n * the caller hits becomes the API they believe exists. It leads with the ROLE-GATED member on purpose —\n * the first thing offered should not be the widest grant.\n */\nexport const MISSING_AUTH_DECORATOR_FIX =\n \"Add one of @AuthJwt({roles: ['admin']}) / @AuthJwt({allRolesAllowed: true}) / @Public() / \" +\n \"@AuthOidc(...callers) / @AuthSharedSecret(key) / @AuthWebhook('vendor') / @AuthApiKey('regime') / \" +\n '@AuthLocalOnly() to ' +\n 'the class or method.';\n\n/**\n * Fail-fast at wiring time if any endpoint lacks an auth mode. Both the server\n * (ApiRoutingFactory) and the task/rpc clients call this so a missing auth\n * decorator is a startup error, never a silent open endpoint.\n * @throws Error naming the first endpoint with no auth decorator, via {@link MISSING_AUTH_DECORATOR_FIX}.\n */\nexport function assertEveryEndpointHasAuthMode(apiClass: Function): void {\n const apiName = apiClass.name || 'Unknown';\n const endpoints = getEndpoints(apiClass) || {};\n for (const methodName of Object.keys(endpoints)) {\n if (!getAuthMeta(apiClass, methodName)) {\n throw new Error(\n `Endpoint '${methodName}' in ${apiName} has no auth decorator. ` +\n MISSING_AUTH_DECORATOR_FIX,\n );\n }\n }\n}\n\n/**\n * Validate that a class/method doesn't have conflicting auth decorators.\n * @throws Error if multiple auth decorators are found on the same target.\n */\nexport function validateNoConflictingDecorators(apiClass: Function, methodName: string | undefined): void {\n const existing = methodName\n ? Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass, methodName)\n : Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass);\n\n if (existing) {\n const targetName = apiClass.name || 'Unknown';\n const location = methodName ? `method '${methodName}' of ${targetName}` : `class ${targetName}`;\n throw new Error(\n `Conflicting auth decorator on ${location}. ` +\n `Only one of @Public() / @AuthJwt({...}) / @AuthOidc(...) / @AuthSharedSecret(...) / ` +\n `@AuthWebhook(...) / @AuthApiKey(...) / @AuthLocalOnly() is allowed per target.`\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"decorators.js","sourceRoot":"","sources":["../../../../../../packages/core/core-util/src/http/decorators.ts"],"names":[],"mappings":";;;AAuGA,0BAUC;AA8CD,4BA8BC;AAoBD,0BAUC;AAOD,kCAIC;AA4BD,wBAEC;AAgBD,0BAEC;AAQD,sCAEC;AAYD,4BAEC;AAQD,4CAEC;AAgCD,kCAEC;AAuDD,gCAEC;AA6BD,sCAEC;AASD,gCAEC;AAMD,oCAEC;AAOD,4CAEC;AAWD,0CAEC;AAMD,gDAIC;AASD,8FAUC;AAOD,gCAEC;AAOD,8BAEC;AAeD,4FAWC;AAKD,8BAEC;AAMD,kCAWC;AAMD,kCAEC;AAsBD,wEAWC;AAMD,0EAcC;AAznBD,4BAA0B;AAC1B,iDAAoD;AACpD,uDAAoI;AACpI,4FAA4F;AAC5F,2CAAoF;AAEpF;;;GAGG;AACU,QAAA,aAAa,GAAG;IACzB,QAAQ,EAAE,oBAAoB;IAC9B,SAAS,EAAE,qBAAqB;IAChC,SAAS,EAAE,qBAAqB;IAChC,uFAAuF;IACvF,QAAQ,EAAE,oBAAoB;IAC9B,mEAAmE;IACnE,cAAc,EAAE,0BAA0B;IAC1C,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CAAC,SAAS,EAAE,QAAQ,EAAE,UAAU,CAAC;QACpE,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,qBAAa,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;IAE7D,IAAI,QAAQ,EAAE,CAAC;QACX,MAAM,UAAU,GAAG,QAAQ,CAAC,IAAI,IAAI,SAAS,CAAC;QAC9C,MAAM,QAAQ,GAAG,UAAU,CAAC,CAAC,CAAC,WAAW,UAAU,QAAQ,UAAU,EAAE,CAAC,CAAC,CAAC,SAAS,UAAU,EAAE,CAAC;QAChG,MAAM,IAAI,KAAK,CACX,iCAAiC,QAAQ,IAAI;YAC7C,sFAAsF;YACtF,gFAAgF,CACnF,CAAC;IACN,CAAC;AACL,CAAC","sourcesContent":["import 'reflect-metadata';\nimport { MaskSpec, MaskMode } from './LogFieldMask';\nimport { DEFAULT_CALLER_KIND, ENDPOINT_CALLER_KEY, ExternalCaller, ExternalSystemKind, getEndpointCaller } from './external-caller';\n// The TYPE layer these decorators attach — split out for file size only (see auth-mode.ts).\nimport { ApiKeyCredentials, AuthMeta, AuthMode, JwtRequirement } from './auth-mode';\n\n/**\n * Metadata keys for storing API routing information.\n * These keys are used by both server-side (routing) and client-side (client generation).\n */\nexport const METADATA_KEYS = {\n API_PATH: 'webpieces:api-path',\n ENDPOINTS: 'webpieces:endpoints',\n AUTH_META: 'webpieces:auth-meta',\n /** 'rpc' (default, sync request/response) vs 'pubsub' (fire-and-forget cloud task). */\n API_KIND: 'webpieces:api-kind',\n /** Per-method Cloud Tasks queue-name override (set via @Queue). */\n QUEUE_OVERRIDE: 'webpieces:queue-override',\n /** Per-method @Endpoint options (e.g. formPost), parallel to ENDPOINTS. */\n ENDPOINT_OPTIONS: 'webpieces:endpoint-options',\n /** Per-method @Endpoint trigger kind (rpc | cloudtasks | cron | external), parallel to ENDPOINTS. */\n ENDPOINT_KIND: 'webpieces:endpoint-kind',\n /** Per-method declared external CALLER (only for kind 'external'), parallel to ENDPOINTS. */\n ENDPOINT_CALLER: ENDPOINT_CALLER_KEY,\n /** Per-method @MaskLog spec (which DTO fields the LogApiCall path masks). */\n MASK_LOG: 'webpieces:mask-log',\n};\n\n/**\n * WHAT TRIGGERS an endpoint at runtime — the single fact that decides how the runtime architecture\n * graph draws it, and which Terraform resource must exist for it to ever fire:\n *\n * - `rpc` — a caller in this repo (or a browser) calls it synchronously. A direct arrow.\n * - `cloudtasks` — a producer ENQUEUES it; Cloud Tasks delivers it later. Drawn producer → queue →\n * consumer, one queue node per METHOD (see {@link Queue}). Producer and consumer\n * being the SAME service is legal and common — the queue decouples them.\n * - `cron` — a scheduler fires it on a clock. Nothing in-repo calls it; drawn hanging off a\n * clock symbol. Backed by a Cloud Scheduler job.\n * - `external` — a system OUTSIDE this repo drives it (a GCP Pub/Sub push subscription, a Twilio\n * or Gmail webhook). Drawn as an inbound dashed arrow from that system.\n *\n * Declared PER METHOD, because one api class routinely mixes them: an admin contract can have\n * caller-driven endpoints AND a nightly cron sweep. A class-level marker cannot express that, which\n * is exactly why the graph could not tell these apart before.\n */\nexport type EndpointKind = 'rpc' | 'cloudtasks' | 'cron' | 'external';\n\n/**\n * Options for a single @Endpoint. Kept in a metadata map PARALLEL to ENDPOINTS so the existing\n * `Record<methodName, path>` shape every consumer iterates stays unchanged.\n */\nexport interface EndpointOptions {\n /**\n * Parse the request body as application/x-www-form-urlencoded (flat key→value) instead of JSON.\n * For EXTERNAL webhooks (e.g. Twilio) that post form-encoded. The request DTO must be FLAT —\n * urlencoded has no nesting (unlike JSON). Default false = JSON.\n */\n formPost?: boolean;\n\n /**\n * RETAIN the verbatim request bytes + the absolute url the sender addressed, so an\n * {@link AuthWebhook} hook can verify a vendor signature over them (see `RawRequest`).\n *\n * Opt-in PER ENDPOINT, sitting beside `formPost` and for the same reason: the cost lands on the\n * handful of webhook routes rather than on every request in the process. It is retention, not\n * new buffering — the express adapter already accumulates the whole body, it simply threw it\n * away once it had parsed a DTO.\n *\n * REQUIRED by `@AuthWebhook`, checked at wiring time (see\n * {@link assertEveryWebhookEndpointRetainsRawBody}) rather than left to fail as a 401 in\n * production: a hook with nothing to verify is a misconfiguration, not a bad request.\n *\n * Combines with `formPost` — `{ formPost: true, rawBody: true }` is the Twilio case, where the\n * hook needs the bytes and the url while the controller still wants the flat parsed DTO.\n */\n rawBody?: boolean;\n}\n\n/**\n * Options for an `external` @Endpoint: everything {@link EndpointOptions} carries, PLUS a REQUIRED\n * declaration of WHO is calling. See {@link Endpoint} for why, `external-caller.ts` for identity.\n */\nexport interface ExternalEndpointOptions extends EndpointOptions {\n /** The outside system that posts here (`'twilio'`) — the graph node IDENTITY, not display text. */\n calledBy: string;\n /** What that caller IS; picks the node's shape. Defaults to `'saas'` (see DEFAULT_CALLER_KIND). */\n callerKind?: ExternalSystemKind;\n}\n\n/**\n * @ApiPath(basePath) - Class decorator that marks a class as an API definition\n * and sets the base path for all endpoints.\n *\n * Usage:\n * ```typescript\n * @AuthJwt({ roles: ['admin'] })\n * @ApiPath('/api/save')\n * abstract class SaveApi {\n * @Endpoint('/item', 'rpc')\n * save(request: SaveRequest): Promise<SaveResponse> { ... }\n * }\n * ```\n */\nexport function ApiPath(basePath: string): ClassDecorator {\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any) => {\n Reflect.defineMetadata(METADATA_KEYS.API_PATH, basePath, target);\n\n // Initialize endpoints map if not exists\n if (!Reflect.hasMetadata(METADATA_KEYS.ENDPOINTS, target)) {\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINTS, {}, target);\n }\n };\n}\n\n/**\n * @Endpoint(path, kind, options?) - Method decorator that registers a POST endpoint at the given\n * path and declares WHAT TRIGGERS it.\n *\n * All endpoints are POST-only (matching gRPC/thrift style).\n *\n * Usage:\n * ```typescript\n * @Endpoint('/item', 'rpc')\n * save(request: SaveRequest): Promise<SaveResponse> { ... }\n *\n * // enqueued by a producer, delivered later by Cloud Tasks:\n * @Endpoint('/send', 'cloudtasks')\n * send(request: SendRequest): Promise<void> { ... }\n *\n * // fired by Cloud Scheduler on a clock, called by nobody in this repo:\n * @Endpoint('/nightly', 'cron')\n * nightly(request: NightlyRequest): Promise<void> { ... }\n *\n * // EXTERNAL webhook posting application/x-www-form-urlencoded (e.g. Twilio):\n * @Endpoint('/hook', 'external', { formPost: true, calledBy: 'twilio' })\n * inbound(request: InboundRequest): Promise<InboundResponse> { ... }\n * ```\n *\n * `kind` is REQUIRED and deliberately positional: it makes every pre-existing single-argument\n * `@Endpoint('/x')` a COMPILE error rather than something a lint rule has to chase, so no endpoint\n * can slip into the runtime architecture graph with its trigger left to guesswork. See\n * {@link EndpointKind} for what each value draws and which Terraform resource backs it.\n *\n * `calledBy` is REQUIRED for `external` FOR EXACTLY THE SAME REASON, enforced by the overloads below:\n * the one box on the runtime graph whose whole job is to say who calls us from outside could only\n * restate OUR OWN contract name, because nothing in the source ever said who the caller was. This is\n * BREAKING for published consumers, intentionally — an existing `@Endpoint(p, 'external', {...})`\n * stops compiling until it names its caller. Migration is one property; see the migration note in\n * `external-caller.ts`. Non-`external` endpoints are completely unaffected.\n *\n * The path write to ENDPOINTS is UNCHANGED (every consumer iterates `[methodName, path]`); kind,\n * options and caller ride PARALLEL ENDPOINT_KIND / ENDPOINT_OPTIONS / ENDPOINT_CALLER maps.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(path: string, kind: 'external', options: ExternalEndpointOptions): MethodDecorator;\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(path: string, kind: Exclude<EndpointKind, 'external'>, options?: EndpointOptions): MethodDecorator;\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function Endpoint(path: string, kind: EndpointKind, options: EndpointOptions = {}): MethodDecorator {\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey: string | symbol, _descriptor: PropertyDescriptor) => {\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n\n const endpoints: Record<string, string> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINTS, metadataTarget) || {};\n\n endpoints[propertyKey as string] = path;\n\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINTS, endpoints, metadataTarget);\n\n const kinds: Record<string, EndpointKind> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_KIND, metadataTarget) || {};\n kinds[propertyKey as string] = kind;\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_KIND, kinds, metadataTarget);\n\n const opts: Record<string, EndpointOptions> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, metadataTarget) || {};\n opts[propertyKey as string] = options;\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, opts, metadataTarget);\n\n // ONLY for 'external', mirroring how a queue name is recorded only for the kinds that HAVE\n // a queue: a caller on an rpc endpoint would be a fact about nothing.\n const declared = options as ExternalEndpointOptions;\n if (kind !== 'external' || typeof declared.calledBy !== 'string' || declared.calledBy === '') return;\n const callers: Record<string, ExternalCaller> = Reflect.getMetadata(METADATA_KEYS.ENDPOINT_CALLER, metadataTarget) || {};\n callers[propertyKey as string] = new ExternalCaller(declared.callerKind ?? DEFAULT_CALLER_KIND, declared.calledBy);\n Reflect.defineMetadata(METADATA_KEYS.ENDPOINT_CALLER, callers, metadataTarget);\n };\n}\n\n/**\n * @MaskLog(fields) - declare which fields of THIS method's request/response DTOs the\n * {@link LogApiCall} logging path must mask, so a secret riding on a DTO (an OAuth refresh token, an\n * id-token JWT) is never written to the logs in cleartext. The REAL value still travels on the wire\n * untouched — masking lives in the logging path only.\n *\n * ```typescript\n * @Endpoint('/account', 'rpc')\n * @MaskLog({ refreshToken: 'full', accessToken: 'last4', credential: 'full' })\n * getEmailAccount(request: GetEmailAccountRequest): Promise<GetEmailAccountResponse> { ... }\n * ```\n *\n * Matching is by field NAME at any depth (nested objects + array elements), so\n * `response.account.refreshToken` is masked. Declared on the SHARED api contract, so BOTH the client\n * `[API-client-*]` and server `[API-server-*]` lines mask it. The spec is read ONCE at route-build\n * time and rides {@link RouteMetadata.mask}, so an unmasked method pays nothing at call time.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function MaskLog(fields: Record<string, MaskMode>): MethodDecorator {\n const spec = new MaskSpec(fields);\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey: string | symbol, _descriptor: PropertyDescriptor) => {\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n const specs: Record<string, MaskSpec> =\n Reflect.getMetadata(METADATA_KEYS.MASK_LOG, metadataTarget) || {};\n specs[propertyKey as string] = spec;\n Reflect.defineMetadata(METADATA_KEYS.MASK_LOG, specs, metadataTarget);\n };\n}\n\n/**\n * The @MaskLog spec for one method, or undefined if the method declared none (the common case — the\n * caller then logs the DTO verbatim on the plain JSON.stringify fast path).\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpointOptions\nexport function getMaskSpec(apiClass: Function, methodName: string): MaskSpec | undefined {\n const specs: Record<string, MaskSpec> =\n Reflect.getMetadata(METADATA_KEYS.MASK_LOG, apiClass) || {};\n return specs[methodName];\n}\n\n/**\n * Shared implementation for every auth decorator: stores an {@link AuthMeta} for\n * the given {@link AuthMode} at class- or method-level, rejecting a second auth\n * decorator on the same target.\n */\nfunction defineAuthMode(mode: AuthMode): ClassDecorator & MethodDecorator {\n const authMeta = new AuthMeta(mode);\n\n // webpieces-disable no-any-unknown -- reflect-metadata decorator API requires any\n return (target: any, propertyKey?: string | symbol, _descriptor?: PropertyDescriptor) => {\n if (propertyKey !== undefined) {\n // Method decorator\n const metadataTarget = typeof target === 'function' ? target : target.constructor;\n validateNoConflictingDecorators(metadataTarget, propertyKey as string);\n Reflect.defineMetadata(METADATA_KEYS.AUTH_META, authMeta, metadataTarget, propertyKey);\n } else {\n // Class decorator\n validateNoConflictingDecorators(target, undefined);\n Reflect.defineMetadata(METADATA_KEYS.AUTH_META, authMeta, target);\n }\n };\n}\n\n/**\n * @Public() - endpoint requires no authentication. Class- or method-level.\n */\nexport function Public(): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'public' });\n}\n\n/**\n * @AuthJwt(requirement) - THE user-facing JWT decorator, covering the whole user-JWT axis: the\n * compiler-enforced role decision ({@link JwtRoles}) plus app-defined fields ({@link JwtRequirement}).\n *\n * ```typescript\n * @AuthJwt({ roles: ['admin', 'editor'] }) // any-of\n * @AuthJwt({ allRolesAllowed: true, inOrg: true }) // wide + an app rule enforced by authorizeJwt\n * ```\n *\n * It absorbed the former `@Auth(requirement)` — same argument, same AuthMode, so two spellings of one\n * decision. One decorator per credential kind now: `@Public` / `@AuthJwt` / `@AuthOidc` /\n * `@AuthSharedSecret` / `@AuthLocalOnly`.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function AuthJwt(requirement: JwtRequirement): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'jwt', requirement });\n}\n\n/**\n * The roles an endpoint accepts, or [] when it accepts every authenticated user. The ONE reader of\n * the {@link JwtRoles} union, so no caller has to re-derive \"does absent mean wide?\" — a question\n * whose two plausible answers is how the widest grant kept hiding behind an absent field.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getAuthMode\nexport function rolesRequired(requirement: JwtRequirement): readonly string[] {\n return requirement.allRolesAllowed === true ? [] : requirement.roles;\n}\n\n/**\n * @AuthOidc(...callers) - Google OIDC service-to-service auth (Cloud Tasks delivery / cross-service\n * RPC). `callers` is an OPTIONAL app-level allow-list of caller service accounts.\n *\n * NO args = TRUST THE EDGE: accept any genuine Google-signed OIDC caller, because a PRIVATE Cloud\n * Run service's edge already gates WHO via `run.invoker` IAM (managed in terraform — one source of\n * truth, no hand-synced list in code). If the service is actually PUBLIC, the verifier logs a loud\n * warning (it can't be the gate then). Pass explicit SAs (`@AuthOidc('svc-a')`) only when you want\n * an additional app-level allow-list as defense-in-depth.\n */\nexport function AuthOidc(...callers: string[]): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'oidc', callers });\n}\n\n/**\n * @AuthSharedSecret(key) - constant-time compare of an inbound header against the secret bound for\n * `key`. `key` is a LOOKUP KEY (not an env var): the server looks up its accepted {@link SharedSecrets}\n * by this key, and each client looks up the value it sends by the SAME key (see {@link Secrets}).\n * For internal callers that cannot mint OIDC tokens.\n */\nexport function AuthSharedSecret(key: string): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'shared-secret', secretKey: key });\n}\n\n/**\n * @AuthWebhook(name) - an OUTSIDE vendor signed this request in its OWN scheme; the app's bound\n * `WebhookAuthCallback` proves it. THE mode for every signed inbound webhook — Sentry, GitHub, Stripe, Slack,\n * Twilio — none of which fits the other kinds: no vendor mints Google OIDC tokens, and none sends its\n * secret (they all send a DERIVATION over the request), so `@Public` was the only reachable posture\n * and `calledBy: 'sentry'` stayed a claim rather than a fact.\n *\n * ```typescript\n * @AuthWebhook('sentry')\n * @Endpoint('/hook/sentry/issue', 'external', { calledBy: 'sentry', rawBody: true })\n * abstract notify(request: SentryIssueHook): Promise<HookAck>;\n * ```\n *\n * `name` is a bare STRING resolved through DI in the server's container, exactly as\n * `@AuthOidc('gmail-push')` already is — never a function reference. An api contract is level 0: a\n * direct reference to a verifier would invert the dependency graph and drag a vendor SDK into the\n * browser bundle that imports the same contract.\n *\n * THE FRAMEWORK IMPLEMENTS NO VENDOR CRYPTO, deliberately. Every vendor ships an official validator\n * (`twilio.validateRequest`, `stripe.webhooks.constructEvent`, `@octokit/webhooks-methods`) and every\n * vendor revises its scheme (Twilio added `bodySHA256` for JSON bodies; Stripe versions its header).\n * Reimplementing five of those is signing up to track five security changelogs forever and to be\n * wrong at the moment being wrong matters. The framework hands the hook enough of the raw request to\n * call the vendor's own library — hence the REQUIRED `{ rawBody: true }` (see\n * {@link EndpointOptions.rawBody}), which is checked at wiring time.\n *\n * FAILS CLOSED: with no `WebhookAuthCallback` bound, every `@AuthWebhook` endpoint 401s, matching `JwtHook`.\n * Silently allowing an unverified webhook is the one default that must not exist.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function AuthWebhook(name: string): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'webhook', name });\n}\n\n/**\n * @AuthApiKey(regime, credentials) - a CUSTOMER holds the credential. The app's bound `ApiKeyHook`\n * authenticates the inbound request against its own datastore and returns the `ContextTuple` entries\n * the framework seeds into `RequestContext`. THE mode for a partner-facing contract consumed by other\n * companies' codebases (POS vendors, back-office platforms, ETL pipelines).\n *\n * ```typescript\n * @AuthApiKey('onetablet-partner', [\n * { in: 'header', name: 'x-api-key', description: 'The key issued to your integration.' },\n * { in: 'header', name: 'x-organization-id', description: 'Which of your organizations to act on.' },\n * ])\n * @ApiPath('/management/v1')\n * abstract class ManagementApi { ... }\n * ```\n *\n * `regime` is a bare STRING selecting WHICH key regime this route belongs to, exactly as\n * `@AuthSharedSecret(key)` and `@AuthWebhook(vendor)` already are — one hook serves several regimes,\n * and an api contract is level 0, so it never references a verifier directly.\n *\n * `credentials` DECLARES where the credential rides ({@link ApiKeyCredential}), so a spec generator\n * reading route auth metadata can emit `components.securitySchemes` instead of a human hand-writing\n * them into a manifest. It is a NON-EMPTY, ORDERED list rather than one credential because a real\n * regime authenticates a PAIR — the key names a customer, a second header names which of that\n * customer's organizations the request acts on, and a mismatch is a 401. Its OpenAPI form is two\n * schemes plus ONE security-requirement object holding BOTH keys (an AND); a LIST of two objects\n * would mean \"either alone suffices\", which is a load-bearing difference a single-credential shape\n * cannot even express. ORDER IS SIGNIFICANT and preserved: it is the order the credentials are\n * presented in the published document.\n *\n * The list can never be EMPTY — a contract that declares a key regime and then names no credential\n * would generate a document with no security block, which is the exact silent failure this argument\n * exists to remove. That is a compile error, not a runtime throw (see {@link JwtRoles}'s non-empty\n * tuple, the same device for the same reason).\n *\n * WHY IT IS NOT `@AuthSharedSecret`. Shared-secret declares that AN INTERNAL SERVICE is on the other\n * end, so the framework BELIEVES the trusted context headers that caller forwarded (see\n * `DestinationTrust.forAuthMode` and `AuthFilter.verifiesCaller`). A customer is not an internal\n * service: declaring a partner endpoint `@AuthSharedSecret` would let that partner assert someone\n * else's org id on the wire and have it admitted — a privilege escalation. `apikey` therefore sits\n * with `jwt` on the caller-NOT-verified side, where an inbound trusted header is admitted only when\n * the hook independently derived the SAME value.\n *\n * WHY THE HOOK SEES THE REQUEST, NOT ONE TOKEN. A real key regime checks the key TOGETHER WITH a\n * second header (the organization it is acting for), and `JwtHook.parseJwt` — handed one pre-extracted\n * token from one header — physically cannot. `ApiKeyHook.verifyApiKey(regime, request)` gets the whole\n * inbound request instead, so the app owns which headers carry the credential and validates them as a\n * PAIR. `credentials` does NOT change that: the framework reads no header from it and performs no\n * extraction. It is DECLARATION for readers of the contract, and enforcement stays entirely the hook's.\n *\n * FAILS CLOSED: with no `ApiKeyHook` bound, every `@AuthApiKey` endpoint 401s, matching `JwtHook` and\n * `WebhookAuthCallback`.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function AuthApiKey(regime: string, credentials: ApiKeyCredentials): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'apikey', regime, credentials });\n}\n\n/**\n * @AuthLocalOnly() - this endpoint exists ONLY on a developer's machine. Off-local it is not\n * registered as a route at all, and if it is somehow reached it 404s. Class- or method-level.\n *\n * ```typescript\n * @AuthLocalOnly()\n * @Endpoint('/logs', 'rpc')\n * sendBatch(request: SendLogBatchRequest): Promise<SendLogBatchResponse> { ... }\n * ```\n *\n * WHY IT IS AN AUTH MODE AND NOT A ROUTE-MODULE `if`. Apps hand-rolled this in TWO places kept in\n * sync by a comment: a route module that registered the route only locally, PLUS a\n * `if (env !== 'local') throw new HttpForbiddenError(...)` at the top of the handler. Neither half\n * was visible on the CONTRACT, so nothing reading the api — a human, a generated client, or an\n * agent — could tell this endpoint from a `@Public` one. Both halves are the framework's job now,\n * driven by this ONE declaration on the contract, which is where every other \"who may call this\"\n * fact already lives.\n *\n * It is DELIBERATELY a peer of @Public / @AuthJwt / @AuthOidc / @AuthSharedSecret / @AuthApiKey rather than an\n * option on one of them: one decorator per credential kind, and \"local-only\" is a different kind of\n * gate — it authenticates nobody, it excludes an entire environment.\n *\n * HOW \"local\" IS DECIDED: {@link RuntimeLocality}, declared once at startup (a REQUIRED input to\n * `RuntimeSetupOptions`). Undeclared means DEPLOYED, so a forgotten wiring call refuses the endpoint\n * rather than exposing it.\n */\n// webpieces-disable no-function-outside-class -- decorator factory; decorators are inherently module-scope\nexport function AuthLocalOnly(): ClassDecorator & MethodDecorator {\n return defineAuthMode({ kind: 'local-only' });\n}\n\n// ============================================================\n// Helper functions\n// ============================================================\n\n/**\n * Get the base path from @ApiPath decorator.\n */\nexport function getApiPath(apiClass: Function): string | undefined {\n return Reflect.getMetadata(METADATA_KEYS.API_PATH, apiClass);\n}\n\n/**\n * Get all endpoints from @Endpoint decorators.\n * Returns a record of methodName -> endpoint path.\n */\nexport function getEndpoints(apiClass: Function): Record<string, string> | undefined {\n return Reflect.getMetadata(METADATA_KEYS.ENDPOINTS, apiClass);\n}\n\n/**\n * Every method's declared trigger kind, as `methodName -> kind`. Parallel to {@link getEndpoints}.\n * Empty for a class carrying no @Endpoint at all.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointKinds(apiClass: Function): Record<string, EndpointKind> {\n return Reflect.getMetadata(METADATA_KEYS.ENDPOINT_KIND, apiClass) || {};\n}\n\n/**\n * What triggers ONE method, or undefined when the method carries no @Endpoint.\n *\n * Defaults to nothing rather than to 'rpc': `kind` is a required argument, so a missing entry means\n * \"this is not an endpoint\", never \"an endpoint that forgot to say\". Silently defaulting here would\n * put an undeclared cron or webhook back into the graph as a normal rpc call — the exact blindness\n * the required argument exists to remove.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointKind(apiClass: Function, methodName: string): EndpointKind | undefined {\n return getEndpointKinds(apiClass)[methodName];\n}\n\n/**\n * Get the @Endpoint options for one method (empty object if the method had no options).\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function getEndpointOptions(apiClass: Function, methodName: string): EndpointOptions {\n const opts: Record<string, EndpointOptions> =\n Reflect.getMetadata(METADATA_KEYS.ENDPOINT_OPTIONS, apiClass) || {};\n return opts[methodName] ?? {};\n}\n\n/**\n * Fail-fast at wiring time when an `external` endpoint declared no caller. The {@link Endpoint}\n * overloads already make that a COMPILE error; this is the backstop for the ways TS is bypassed —\n * a JS caller, an `as any` options object, a hand-rolled Reflect.defineMetadata.\n * @throws Error naming the first external endpoint with no `calledBy`.\n */\n// webpieces-disable no-function-outside-class -- wiring-time assert, sibling of assertEveryEndpointHasAuthMode\nexport function assertEveryExternalEndpointDeclaresCaller(apiClass: Function): void {\n const kinds = getEndpointKinds(apiClass);\n for (const methodName of Object.keys(kinds)) {\n if (kinds[methodName] !== 'external' || getEndpointCaller(apiClass, methodName) !== undefined) continue;\n throw new Error(\n `External endpoint '${methodName}' in ${apiClass.name || 'Unknown'} declares no caller. Say WHO ` +\n `posts to it: @Endpoint(path, 'external', { calledBy: '<vendor>' }) — the runtime architecture ` +\n `graph cannot name an inbound caller it was never told about.`,\n );\n }\n}\n\n/**\n * True when the method's @Endpoint declared `{ formPost: true }` — its body is\n * application/x-www-form-urlencoded (flat), not JSON.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of getEndpoints\nexport function isFormPost(apiClass: Function, methodName: string): boolean {\n return getEndpointOptions(apiClass, methodName).formPost === true;\n}\n\n/**\n * True when the method's @Endpoint declared `{ rawBody: true }` — the transport must retain the\n * verbatim bytes + absolute url for an {@link AuthWebhook} hook to verify.\n */\n// webpieces-disable no-function-outside-class -- reflect-metadata reader, sibling of isFormPost\nexport function isRawBody(apiClass: Function, methodName: string): boolean {\n return getEndpointOptions(apiClass, methodName).rawBody === true;\n}\n\n/**\n * Fail-fast at wiring time when an `@AuthWebhook` endpoint did not ask the transport to keep the\n * bytes it is supposed to verify. A hook with nothing to verify is a MISCONFIGURATION, and it must\n * surface at startup, naming the fix — not as a 401 in production on exactly the traffic the endpoint\n * exists for.\n *\n * This pairing is a runtime assert rather than a type because the two halves live on DIFFERENT\n * decorators (`@AuthWebhook` and `@Endpoint`), and no union over one decorator's argument can say\n * anything about the other's.\n *\n * @throws Error naming the first `@AuthWebhook` endpoint missing `{ rawBody: true }`.\n */\n// webpieces-disable no-function-outside-class -- wiring-time assert, sibling of assertEveryEndpointHasAuthMode\nexport function assertEveryWebhookEndpointRetainsRawBody(apiClass: Function): void {\n const endpoints = getEndpoints(apiClass) || {};\n for (const methodName of Object.keys(endpoints)) {\n if (getAuthMode(apiClass, methodName)?.kind !== 'webhook' || isRawBody(apiClass, methodName)) continue;\n throw new Error(\n `Endpoint '${methodName}' in ${apiClass.name || 'Unknown'} is @AuthWebhook but its @Endpoint ` +\n `does not declare { rawBody: true }. A webhook hook verifies a signature over the bytes and ` +\n `the url the SENDER transmitted, and without that option the transport parses the body and ` +\n `throws them away — leaving the hook nothing to check.`,\n );\n }\n}\n\n/**\n * Check if a class has @ApiPath decorator.\n */\nexport function isApiPath(apiClass: Function): boolean {\n return Reflect.hasMetadata(METADATA_KEYS.API_PATH, apiClass);\n}\n\n/**\n * Get auth metadata for a specific method, falling back to class-level auth.\n * Method-level auth takes precedence over class-level auth.\n */\nexport function getAuthMeta(apiClass: Function, methodName?: string): AuthMeta | undefined {\n // Check method-level first\n if (methodName) {\n const methodAuth = Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass, methodName);\n if (methodAuth) {\n return methodAuth;\n }\n }\n\n // Fall back to class-level\n return Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass);\n}\n\n/**\n * Get the auth mode for a method (falling back to class-level), or undefined.\n * Convenience wrapper over getAuthMeta for callers that only want the mode.\n */\nexport function getAuthMode(apiClass: Function, methodName?: string): AuthMode | undefined {\n return getAuthMeta(apiClass, methodName)?.mode;\n}\n\n/**\n * The ONE prescription for \"this endpoint declares no auth\", shared by the two places that raise it\n * (here and http-routing's ApiRoutingFactory) because they had drifted into teaching different menus.\n * A message teaching an incomplete API is the same defect as an API with two spellings: whichever menu\n * the caller hits becomes the API they believe exists. It leads with the ROLE-GATED member on purpose —\n * the first thing offered should not be the widest grant.\n */\nexport const MISSING_AUTH_DECORATOR_FIX =\n \"Add one of @AuthJwt({roles: ['admin']}) / @AuthJwt({allRolesAllowed: true}) / @Public() / \" +\n '@AuthOidc(...callers) / @AuthSharedSecret(key) / ' +\n \"@AuthWebhook('vendor') / @AuthApiKey('regime', [{in: 'header', name: 'x-api-key'}]) / \" +\n '@AuthLocalOnly() to ' +\n 'the class or method.';\n\n/**\n * Fail-fast at wiring time if any endpoint lacks an auth mode. Both the server\n * (ApiRoutingFactory) and the task/rpc clients call this so a missing auth\n * decorator is a startup error, never a silent open endpoint.\n * @throws Error naming the first endpoint with no auth decorator, via {@link MISSING_AUTH_DECORATOR_FIX}.\n */\nexport function assertEveryEndpointHasAuthMode(apiClass: Function): void {\n const apiName = apiClass.name || 'Unknown';\n const endpoints = getEndpoints(apiClass) || {};\n for (const methodName of Object.keys(endpoints)) {\n if (!getAuthMeta(apiClass, methodName)) {\n throw new Error(\n `Endpoint '${methodName}' in ${apiName} has no auth decorator. ` +\n MISSING_AUTH_DECORATOR_FIX,\n );\n }\n }\n}\n\n/**\n * Validate that a class/method doesn't have conflicting auth decorators.\n * @throws Error if multiple auth decorators are found on the same target.\n */\nexport function validateNoConflictingDecorators(apiClass: Function, methodName: string | undefined): void {\n const existing = methodName\n ? Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass, methodName)\n : Reflect.getMetadata(METADATA_KEYS.AUTH_META, apiClass);\n\n if (existing) {\n const targetName = apiClass.name || 'Unknown';\n const location = methodName ? `method '${methodName}' of ${targetName}` : `class ${targetName}`;\n throw new Error(\n `Conflicting auth decorator on ${location}. ` +\n `Only one of @Public() / @AuthJwt({...}) / @AuthOidc(...) / @AuthSharedSecret(...) / ` +\n `@AuthWebhook(...) / @AuthApiKey(...) / @AuthLocalOnly() is allowed per target.`\n );\n }\n}\n"]}
|
package/src/index.d.ts
CHANGED
|
@@ -17,9 +17,11 @@ export { ConsoleLogger } from './logging/ConsoleLogger';
|
|
|
17
17
|
export { ConsoleLoggerFactory } from './logging/ConsoleLoggerFactory';
|
|
18
18
|
export { LogManager } from './logging/LogManager';
|
|
19
19
|
export { LogChunker, LogChunkerImpl, LogChunkInfo, MAX_GCP_LOG_BYTES, GCP_LOG_BUDGET_BYTES } from './logging/LogChunker';
|
|
20
|
-
export { ApiPath, Endpoint, Public, AuthJwt, rolesRequired, MISSING_AUTH_DECORATOR_FIX, AuthOidc, AuthSharedSecret, AuthWebhook, AuthApiKey, AuthLocalOnly, MaskLog, getApiPath, getEndpoints, getEndpointOptions, getEndpointKind, getEndpointKinds, getMaskSpec, isFormPost, isRawBody, isApiPath, getAuthMeta, getAuthMode, assertEveryEndpointHasAuthMode, assertEveryExternalEndpointDeclaresCaller, assertEveryWebhookEndpointRetainsRawBody, validateNoConflictingDecorators,
|
|
20
|
+
export { ApiPath, Endpoint, Public, AuthJwt, rolesRequired, MISSING_AUTH_DECORATOR_FIX, AuthOidc, AuthSharedSecret, AuthWebhook, AuthApiKey, AuthLocalOnly, MaskLog, getApiPath, getEndpoints, getEndpointOptions, getEndpointKind, getEndpointKinds, getMaskSpec, isFormPost, isRawBody, isApiPath, getAuthMeta, getAuthMode, assertEveryEndpointHasAuthMode, assertEveryExternalEndpointDeclaresCaller, assertEveryWebhookEndpointRetainsRawBody, validateNoConflictingDecorators, METADATA_KEYS, } from './http/decorators';
|
|
21
21
|
export { RouteMetadata } from './http/RouteMetadata';
|
|
22
|
-
export type {
|
|
22
|
+
export type { EndpointKind, EndpointOptions, ExternalEndpointOptions } from './http/decorators';
|
|
23
|
+
export { AuthMeta } from './http/auth-mode';
|
|
24
|
+
export type { AuthMode, ApiKeyCredential, ApiKeyCredentials, JwtRoles, JwtRequirement } from './http/auth-mode';
|
|
23
25
|
export { Rpc, PubSub, Queue, ENDPOINT_KINDS_BY_API_KIND, getApiKind, assertApiKind, assertPubSubConventions, getQueueName, } from './http/api-kind';
|
|
24
26
|
export type { ApiKind } from './http/api-kind';
|
|
25
27
|
export { EXTERNAL_SYSTEM_KINDS, DEFAULT_CALLER_KIND, ExternalCaller, isExternalSystemKind, getEndpointCaller } from './http/external-caller';
|
package/src/index.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* @packageDocumentation
|
|
9
9
|
*/
|
|
10
10
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
-
exports.assertApiKind = exports.getApiKind = exports.ENDPOINT_KINDS_BY_API_KIND = exports.Queue = exports.PubSub = exports.Rpc = exports.
|
|
11
|
+
exports.assertApiKind = exports.getApiKind = exports.ENDPOINT_KINDS_BY_API_KIND = exports.Queue = exports.PubSub = exports.Rpc = exports.AuthMeta = exports.RouteMetadata = exports.METADATA_KEYS = exports.validateNoConflictingDecorators = exports.assertEveryWebhookEndpointRetainsRawBody = exports.assertEveryExternalEndpointDeclaresCaller = exports.assertEveryEndpointHasAuthMode = exports.getAuthMode = exports.getAuthMeta = exports.isApiPath = exports.isRawBody = exports.isFormPost = exports.getMaskSpec = exports.getEndpointKinds = exports.getEndpointKind = exports.getEndpointOptions = exports.getEndpoints = exports.getApiPath = exports.MaskLog = exports.AuthLocalOnly = exports.AuthApiKey = exports.AuthWebhook = exports.AuthSharedSecret = exports.AuthOidc = exports.MISSING_AUTH_DECORATOR_FIX = exports.rolesRequired = exports.AuthJwt = exports.Public = exports.Endpoint = exports.ApiPath = exports.GCP_LOG_BUDGET_BYTES = exports.MAX_GCP_LOG_BYTES = exports.LogChunkInfo = exports.LogChunkerImpl = exports.LogChunker = exports.LogManager = exports.ConsoleLoggerFactory = exports.ConsoleLogger = exports.DESIGN_METADATA_KEYS = exports.isDocumentDesign = exports.DocumentDesign = exports.ContextTuple = exports.ContextKey = exports.toError = void 0;
|
|
12
12
|
exports.ContextMgr = exports.DestinationTrust = exports.WebpiecesCoreHeaders = exports.templateDeriver = exports.WEBPIECES_DEFAULT_FAILURE_CLASSIFIER = exports.WebpiecesDefaultFailureClassifier = exports.KeyedFailureClassifier = exports.ErrorWireForm = exports.RuntimeLocality = exports.ServiceInfo = exports.ClientRegistry = exports.HeaderRegistry = exports.DateTimeUtil = exports.TimeUtil = exports.DateUtil = exports.InstantUtil = exports.NetworkRejectClassifier = exports.NO_REG_CODE = exports.WRONG_COMPANY = exports.WRONG_DOMAIN = exports.EMAIL_NOT_CONFIRMED = exports.NOT_APPROVED = exports.WRONG_LOGIN = exports.WRONG_LOGIN_TYPE = exports.ENTITY_NOT_FOUND = exports.OfflineError = exports.HttpUserError = exports.HttpVendorError = exports.HttpTooManyRequestsError = exports.HttpInternalServerError = exports.HttpGatewayTimeoutError = exports.HttpServiceUnavailableError = exports.HttpBadGatewayError = exports.HttpTimeoutError = exports.HttpForbiddenError = exports.HttpUnauthorizedError = exports.HttpBadRequestError = exports.EndpointNotFoundError = exports.HttpNotFoundError = exports.HttpError = exports.ProtocolError = exports.SECRETS = exports.Secrets = exports.getEndpointCaller = exports.isExternalSystemKind = exports.ExternalCaller = exports.DEFAULT_CALLER_KIND = exports.EXTERNAL_SYSTEM_KINDS = exports.getQueueName = exports.assertPubSubConventions = void 0;
|
|
13
13
|
exports.SerializedError = exports.SerializedMap = exports.RecordSerializer = exports.getDoNotRecordFields = exports.DoNotRecord = exports.RecordedTestCase = exports.RecordedError = exports.RecordedEndpoint = exports.RecorderKeys = exports.ApiCallContextHolder = exports.ApiMethodInfo = exports.LOG_API_CALL_LOGGER_NAME = exports.ApiCallLogNameImpl = exports.ApiCallLogName = exports.ApiCallInfo = exports.MaskSpec = exports.LogApiCallImpl = exports.LogApiCall = void 0;
|
|
14
14
|
var errorUtils_1 = require("./lib/errorUtils");
|
|
@@ -71,11 +71,13 @@ Object.defineProperty(exports, "assertEveryEndpointHasAuthMode", { enumerable: t
|
|
|
71
71
|
Object.defineProperty(exports, "assertEveryExternalEndpointDeclaresCaller", { enumerable: true, get: function () { return decorators_1.assertEveryExternalEndpointDeclaresCaller; } });
|
|
72
72
|
Object.defineProperty(exports, "assertEveryWebhookEndpointRetainsRawBody", { enumerable: true, get: function () { return decorators_1.assertEveryWebhookEndpointRetainsRawBody; } });
|
|
73
73
|
Object.defineProperty(exports, "validateNoConflictingDecorators", { enumerable: true, get: function () { return decorators_1.validateNoConflictingDecorators; } });
|
|
74
|
-
Object.defineProperty(exports, "AuthMeta", { enumerable: true, get: function () { return decorators_1.AuthMeta; } });
|
|
75
74
|
Object.defineProperty(exports, "METADATA_KEYS", { enumerable: true, get: function () { return decorators_1.METADATA_KEYS; } });
|
|
76
75
|
// The runtime representation of ONE route (split out of decorators.ts for file size only).
|
|
77
76
|
var RouteMetadata_1 = require("./http/RouteMetadata");
|
|
78
77
|
Object.defineProperty(exports, "RouteMetadata", { enumerable: true, get: function () { return RouteMetadata_1.RouteMetadata; } });
|
|
78
|
+
// The TYPE layer of the auth surface — likewise split out of decorators.ts for file size only.
|
|
79
|
+
var auth_mode_1 = require("./http/auth-mode");
|
|
80
|
+
Object.defineProperty(exports, "AuthMeta", { enumerable: true, get: function () { return auth_mode_1.AuthMeta; } });
|
|
79
81
|
// API kind (RPC vs PubSub/Cloud Tasks) + queue naming. Split out of decorators.ts for file size only;
|
|
80
82
|
// one-way dependency api-kind -> decorators, and the barrel keeps the surface identical.
|
|
81
83
|
var api_kind_1 = require("./http/api-kind");
|
package/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/core/core-util/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;;;AAEH,+CAA2C;AAAlC,qGAAA,OAAO,OAAA;AAChB,2CAA0C;AAAjC,wGAAA,UAAU,OAAA;AAEnB,+CAA8C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AAA;AAAE,0HAAA,wBAAwB,OAAA;AACrE,sDAAqD;AAA5C,8GAAA,aAAa,OAAA;AAEtB,wDAA6D;AAApD,sHAAA,oBAAoB,OAAA;AAG7B,iFAAiF;AACjF,qEAAkF;AAAvD,gHAAA,YAAY,OAAA;AACvC,qEAAqG;AAA5F,oHAAA,gBAAgB,OAAA;AAAE,iHAAA,aAAa,OAAA;AAAE,oHAAA,gBAAgB,OAAA;AAC1D,2DAAgF;AAAvE,0GAAA,WAAW,OAAA;AAAE,mHAAA,oBAAoB,OAAA;AAC1C,qEAAoG;AAA3F,oHAAA,gBAAgB,OAAA;AAAE,iHAAA,aAAa,OAAA;AAAE,mHAAA,eAAe,OAAA","sourcesContent":["/**\n * @webpieces/core-util\n *\n * Utility functions for WebPieces applications.\n * This package works in both browser and Node.js environments.\n *\n * @packageDocumentation\n */\n\nexport { toError } from './lib/errorUtils';\nexport { ContextKey } from './ContextKey';\nexport type { AnyContextKey, AnyTrustedContextKey, AnyUntrustedContextKey, Trust } from './ContextKey';\nexport { ContextTuple } from './ContextTuple';\n\n// @DocumentDesign — DI-design-root marker. Applies to ANY project kind (server\n// controllers AND library impl classes), so it lives here (browser + Node) rather\n// than in a server-only routing package.\nexport { DocumentDesign, isDocumentDesign, DESIGN_METADATA_KEYS } from './DocumentDesign';\n\n// Logging (merged from former @webpieces/wp-logging).\n// Pluggable logging interface + a browser-safe console default; apps plug in\n// bunyan/winston/pino/etc. via LogManager.setFactory(...). Browser + Node.\nexport type { Logger, LogLevel } from './logging/Logger';\nexport type { LoggerFactory } from './logging/LoggerFactory';\nexport { ConsoleLogger } from './logging/ConsoleLogger';\nexport { ConsoleLoggerFactory } from './logging/ConsoleLoggerFactory';\nexport { LogManager } from './logging/LogManager';\nexport { LogChunker, LogChunkerImpl, LogChunkInfo, MAX_GCP_LOG_BYTES, GCP_LOG_BUDGET_BYTES } from './logging/LogChunker';\n\n// HTTP API contract (merged from former @webpieces/http-api).\n// Shared HTTP API definition consumed by both client and server: REST\n// decorators, the HttpError hierarchy, datetime DTOs, platform-header\n// registry/readers, ValidateImplementation, and the test-case recorder\n// contract. Pure definitions — express-free, browser + Node safe.\n\n// API definition decorators\nexport {\n ApiPath,\n Endpoint,\n // Auth mode decorators (clean service-to-service + user JWT model)\n Public,\n AuthJwt,\n rolesRequired,\n MISSING_AUTH_DECORATOR_FIX,\n AuthOidc,\n AuthSharedSecret,\n AuthWebhook,\n AuthApiKey,\n AuthLocalOnly,\n MaskLog,\n getApiPath,\n getEndpoints,\n getEndpointOptions,\n getEndpointKind,\n getEndpointKinds,\n getMaskSpec,\n isFormPost,\n isRawBody,\n isApiPath,\n getAuthMeta,\n getAuthMode,\n assertEveryEndpointHasAuthMode,\n assertEveryExternalEndpointDeclaresCaller,\n assertEveryWebhookEndpointRetainsRawBody,\n validateNoConflictingDecorators,\n AuthMeta,\n METADATA_KEYS,\n} from './http/decorators';\n// The runtime representation of ONE route (split out of decorators.ts for file size only).\nexport { RouteMetadata } from './http/RouteMetadata';\nexport type { AuthMode, EndpointKind, JwtRoles, JwtRequirement, EndpointOptions, ExternalEndpointOptions } from './http/decorators';\n// API kind (RPC vs PubSub/Cloud Tasks) + queue naming. Split out of decorators.ts for file size only;\n// one-way dependency api-kind -> decorators, and the barrel keeps the surface identical.\nexport {\n Rpc,\n PubSub,\n Queue,\n ENDPOINT_KINDS_BY_API_KIND,\n getApiKind,\n assertApiKind,\n assertPubSubConventions,\n getQueueName,\n} from './http/api-kind';\nexport type { ApiKind } from './http/api-kind';\n// WHO calls an `external` endpoint — the caller declaration @Endpoint(..., 'external', {calledBy})\n// requires, and the reader for it.\nexport { EXTERNAL_SYSTEM_KINDS, DEFAULT_CALLER_KIND, ExternalCaller, isExternalSystemKind, getEndpointCaller } from './http/external-caller';\nexport type { ExternalSystemKind } from './http/external-caller';\n// Client-side shared-secret store (the value THIS service sends per @AuthSharedSecret key).\nexport { Secrets, SECRETS } from './http/Secrets';\n\n// Type validators\nexport { ValidateImplementation } from './http/validators';\n\n// HTTP errors\nexport {\n ProtocolError,\n HttpError,\n HttpNotFoundError,\n EndpointNotFoundError,\n HttpBadRequestError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpTimeoutError,\n HttpBadGatewayError,\n HttpServiceUnavailableError,\n HttpGatewayTimeoutError,\n HttpInternalServerError,\n HttpTooManyRequestsError,\n HttpVendorError,\n HttpUserError,\n OfflineError,\n // Error subtype constants\n ENTITY_NOT_FOUND,\n WRONG_LOGIN_TYPE,\n WRONG_LOGIN,\n NOT_APPROVED,\n EMAIL_NOT_CONFIRMED,\n WRONG_DOMAIN,\n WRONG_COMPANY,\n NO_REG_CODE,\n} from './http/errors';\n\nexport { NetworkRejectClassifier } from './http/networkReject';\n\n// Date/Time DTOs and Utilities (inspired by Java Time / JSR-310)\nexport {\n InstantDto,\n DateDto,\n TimeDto,\n DateTimeDto,\n InstantUtil,\n DateUtil,\n TimeUtil,\n DateTimeUtil,\n} from './http/datetime';\n\n// Context keys + registry (the global magic-context header system)\nexport { HeaderRegistry } from './http/HeaderRegistry';\nexport { ClientRegistry } from './http/ClientRegistry';\nexport type { ServiceUrlDeriver } from './http/ClientRegistry';\n\n// \"What service am I\" — set once at startup, read by the logging backends and by\n// RequestContextHeaders (to stamp requestIdSource on ids this service mints).\nexport { ServiceInfo } from './http/ServiceInfo';\n// \"Where am I running\" — declared once at startup (setupRuntime, from RuntimeSetupOptions.locality).\n// The ONE input to @AuthLocalOnly enforcement. Undeclared reads as DEPLOYED (fail safe).\nexport { RuntimeLocality } from './http/RuntimeLocality';\nexport type { Locality } from './http/RuntimeLocality';\n// Pluggable, bidirectional error translation (app exception <-> wire form). Registered on\n// ClientRegistry at startup; consulted before the built-in webpieces mapping on BOTH sides.\nexport { ErrorWireForm } from './http/ErrorTranslation';\nexport type { ErrorTranslation } from './http/ErrorTranslation';\n// Pluggable per-client failure classification (is a thrown API-call error a real failure or an\n// expected non-failure?). Registered on ClientRegistry at startup; consulted by LogApiCall.\nexport type { FailureClassifier } from './http/FailureClassifier';\nexport { KeyedFailureClassifier } from './http/FailureClassifier';\nexport {\n WebpiecesDefaultFailureClassifier,\n WEBPIECES_DEFAULT_FAILURE_CLASSIFIER,\n} from './http/WebpiecesDefaultFailureClassifier';\nexport { templateDeriver } from './http/templateDeriver';\nexport { WebpiecesCoreHeaders } from './http/WebpiecesCoreHeaders';\nexport { ContextReader } from './http/ContextReader';\n\n// The OUTBOUND half of the trust model: whether a TRUSTED context key may ride to the endpoint being\n// called. Built ONLY from the destination endpoint's AuthMode — see the class doc.\nexport { DestinationTrust } from './http/DestinationTrust';\n\n// BROWSER-ONLY outbound-header propagation (app-held store + registry -> outbound HTTP headers).\n// Only @webpieces/http-client-browser may name it; the server reads RequestContext directly via\n// RequestContextHeaders in the Node-only @webpieces/core-context.\nexport { ContextMgr } from './http/ContextMgr';\n\n// API-call logging helper (uses LogManager above). Singleton: use the LogApiCall constant, not `new`.\nexport { LogApiCall, LogApiCallImpl } from './http/LogApiCall';\n\n// Opt-in field masking for the LogApiCall log path — declare per-api sensitive fields so secrets\n// (OAuth refresh tokens, id-token JWTs) are masked in the logs while the real value stays on the wire.\nexport { MaskSpec } from './http/LogFieldMask';\nexport type { MaskMode } from './http/LogFieldMask';\n\n// The structured `api` tag + the context-writer seam LogApiCall stamps through. The Node\n// RequestContext-backed impl is installed by @webpieces/core-context; the browser gets the no-op.\nexport { ApiCallInfo } from './http/ApiCallInfo';\nexport type { ApiType, ApiResult } from './http/ApiCallInfo';\n// Console-render bridge: turns LogApiCall's [LogApiCall] bracket into [API.{side}.{phase}] locally.\nexport { ApiCallLogName, ApiCallLogNameImpl, LOG_API_CALL_LOGGER_NAME } from './http/ApiCallLogName';\nexport { ApiMethodInfo } from './http/ApiMethodInfo';\nexport type { ApiSide } from './http/ApiMethodInfo';\nexport { ApiCallContextHolder } from './http/ApiCallContext';\nexport type { ApiCallContext } from './http/ApiCallContext';\n\n// Test-case recording contract (impl lives in http-server; hooks in http-client)\nexport { TestCaseRecorder, RecorderKeys } from './http/recorder/TestCaseRecorder';\nexport { RecordedEndpoint, RecordedError, RecordedTestCase } from './http/recorder/RecordedEndpoint';\nexport { DoNotRecord, getDoNotRecordFields } from './http/recorder/DoNotRecord';\nexport { RecordSerializer, SerializedMap, SerializedError } from './http/recorder/RecordSerializer';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/core/core-util/src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;;;AAEH,+CAA2C;AAAlC,qGAAA,OAAO,OAAA;AAChB,2CAA0C;AAAjC,wGAAA,UAAU,OAAA;AAEnB,+CAA8C;AAArC,4GAAA,YAAY,OAAA;AAErB,+EAA+E;AAC/E,kFAAkF;AAClF,yCAAyC;AACzC,mDAA0F;AAAjF,gHAAA,cAAc,OAAA;AAAE,kHAAA,gBAAgB,OAAA;AAAE,sHAAA,oBAAoB,OAAA;AAO/D,yDAAwD;AAA/C,8GAAA,aAAa,OAAA;AACtB,uEAAsE;AAA7D,4HAAA,oBAAoB,OAAA;AAC7B,mDAAkD;AAAzC,wGAAA,UAAU,OAAA;AACnB,mDAAyH;AAAhH,wGAAA,UAAU,OAAA;AAAE,4GAAA,cAAc,OAAA;AAAE,0GAAA,YAAY,OAAA;AAAE,+GAAA,iBAAiB,OAAA;AAAE,kHAAA,oBAAoB,OAAA;AAE1F,8DAA8D;AAC9D,sEAAsE;AACtE,sEAAsE;AACtE,uEAAuE;AACvE,kEAAkE;AAElE,4BAA4B;AAC5B,gDA8B2B;AA7BvB,qGAAA,OAAO,OAAA;AACP,sGAAA,QAAQ,OAAA;AACR,mEAAmE;AACnE,oGAAA,MAAM,OAAA;AACN,qGAAA,OAAO,OAAA;AACP,2GAAA,aAAa,OAAA;AACb,wHAAA,0BAA0B,OAAA;AAC1B,sGAAA,QAAQ,OAAA;AACR,8GAAA,gBAAgB,OAAA;AAChB,yGAAA,WAAW,OAAA;AACX,wGAAA,UAAU,OAAA;AACV,2GAAA,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mF;AACnF,4DAA2D;AAAlD,oHAAA,gBAAgB,OAAA;AAEzB,iGAAiG;AACjG,gGAAgG;AAChG,kEAAkE;AAClE,gDAA+C;AAAtC,wGAAA,UAAU,OAAA;AAEnB,sGAAsG;AACtG,gDAA+D;AAAtD,wGAAA,UAAU,OAAA;AAAE,4GAAA,cAAc,OAAA;AAEnC,iGAAiG;AACjG,uGAAuG;AACvG,oDAA+C;AAAtC,wGAAA,QAAQ,OAAA;AAGjB,yFAAyF;AACzF,kGAAkG;AAClG,kDAAiD;AAAxC,0GAAA,WAAW,OAAA;AAEpB,oGAAoG;AACpG,wDAAqG;AAA5F,gHAAA,cAAc,OAAA;AAAE,oHAAA,kBAAkB,OAAA;AAAE,0HAAA,wBAAwB,OAAA;AACrE,sDAAqD;AAA5C,8GAAA,aAAa,OAAA;AAEtB,wDAA6D;AAApD,sHAAA,oBAAoB,OAAA;AAG7B,iFAAiF;AACjF,qEAAkF;AAAvD,gHAAA,YAAY,OAAA;AACvC,qEAAqG;AAA5F,oHAAA,gBAAgB,OAAA;AAAE,iHAAA,aAAa,OAAA;AAAE,oHAAA,gBAAgB,OAAA;AAC1D,2DAAgF;AAAvE,0GAAA,WAAW,OAAA;AAAE,mHAAA,oBAAoB,OAAA;AAC1C,qEAAoG;AAA3F,oHAAA,gBAAgB,OAAA;AAAE,iHAAA,aAAa,OAAA;AAAE,mHAAA,eAAe,OAAA","sourcesContent":["/**\n * @webpieces/core-util\n *\n * Utility functions for WebPieces applications.\n * This package works in both browser and Node.js environments.\n *\n * @packageDocumentation\n */\n\nexport { toError } from './lib/errorUtils';\nexport { ContextKey } from './ContextKey';\nexport type { AnyContextKey, AnyTrustedContextKey, AnyUntrustedContextKey, Trust } from './ContextKey';\nexport { ContextTuple } from './ContextTuple';\n\n// @DocumentDesign — DI-design-root marker. Applies to ANY project kind (server\n// controllers AND library impl classes), so it lives here (browser + Node) rather\n// than in a server-only routing package.\nexport { DocumentDesign, isDocumentDesign, DESIGN_METADATA_KEYS } from './DocumentDesign';\n\n// Logging (merged from former @webpieces/wp-logging).\n// Pluggable logging interface + a browser-safe console default; apps plug in\n// bunyan/winston/pino/etc. via LogManager.setFactory(...). Browser + Node.\nexport type { Logger, LogLevel } from './logging/Logger';\nexport type { LoggerFactory } from './logging/LoggerFactory';\nexport { ConsoleLogger } from './logging/ConsoleLogger';\nexport { ConsoleLoggerFactory } from './logging/ConsoleLoggerFactory';\nexport { LogManager } from './logging/LogManager';\nexport { LogChunker, LogChunkerImpl, LogChunkInfo, MAX_GCP_LOG_BYTES, GCP_LOG_BUDGET_BYTES } from './logging/LogChunker';\n\n// HTTP API contract (merged from former @webpieces/http-api).\n// Shared HTTP API definition consumed by both client and server: REST\n// decorators, the HttpError hierarchy, datetime DTOs, platform-header\n// registry/readers, ValidateImplementation, and the test-case recorder\n// contract. Pure definitions — express-free, browser + Node safe.\n\n// API definition decorators\nexport {\n ApiPath,\n Endpoint,\n // Auth mode decorators (clean service-to-service + user JWT model)\n Public,\n AuthJwt,\n rolesRequired,\n MISSING_AUTH_DECORATOR_FIX,\n AuthOidc,\n AuthSharedSecret,\n AuthWebhook,\n AuthApiKey,\n AuthLocalOnly,\n MaskLog,\n getApiPath,\n getEndpoints,\n getEndpointOptions,\n getEndpointKind,\n getEndpointKinds,\n getMaskSpec,\n isFormPost,\n isRawBody,\n isApiPath,\n getAuthMeta,\n getAuthMode,\n assertEveryEndpointHasAuthMode,\n assertEveryExternalEndpointDeclaresCaller,\n assertEveryWebhookEndpointRetainsRawBody,\n validateNoConflictingDecorators,\n METADATA_KEYS,\n} from './http/decorators';\n// The runtime representation of ONE route (split out of decorators.ts for file size only).\nexport { RouteMetadata } from './http/RouteMetadata';\nexport type { EndpointKind, EndpointOptions, ExternalEndpointOptions } from './http/decorators';\n// The TYPE layer of the auth surface — likewise split out of decorators.ts for file size only.\nexport { AuthMeta } from './http/auth-mode';\nexport type { AuthMode, ApiKeyCredential, ApiKeyCredentials, JwtRoles, JwtRequirement } from './http/auth-mode';\n// API kind (RPC vs PubSub/Cloud Tasks) + queue naming. Split out of decorators.ts for file size only;\n// one-way dependency api-kind -> decorators, and the barrel keeps the surface identical.\nexport {\n Rpc,\n PubSub,\n Queue,\n ENDPOINT_KINDS_BY_API_KIND,\n getApiKind,\n assertApiKind,\n assertPubSubConventions,\n getQueueName,\n} from './http/api-kind';\nexport type { ApiKind } from './http/api-kind';\n// WHO calls an `external` endpoint — the caller declaration @Endpoint(..., 'external', {calledBy})\n// requires, and the reader for it.\nexport { EXTERNAL_SYSTEM_KINDS, DEFAULT_CALLER_KIND, ExternalCaller, isExternalSystemKind, getEndpointCaller } from './http/external-caller';\nexport type { ExternalSystemKind } from './http/external-caller';\n// Client-side shared-secret store (the value THIS service sends per @AuthSharedSecret key).\nexport { Secrets, SECRETS } from './http/Secrets';\n\n// Type validators\nexport { ValidateImplementation } from './http/validators';\n\n// HTTP errors\nexport {\n ProtocolError,\n HttpError,\n HttpNotFoundError,\n EndpointNotFoundError,\n HttpBadRequestError,\n HttpUnauthorizedError,\n HttpForbiddenError,\n HttpTimeoutError,\n HttpBadGatewayError,\n HttpServiceUnavailableError,\n HttpGatewayTimeoutError,\n HttpInternalServerError,\n HttpTooManyRequestsError,\n HttpVendorError,\n HttpUserError,\n OfflineError,\n // Error subtype constants\n ENTITY_NOT_FOUND,\n WRONG_LOGIN_TYPE,\n WRONG_LOGIN,\n NOT_APPROVED,\n EMAIL_NOT_CONFIRMED,\n WRONG_DOMAIN,\n WRONG_COMPANY,\n NO_REG_CODE,\n} from './http/errors';\n\nexport { NetworkRejectClassifier } from './http/networkReject';\n\n// Date/Time DTOs and Utilities (inspired by Java Time / JSR-310)\nexport {\n InstantDto,\n DateDto,\n TimeDto,\n DateTimeDto,\n InstantUtil,\n DateUtil,\n TimeUtil,\n DateTimeUtil,\n} from './http/datetime';\n\n// Context keys + registry (the global magic-context header system)\nexport { HeaderRegistry } from './http/HeaderRegistry';\nexport { ClientRegistry } from './http/ClientRegistry';\nexport type { ServiceUrlDeriver } from './http/ClientRegistry';\n\n// \"What service am I\" — set once at startup, read by the logging backends and by\n// RequestContextHeaders (to stamp requestIdSource on ids this service mints).\nexport { ServiceInfo } from './http/ServiceInfo';\n// \"Where am I running\" — declared once at startup (setupRuntime, from RuntimeSetupOptions.locality).\n// The ONE input to @AuthLocalOnly enforcement. Undeclared reads as DEPLOYED (fail safe).\nexport { RuntimeLocality } from './http/RuntimeLocality';\nexport type { Locality } from './http/RuntimeLocality';\n// Pluggable, bidirectional error translation (app exception <-> wire form). Registered on\n// ClientRegistry at startup; consulted before the built-in webpieces mapping on BOTH sides.\nexport { ErrorWireForm } from './http/ErrorTranslation';\nexport type { ErrorTranslation } from './http/ErrorTranslation';\n// Pluggable per-client failure classification (is a thrown API-call error a real failure or an\n// expected non-failure?). Registered on ClientRegistry at startup; consulted by LogApiCall.\nexport type { FailureClassifier } from './http/FailureClassifier';\nexport { KeyedFailureClassifier } from './http/FailureClassifier';\nexport {\n WebpiecesDefaultFailureClassifier,\n WEBPIECES_DEFAULT_FAILURE_CLASSIFIER,\n} from './http/WebpiecesDefaultFailureClassifier';\nexport { templateDeriver } from './http/templateDeriver';\nexport { WebpiecesCoreHeaders } from './http/WebpiecesCoreHeaders';\nexport { ContextReader } from './http/ContextReader';\n\n// The OUTBOUND half of the trust model: whether a TRUSTED context key may ride to the endpoint being\n// called. Built ONLY from the destination endpoint's AuthMode — see the class doc.\nexport { DestinationTrust } from './http/DestinationTrust';\n\n// BROWSER-ONLY outbound-header propagation (app-held store + registry -> outbound HTTP headers).\n// Only @webpieces/http-client-browser may name it; the server reads RequestContext directly via\n// RequestContextHeaders in the Node-only @webpieces/core-context.\nexport { ContextMgr } from './http/ContextMgr';\n\n// API-call logging helper (uses LogManager above). Singleton: use the LogApiCall constant, not `new`.\nexport { LogApiCall, LogApiCallImpl } from './http/LogApiCall';\n\n// Opt-in field masking for the LogApiCall log path — declare per-api sensitive fields so secrets\n// (OAuth refresh tokens, id-token JWTs) are masked in the logs while the real value stays on the wire.\nexport { MaskSpec } from './http/LogFieldMask';\nexport type { MaskMode } from './http/LogFieldMask';\n\n// The structured `api` tag + the context-writer seam LogApiCall stamps through. The Node\n// RequestContext-backed impl is installed by @webpieces/core-context; the browser gets the no-op.\nexport { ApiCallInfo } from './http/ApiCallInfo';\nexport type { ApiType, ApiResult } from './http/ApiCallInfo';\n// Console-render bridge: turns LogApiCall's [LogApiCall] bracket into [API.{side}.{phase}] locally.\nexport { ApiCallLogName, ApiCallLogNameImpl, LOG_API_CALL_LOGGER_NAME } from './http/ApiCallLogName';\nexport { ApiMethodInfo } from './http/ApiMethodInfo';\nexport type { ApiSide } from './http/ApiMethodInfo';\nexport { ApiCallContextHolder } from './http/ApiCallContext';\nexport type { ApiCallContext } from './http/ApiCallContext';\n\n// Test-case recording contract (impl lives in http-server; hooks in http-client)\nexport { TestCaseRecorder, RecorderKeys } from './http/recorder/TestCaseRecorder';\nexport { RecordedEndpoint, RecordedError, RecordedTestCase } from './http/recorder/RecordedEndpoint';\nexport { DoNotRecord, getDoNotRecordFields } from './http/recorder/DoNotRecord';\nexport { RecordSerializer, SerializedMap, SerializedError } from './http/recorder/RecordSerializer';\n"]}
|