@venizia/ignis 0.4.8-1 → 0.4.8-10

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.
Files changed (108) hide show
  1. package/README.md +7 -14
  2. package/dist/esm/base/applications/server.d.ts +12 -0
  3. package/dist/esm/base/applications/server.js +11 -0
  4. package/dist/esm/base/applications/server.js.map +1 -1
  5. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.d.ts +1 -0
  6. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js +9 -2
  7. package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js.map +1 -1
  8. package/dist/esm/components/auth/authenticate/component.js +37 -1
  9. package/dist/esm/components/auth/authenticate/component.js.map +1 -1
  10. package/dist/esm/components/auth/authenticate/controllers/factory.d.ts +1 -0
  11. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.d.ts +56 -5
  12. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js +115 -11
  13. package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js.map +1 -1
  14. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js +2 -2
  15. package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js.map +1 -1
  16. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js +10 -3
  17. package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js.map +1 -1
  18. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.d.ts +11 -0
  19. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js +25 -3
  20. package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js.map +1 -1
  21. package/dist/esm/components/auth/authenticate/services/index.d.ts +1 -0
  22. package/dist/esm/components/auth/authenticate/services/index.js +1 -0
  23. package/dist/esm/components/auth/authenticate/services/index.js.map +1 -1
  24. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.d.ts +42 -0
  25. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js +162 -0
  26. package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js.map +1 -0
  27. package/dist/esm/components/auth/authenticate/services/service/verifier.service.js +7 -1
  28. package/dist/esm/components/auth/authenticate/services/service/verifier.service.js.map +1 -1
  29. package/dist/esm/components/auth/authenticate/strategies/service.strategy.js +2 -4
  30. package/dist/esm/components/auth/authenticate/strategies/service.strategy.js.map +1 -1
  31. package/dist/esm/components/auth/authorize/adapters/base-filtered.d.ts +1 -1
  32. package/dist/esm/components/auth/authorize/adapters/base-filtered.js +3 -2
  33. package/dist/esm/components/auth/authorize/adapters/base-filtered.js.map +1 -1
  34. package/dist/esm/components/auth/authorize/adapters/common/types.d.ts +2 -0
  35. package/dist/esm/components/auth/authorize/adapters/common/types.js.map +1 -1
  36. package/dist/esm/components/auth/authorize/adapters/connector.d.ts +2 -2
  37. package/dist/esm/components/auth/authorize/adapters/connector.js +3 -2
  38. package/dist/esm/components/auth/authorize/adapters/connector.js.map +1 -1
  39. package/dist/esm/components/auth/authorize/adapters/custom-grant-expander.js +1 -1
  40. package/dist/esm/components/auth/authorize/adapters/custom-grant-expander.js.map +1 -1
  41. package/dist/esm/components/health-check/reporter.js +2 -2
  42. package/dist/esm/components/health-check/reporter.js.map +1 -1
  43. package/dist/esm/components/index.d.ts +1 -0
  44. package/dist/esm/components/index.js +1 -0
  45. package/dist/esm/components/index.js.map +1 -1
  46. package/dist/esm/components/mail/common/types/verification.d.ts +1 -0
  47. package/dist/esm/components/mail/common/types/verification.js.map +1 -1
  48. package/dist/esm/components/mail/services/generators/numeric-code.d.ts +1 -6
  49. package/dist/esm/components/mail/services/generators/numeric-code.js +3 -31
  50. package/dist/esm/components/mail/services/generators/numeric-code.js.map +1 -1
  51. package/dist/esm/components/mail/services/generators/random-token.d.ts +4 -1
  52. package/dist/esm/components/mail/services/generators/random-token.js +9 -6
  53. package/dist/esm/components/mail/services/generators/random-token.js.map +1 -1
  54. package/dist/esm/components/mail/utilities/mime.utility.js +4 -4
  55. package/dist/esm/components/mail/utilities/mime.utility.js.map +1 -1
  56. package/dist/esm/components/server-info/common/constants.d.ts +6 -0
  57. package/dist/esm/components/server-info/common/constants.js +6 -0
  58. package/dist/esm/components/server-info/common/constants.js.map +1 -0
  59. package/dist/esm/components/server-info/common/index.d.ts +5 -0
  60. package/dist/esm/components/server-info/common/index.js +5 -0
  61. package/dist/esm/components/server-info/common/index.js.map +1 -0
  62. package/dist/esm/components/server-info/common/keys.d.ts +5 -0
  63. package/dist/esm/components/server-info/common/keys.js +5 -0
  64. package/dist/esm/components/server-info/common/keys.js.map +1 -0
  65. package/dist/esm/components/server-info/common/rest-paths.d.ts +5 -0
  66. package/dist/esm/components/server-info/common/rest-paths.js +5 -0
  67. package/dist/esm/components/server-info/common/rest-paths.js.map +1 -0
  68. package/dist/esm/components/server-info/common/types.d.ts +68 -0
  69. package/dist/esm/components/server-info/common/types.js +2 -0
  70. package/dist/esm/components/server-info/common/types.js.map +1 -0
  71. package/dist/esm/components/server-info/component.d.ts +31 -0
  72. package/dist/esm/components/server-info/component.js +87 -0
  73. package/dist/esm/components/server-info/component.js.map +1 -0
  74. package/dist/esm/components/server-info/controller.d.ts +14 -0
  75. package/dist/esm/components/server-info/controller.js +68 -0
  76. package/dist/esm/components/server-info/controller.js.map +1 -0
  77. package/dist/esm/components/server-info/index.d.ts +5 -0
  78. package/dist/esm/components/server-info/index.js +5 -0
  79. package/dist/esm/components/server-info/index.js.map +1 -0
  80. package/dist/esm/components/server-info/reporter.d.ts +25 -0
  81. package/dist/esm/components/server-info/reporter.js +68 -0
  82. package/dist/esm/components/server-info/reporter.js.map +1 -0
  83. package/dist/esm/components/static-asset/common/constants.d.ts +2 -0
  84. package/dist/esm/components/static-asset/common/constants.js +2 -0
  85. package/dist/esm/components/static-asset/common/constants.js.map +1 -1
  86. package/dist/esm/components/static-asset/common/types.d.ts +6 -0
  87. package/dist/esm/components/static-asset/common/types.js.map +1 -1
  88. package/dist/esm/components/static-asset/controller/base.definition.d.ts +2 -0
  89. package/dist/esm/components/static-asset/controller/base.definition.js +6 -4
  90. package/dist/esm/components/static-asset/controller/base.definition.js.map +1 -1
  91. package/dist/esm/components/static-asset/controller/factory.d.ts +1 -0
  92. package/dist/esm/components/static-asset/controller/factory.js +17 -9
  93. package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
  94. package/dist/esm/components/static-asset/controller/meta-link.js +1 -1
  95. package/dist/esm/components/static-asset/controller/meta-link.js.map +1 -1
  96. package/dist/esm/components/static-asset/controller/route-options.d.ts +9 -0
  97. package/dist/esm/components/static-asset/controller/route-options.js +16 -3
  98. package/dist/esm/components/static-asset/controller/route-options.js.map +1 -1
  99. package/dist/esm/components/static-asset/ingest.d.ts +2 -2
  100. package/dist/esm/components/static-asset/ingest.js +2 -2
  101. package/dist/esm/components/static-asset/ingest.js.map +1 -1
  102. package/dist/esm/testing/assert-application-boots.d.ts +9 -0
  103. package/dist/esm/testing/assert-application-boots.js +11 -1
  104. package/dist/esm/testing/assert-application-boots.js.map +1 -1
  105. package/dist/presets/app/preset.json +4 -4
  106. package/dist/presets/lib/preset.json +3 -3
  107. package/dist/presets/shared/preset.json +1 -1
  108. package/package.json +8 -8
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and
3
+ * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or
4
+ * is listed in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion
5
+ * callers: both fetch a key set to decide who may call.
6
+ *
7
+ * The opt-in is an EXACT entry, never a pattern or a range: a host name, an IPv4 address, or an IPv6 address in
8
+ * brackets, each optionally with a port (`identity-service`, `10.0.0.5:8080`, `[fd00::1]:8443`). An entry without a
9
+ * port covers every port of that host; an entry with one covers that port only. An entry and a URL are both read by
10
+ * the URL parser, so the two sides are compared in the form the parser gives them: `http://2130706433` is
11
+ * `127.0.0.1`, and `http://[::ffff:10.0.0.5]` is `[::ffff:a00:5]`, which is not `10.0.0.5`.
12
+ */
13
+ export declare class JWKSUrlPolicy {
14
+ /**
15
+ * Refuses an entry of `jwks.hosts.http` that is not exactly a host with an optional port, and answers the entries
16
+ * in the form a URL is matched in: the host as the URL parser writes it (lower case), then `:port` when there is one.
17
+ * An entry is valid only when `new URL('http://' + entry)` gives the same host back, and the same port.
18
+ */
19
+ static resolveHttpHosts(opts: {
20
+ scope: string;
21
+ hosts?: unknown;
22
+ }): ReadonlySet<string>;
23
+ /** The canonical form of one entry, or `undefined` when it is not exactly a host with an optional port. */
24
+ private static canonicalEntry;
25
+ /** Whether a name is within the DNS limits: 253 characters, and 63 for each label. */
26
+ private static isWithinLimits;
27
+ /** `http://<authority>` through the URL parser, or `undefined` when it refuses it. */
28
+ private static parseHttp;
29
+ /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */
30
+ static isLoopback(hostname: string): boolean;
31
+ /**
32
+ * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in
33
+ * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.
34
+ */
35
+ static assertUrl(opts: {
36
+ scope: string;
37
+ label: string;
38
+ url: string;
39
+ hosts?: unknown;
40
+ }): URL;
41
+ }
42
+ //# sourceMappingURL=jwks-url-policy.d.ts.map
@@ -0,0 +1,162 @@
1
+ import { HTTP } from '@venizia/ignis-helpers/common';
2
+ import { getError } from '@venizia/ignis-helpers/core';
3
+ /** One host name: labels of letters, digits and hyphens joined by single dots - no empty label, no wildcard. */
4
+ const HOST_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;
5
+ /** An IPv4 address, in any spelling a caller might write; the URL parser decides whether it is the address it looks like. */
6
+ const IPV4_PATTERN = /^\d{1,3}(?:\.\d{1,3}){3}$/;
7
+ /**
8
+ * An entry of `jwks.hosts.http`: a host (a name, an IPv4 address, or an IPv6 address in brackets) and an optional
9
+ * `:port`. Nothing else: no scheme, path, userinfo or wildcard.
10
+ */
11
+ const ENTRY_PATTERN = /^(?<host>\[[0-9a-f:.]+\]|[a-z0-9][a-z0-9.-]*)(?::(?<port>[0-9]{1,5}))?$/;
12
+ /** The port of an `http:` URL that names none. */
13
+ const DEFAULT_HTTP_PORT = '80';
14
+ /** The longest label and the longest name DNS has (RFC 1035): a longer entry is not a host name. */
15
+ const MAX_LABEL_LENGTH = 63;
16
+ const MAX_NAME_LENGTH = 253;
17
+ /** The addresses that mean "any local address", not a host: as the URL parser writes them. */
18
+ const UNSPECIFIED_HOSTS = new Set(['0.0.0.0', '[::]']);
19
+ /** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */
20
+ const LOOPBACK_IPV4_PATTERN = /^127(?:\.\d{1,3}){3}$/;
21
+ const LOOPBACK_HOSTS = new Set(['localhost', '[::1]']);
22
+ /**
23
+ * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and
24
+ * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or
25
+ * is listed in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion
26
+ * callers: both fetch a key set to decide who may call.
27
+ *
28
+ * The opt-in is an EXACT entry, never a pattern or a range: a host name, an IPv4 address, or an IPv6 address in
29
+ * brackets, each optionally with a port (`identity-service`, `10.0.0.5:8080`, `[fd00::1]:8443`). An entry without a
30
+ * port covers every port of that host; an entry with one covers that port only. An entry and a URL are both read by
31
+ * the URL parser, so the two sides are compared in the form the parser gives them: `http://2130706433` is
32
+ * `127.0.0.1`, and `http://[::ffff:10.0.0.5]` is `[::ffff:a00:5]`, which is not `10.0.0.5`.
33
+ */
34
+ export class JWKSUrlPolicy {
35
+ /**
36
+ * Refuses an entry of `jwks.hosts.http` that is not exactly a host with an optional port, and answers the entries
37
+ * in the form a URL is matched in: the host as the URL parser writes it (lower case), then `:port` when there is one.
38
+ * An entry is valid only when `new URL('http://' + entry)` gives the same host back, and the same port.
39
+ */
40
+ static resolveHttpHosts(opts) {
41
+ const { scope, hosts } = opts;
42
+ if (hosts === undefined) {
43
+ return new Set();
44
+ }
45
+ if (!Array.isArray(hosts)) {
46
+ throw getError({
47
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
48
+ message: `[${scope}] jwks.hosts.http must be a list of hosts`,
49
+ });
50
+ }
51
+ const resolved = new Set();
52
+ for (const entry of hosts) {
53
+ const canonical = typeof entry === 'string' ? JWKSUrlPolicy.canonicalEntry({ entry }) : undefined;
54
+ if (canonical === undefined) {
55
+ throw getError({
56
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
57
+ message: `[${scope}] jwks.hosts.http holds ${JSON.stringify(entry)} | list exact hosts only: a name, an IPv4 address or an IPv6 address in brackets, with an optional :port, for example 'identity-service', '10.0.0.5:8080' or '[fd00::1]:8443' - no scheme, path, credentials, wildcard or range`,
58
+ });
59
+ }
60
+ resolved.add(canonical);
61
+ }
62
+ return resolved;
63
+ }
64
+ /** The canonical form of one entry, or `undefined` when it is not exactly a host with an optional port. */
65
+ static canonicalEntry(opts) {
66
+ // Not trimmed: an entry with a space, a tab or a newline around it is a typo, and is refused rather than corrected.
67
+ const matched = ENTRY_PATTERN.exec(opts.entry.toLowerCase());
68
+ const { host, port } = matched?.groups ?? {};
69
+ if (host === undefined) {
70
+ return undefined;
71
+ }
72
+ // A name has labels of its own shape; an IPv4 or an IPv6 address is judged by the parser alone, below.
73
+ const isAddress = host.startsWith('[') || IPV4_PATTERN.test(host);
74
+ if (!isAddress &&
75
+ !(HOST_NAME_PATTERN.test(host) && JWKSUrlPolicy.isWithinLimits({ name: host }))) {
76
+ return undefined;
77
+ }
78
+ const parsed = JWKSUrlPolicy.parseHttp({
79
+ authority: port === undefined ? host : `${host}:${port}`,
80
+ });
81
+ // The host must be what the parser makes of it: `2130706433`, `0x7f000001`, `1.2.3`, `010.0.0.5` and
82
+ // `[::ffff:10.0.0.5]` are spellings the parser rewrites, so none of them is the host it looks like.
83
+ if (parsed === undefined || parsed.hostname !== host || UNSPECIFIED_HOSTS.has(host)) {
84
+ return undefined;
85
+ }
86
+ if (port === undefined) {
87
+ return host;
88
+ }
89
+ // The parser drops the default port, so `:80` reads back as no port; a port is valid only as the parser keeps it.
90
+ const kept = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;
91
+ if (kept !== port || Number(port) < 1) {
92
+ return undefined;
93
+ }
94
+ return `${host}:${port}`;
95
+ }
96
+ /** Whether a name is within the DNS limits: 253 characters, and 63 for each label. */
97
+ static isWithinLimits(opts) {
98
+ return (opts.name.length <= MAX_NAME_LENGTH &&
99
+ opts.name.split('.').every((label) => label.length <= MAX_LABEL_LENGTH));
100
+ }
101
+ /** `http://<authority>` through the URL parser, or `undefined` when it refuses it. */
102
+ static parseHttp(opts) {
103
+ try {
104
+ return new URL(`http://${opts.authority}`);
105
+ // eslint-disable-next-line venizia/no-silent-catch -- an authority the parser refuses is not a host: the caller refuses the entry
106
+ }
107
+ catch {
108
+ return undefined;
109
+ }
110
+ }
111
+ /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */
112
+ static isLoopback(hostname) {
113
+ return LOOPBACK_HOSTS.has(hostname) || LOOPBACK_IPV4_PATTERN.test(hostname);
114
+ }
115
+ /**
116
+ * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in
117
+ * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.
118
+ */
119
+ static assertUrl(opts) {
120
+ const { scope, label, url } = opts;
121
+ let parsed;
122
+ try {
123
+ parsed = new URL(url);
124
+ // eslint-disable-next-line venizia/no-silent-catch -- the refusal below names the key and withholds the URL, which may carry credentials
125
+ }
126
+ catch {
127
+ throw getError({
128
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
129
+ message: `[${scope}] ${label} is not a valid URL`,
130
+ });
131
+ }
132
+ if (parsed.protocol === 'https:') {
133
+ return parsed;
134
+ }
135
+ if (parsed.protocol !== 'http:') {
136
+ throw getError({
137
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
138
+ message: `[${scope}] ${label} must use https | scheme: ${parsed.protocol}`,
139
+ });
140
+ }
141
+ const allowed = JWKSUrlPolicy.resolveHttpHosts({ scope, hosts: opts.hosts });
142
+ // Nothing listens on port 0: a URL that names it is a mistake, and no entry without a port should cover it.
143
+ if (parsed.port === '0') {
144
+ throw getError({
145
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
146
+ message: `[${scope}] ${label} uses port 0 | the host is '${parsed.hostname}'`,
147
+ });
148
+ }
149
+ // An entry without a port covers every port; one with a port covers that port only (an `http:` URL with none is on 80).
150
+ const port = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;
151
+ if (JWKSUrlPolicy.isLoopback(parsed.hostname) ||
152
+ allowed.has(parsed.hostname) ||
153
+ allowed.has(`${parsed.hostname}:${port}`)) {
154
+ return parsed;
155
+ }
156
+ throw getError({
157
+ statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
158
+ message: `[${scope}] ${label} uses http: and the host '${parsed.hostname}' is not allowed | use https, or list the host in jwks.hosts.http`,
159
+ });
160
+ }
161
+ }
162
+ //# sourceMappingURL=jwks-url-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwks-url-policy.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/jwks-url-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,gHAAgH;AAChH,MAAM,iBAAiB,GAAG,yEAAyE,CAAC;AAEpG,6HAA6H;AAC7H,MAAM,YAAY,GAAG,2BAA2B,CAAC;AAEjD;;;GAGG;AACH,MAAM,aAAa,GAAG,yEAAyE,CAAC;AAEhG,kDAAkD;AAClD,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAE/B,oGAAoG;AACpG,MAAM,gBAAgB,G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EACzC,CAAC;YACD,OAAO,MAAM,CAAC;QAChB,CAAC;QAED,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,IAAI,KAAK,KAAK,KAAK,6BAA6B,MAAM,CAAC,QAAQ,mEAAmE;SAC5I,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\n\n/** One host name: labels of letters, digits and hyphens joined by single dots - no empty label, no wildcard. */\nconst HOST_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/;\n\n/** An IPv4 address, in any spelling a caller might write; the URL parser decides whether it is the address it looks like. */\nconst IPV4_PATTERN = /^\\d{1,3}(?:\\.\\d{1,3}){3}$/;\n\n/**\n * An entry of `jwks.hosts.http`: a host (a name, an IPv4 address, or an IPv6 address in brackets) and an optional\n * `:port`. Nothing else: no scheme, path, userinfo or wildcard.\n */\nconst ENTRY_PATTERN = /^(?<host>\\[[0-9a-f:.]+\\]|[a-z0-9][a-z0-9.-]*)(?::(?<port>[0-9]{1,5}))?$/;\n\n/** The port of an `http:` URL that names none. */\nconst DEFAULT_HTTP_PORT = '80';\n\n/** The longest label and the longest name DNS has (RFC 1035): a longer entry is not a host name. */\nconst MAX_LABEL_LENGTH = 63;\nconst MAX_NAME_LENGTH = 253;\n\n/** The addresses that mean \"any local address\", not a host: as the URL parser writes them. */\nconst UNSPECIFIED_HOSTS: ReadonlySet<string> = new Set(['0.0.0.0', '[::]']);\n\n/** `127.0.0.0/8`, as the URL parser writes an IPv4 host. */\nconst LOOPBACK_IPV4_PATTERN = /^127(?:\\.\\d{1,3}){3}$/;\n\nconst LOOPBACK_HOSTS: ReadonlySet<string> = new Set(['localhost', '[::1]']);\n\n/**\n * Where a JWKS may be fetched from. A key set read over plain `http:` can be replaced on the way, and\n * whoever replaces it signs tokens that verify, so a JWKS URL is `https:` unless its host is loopback or\n * is listed in `jwks.hosts.http`. The one policy serves the JWKS verifier and the service-assertion\n * callers: both fetch a key set to decide who may call.\n *\n * The opt-in is an EXACT entry, never a pattern or a range: a host name, an IPv4 address, or an IPv6 address in\n * brackets, each optionally with a port (`identity-service`, `10.0.0.5:8080`, `[fd00::1]:8443`). An entry without a\n * port covers every port of that host; an entry with one covers that port only. An entry and a URL are both read by\n * the URL parser, so the two sides are compared in the form the parser gives them: `http://2130706433` is\n * `127.0.0.1`, and `http://[::ffff:10.0.0.5]` is `[::ffff:a00:5]`, which is not `10.0.0.5`.\n */\nexport class JWKSUrlPolicy {\n /**\n * Refuses an entry of `jwks.hosts.http` that is not exactly a host with an optional port, and answers the entries\n * in the form a URL is matched in: the host as the URL parser writes it (lower case), then `:port` when there is one.\n * An entry is valid only when `new URL('http://' + entry)` gives the same host back, and the same port.\n */\n static resolveHttpHosts(opts: { scope: string; hosts?: unknown }): ReadonlySet<string> {\n const { scope, hosts } = opts;\n\n if (hosts === undefined) {\n return new Set();\n }\n\n if (!Array.isArray(hosts)) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] jwks.hosts.http must be a list of hosts`,\n });\n }\n\n const resolved = new Set<string>();\n\n for (const entry of hosts) {\n const canonical =\n typeof entry === 'string' ? JWKSUrlPolicy.canonicalEntry({ entry }) : undefined;\n\n if (canonical === undefined) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] jwks.hosts.http holds ${JSON.stringify(entry)} | list exact hosts only: a name, an IPv4 address or an IPv6 address in brackets, with an optional :port, for example 'identity-service', '10.0.0.5:8080' or '[fd00::1]:8443' - no scheme, path, credentials, wildcard or range`,\n });\n }\n\n resolved.add(canonical);\n }\n\n return resolved;\n }\n\n /** The canonical form of one entry, or `undefined` when it is not exactly a host with an optional port. */\n private static canonicalEntry(opts: { entry: string }): string | undefined {\n // Not trimmed: an entry with a space, a tab or a newline around it is a typo, and is refused rather than corrected.\n const matched = ENTRY_PATTERN.exec(opts.entry.toLowerCase());\n const { host, port } = matched?.groups ?? {};\n\n if (host === undefined) {\n return undefined;\n }\n\n // A name has labels of its own shape; an IPv4 or an IPv6 address is judged by the parser alone, below.\n const isAddress = host.startsWith('[') || IPV4_PATTERN.test(host);\n\n if (\n !isAddress &&\n !(HOST_NAME_PATTERN.test(host) && JWKSUrlPolicy.isWithinLimits({ name: host }))\n ) {\n return undefined;\n }\n\n const parsed = JWKSUrlPolicy.parseHttp({\n authority: port === undefined ? host : `${host}:${port}`,\n });\n\n // The host must be what the parser makes of it: `2130706433`, `0x7f000001`, `1.2.3`, `010.0.0.5` and\n // `[::ffff:10.0.0.5]` are spellings the parser rewrites, so none of them is the host it looks like.\n if (parsed === undefined || parsed.hostname !== host || UNSPECIFIED_HOSTS.has(host)) {\n return undefined;\n }\n\n if (port === undefined) {\n return host;\n }\n\n // The parser drops the default port, so `:80` reads back as no port; a port is valid only as the parser keeps it.\n const kept = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;\n\n if (kept !== port || Number(port) < 1) {\n return undefined;\n }\n\n return `${host}:${port}`;\n }\n\n /** Whether a name is within the DNS limits: 253 characters, and 63 for each label. */\n private static isWithinLimits(opts: { name: string }): boolean {\n return (\n opts.name.length <= MAX_NAME_LENGTH &&\n opts.name.split('.').every((label) => label.length <= MAX_LABEL_LENGTH)\n );\n }\n\n /** `http://<authority>` through the URL parser, or `undefined` when it refuses it. */\n private static parseHttp(opts: { authority: string }): URL | undefined {\n try {\n return new URL(`http://${opts.authority}`);\n // eslint-disable-next-line venizia/no-silent-catch -- an authority the parser refuses is not a host: the caller refuses the entry\n } catch {\n return undefined;\n }\n }\n\n /** Whether the URL parser's hostname is a loopback one: `localhost`, `127.0.0.0/8` or `::1`. */\n static isLoopback(hostname: string): boolean {\n return LOOPBACK_HOSTS.has(hostname) || LOOPBACK_IPV4_PATTERN.test(hostname);\n }\n\n /**\n * Parses a JWKS URL and refuses it unless it is `https:`, or `http:` to a loopback host or a host listed in\n * `jwks.hosts.http`. Only the host name goes into the message: a URL may carry credentials.\n */\n static assertUrl(opts: { scope: string; label: string; url: string; hosts?: unknown }): URL {\n const { scope, label, url } = opts;\n\n let parsed: URL;\n\n try {\n parsed = new URL(url);\n // eslint-disable-next-line venizia/no-silent-catch -- the refusal below names the key and withholds the URL, which may carry credentials\n } catch {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} is not a valid URL`,\n });\n }\n\n if (parsed.protocol === 'https:') {\n return parsed;\n }\n\n if (parsed.protocol !== 'http:') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} must use https | scheme: ${parsed.protocol}`,\n });\n }\n\n const allowed = JWKSUrlPolicy.resolveHttpHosts({ scope, hosts: opts.hosts });\n\n // Nothing listens on port 0: a URL that names it is a mistake, and no entry without a port should cover it.\n if (parsed.port === '0') {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} uses port 0 | the host is '${parsed.hostname}'`,\n });\n }\n\n // An entry without a port covers every port; one with a port covers that port only (an `http:` URL with none is on 80).\n const port = parsed.port === '' ? DEFAULT_HTTP_PORT : parsed.port;\n\n if (\n JWKSUrlPolicy.isLoopback(parsed.hostname) ||\n allowed.has(parsed.hostname) ||\n allowed.has(`${parsed.hostname}:${port}`)\n ) {\n return parsed;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${label} uses http: and the host '${parsed.hostname}' is not allowed | use https, or list the host in jwks.hosts.http`,\n });\n }\n}\n"]}
@@ -15,6 +15,7 @@ import { inject } from '../../../../../base/metadata/index.js';
15
15
  import { AuthenticateBindingKeys, AuthenticationErrors, BaseService, ServiceAssertion, } from '@venizia/ignis-kernel';
16
16
  import { getError } from '@venizia/ignis-helpers/core';
17
17
  import { JoseLoader } from '../jose-loader.js';
18
+ import { JWKSUrlPolicy } from '../jwks-url-policy.js';
18
19
  /**
19
20
  * Verifies an incoming service assertion against the CALLER's own JWKS.
20
21
  *
@@ -91,7 +92,12 @@ let ServiceAssertionVerifierService = ServiceAssertionVerifierService_1 = class
91
92
  callerOverride: typeof entry === 'string' ? undefined : entry.acceptMaxAgeSeconds,
92
93
  serviceDefault: this.options.acceptMaxAgeSeconds,
93
94
  }));
94
- const keySet = jose.createRemoteJWKSet(new URL(jwksUrl), {
95
+ const keySet = jose.createRemoteJWKSet(JWKSUrlPolicy.assertUrl({
96
+ scope: ServiceAssertionVerifierService_1.name,
97
+ label: 'the caller jwksUrl',
98
+ url: jwksUrl,
99
+ hosts: this.options.jwks?.hosts?.http,
100
+ }), {
95
101
  cacheMaxAge: this.options.jwks?.cacheMaxAgeMs ?? ServiceAssertion.DEFAULT_JWKS_CACHE_MAX_AGE_MS,
96
102
  cooldownDuration: this.options.jwks?.cooldownMs ?? ServiceAssertion.DEFAULT_JWKS_COOLDOWN_MS,
97
103
  });
@@ -1 +1 @@
1
- {"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/service/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,WAAW,EACX,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAI5C;;;;;;;;GAQG;AACH,IAAa,+BAA+B,uCAA5C,MAAa,+BAAgC,SAAQ,WAAW;IAO9D,YAEE,OAA6C;QAE7C,KAAK,CAAC,EAAE,KAAK,EAAE,iCAA+B,CAAC,IAAI,EAAE,CAAC,CAAC;QAFtC,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AC;aACnC,IAAI,CAAC,oDAAoD,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QAE9E,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,wBAAwB,EAAE,CAAC,CAAC;IAC3E,CAAC;CACF,CAAA;AAhLY,+BAA+B;IAQvC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,eAAe,EAAE,CAAC,CAAA;;GARhD,+BAA+B,CAgL3C","sourcesContent":["import { inject } from '@/base/metadata';\nimport {\n AuthenticateBindingKeys,\n AuthenticationErrors,\n BaseService,\n ServiceAssertion,\n} from '@venizia/ignis-kernel';\nimport type { IServiceAssertionClaims, IServiceAuthOptions } from '@venizia/ignis-kernel';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { createRemoteJWKSet } from 'jose';\nimport { JoseLoader } from '../jose-loader';\n\ntype TRemoteKeySet = ReturnType<typeof createRemoteJWKSet>;\n\n/**\n * Verifies an incoming service assertion against the CALLER's own JWKS.\n *\n * What the assertion covers, and nothing else: the HTTP method and the percent-encoded path. It does\n * NOT cover the query string, any header, or the body. Tenant selectors in particular are usually a\n * header or a query parameter, so an assertion alone does not authenticate which tenant a call acts\n * on - the caller allowlist and the application's own scoping have to do that. Stated because the\n * gap is invisible from the call site.\n */\nexport class ServiceAssertionVerifierService extends BaseService {\n /** One remote key set per caller, kept because `createRemoteJWKSet` owns its own cache. */\n private readonly keySets = new Map<string, TRemoteKeySet>();\n\n /** Per-caller accepted age, resolved once alongside its key set. */\n private readonly acceptMaxAges = new Map<string, number>();\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.SERVICE_OPTIONS })\n private readonly options: IServiceAuthOptions,\n ) {\n super({ scope: ServiceAssertionVerifierService.name });\n }\n\n /**\n * @param path The percent-ENCODED pathname, from `new URL(context.req.url).pathname`. Never\n * `context.req.path` - Hono decodes that one, and the caller signed the encoded form.\n */\n async verify(opts: { token: string; method: string; path: string }): Promise<{ issuer: string }> {\n const { token, method, path } = opts;\n\n const jose = await JoseLoader.load();\n const issuer = this.readIssuer({ token, jose });\n const keySet = this.resolveKeySet({ issuer, jose });\n const payload = await this.runVerify({ token, issuer, keySet, jose });\n\n this.assertRequestBinding({ payload, method, path });\n\n return { issuer };\n }\n\n /**\n * Reads `iss` WITHOUT verifying, only to choose which key set checks the signature. The same value\n * is then enforced as the expected issuer, so a forged `iss` buys nothing beyond selecting the key\n * set that will reject it.\n */\n private readIssuer(opts: { token: string; jose: typeof import('jose') }): string {\n let issuer: unknown;\n\n try {\n ({ iss: issuer } = opts.jose.decodeJwt(opts.token));\n } catch (error) {\n this.logger.for(this.readIssuer.name).warn('Undecodable assertion | error: %s', error);\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n // Typed, not merely present: a numeric `iss` would index the caller map by coercion.\n if (typeof issuer !== 'string' || issuer.length === 0) {\n this.logger\n .for(this.readIssuer.name)\n .warn('Undecodable assertion | iss is missing or not a string');\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n return issuer;\n }\n\n private resolveKeySet(opts: { issuer: string; jose: typeof import('jose') }): TRemoteKeySet {\n const { issuer, jose } = opts;\n\n const cached = this.keySets.get(issuer);\n\n if (cached) {\n return cached;\n }\n\n const callers = this.options.callers ?? {};\n\n // `Object.hasOwn`, never a truthiness check on the index: the map arrives as a plain object, so\n // `iss: 'constructor'` would otherwise return `Function` - truthy - walk past this guard, and\n // reach `new URL(<function>)` as an uncaught TypeError.\n if (!Object.hasOwn(callers, issuer)) {\n this.logger\n .for(this.resolveKeySet.name)\n .warn('Caller not on the allowlist | iss: %s', issuer);\n throw getError({ error: AuthenticationErrors.CALLER_NOT_ALLOWED });\n }\n\n const entry = callers[issuer];\n const jwksUrl = typeof entry === 'string' ? entry : entry.jwksUrl;\n\n this.acceptMaxAges.set(\n issuer,\n ServiceAssertion.resolveAcceptMaxAge({\n callerOverride: typeof entry === 'string' ? undefined : entry.acceptMaxAgeSeconds,\n serviceDefault: this.options.acceptMaxAgeSeconds,\n }),\n );\n\n const keySet = jose.createRemoteJWKSet(new URL(jwksUrl), {\n cacheMaxAge:\n this.options.jwks?.cacheMaxAgeMs ?? ServiceAssertion.DEFAULT_JWKS_CACHE_MAX_AGE_MS,\n cooldownDuration: this.options.jwks?.cooldownMs ?? ServiceAssertion.DEFAULT_JWKS_COOLDOWN_MS,\n });\n\n this.keySets.set(issuer, keySet);\n\n return keySet;\n }\n\n private async runVerify(opts: {\n token: string;\n issuer: string;\n keySet: TRemoteKeySet;\n jose: typeof import('jose');\n }): Promise<IServiceAssertionClaims> {\n const { token, issuer, keySet, jose } = opts;\n\n // Resolved when the key set was, so a per-caller override is already folded in.\n const maxTokenAge =\n this.acceptMaxAges.get(issuer) ??\n ServiceAssertion.resolveAcceptMaxAge({\n serviceDefault: this.options.acceptMaxAgeSeconds,\n });\n\n const clockTolerance =\n this.options.clockToleranceSeconds ?? ServiceAssertion.DEFAULT_CLOCK_TOLERANCE_SECONDS;\n\n try {\n const { payload } = await jose.jwtVerify<IServiceAssertionClaims>(token, keySet, {\n algorithms: [ServiceAssertion.ALGORITHM],\n typ: ServiceAssertion.TYP,\n issuer,\n audience: this.options.name,\n // NOT redundant with `exp`, though it looks it. An honest caller stamps `exp = iat +\n // lifetime`, so the two are numerically tied and jose reaches `exp` first - measured.\n // `maxTokenAge` is the only bound that still holds when the CALLER is the attacker and picks\n // its own `exp`, which is precisely the case it exists for. Do not delete it as dead config.\n //\n // And it is the CALLEE's number, never one the caller may request: a caller that could ask\n // for a longer window would be choosing its own replay window, which is the whole thing this\n // is here to deny.\n //\n // TWO NUMBERS, and they answer different questions. Measured at the defaults, 60 + 5:\n // - 65s is the ACCEPTANCE window on this machine's clock. Age 64 passes, 65 does not.\n // - 70s is the REPLAY window in wall-clock time, when the caller's clock runs the full\n // tolerance fast: we accept an `iat` up to 5s in our future, then keep accepting for\n // another 64. Measured: still accepted 69s after minting.\n // The second is the one a threat model asks for. Widening `clockToleranceSeconds` widens it\n // second for second, so it is a security knob, not an operational one.\n maxTokenAge,\n clockTolerance,\n requiredClaims: ['htm', 'htu', 'jti'],\n });\n\n return payload;\n } catch (error) {\n // One code out, the reason on `cause`: a wrong audience, clock skew and a rotated key are\n // otherwise the same string to whoever is reading the log at 2am.\n const reason = (error as { cause?: unknown })?.cause ?? error;\n this.logger.for(this.runVerify.name).warn('Rejected | iss: %s | reason: %s', issuer, reason);\n\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID, cause: error });\n }\n }\n\n private assertRequestBinding(opts: {\n payload: IServiceAssertionClaims;\n method: string;\n path: string;\n }): void {\n const { payload, method, path } = opts;\n\n const signed = `${payload.htm} ${payload.htu}`;\n const actual = `${method.toUpperCase()} ${path}`;\n\n if (signed === actual) {\n return;\n }\n\n this.logger\n .for(this.assertRequestBinding.name)\n .warn('Request binding mismatch | signed: %s | actual: %s', signed, actual);\n\n throw getError({ error: AuthenticationErrors.REQUEST_BINDING_MISMATCH });\n }\n}\n"]}
1
+ {"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/service/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AACzC,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,WAAW,EACX,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAEvD,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAInD;;;;;;;;GAQG;AACH,IAAa,+BAA+B,uCAA5C,MAAa,+BAAgC,SAAQ,WAAW;IAO9D,YAEE,OAA6C;QAE7C,KAAK,CAAC,EAAE,KAAK,EAAE,iCAA+B,CAAC,IAAI,EAAE,CAAC,CAAC;QAFtC,YAAO,GAAP,OAAO,CAAqB;QA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jD,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;YACtB,OAAO;QACT,CAAC;QAED,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,oBAAoB,CAAC,IAAI,CAAC;aACnC,IAAI,CAAC,oDAAoD,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;QAE9E,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,wBAAwB,EAAE,CAAC,CAAC;IAC3E,CAAC;CACF,CAAA;AAzLY,+BAA+B;IAQvC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,eAAe,EAAE,CAAC,CAAA;;GARhD,+BAA+B,CAyL3C","sourcesContent":["import { inject } from '@/base/metadata';\nimport {\n AuthenticateBindingKeys,\n AuthenticationErrors,\n BaseService,\n ServiceAssertion,\n} from '@venizia/ignis-kernel';\nimport type { IServiceAssertionClaims, IServiceAuthOptions } from '@venizia/ignis-kernel';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type { createRemoteJWKSet } from 'jose';\nimport { JoseLoader } from '../jose-loader';\nimport { JWKSUrlPolicy } from '../jwks-url-policy';\n\ntype TRemoteKeySet = ReturnType<typeof createRemoteJWKSet>;\n\n/**\n * Verifies an incoming service assertion against the CALLER's own JWKS.\n *\n * What the assertion covers, and nothing else: the HTTP method and the percent-encoded path. It does\n * NOT cover the query string, any header, or the body. Tenant selectors in particular are usually a\n * header or a query parameter, so an assertion alone does not authenticate which tenant a call acts\n * on - the caller allowlist and the application's own scoping have to do that. Stated because the\n * gap is invisible from the call site.\n */\nexport class ServiceAssertionVerifierService extends BaseService {\n /** One remote key set per caller, kept because `createRemoteJWKSet` owns its own cache. */\n private readonly keySets = new Map<string, TRemoteKeySet>();\n\n /** Per-caller accepted age, resolved once alongside its key set. */\n private readonly acceptMaxAges = new Map<string, number>();\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.SERVICE_OPTIONS })\n private readonly options: IServiceAuthOptions,\n ) {\n super({ scope: ServiceAssertionVerifierService.name });\n }\n\n /**\n * @param path The percent-ENCODED pathname, from `new URL(context.req.url).pathname`. Never\n * `context.req.path` - Hono decodes that one, and the caller signed the encoded form.\n */\n async verify(opts: { token: string; method: string; path: string }): Promise<{ issuer: string }> {\n const { token, method, path } = opts;\n\n const jose = await JoseLoader.load();\n const issuer = this.readIssuer({ token, jose });\n const keySet = this.resolveKeySet({ issuer, jose });\n const payload = await this.runVerify({ token, issuer, keySet, jose });\n\n this.assertRequestBinding({ payload, method, path });\n\n return { issuer };\n }\n\n /**\n * Reads `iss` WITHOUT verifying, only to choose which key set checks the signature. The same value\n * is then enforced as the expected issuer, so a forged `iss` buys nothing beyond selecting the key\n * set that will reject it.\n */\n private readIssuer(opts: { token: string; jose: typeof import('jose') }): string {\n let issuer: unknown;\n\n try {\n ({ iss: issuer } = opts.jose.decodeJwt(opts.token));\n } catch (error) {\n this.logger.for(this.readIssuer.name).warn('Undecodable assertion | error: %s', error);\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n // Typed, not merely present: a numeric `iss` would index the caller map by coercion.\n if (typeof issuer !== 'string' || issuer.length === 0) {\n this.logger\n .for(this.readIssuer.name)\n .warn('Undecodable assertion | iss is missing or not a string');\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID });\n }\n\n return issuer;\n }\n\n private resolveKeySet(opts: { issuer: string; jose: typeof import('jose') }): TRemoteKeySet {\n const { issuer, jose } = opts;\n\n const cached = this.keySets.get(issuer);\n\n if (cached) {\n return cached;\n }\n\n const callers = this.options.callers ?? {};\n\n // `Object.hasOwn`, never a truthiness check on the index: the map arrives as a plain object, so\n // `iss: 'constructor'` would otherwise return `Function` - truthy - walk past this guard, and\n // reach `new URL(<function>)` as an uncaught TypeError.\n if (!Object.hasOwn(callers, issuer)) {\n this.logger\n .for(this.resolveKeySet.name)\n .warn('Caller not on the allowlist | iss: %s', issuer);\n throw getError({ error: AuthenticationErrors.CALLER_NOT_ALLOWED });\n }\n\n const entry = callers[issuer];\n const jwksUrl = typeof entry === 'string' ? entry : entry.jwksUrl;\n\n this.acceptMaxAges.set(\n issuer,\n ServiceAssertion.resolveAcceptMaxAge({\n callerOverride: typeof entry === 'string' ? undefined : entry.acceptMaxAgeSeconds,\n serviceDefault: this.options.acceptMaxAgeSeconds,\n }),\n );\n\n const keySet = jose.createRemoteJWKSet(\n JWKSUrlPolicy.assertUrl({\n scope: ServiceAssertionVerifierService.name,\n label: 'the caller jwksUrl',\n url: jwksUrl,\n hosts: this.options.jwks?.hosts?.http,\n }),\n {\n cacheMaxAge:\n this.options.jwks?.cacheMaxAgeMs ?? ServiceAssertion.DEFAULT_JWKS_CACHE_MAX_AGE_MS,\n cooldownDuration:\n this.options.jwks?.cooldownMs ?? ServiceAssertion.DEFAULT_JWKS_COOLDOWN_MS,\n },\n );\n\n this.keySets.set(issuer, keySet);\n\n return keySet;\n }\n\n private async runVerify(opts: {\n token: string;\n issuer: string;\n keySet: TRemoteKeySet;\n jose: typeof import('jose');\n }): Promise<IServiceAssertionClaims> {\n const { token, issuer, keySet, jose } = opts;\n\n // Resolved when the key set was, so a per-caller override is already folded in.\n const maxTokenAge =\n this.acceptMaxAges.get(issuer) ??\n ServiceAssertion.resolveAcceptMaxAge({\n serviceDefault: this.options.acceptMaxAgeSeconds,\n });\n\n const clockTolerance =\n this.options.clockToleranceSeconds ?? ServiceAssertion.DEFAULT_CLOCK_TOLERANCE_SECONDS;\n\n try {\n const { payload } = await jose.jwtVerify<IServiceAssertionClaims>(token, keySet, {\n algorithms: [ServiceAssertion.ALGORITHM],\n typ: ServiceAssertion.TYP,\n issuer,\n audience: this.options.name,\n // NOT redundant with `exp`, though it looks it. An honest caller stamps `exp = iat +\n // lifetime`, so the two are numerically tied and jose reaches `exp` first - measured.\n // `maxTokenAge` is the only bound that still holds when the CALLER is the attacker and picks\n // its own `exp`, which is precisely the case it exists for. Do not delete it as dead config.\n //\n // And it is the CALLEE's number, never one the caller may request: a caller that could ask\n // for a longer window would be choosing its own replay window, which is the whole thing this\n // is here to deny.\n //\n // TWO NUMBERS, and they answer different questions. Measured at the defaults, 60 + 5:\n // - 65s is the ACCEPTANCE window on this machine's clock. Age 64 passes, 65 does not.\n // - 70s is the REPLAY window in wall-clock time, when the caller's clock runs the full\n // tolerance fast: we accept an `iat` up to 5s in our future, then keep accepting for\n // another 64. Measured: still accepted 69s after minting.\n // The second is the one a threat model asks for. Widening `clockToleranceSeconds` widens it\n // second for second, so it is a security knob, not an operational one.\n maxTokenAge,\n clockTolerance,\n requiredClaims: ['htm', 'htu', 'jti'],\n });\n\n return payload;\n } catch (error) {\n // One code out, the reason on `cause`: a wrong audience, clock skew and a rotated key are\n // otherwise the same string to whoever is reading the log at 2am.\n const reason = (error as { cause?: unknown })?.cause ?? error;\n this.logger.for(this.runVerify.name).warn('Rejected | iss: %s | reason: %s', issuer, reason);\n\n throw getError({ error: AuthenticationErrors.ASSERTION_INVALID, cause: error });\n }\n }\n\n private assertRequestBinding(opts: {\n payload: IServiceAssertionClaims;\n method: string;\n path: string;\n }): void {\n const { payload, method, path } = opts;\n\n const signed = `${payload.htm} ${payload.htu}`;\n const actual = `${method.toUpperCase()} ${path}`;\n\n if (signed === actual) {\n return;\n }\n\n this.logger\n .for(this.assertRequestBinding.name)\n .warn('Request binding mismatch | signed: %s | actual: %s', signed, actual);\n\n throw getError({ error: AuthenticationErrors.REQUEST_BINDING_MISMATCH });\n }\n}\n"]}
@@ -42,10 +42,8 @@ let ServiceAuthenticationStrategy = ServiceAuthenticationStrategy_1 = class Serv
42
42
  path: new URL(context.req.url).pathname,
43
43
  });
44
44
  const principal = await this.options.resolvePrincipal({ issuer, context });
45
- // Validated rather than trusted. `executeAnyMode` calls `setCurrentUser` unconditionally, so an
46
- // application returning a principal without a `userId` would authenticate the request and then
47
- // fail at the first write, far from here. `executeAllMode` already refuses it; this closes the
48
- // gap between the two modes.
45
+ // Validated rather than trusted. The provider also refuses an answer without a `userId`, but a principal an
46
+ // application resolves wrongly is reported here, at the cause, with the issuer and the strategy named.
49
47
  if (!principal?.userId) {
50
48
  this.logger
51
49
  .for(this.authenticate.name)
@@ -1 +1 @@
1
- {"version":3,"file":"service.strategy.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/strategies/service.strategy.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAEvD,OAAO,EACL,uBAAuB,EACvB,cAAc,EACd,oBAAoB,EACpB,iBAAiB,EACjB,gBAAgB,EAChB,MAAM,GACP,MAAM,uBAAuB,CAAC;AAO/B,OAAO,EAAE,+BAA+B,EAAE,MAAM,sCAAsC,CAAC;AAEvF;;;;;;GAMG;AACH,IAAa,6BAA6B,qCAA1C,MAAa,6BACX,SAAQ,UAAU;IAKlB,YAOE,QAA0D,EAE1D,OAAgD;QAEhD,KAAK,CAAC,EAAE,KAAK,EAAE,+BAA6B,CAAC,IAAI,EAAE,CAAC,CAAC;QAJpC,aAAQ,GAAR,QAAQ,CAAiC;QAEzC,YAAO,GAAP,OAAO,CAAwB;QAXlD,SAAI,GAAG,cAAc,CAAC,gBAAgB,CAAC;IAcvC,CAAC;IAED,KAAK,CAAC,YAAY,CAAC,OAA4B;QAC7C,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,gBAAgB,CAAC,MAAM,CAAC,CAAC;QAE1D,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,iBAAiB,EAAE,CAAC,CAAC;QACpE,CAAC;QAED,iGAAiG;QACjG,oFAAoF;QACpF,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC;YAC5C,KAAK;YACL,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,MAAM;YAC1B,IAAI,EAAE,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ;SACxC,CAAC,CAAC;QAEH,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,gBAAgB,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;QAE3E,gGAAgG;QAChG,+FAA+F;QAC/F,+FAA+F;QAC/F,6BAA6B;QAC7B,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC;YACvB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC;iBAC3B,IAAI,CAAC,yDAAyD,EAAE,MAAM,CAAC,CAAC;YAC3E,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,oBAAoB,EAAE,CAAC,CAAC;QACvE,CAAC;QAED,2FAA2F;QAC3F,OAAO,EAAE,GAAG,SAAS,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC;IACjD,CAAC;CACF,CAAA;AAnDY,6BAA6B;IAOrC,WAAA,MAAM,CAAC;QACN,GAAG,EAAE,WAAW,CAAC,KAAK,CAAC;YACrB,SAAS,EAAE,iBAAiB,CAAC,OAAO;YACpC,GAAG,EAAE,+BAA+B,CAAC,IAAI;SAC1C,CAAC;KACH,CAAC,CAAA;IAED,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,eAAe,EAAE,CAAC,CAAA;qCAD9B,+BAA+B;GAbjD,6BAA6B,CAmDzC","sourcesContent":["import { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { BindingKeys } from '@venizia/ignis-inversion';\nimport type { Env } from 'hono';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationErrors,\n BindingNamespaces,\n ServiceAssertion,\n inject,\n} from '@venizia/ignis-kernel';\nimport type {\n IAuthUser,\n IAuthenticationStrategy,\n IServiceAuthOptions,\n TContext,\n} from '@venizia/ignis-kernel';\nimport { ServiceAssertionVerifierService } from '../services/service/verifier.service';\n\n/**\n * Proves the CALLING SERVICE, from a per-request Ed25519 assertion verified against that caller's\n * own JWKS. No identity round trip and no shared password.\n *\n * It proves which service called, never which user. `resolvePrincipal` is where the application\n * turns a caller name into one of its own principals.\n */\nexport class ServiceAuthenticationStrategy<E extends Env = Env>\n extends BaseHelper\n implements IAuthenticationStrategy<E>\n{\n name = Authentication.STRATEGY_SERVICE;\n\n constructor(\n @inject({\n key: BindingKeys.build({\n namespace: BindingNamespaces.SERVICE,\n key: ServiceAssertionVerifierService.name,\n }),\n })\n private readonly verifier: ServiceAssertionVerifierService,\n @inject({ key: AuthenticateBindingKeys.SERVICE_OPTIONS })\n private readonly options: IServiceAuthOptions<E>,\n ) {\n super({ scope: ServiceAuthenticationStrategy.name });\n }\n\n async authenticate(context: TContext<E, string>): Promise<IAuthUser> {\n const token = context.req.header(ServiceAssertion.HEADER);\n\n if (!token) {\n throw getError({ error: AuthenticationErrors.ASSERTION_MISSING });\n }\n\n // The raw url, NOT `context.req.path`: Hono hands that back percent-DECODED, so a route carrying\n // a space or a non-ASCII slug would never match the encoded path the caller signed.\n const { issuer } = await this.verifier.verify({\n token,\n method: context.req.method,\n path: new URL(context.req.url).pathname,\n });\n\n const principal = await this.options.resolvePrincipal({ issuer, context });\n\n // Validated rather than trusted. `executeAnyMode` calls `setCurrentUser` unconditionally, so an\n // application returning a principal without a `userId` would authenticate the request and then\n // fail at the first write, far from here. `executeAllMode` already refuses it; this closes the\n // gap between the two modes.\n if (!principal?.userId) {\n this.logger\n .for(this.authenticate.name)\n .warn('resolvePrincipal returned no usable principal | iss: %s', issuer);\n throw getError({ error: AuthenticationErrors.PRINCIPAL_UNRESOLVED });\n }\n\n // Which service called is audit-relevant even when the principal is shared across callers.\n return { ...principal, callerService: issuer };\n }\n}\n"]}
1
+ {"version":3,"file":"service.strategy.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/strategies/service.strategy.ts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E,MAAM,EAAE,OAAO,EAAE,CAAC,CAAC;QAE3E,4GAA4G;QAC5G,uGAAuG;QACvG,IAAI,CAAC,SAAS,EAAE,MAAM,EAAE,CAAC;YACvB,IAAI,CAAC,MAAM;iBACR,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC;iBAC3B,IAAI,CAAC,yDAAyD,EAAE,MAAM,CAAC,CAAC;YAC3E,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAE,oBAAoB,CAAC,oBAAoB,EAAE,CAAC,CAAC;QACvE,CAAC;QAED,2FAA2F;QAC3F,OAAO,EAAE,GAAG,SAAS,EAAE,aAAa,EAAE,MAAM,EAAE,CAAC;IACjD,CAAC;CACF,CAAA;AAjDY,6BAA6B;IAOrC,WAAA,MAAM,CAAC;QACN,GAAG,EAAE,WAAW,CAAC,KAAK,CAAC;YACrB,SAAS,EAAE,iBAAiB,CAAC,OAAO;YACpC,GAAG,EAAE,+BAA+B,CAAC,IAAI;SAC1C,CAAC;KACH,CAAC,CAAA;IAED,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,eAAe,EAAE,CAAC,CAAA;qCAD9B,+BAA+B;GAbjD,6BAA6B,CAiDzC","sourcesContent":["import { BaseHelper, getError } from '@venizia/ignis-helpers/core';\nimport { BindingKeys } from '@venizia/ignis-inversion';\nimport type { Env } from 'hono';\nimport {\n AuthenticateBindingKeys,\n Authentication,\n AuthenticationErrors,\n BindingNamespaces,\n ServiceAssertion,\n inject,\n} from '@venizia/ignis-kernel';\nimport type {\n IAuthUser,\n IAuthenticationStrategy,\n IServiceAuthOptions,\n TContext,\n} from '@venizia/ignis-kernel';\nimport { ServiceAssertionVerifierService } from '../services/service/verifier.service';\n\n/**\n * Proves the CALLING SERVICE, from a per-request Ed25519 assertion verified against that caller's\n * own JWKS. No identity round trip and no shared password.\n *\n * It proves which service called, never which user. `resolvePrincipal` is where the application\n * turns a caller name into one of its own principals.\n */\nexport class ServiceAuthenticationStrategy<E extends Env = Env>\n extends BaseHelper\n implements IAuthenticationStrategy<E>\n{\n name = Authentication.STRATEGY_SERVICE;\n\n constructor(\n @inject({\n key: BindingKeys.build({\n namespace: BindingNamespaces.SERVICE,\n key: ServiceAssertionVerifierService.name,\n }),\n })\n private readonly verifier: ServiceAssertionVerifierService,\n @inject({ key: AuthenticateBindingKeys.SERVICE_OPTIONS })\n private readonly options: IServiceAuthOptions<E>,\n ) {\n super({ scope: ServiceAuthenticationStrategy.name });\n }\n\n async authenticate(context: TContext<E, string>): Promise<IAuthUser> {\n const token = context.req.header(ServiceAssertion.HEADER);\n\n if (!token) {\n throw getError({ error: AuthenticationErrors.ASSERTION_MISSING });\n }\n\n // The raw url, NOT `context.req.path`: Hono hands that back percent-DECODED, so a route carrying\n // a space or a non-ASCII slug would never match the encoded path the caller signed.\n const { issuer } = await this.verifier.verify({\n token,\n method: context.req.method,\n path: new URL(context.req.url).pathname,\n });\n\n const principal = await this.options.resolvePrincipal({ issuer, context });\n\n // Validated rather than trusted. The provider also refuses an answer without a `userId`, but a principal an\n // application resolves wrongly is reported here, at the cause, with the issuer and the strategy named.\n if (!principal?.userId) {\n this.logger\n .for(this.authenticate.name)\n .warn('resolvePrincipal returned no usable principal | iss: %s', issuer);\n throw getError({ error: AuthenticationErrors.PRINCIPAL_UNRESOLVED });\n }\n\n // Which service called is audit-relevant even when the principal is shared across callers.\n return { ...principal, callerService: issuer };\n }\n}\n"]}
@@ -9,7 +9,7 @@ export declare abstract class BaseFilteredAdapter<TFilter = ICasbinPolicyFilter>
9
9
  scope: string;
10
10
  dataSource: ICasbinPolicySource;
11
11
  });
12
- protected get connector(): TCasbinPolicyConnector;
12
+ protected resolveConnector(): Promise<TCasbinPolicyConnector>;
13
13
  /** Runs a raw statement and returns its rows. Drizzle's `execute()` shape differs per driver (node-postgres `{ rows }`, postgres-js the row list itself) - never read `.rows` directly. */
14
14
  protected query<TRow>(opts: {
15
15
  statement: SQL;
@@ -8,7 +8,7 @@ export class BaseFilteredAdapter extends BaseHelper {
8
8
  super({ scope: opts.scope });
9
9
  this.dataSource = opts.dataSource;
10
10
  }
11
- get connector() {
11
+ resolveConnector() {
12
12
  return PolicyConnectorResolver.resolve({
13
13
  source: this.dataSource,
14
14
  caller: 'BaseFilteredAdapter',
@@ -16,7 +16,8 @@ export class BaseFilteredAdapter extends BaseHelper {
16
16
  }
17
17
  /** Runs a raw statement and returns its rows. Drizzle's `execute()` shape differs per driver (node-postgres `{ rows }`, postgres-js the row list itself) - never read `.rows` directly. */
18
18
  async query(opts) {
19
- const result = await this.connector.execute(opts.statement);
19
+ const connector = await this.resolveConnector();
20
+ const result = await connector.execute(opts.statement);
20
21
  return DrizzleResultUtility.readResultRows({ result });
21
22
  }
22
23
  isFiltered() {
@@ -1 +1 @@
1
- {"version":3,"file":"base-filtered.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/base-filtered.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAGzD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,0LAA0L;AAC1L,MAAM,OAAgB,mBACpB,SAAQ,UAAU;IAKlB,YAAY,IAAwD;QAClE,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;IACpC,CAAC;IAED,IAAc,SAAS;QACrB,OAAO,uBAAuB,CAAC,OAAO,CAAC;YACrC,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,MAAM,EAAE,qBAAqB;SAC9B,CAAC,CAAC;IACL,CAAC;IAED,2LAA2L;IACjL,KAAK,CAAC,KAAK,CAAO,IAAwB;QAClD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAE5D,OAAO,oBAAoB,CAAC,cAAc,CAAO,EAAE,MAAM,EAAE,CAAC,CAAC;IAC/D,CAAC;IAKD,UAAU;QACR,OAAO,IAAI,CAAC;IACd,CAAC;IAED,4DAA4D;IAC5D,KAAK,CAAC,UAAU,KAAmB,CAAC;IACpC,KAAK,CAAC,UAAU;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,SAAS,KAAmB,CAAC;IACnC,KAAK,CAAC,YAAY,KAAmB,CAAC;IACtC,KAAK,CAAC,oBAAoB,KAAmB,CAAC;IAE9C,+FAA+F;IACrF,KAAK,CAAC,SAAS,CAAC,IAAuC;QAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,YAAY,CAAC,IAAI,EAAE,CAAC;QAE7C,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC9B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;CACF","sourcesContent":["import { DrizzleResultUtility } from '@/utilities';\nimport { BaseHelper } from '@venizia/ignis-helpers/core';\nimport { type FilteredAdapter, type Model } from 'casbin';\nimport type { SQL } from 'drizzle-orm';\nimport { CasbinModule } from '../enforcers/casbin-module';\nimport { PolicyConnectorResolver } from './connector';\nimport type { ICasbinPolicyFilter, ICasbinPolicySource, TCasbinPolicyConnector } from './common';\n\n/** Read-only base for casbin FilteredAdapters backed by a datasource - owns connector plumbing and no-op write methods; subclasses implement {@link loadFilteredPolicy} per principal. */\nexport abstract class BaseFilteredAdapter<TFilter = ICasbinPolicyFilter>\n extends BaseHelper\n implements FilteredAdapter\n{\n protected readonly dataSource: ICasbinPolicySource;\n\n constructor(opts: { scope: string; dataSource: ICasbinPolicySource }) {\n super({ scope: opts.scope });\n this.dataSource = opts.dataSource;\n }\n\n protected get connector(): TCasbinPolicyConnector {\n return PolicyConnectorResolver.resolve({\n source: this.dataSource,\n caller: 'BaseFilteredAdapter',\n });\n }\n\n /** Runs a raw statement and returns its rows. Drizzle's `execute()` shape differs per driver (node-postgres `{ rows }`, postgres-js the row list itself) - never read `.rows` directly. */\n protected async query<TRow>(opts: { statement: SQL }): Promise<TRow[]> {\n const result = await this.connector.execute(opts.statement);\n\n return DrizzleResultUtility.readResultRows<TRow>({ result });\n }\n\n /** Load ONLY the policies matching `filter` into `model` (the store is read for one principal). */\n abstract loadFilteredPolicy(model: Model, filter: TFilter): Promise<void>;\n\n isFiltered(): boolean {\n return true;\n }\n\n // Read-only adapter - write methods are intentional no-ops.\n async loadPolicy(): Promise<void> {}\n async savePolicy(): Promise<boolean> {\n return true;\n }\n\n async addPolicy(): Promise<void> {}\n async removePolicy(): Promise<void> {}\n async removeFilteredPolicy(): Promise<void> {}\n\n /** Parse + load casbin policy lines into a model. Shared by subclasses' loadFilteredPolicy. */\n protected async loadLines(opts: { model: Model; lines: string[] }): Promise<void> {\n const { Helper } = await CasbinModule.load();\n\n for (const line of opts.lines) {\n Helper.loadPolicyLine(line, opts.model);\n }\n }\n}\n"]}
1
+ {"version":3,"file":"base-filtered.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/base-filtered.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAGzD,OAAO,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC1D,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,0LAA0L;AAC1L,MAAM,OAAgB,mBACpB,SAAQ,UAAU;IAKlB,YAAY,IAAwD;QAClE,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;IACpC,CAAC;IAES,gBAAgB;QACxB,OAAO,uBAAuB,CAAC,OAAO,CAAC;YACrC,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,MAAM,EAAE,qBAAqB;SAC9B,CAAC,CAAC;IACL,CAAC;IAED,2LAA2L;IACjL,KAAK,CAAC,KAAK,CAAO,IAAwB;QAClD,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;QAChD,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAEvD,OAAO,oBAAoB,CAAC,cAAc,CAAO,EAAE,MAAM,EAAE,CAAC,CAAC;IAC/D,CAAC;IAKD,UAAU;QACR,OAAO,IAAI,CAAC;IACd,CAAC;IAED,4DAA4D;IAC5D,KAAK,CAAC,UAAU,KAAmB,CAAC;IACpC,KAAK,CAAC,UAAU;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK,CAAC,SAAS,KAAmB,CAAC;IACnC,KAAK,CAAC,YAAY,KAAmB,CAAC;IACtC,KAAK,CAAC,oBAAoB,KAAmB,CAAC;IAE9C,+FAA+F;IACrF,KAAK,CAAC,SAAS,CAAC,IAAuC;QAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,MAAM,YAAY,CAAC,IAAI,EAAE,CAAC;QAE7C,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,KAAK,EAAE,CAAC;YAC9B,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;CACF","sourcesContent":["import { DrizzleResultUtility } from '@/utilities';\nimport { BaseHelper } from '@venizia/ignis-helpers/core';\nimport { type FilteredAdapter, type Model } from 'casbin';\nimport type { SQL } from 'drizzle-orm';\nimport { CasbinModule } from '../enforcers/casbin-module';\nimport { PolicyConnectorResolver } from './connector';\nimport type { ICasbinPolicyFilter, ICasbinPolicySource, TCasbinPolicyConnector } from './common';\n\n/** Read-only base for casbin FilteredAdapters backed by a datasource - owns connector plumbing and no-op write methods; subclasses implement {@link loadFilteredPolicy} per principal. */\nexport abstract class BaseFilteredAdapter<TFilter = ICasbinPolicyFilter>\n extends BaseHelper\n implements FilteredAdapter\n{\n protected readonly dataSource: ICasbinPolicySource;\n\n constructor(opts: { scope: string; dataSource: ICasbinPolicySource }) {\n super({ scope: opts.scope });\n this.dataSource = opts.dataSource;\n }\n\n protected resolveConnector(): Promise<TCasbinPolicyConnector> {\n return PolicyConnectorResolver.resolve({\n source: this.dataSource,\n caller: 'BaseFilteredAdapter',\n });\n }\n\n /** Runs a raw statement and returns its rows. Drizzle's `execute()` shape differs per driver (node-postgres `{ rows }`, postgres-js the row list itself) - never read `.rows` directly. */\n protected async query<TRow>(opts: { statement: SQL }): Promise<TRow[]> {\n const connector = await this.resolveConnector();\n const result = await connector.execute(opts.statement);\n\n return DrizzleResultUtility.readResultRows<TRow>({ result });\n }\n\n /** Load ONLY the policies matching `filter` into `model` (the store is read for one principal). */\n abstract loadFilteredPolicy(model: Model, filter: TFilter): Promise<void>;\n\n isFiltered(): boolean {\n return true;\n }\n\n // Read-only adapter - write methods are intentional no-ops.\n async loadPolicy(): Promise<void> {}\n async savePolicy(): Promise<boolean> {\n return true;\n }\n\n async addPolicy(): Promise<void> {}\n async removePolicy(): Promise<void> {}\n async removeFilteredPolicy(): Promise<void> {}\n\n /** Parse + load casbin policy lines into a model. Shared by subclasses' loadFilteredPolicy. */\n protected async loadLines(opts: { model: Model; lines: string[] }): Promise<void> {\n const { Helper } = await CasbinModule.load();\n\n for (const line of opts.lines) {\n Helper.loadPolicyLine(line, opts.model);\n }\n }\n}\n"]}
@@ -12,6 +12,8 @@ export interface ICasbinPolicyFilter {
12
12
  export type TCasbinPolicyConnector = PgDatabase<PgQueryResultHKT, Record<string, AnyType>>;
13
13
  /** Minimal source the adapters depend on - any drizzle-backed datasource satisfies it. */
14
14
  export interface ICasbinPolicySource {
15
+ /** A datasource that opens on first use opens here; one that opens at start resolves at once. */
16
+ ensureOpen?(): Promise<void>;
15
17
  /** Preferred: lazily wires the driver on first read and survives pool rotation, mirroring repositories. */
16
18
  getConnector?(): TCasbinPolicyConnector;
17
19
  /** Back-compat: a pre-wired connector. Prefer getConnector on a real datasource. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authorize/adapters/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { IdType } from '@/base';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';\n\n/** Filter passed to loadFilteredPolicy: which principal's policies to load. */\nexport interface ICasbinPolicyFilter {\n principal: { type: string; id: IdType };\n}\n\n/** Drizzle connector for policy queries, typed on the shared `PgDatabase` base so postgres-js fits too. Declared here rather than imported from `@/connectors/postgres`: components depend on a minimal local contract, never a connector class. */\nexport type TCasbinPolicyConnector = PgDatabase<PgQueryResultHKT, Record<string, AnyType>>;\n\n/** Minimal source the adapters depend on - any drizzle-backed datasource satisfies it. */\nexport interface ICasbinPolicySource {\n /** Preferred: lazily wires the driver on first read and survives pool rotation, mirroring repositories. */\n getConnector?(): TCasbinPolicyConnector;\n\n /** Back-compat: a pre-wired connector. Prefer getConnector on a real datasource. */\n connector?: TCasbinPolicyConnector;\n}\n\n/** Maps a logical table onto its physical name + schema. */\nexport interface IScopedCasbinTable {\n tableName: string;\n schemaName?: string;\n}\n\n/** All physical mapping the ScopedCasbinAdapter needs. App provides this; framework stays decoupled. */\nexport interface IScopedCasbinEntities {\n policyDefinition: IScopedCasbinTable & {\n metadata?: { columnName: string };\n };\n\n /** Permission catalog (id, code, ...). */\n permission: IScopedCasbinTable;\n\n /** Principal type labels used as casbin name prefixes. */\n principals: { user: string; role: string };\n\n /** Domain type labels (e.g. ['Merchant', 'Organizer']). */\n domainTypes: string[];\n\n /** Soft-delete handling for both tables. */\n softDelete?: { use: false } | { use: true; columnName: string };\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authorize/adapters/common/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { IdType } from '@/base';\nimport type { AnyType } from '@venizia/ignis-helpers/common';\nimport type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core';\n\n/** Filter passed to loadFilteredPolicy: which principal's policies to load. */\nexport interface ICasbinPolicyFilter {\n principal: { type: string; id: IdType };\n}\n\n/** Drizzle connector for policy queries, typed on the shared `PgDatabase` base so postgres-js fits too. Declared here rather than imported from `@/connectors/postgres`: components depend on a minimal local contract, never a connector class. */\nexport type TCasbinPolicyConnector = PgDatabase<PgQueryResultHKT, Record<string, AnyType>>;\n\n/** Minimal source the adapters depend on - any drizzle-backed datasource satisfies it. */\nexport interface ICasbinPolicySource {\n /** A datasource that opens on first use opens here; one that opens at start resolves at once. */\n ensureOpen?(): Promise<void>;\n\n /** Preferred: lazily wires the driver on first read and survives pool rotation, mirroring repositories. */\n getConnector?(): TCasbinPolicyConnector;\n\n /** Back-compat: a pre-wired connector. Prefer getConnector on a real datasource. */\n connector?: TCasbinPolicyConnector;\n}\n\n/** Maps a logical table onto its physical name + schema. */\nexport interface IScopedCasbinTable {\n tableName: string;\n schemaName?: string;\n}\n\n/** All physical mapping the ScopedCasbinAdapter needs. App provides this; framework stays decoupled. */\nexport interface IScopedCasbinEntities {\n policyDefinition: IScopedCasbinTable & {\n metadata?: { columnName: string };\n };\n\n /** Permission catalog (id, code, ...). */\n permission: IScopedCasbinTable;\n\n /** Principal type labels used as casbin name prefixes. */\n principals: { user: string; role: string };\n\n /** Domain type labels (e.g. ['Merchant', 'Organizer']). */\n domainTypes: string[];\n\n /** Soft-delete handling for both tables. */\n softDelete?: { use: false } | { use: true; columnName: string };\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  import type { ICasbinPolicySource, TCasbinPolicyConnector } from './common/index.js';
2
2
  /** Connector-resolution logic shared by every adapter/loader reading the casbin policy store. */
3
3
  export declare class PolicyConnectorResolver {
4
- /** Resolve the wired connector off a policy datasource. */
4
+ /** Resolve the wired connector off a policy datasource, once the datasource is open (one that opens on first use opens here). */
5
5
  static resolve(opts: {
6
6
  source: ICasbinPolicySource;
7
7
  caller: string;
8
- }): TCasbinPolicyConnector;
8
+ }): Promise<TCasbinPolicyConnector>;
9
9
  }
10
10
  //# sourceMappingURL=connector.d.ts.map
@@ -1,9 +1,10 @@
1
1
  import { getError } from '@venizia/ignis-helpers/core';
2
2
  /** Connector-resolution logic shared by every adapter/loader reading the casbin policy store. */
3
3
  export class PolicyConnectorResolver {
4
- /** Resolve the wired connector off a policy datasource. */
5
- static resolve(opts) {
4
+ /** Resolve the wired connector off a policy datasource, once the datasource is open (one that opens on first use opens here). */
5
+ static async resolve(opts) {
6
6
  const { source, caller } = opts;
7
+ await source.ensureOpen?.();
7
8
  const resolved = source.getConnector?.() ?? source.connector;
8
9
  if (!resolved) {
9
10
  throw getError({
@@ -1 +1 @@
1
- {"version":3,"file":"connector.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/connector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD,iGAAiG;AACjG,MAAM,OAAO,uBAAuB;IAClC,2DAA2D;IAC3D,MAAM,CAAC,OAAO,CAAC,IAAqD;QAClE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAChC,MAAM,QAAQ,GAAG,MAAM,CAAC,YAAY,EAAE,EAAE,IAAI,MAAM,CAAC,SAAS,CAAC;QAE7D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,MAAM,gJAAgJ;aACpK,CAAC,CAAC;QACL,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { getError } from '@venizia/ignis-helpers/core';\nimport type { ICasbinPolicySource, TCasbinPolicyConnector } from './common';\n\n/** Connector-resolution logic shared by every adapter/loader reading the casbin policy store. */\nexport class PolicyConnectorResolver {\n /** Resolve the wired connector off a policy datasource. */\n static resolve(opts: { source: ICasbinPolicySource; caller: string }): TCasbinPolicyConnector {\n const { source, caller } = opts;\n const resolved = source.getConnector?.() ?? source.connector;\n\n if (!resolved) {\n throw getError({\n message: `[${caller}] datasource exposes neither a getConnector() accessor nor a wired connector - pass a datasource whose getConnector() lazily wires the driver.`,\n });\n }\n\n return resolved;\n }\n}\n"]}
1
+ {"version":3,"file":"connector.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/connector.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AAGvD,iGAAiG;AACjG,MAAM,OAAO,uBAAuB;IAClC,iIAAiI;IACjI,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAGpB;QACC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;QAEhC,MAAM,MAAM,CAAC,UAAU,EAAE,EAAE,CAAC;QAE5B,MAAM,QAAQ,GAAG,MAAM,CAAC,YAAY,EAAE,EAAE,IAAI,MAAM,CAAC,SAAS,CAAC;QAE7D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACd,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,IAAI,MAAM,gJAAgJ;aACpK,CAAC,CAAC;QACL,CAAC;QAED,OAAO,QAAQ,CAAC;IAClB,CAAC;CACF","sourcesContent":["import { getError } from '@venizia/ignis-helpers/core';\nimport type { ICasbinPolicySource, TCasbinPolicyConnector } from './common';\n\n/** Connector-resolution logic shared by every adapter/loader reading the casbin policy store. */\nexport class PolicyConnectorResolver {\n /** Resolve the wired connector off a policy datasource, once the datasource is open (one that opens on first use opens here). */\n static async resolve(opts: {\n source: ICasbinPolicySource;\n caller: string;\n }): Promise<TCasbinPolicyConnector> {\n const { source, caller } = opts;\n\n await source.ensureOpen?.();\n\n const resolved = source.getConnector?.() ?? source.connector;\n\n if (!resolved) {\n throw getError({\n message: `[${caller}] datasource exposes neither a getConnector() accessor nor a wired connector - pass a datasource whose getConnector() lazily wires the driver.`,\n });\n }\n\n return resolved;\n }\n}\n"]}
@@ -89,7 +89,7 @@ export class CustomGrantExpander extends BaseHelper {
89
89
  return [];
90
90
  }
91
91
  const permissionTable = this.qualifiedTable({ table: this.permission });
92
- const connector = PolicyConnectorResolver.resolve({
92
+ const connector = await PolicyConnectorResolver.resolve({
93
93
  source: this.dataSource,
94
94
  caller: CustomGrantExpander.name,
95
95
  });
@@ -1 +1 @@
1
- {"version":3,"file":"custom-grant-expander.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/custom-grant-expander.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EACL,oBAAoB,EACpB,8BAA8B,EAC9B,2BAA2B,EAC3B,YAAY,GAEb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,GAAG,EAAY,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,MAAM,cAAc,GAAG,QAAQ,CAAC;AAWhC;;;;GAIG;AACH,MAAM,OAAO,mBAAoB,SAAQ,UAAU;IAKjD,YAAY,IAGX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,mBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QAClC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC;IAC7C,CAAC;IAED,yFAAyF;IACzF,eAAe,CAAC,IAKf;QACC,MAAM,EAAE,GAA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IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QACxE,MAAM,SAAS,GAAG,uBAAuB,CAAC,OAAO,CAAC;YAChD,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,MAAM,EAAE,mBAAmB,CAAC,IAAI;SACjC,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,GAAG,CAAA;;aAEjC,eAAe;0DAC8B,GAAG,CAAC,IAAI,CAC1D,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAA,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,CAAC,MAAM,GAAG,CAAC,EAChE,GAAG,CAAA,IAAI,CACR;mCAC4B,8BAA8B,CAAC,oBAAoB,GAAG,IAAI,CAAC,gBAAgB,CACpG,EAAE,KAAK,EAAE,YAAY,EAAE,CACxB;KACJ,CAAC,CAAC;QAEH,OAAO,oBAAoB,CAAC,cAAc,CAKvC;YACD,MAAM;SACP,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type { IdType } from '@/base';\nimport { DrizzleResultUtility } from '@/utilities';\nimport { BaseHelper } from '@venizia/ignis-helpers/core';\nimport {\n AuthorizationActions,\n AuthorizationPermissionBuilder,\n AuthorizationPolicyVariants,\n GrantBuilder,\n type TCustomGrantMetadata,\n} from '@venizia/ignis-kernel';\nimport { sql, type SQL } from 'drizzle-orm';\nimport { PolicyConnectorResolver } from './connector';\nimport type { ICasbinPolicySource, IScopedCasbinEntities } from './common';\n\nconst DEFAULT_SCHEMA = 'public';\n\n/** A custom row that survived {@link CustomGrantExpander.rejectCustomRow}, ready for op-to-catalog resolution. */\nexport type TCustomGrantRow = {\n subjectId: IdType;\n objectSubject: string;\n ops: string[];\n domain: string;\n effect: string;\n};\n\n/**\n * Expands \"custom\" operation-subset grants (`metadata.ops`) into one casbin line per catalogued\n * operation. Isolated from the filtered-policy loader on purpose: it owns its own SQL\n * (`queryOperationCatalog`) and error vocabulary, and never reaches back into ScopedCasbinAdapter.\n */\nexport class CustomGrantExpander extends BaseHelper {\n protected readonly dataSource: ICasbinPolicySource;\n protected readonly permission: IScopedCasbinEntities['permission'];\n protected readonly softDelete: IScopedCasbinEntities['softDelete'];\n\n constructor(opts: {\n dataSource: ICasbinPolicySource;\n entities: Pick<IScopedCasbinEntities, 'permission' | 'softDelete'>;\n }) {\n super({ scope: CustomGrantExpander.name });\n this.dataSource = opts.dataSource;\n this.permission = opts.entities.permission;\n this.softDelete = opts.entities.softDelete;\n }\n\n /** Why a custom-looking grant row cannot be honoured, or null when it is well formed. */\n rejectCustomRow(opts: {\n row: { subjectId: IdType; objectCode: string; objectMethod: string };\n parsed: TCustomGrantMetadata | null;\n isCustomAction: boolean;\n metadataColumnName?: string;\n }): string | null {\n const { row, parsed, isCustomAction, metadataColumnName } = opts;\n\n if (isCustomAction && !metadataColumnName) {\n return `Skipping custom grant - entities.policyDefinition.metadata.columnName is not mapped, so metadata.ops cannot be read | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (isCustomAction && !parsed) {\n return `Skipping custom grant - metadata.ops is missing, empty, or not an array of non-empty strings | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (!isCustomAction && parsed) {\n return `Skipping grant - metadata.ops is present but action is not \"${AuthorizationActions.CUSTOM}\", so the intent is ambiguous | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (row.objectMethod !== AuthorizationPermissionBuilder.RESOURCE_NODE_METHOD) {\n return `Skipping custom grant - the target must be a subject-level resource node | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n return null;\n }\n\n /** Resolve every custom row's ops in one catalog query, then emit one line per resolved operation. Unresolvable ops come back as `rejections` rather than being logged here - the caller owns the logger the tests swap. */\n async expandCustomGrants(opts: {\n subjectType: string;\n customRows: TCustomGrantRow[];\n }): Promise<{ lines: string[]; rejections: string[] }> {\n if (!opts.customRows.length) {\n return { lines: [], rejections: [] };\n }\n\n const seen = new Set<string>();\n const pairs: Array<{ subject: string; method: string }> = [];\n\n const candidates = opts.customRows.flatMap((row) =>\n row.ops.map((op) => ({ subject: row.objectSubject, method: op })),\n );\n\n for (const candidate of candidates) {\n const key = `${candidate.subject}.${candidate.method}`;\n\n if (seen.has(key)) {\n continue;\n }\n\n seen.add(key);\n pairs.push(candidate);\n }\n\n const catalog = await this.queryOperationCatalog({ pairs });\n const byKey = new Map(catalog.map((entry) => [`${entry.subject}.${entry.method}`, entry]));\n const lines: string[] = [];\n const rejections: string[] = [];\n\n for (const row of opts.customRows) {\n const { valid, unknown } = GrantBuilder.getInstance().validateCustomGrantOps({\n ops: row.ops,\n subject: row.objectSubject,\n catalog,\n });\n\n if (unknown.length) {\n rejections.push(\n `Skipping unresolvable operations in a custom grant | subject id: ${row.subjectId} | resource: ${row.objectSubject} | unknown: ${unknown.join(', ')}`,\n );\n }\n\n for (const op of valid) {\n const entry = byKey.get(`${row.objectSubject}.${op}`)!;\n\n lines.push(\n `${AuthorizationPolicyVariants.GRANT.rule}, ${opts.subjectType}_${row.subjectId}, ${row.domain}, ${entry.code}, ${entry.action}, ${row.effect}`,\n );\n }\n }\n\n return { lines, rejections };\n }\n\n /** Schema-qualified table reference (`\"<schema>\".\"<table>\"`) for use after FROM/JOIN with an alias. */\n private qualifiedTable(opts: { table: { schemaName?: string; tableName: string } }): SQL {\n const { table } = opts;\n const schema = table.schemaName ?? DEFAULT_SCHEMA;\n\n return sql`${sql.identifier(schema)}.${sql.identifier(table.tableName)}`;\n }\n\n /** `AND <alias>.<col> IS NULL` when soft-delete is on, else empty. The alias is emitted raw to match the unquoted FROM alias - quoting folds it to a different case and breaks the join. */\n private softDeleteClause(opts: { alias: string }): SQL {\n const sd = this.softDelete;\n\n if (!sd?.use) {\n return sql.empty();\n }\n\n return sql` AND ${sql.raw(opts.alias)}.${sql.identifier(sd.columnName)} IS NULL`;\n }\n\n /** Resolve `(subject, method)` pairs to catalogued operations. One query for the whole extraction. */\n private async queryOperationCatalog(opts: {\n pairs: Array<{ subject: string; method: string }>;\n }): Promise<Array<{ subject: string; method: string; code: string; action: string }>> {\n if (!opts.pairs.length) {\n return [];\n }\n\n const permissionTable = this.qualifiedTable({ table: this.permission });\n const connector = PolicyConnectorResolver.resolve({\n source: this.dataSource,\n caller: CustomGrantExpander.name,\n });\n\n const result = await connector.execute(sql`\n SELECT permission.subject, permission.method, permission.code, permission.action\n FROM ${permissionTable} permission\n WHERE (permission.subject, permission.method) IN (${sql.join(\n opts.pairs.map((pair) => sql`(${pair.subject}, ${pair.method})`),\n sql`, `,\n )})\n AND permission.method <> ${AuthorizationPermissionBuilder.RESOURCE_NODE_METHOD}${this.softDeleteClause(\n { alias: 'permission' },\n )}\n `);\n\n return DrizzleResultUtility.readResultRows<{\n subject: string;\n method: string;\n code: string;\n action: string;\n }>({\n result,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"custom-grant-expander.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authorize/adapters/custom-grant-expander.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EACL,oBAAoB,EACpB,8BAA8B,EAC9B,2BAA2B,EAC3B,YAAY,GAEb,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,GAAG,EAAY,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAGtD,MAAM,cAAc,GAAG,QAAQ,CAAC;AAWhC;;;;GAIG;AACH,MAAM,OAAO,mBAAoB,SAAQ,UAAU;IAKjD,YAAY,IAGX;QACC,KAAK,CAAC,EAAE,KAAK,EAAE,mBAAmB,CAAC,IAAI,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;QAClC,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,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EnC;QACC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,CAAC;YACvB,OAAO,EAAE,CAAC;QACZ,CAAC;QAED,MAAM,eAAe,GAAG,IAAI,CAAC,cAAc,CAAC,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;QACxE,MAAM,SAAS,GAAG,MAAM,uBAAuB,CAAC,OAAO,CAAC;YACtD,MAAM,EAAE,IAAI,CAAC,UAAU;YACvB,MAAM,EAAE,mBAAmB,CAAC,IAAI;SACjC,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,GAAG,CAAA;;aAEjC,eAAe;0DAC8B,GAAG,CAAC,IAAI,CAC1D,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAA,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,CAAC,MAAM,GAAG,CAAC,EAChE,GAAG,CAAA,IAAI,CACR;mCAC4B,8BAA8B,CAAC,oBAAoB,GAAG,IAAI,CAAC,gBAAgB,CACpG,EAAE,KAAK,EAAE,YAAY,EAAE,CACxB;KACJ,CAAC,CAAC;QAEH,OAAO,oBAAoB,CAAC,cAAc,CAKvC;YACD,MAAM;SACP,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type { IdType } from '@/base';\nimport { DrizzleResultUtility } from '@/utilities';\nimport { BaseHelper } from '@venizia/ignis-helpers/core';\nimport {\n AuthorizationActions,\n AuthorizationPermissionBuilder,\n AuthorizationPolicyVariants,\n GrantBuilder,\n type TCustomGrantMetadata,\n} from '@venizia/ignis-kernel';\nimport { sql, type SQL } from 'drizzle-orm';\nimport { PolicyConnectorResolver } from './connector';\nimport type { ICasbinPolicySource, IScopedCasbinEntities } from './common';\n\nconst DEFAULT_SCHEMA = 'public';\n\n/** A custom row that survived {@link CustomGrantExpander.rejectCustomRow}, ready for op-to-catalog resolution. */\nexport type TCustomGrantRow = {\n subjectId: IdType;\n objectSubject: string;\n ops: string[];\n domain: string;\n effect: string;\n};\n\n/**\n * Expands \"custom\" operation-subset grants (`metadata.ops`) into one casbin line per catalogued\n * operation. Isolated from the filtered-policy loader on purpose: it owns its own SQL\n * (`queryOperationCatalog`) and error vocabulary, and never reaches back into ScopedCasbinAdapter.\n */\nexport class CustomGrantExpander extends BaseHelper {\n protected readonly dataSource: ICasbinPolicySource;\n protected readonly permission: IScopedCasbinEntities['permission'];\n protected readonly softDelete: IScopedCasbinEntities['softDelete'];\n\n constructor(opts: {\n dataSource: ICasbinPolicySource;\n entities: Pick<IScopedCasbinEntities, 'permission' | 'softDelete'>;\n }) {\n super({ scope: CustomGrantExpander.name });\n this.dataSource = opts.dataSource;\n this.permission = opts.entities.permission;\n this.softDelete = opts.entities.softDelete;\n }\n\n /** Why a custom-looking grant row cannot be honoured, or null when it is well formed. */\n rejectCustomRow(opts: {\n row: { subjectId: IdType; objectCode: string; objectMethod: string };\n parsed: TCustomGrantMetadata | null;\n isCustomAction: boolean;\n metadataColumnName?: string;\n }): string | null {\n const { row, parsed, isCustomAction, metadataColumnName } = opts;\n\n if (isCustomAction && !metadataColumnName) {\n return `Skipping custom grant - entities.policyDefinition.metadata.columnName is not mapped, so metadata.ops cannot be read | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (isCustomAction && !parsed) {\n return `Skipping custom grant - metadata.ops is missing, empty, or not an array of non-empty strings | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (!isCustomAction && parsed) {\n return `Skipping grant - metadata.ops is present but action is not \"${AuthorizationActions.CUSTOM}\", so the intent is ambiguous | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n if (row.objectMethod !== AuthorizationPermissionBuilder.RESOURCE_NODE_METHOD) {\n return `Skipping custom grant - the target must be a subject-level resource node | subject id: ${row.subjectId} | object: ${row.objectCode}`;\n }\n\n return null;\n }\n\n /** Resolve every custom row's ops in one catalog query, then emit one line per resolved operation. Unresolvable ops come back as `rejections` rather than being logged here - the caller owns the logger the tests swap. */\n async expandCustomGrants(opts: {\n subjectType: string;\n customRows: TCustomGrantRow[];\n }): Promise<{ lines: string[]; rejections: string[] }> {\n if (!opts.customRows.length) {\n return { lines: [], rejections: [] };\n }\n\n const seen = new Set<string>();\n const pairs: Array<{ subject: string; method: string }> = [];\n\n const candidates = opts.customRows.flatMap((row) =>\n row.ops.map((op) => ({ subject: row.objectSubject, method: op })),\n );\n\n for (const candidate of candidates) {\n const key = `${candidate.subject}.${candidate.method}`;\n\n if (seen.has(key)) {\n continue;\n }\n\n seen.add(key);\n pairs.push(candidate);\n }\n\n const catalog = await this.queryOperationCatalog({ pairs });\n const byKey = new Map(catalog.map((entry) => [`${entry.subject}.${entry.method}`, entry]));\n const lines: string[] = [];\n const rejections: string[] = [];\n\n for (const row of opts.customRows) {\n const { valid, unknown } = GrantBuilder.getInstance().validateCustomGrantOps({\n ops: row.ops,\n subject: row.objectSubject,\n catalog,\n });\n\n if (unknown.length) {\n rejections.push(\n `Skipping unresolvable operations in a custom grant | subject id: ${row.subjectId} | resource: ${row.objectSubject} | unknown: ${unknown.join(', ')}`,\n );\n }\n\n for (const op of valid) {\n const entry = byKey.get(`${row.objectSubject}.${op}`)!;\n\n lines.push(\n `${AuthorizationPolicyVariants.GRANT.rule}, ${opts.subjectType}_${row.subjectId}, ${row.domain}, ${entry.code}, ${entry.action}, ${row.effect}`,\n );\n }\n }\n\n return { lines, rejections };\n }\n\n /** Schema-qualified table reference (`\"<schema>\".\"<table>\"`) for use after FROM/JOIN with an alias. */\n private qualifiedTable(opts: { table: { schemaName?: string; tableName: string } }): SQL {\n const { table } = opts;\n const schema = table.schemaName ?? DEFAULT_SCHEMA;\n\n return sql`${sql.identifier(schema)}.${sql.identifier(table.tableName)}`;\n }\n\n /** `AND <alias>.<col> IS NULL` when soft-delete is on, else empty. The alias is emitted raw to match the unquoted FROM alias - quoting folds it to a different case and breaks the join. */\n private softDeleteClause(opts: { alias: string }): SQL {\n const sd = this.softDelete;\n\n if (!sd?.use) {\n return sql.empty();\n }\n\n return sql` AND ${sql.raw(opts.alias)}.${sql.identifier(sd.columnName)} IS NULL`;\n }\n\n /** Resolve `(subject, method)` pairs to catalogued operations. One query for the whole extraction. */\n private async queryOperationCatalog(opts: {\n pairs: Array<{ subject: string; method: string }>;\n }): Promise<Array<{ subject: string; method: string; code: string; action: string }>> {\n if (!opts.pairs.length) {\n return [];\n }\n\n const permissionTable = this.qualifiedTable({ table: this.permission });\n const connector = await PolicyConnectorResolver.resolve({\n source: this.dataSource,\n caller: CustomGrantExpander.name,\n });\n\n const result = await connector.execute(sql`\n SELECT permission.subject, permission.method, permission.code, permission.action\n FROM ${permissionTable} permission\n WHERE (permission.subject, permission.method) IN (${sql.join(\n opts.pairs.map((pair) => sql`(${pair.subject}, ${pair.method})`),\n sql`, `,\n )})\n AND permission.method <> ${AuthorizationPermissionBuilder.RESOURCE_NODE_METHOD}${this.softDeleteClause(\n { alias: 'permission' },\n )}\n `);\n\n return DrizzleResultUtility.readResultRows<{\n subject: string;\n method: string;\n code: string;\n action: string;\n }>({\n result,\n });\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { Environment } from '@venizia/ignis-helpers';
1
+ import { Environment, Hash } from '@venizia/ignis-helpers';
2
2
  import { BuildInfoRegistry } from '@venizia/ignis-helpers/core';
3
3
  /**
4
4
  * Assembles what `GET /health` and `GET /health/stats` answer.
@@ -76,7 +76,7 @@ export class HealthCheckReporter {
76
76
  if (typeof secretKey !== 'string' || secretKey.trim().length === 0) {
77
77
  return false;
78
78
  }
79
- return opts.header === secretKey;
79
+ return Hash.equals({ value: opts.header ?? '', expected: secretKey });
80
80
  }
81
81
  /** The slot is a process-wide `globalThis` entry any dependency can write, and `IBuildInfo` types it without checking - so a non-string never reaches the response schema, which declares `z.string()`. */
82
82
  static extractText(opts) {