@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.
- package/README.md +7 -14
- package/dist/esm/base/applications/server.d.ts +12 -0
- package/dist/esm/base/applications/server.js +11 -0
- package/dist/esm/base/applications/server.js.map +1 -1
- package/dist/esm/base/middlewares/request-spy/request-spy.middleware.d.ts +1 -0
- package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js +9 -2
- package/dist/esm/base/middlewares/request-spy/request-spy.middleware.js.map +1 -1
- package/dist/esm/components/auth/authenticate/component.js +37 -1
- package/dist/esm/components/auth/authenticate/component.js.map +1 -1
- package/dist/esm/components/auth/authenticate/controllers/factory.d.ts +1 -0
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.d.ts +56 -5
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js +115 -11
- package/dist/esm/components/auth/authenticate/services/bearer/abstract.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js +2 -2
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/issuer.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js +10 -3
- package/dist/esm/components/auth/authenticate/services/bearer/jwks/verifier.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/bearer/jws.service.d.ts +11 -0
- package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js +25 -3
- package/dist/esm/components/auth/authenticate/services/bearer/jws.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/index.d.ts +1 -0
- package/dist/esm/components/auth/authenticate/services/index.js +1 -0
- package/dist/esm/components/auth/authenticate/services/index.js.map +1 -1
- package/dist/esm/components/auth/authenticate/services/jwks-url-policy.d.ts +42 -0
- package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js +162 -0
- package/dist/esm/components/auth/authenticate/services/jwks-url-policy.js.map +1 -0
- package/dist/esm/components/auth/authenticate/services/service/verifier.service.js +7 -1
- package/dist/esm/components/auth/authenticate/services/service/verifier.service.js.map +1 -1
- package/dist/esm/components/auth/authenticate/strategies/service.strategy.js +2 -4
- package/dist/esm/components/auth/authenticate/strategies/service.strategy.js.map +1 -1
- package/dist/esm/components/auth/authorize/adapters/base-filtered.d.ts +1 -1
- package/dist/esm/components/auth/authorize/adapters/base-filtered.js +3 -2
- package/dist/esm/components/auth/authorize/adapters/base-filtered.js.map +1 -1
- package/dist/esm/components/auth/authorize/adapters/common/types.d.ts +2 -0
- package/dist/esm/components/auth/authorize/adapters/common/types.js.map +1 -1
- package/dist/esm/components/auth/authorize/adapters/connector.d.ts +2 -2
- package/dist/esm/components/auth/authorize/adapters/connector.js +3 -2
- package/dist/esm/components/auth/authorize/adapters/connector.js.map +1 -1
- package/dist/esm/components/auth/authorize/adapters/custom-grant-expander.js +1 -1
- package/dist/esm/components/auth/authorize/adapters/custom-grant-expander.js.map +1 -1
- package/dist/esm/components/health-check/reporter.js +2 -2
- package/dist/esm/components/health-check/reporter.js.map +1 -1
- package/dist/esm/components/index.d.ts +1 -0
- package/dist/esm/components/index.js +1 -0
- package/dist/esm/components/index.js.map +1 -1
- package/dist/esm/components/mail/common/types/verification.d.ts +1 -0
- package/dist/esm/components/mail/common/types/verification.js.map +1 -1
- package/dist/esm/components/mail/services/generators/numeric-code.d.ts +1 -6
- package/dist/esm/components/mail/services/generators/numeric-code.js +3 -31
- package/dist/esm/components/mail/services/generators/numeric-code.js.map +1 -1
- package/dist/esm/components/mail/services/generators/random-token.d.ts +4 -1
- package/dist/esm/components/mail/services/generators/random-token.js +9 -6
- package/dist/esm/components/mail/services/generators/random-token.js.map +1 -1
- package/dist/esm/components/mail/utilities/mime.utility.js +4 -4
- package/dist/esm/components/mail/utilities/mime.utility.js.map +1 -1
- package/dist/esm/components/server-info/common/constants.d.ts +6 -0
- package/dist/esm/components/server-info/common/constants.js +6 -0
- package/dist/esm/components/server-info/common/constants.js.map +1 -0
- package/dist/esm/components/server-info/common/index.d.ts +5 -0
- package/dist/esm/components/server-info/common/index.js +5 -0
- package/dist/esm/components/server-info/common/index.js.map +1 -0
- package/dist/esm/components/server-info/common/keys.d.ts +5 -0
- package/dist/esm/components/server-info/common/keys.js +5 -0
- package/dist/esm/components/server-info/common/keys.js.map +1 -0
- package/dist/esm/components/server-info/common/rest-paths.d.ts +5 -0
- package/dist/esm/components/server-info/common/rest-paths.js +5 -0
- package/dist/esm/components/server-info/common/rest-paths.js.map +1 -0
- package/dist/esm/components/server-info/common/types.d.ts +68 -0
- package/dist/esm/components/server-info/common/types.js +2 -0
- package/dist/esm/components/server-info/common/types.js.map +1 -0
- package/dist/esm/components/server-info/component.d.ts +31 -0
- package/dist/esm/components/server-info/component.js +87 -0
- package/dist/esm/components/server-info/component.js.map +1 -0
- package/dist/esm/components/server-info/controller.d.ts +14 -0
- package/dist/esm/components/server-info/controller.js +68 -0
- package/dist/esm/components/server-info/controller.js.map +1 -0
- package/dist/esm/components/server-info/index.d.ts +5 -0
- package/dist/esm/components/server-info/index.js +5 -0
- package/dist/esm/components/server-info/index.js.map +1 -0
- package/dist/esm/components/server-info/reporter.d.ts +25 -0
- package/dist/esm/components/server-info/reporter.js +68 -0
- package/dist/esm/components/server-info/reporter.js.map +1 -0
- package/dist/esm/components/static-asset/common/constants.d.ts +2 -0
- package/dist/esm/components/static-asset/common/constants.js +2 -0
- package/dist/esm/components/static-asset/common/constants.js.map +1 -1
- package/dist/esm/components/static-asset/common/types.d.ts +6 -0
- package/dist/esm/components/static-asset/common/types.js.map +1 -1
- package/dist/esm/components/static-asset/controller/base.definition.d.ts +2 -0
- package/dist/esm/components/static-asset/controller/base.definition.js +6 -4
- package/dist/esm/components/static-asset/controller/base.definition.js.map +1 -1
- package/dist/esm/components/static-asset/controller/factory.d.ts +1 -0
- package/dist/esm/components/static-asset/controller/factory.js +17 -9
- package/dist/esm/components/static-asset/controller/factory.js.map +1 -1
- package/dist/esm/components/static-asset/controller/meta-link.js +1 -1
- package/dist/esm/components/static-asset/controller/meta-link.js.map +1 -1
- package/dist/esm/components/static-asset/controller/route-options.d.ts +9 -0
- package/dist/esm/components/static-asset/controller/route-options.js +16 -3
- package/dist/esm/components/static-asset/controller/route-options.js.map +1 -1
- package/dist/esm/components/static-asset/ingest.d.ts +2 -2
- package/dist/esm/components/static-asset/ingest.js +2 -2
- package/dist/esm/components/static-asset/ingest.js.map +1 -1
- package/dist/esm/testing/assert-application-boots.d.ts +9 -0
- package/dist/esm/testing/assert-application-boots.js +11 -1
- package/dist/esm/testing/assert-application-boots.js.map +1 -1
- package/dist/presets/app/preset.json +4 -4
- package/dist/presets/lib/preset.json +3 -3
- package/dist/presets/shared/preset.json +1 -1
- package/package.json +8 -8
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { AES } from '@venizia/ignis-helpers';
|
|
2
2
|
import { HTTP } from '@venizia/ignis-helpers/common';
|
|
3
|
-
import { getError } from '@venizia/ignis-helpers/core';
|
|
4
|
-
import { Authentication, AuthenticationErrors, BaseService } from '@venizia/ignis-kernel';
|
|
3
|
+
import { getError, RecordUtility } from '@venizia/ignis-helpers/core';
|
|
4
|
+
import { Authentication, AuthenticationErrors, BaseService, ServiceAssertion, } from '@venizia/ignis-kernel';
|
|
5
|
+
import { JoseLoader } from '../jose-loader.js';
|
|
5
6
|
/** Abstract base for Bearer-token services (JWS, JWKS) with optional AES payload encryption. */
|
|
6
7
|
export class AbstractBearerTokenService extends BaseService {
|
|
7
8
|
constructor() {
|
|
@@ -9,8 +10,10 @@ export class AbstractBearerTokenService extends BaseService {
|
|
|
9
10
|
this.aes = null;
|
|
10
11
|
this.applicationSecret = null;
|
|
11
12
|
this.fieldCodecs = new Map();
|
|
12
|
-
/** Configured `iss` / `aud
|
|
13
|
-
this.
|
|
13
|
+
/** Configured `iss` / `aud`: stamped on every issued token, authoritative over anything the payload carries, and required on every verified one. */
|
|
14
|
+
this.claimOptions = null;
|
|
15
|
+
/** What jose verifies against: the claims, the algorithm pin and the `verify` checks. */
|
|
16
|
+
this.verifyOptions = null;
|
|
14
17
|
}
|
|
15
18
|
/** Standard JWT fields that are never encrypted. */
|
|
16
19
|
static { this.JWT_COMMON_FIELDS = new Set([
|
|
@@ -22,10 +25,85 @@ export class AbstractBearerTokenService extends BaseService {
|
|
|
22
25
|
'exp',
|
|
23
26
|
'iat',
|
|
24
27
|
]); }
|
|
28
|
+
/** The keys a `claims` object may hold. */
|
|
29
|
+
static { this.CLAIM_KEYS = ['issuer', 'audience']; }
|
|
30
|
+
/**
|
|
31
|
+
* Validates the claims configuration of a token service and answers what the service uses. It throws, naming the
|
|
32
|
+
* key, when `claims.issuer` is missing or empty, when `claims.audience` is present but not a non-empty string or a
|
|
33
|
+
* non-empty list of them, when `claims` holds another key, when the removed `sign` or `verify.issuer` /
|
|
34
|
+
* `verify.audience` is still passed, and when no algorithm is pinned. `claims.audience` is optional: without it
|
|
35
|
+
* no `aud` is stamped and none is checked.
|
|
36
|
+
* `pinnedAlgorithms` is what the service signs with; a verifier has none and requires `verify.algorithms`.
|
|
37
|
+
* The component calls it at boot, and a service calls it when it is built, so neither can start without them.
|
|
38
|
+
*/
|
|
39
|
+
static resolveClaimsConfig(opts) {
|
|
40
|
+
const { scope, options, pinnedAlgorithms } = opts;
|
|
41
|
+
const fail = (detail) => getError({
|
|
42
|
+
statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
|
|
43
|
+
message: `[${scope}] ${detail}`,
|
|
44
|
+
});
|
|
45
|
+
if (options.sign !== undefined) {
|
|
46
|
+
throw fail('`sign` was removed | put the issuer and the audience in `claims: { issuer, audience }`: they are stamped on every token and required on every verified one');
|
|
47
|
+
}
|
|
48
|
+
if (options.verify !== undefined && !RecordUtility.isPlainRecord(options.verify)) {
|
|
49
|
+
throw fail('verify must be an object | its checks (maxTokenAge, subject, ...) would be dropped silently');
|
|
50
|
+
}
|
|
51
|
+
const verify = RecordUtility.isPlainRecord(options.verify) ? options.verify : {};
|
|
52
|
+
for (const key of AbstractBearerTokenService.CLAIM_KEYS) {
|
|
53
|
+
if (key in verify) {
|
|
54
|
+
throw fail(`verify.${key} was removed | set claims.${key}: it is stamped on every token and required on every verified one`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const { claims } = options;
|
|
58
|
+
if (!RecordUtility.isPlainRecord(claims)) {
|
|
59
|
+
throw fail('claims is required | pass claims: { issuer: string, audience: string | string[] }: a token signed with the same key for another purpose must not authenticate a request');
|
|
60
|
+
}
|
|
61
|
+
const unknown = Object.keys(claims).filter((key) => !AbstractBearerTokenService.CLAIM_KEYS.includes(key));
|
|
62
|
+
if (unknown.length > 0) {
|
|
63
|
+
throw fail(`claims holds unknown keys ${JSON.stringify(unknown)} | accepted: ${AbstractBearerTokenService.CLAIM_KEYS.join(', ')}`);
|
|
64
|
+
}
|
|
65
|
+
const { issuer, audience } = claims;
|
|
66
|
+
const isName = (value) => typeof value === 'string' && value.trim().length > 0;
|
|
67
|
+
if (!isName(issuer)) {
|
|
68
|
+
throw fail('claims.issuer is required | a non-empty string');
|
|
69
|
+
}
|
|
70
|
+
// Optional, but a present value is checked: `null`, `''` and `[]` are mistakes, not "no audience".
|
|
71
|
+
if (audience !== undefined &&
|
|
72
|
+
!isName(audience) &&
|
|
73
|
+
!(Array.isArray(audience) && audience.length > 0 && audience.every(isName))) {
|
|
74
|
+
throw fail('claims.audience must be a non-empty string or a non-empty list of them | or leave it out');
|
|
75
|
+
}
|
|
76
|
+
const resolvedAudience = Array.isArray(audience) ? [...audience] : audience;
|
|
77
|
+
const algorithms = verify.algorithms ?? pinnedAlgorithms;
|
|
78
|
+
if (!Array.isArray(algorithms) || algorithms.length === 0 || !algorithms.every(isName)) {
|
|
79
|
+
throw fail("verify.algorithms is required | the accepted JWS algorithms, for example ['RS256']: a verifier cannot know what the issuer signs with");
|
|
80
|
+
}
|
|
81
|
+
if (algorithms.some((algorithm) => algorithm.trim().toLowerCase() === 'none')) {
|
|
82
|
+
throw fail("the algorithm 'none' is refused | a token with no signature verifies nothing");
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
claims: { issuer, ...(resolvedAudience === undefined ? {} : { audience: resolvedAudience }) },
|
|
86
|
+
verify: {
|
|
87
|
+
...verify,
|
|
88
|
+
issuer,
|
|
89
|
+
...(resolvedAudience === undefined ? {} : { audience: resolvedAudience }),
|
|
90
|
+
algorithms: [...algorithms],
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** Validates the claims configuration (see {@link AbstractBearerTokenService.resolveClaimsConfig}) and keeps the result. */
|
|
95
|
+
configureClaims(opts) {
|
|
96
|
+
const resolved = AbstractBearerTokenService.resolveClaimsConfig({
|
|
97
|
+
scope: this.scope,
|
|
98
|
+
options: opts.options,
|
|
99
|
+
pinnedAlgorithms: opts.pinnedAlgorithms,
|
|
100
|
+
});
|
|
101
|
+
this.claimOptions = resolved.claims;
|
|
102
|
+
this.verifyOptions = resolved.verify;
|
|
103
|
+
}
|
|
25
104
|
/** Configures AES payload encryption and field codecs. Both aesAlgorithm and applicationSecret required to activate encryption. */
|
|
26
105
|
configurePayloadEncryption(opts) {
|
|
27
|
-
const { aesAlgorithm = 'aes-256-cbc', applicationSecret, fieldCodecs
|
|
28
|
-
this.signOptions = sign ?? null;
|
|
106
|
+
const { aesAlgorithm = 'aes-256-cbc', applicationSecret, fieldCodecs } = opts;
|
|
29
107
|
if (fieldCodecs) {
|
|
30
108
|
for (const codec of fieldCodecs) {
|
|
31
109
|
this.fieldCodecs.set(codec.key, codec);
|
|
@@ -72,6 +150,7 @@ export class AbstractBearerTokenService extends BaseService {
|
|
|
72
150
|
});
|
|
73
151
|
}
|
|
74
152
|
try {
|
|
153
|
+
await this.assertNotServiceAssertion({ token });
|
|
75
154
|
const result = await this.doVerify(token);
|
|
76
155
|
return result;
|
|
77
156
|
}
|
|
@@ -85,6 +164,21 @@ export class AbstractBearerTokenService extends BaseService {
|
|
|
85
164
|
});
|
|
86
165
|
}
|
|
87
166
|
}
|
|
167
|
+
/**
|
|
168
|
+
* A service assertion (`typ: svc+jwt`) is not a user token. When a JWKS issuer shares the key of the service
|
|
169
|
+
* assertions and the names collide, an assertion would otherwise verify here, so the user-token path refuses it.
|
|
170
|
+
*/
|
|
171
|
+
async assertNotServiceAssertion(opts) {
|
|
172
|
+
const { decodeProtectedHeader } = await JoseLoader.load();
|
|
173
|
+
const { typ } = decodeProtectedHeader(opts.token);
|
|
174
|
+
const kind = typeof typ === 'string' ? typ.toLowerCase().replace(/^application\//, '') : '';
|
|
175
|
+
if (kind === ServiceAssertion.TYP) {
|
|
176
|
+
throw getError({
|
|
177
|
+
error: AuthenticationErrors.TOKEN_INVALID,
|
|
178
|
+
message: '[verify] A service assertion is not a user token',
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
}
|
|
88
182
|
async generate(opts) {
|
|
89
183
|
const { payload, claims, getTokenExpiresFn = this.getDefaultTokenExpiresFn() } = opts;
|
|
90
184
|
if (!payload) {
|
|
@@ -107,14 +201,21 @@ export class AbstractBearerTokenService extends BaseService {
|
|
|
107
201
|
});
|
|
108
202
|
}
|
|
109
203
|
}
|
|
204
|
+
/** A `null` is written as `null` whatever the field's codec is: a codec converts a value, and `null` is none. */
|
|
110
205
|
serializeField(opts) {
|
|
111
206
|
const { key, value } = opts;
|
|
112
|
-
const codec = this.fieldCodecs.get(key);
|
|
207
|
+
const codec = value === null ? undefined : this.fieldCodecs.get(key);
|
|
113
208
|
if (codec) {
|
|
114
209
|
return codec.serialize({ value });
|
|
115
210
|
}
|
|
116
211
|
return JSON.stringify(value);
|
|
117
212
|
}
|
|
213
|
+
/**
|
|
214
|
+
* With `applicationSecret` set, AES-encrypts the key and the value of every claim outside `JWT_COMMON_FIELDS`;
|
|
215
|
+
* without it, returns the payload as is. A `null` claim is encrypted like any other value and decodes as `null`,
|
|
216
|
+
* so the token decodes to the same payload with encryption on or off and `null` stays distinct from absent. An
|
|
217
|
+
* `undefined` claim is skipped, as JSON drops it.
|
|
218
|
+
*/
|
|
118
219
|
async encryptPayload(payload) {
|
|
119
220
|
if (!this.aes || !this.applicationSecret) {
|
|
120
221
|
return payload;
|
|
@@ -127,8 +228,10 @@ export class AbstractBearerTokenService extends BaseService {
|
|
|
127
228
|
rs[key] = value;
|
|
128
229
|
continue;
|
|
129
230
|
}
|
|
130
|
-
//
|
|
131
|
-
|
|
231
|
+
// Only `undefined` is skipped: JSON drops it too, so the claim is absent either way. `null` is a value, and
|
|
232
|
+
// `serializeField` writes it as `null`, which `deserializeField` reads back, so an encrypted token decodes the
|
|
233
|
+
// same payload as a plain one.
|
|
234
|
+
if (value === undefined) {
|
|
132
235
|
continue;
|
|
133
236
|
}
|
|
134
237
|
const encryptedKey = await this.aes.encrypt({
|
|
@@ -144,9 +247,10 @@ export class AbstractBearerTokenService extends BaseService {
|
|
|
144
247
|
}
|
|
145
248
|
return rs;
|
|
146
249
|
}
|
|
250
|
+
/** The text `null` reads as `null` before any codec sees it, the other half of {@link serializeField}. */
|
|
147
251
|
deserializeField(opts) {
|
|
148
252
|
const { key, value } = opts;
|
|
149
|
-
const codec = this.fieldCodecs.get(key);
|
|
253
|
+
const codec = value === 'null' ? undefined : this.fieldCodecs.get(key);
|
|
150
254
|
if (codec) {
|
|
151
255
|
return codec.deserialize({ raw: value });
|
|
152
256
|
}
|
|
@@ -165,7 +269,7 @@ export class AbstractBearerTokenService extends BaseService {
|
|
|
165
269
|
*/
|
|
166
270
|
applySignClaims(opts) {
|
|
167
271
|
const { signer, payload, claims } = opts;
|
|
168
|
-
const configured = this.
|
|
272
|
+
const configured = this.claimOptions;
|
|
169
273
|
const issuer = claims?.issuer ?? configured?.issuer;
|
|
170
274
|
const audience = claims?.audience ?? configured?.audience;
|
|
171
275
|
const logger = this.logger.for(this.applySignClaims.name);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"abstract.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/bearer/abstract.service.ts"],"names":[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ACX,CAAC;YAED,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC;gBAC1C,OAAO,EAAE,GAAG;gBACZ,MAAM,EAAE,IAAI,CAAC,iBAAiB;aAC/B,CAAC,CAAC;YACH,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC;gBAC5C,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC;gBACrB,MAAM,EAAE,IAAI,CAAC,iBAAiB;aAC/B,CAAC,CAAC;YAEH,EAAE,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,EAAE,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC;QACzF,CAAC;QAED,OAAO,EAAE,CAAC;IACZ,CAAC","sourcesContent":["import type { AESAlgorithmType } from '@venizia/ignis-helpers';\nimport { AES } from '@venizia/ignis-helpers';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport type {\n IJWTIssueClaims,\n IJWTSignOptions,\n IJWTTokenPayload,\n IPayloadFieldCodec,\n TContext,\n TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { Authentication, AuthenticationErrors, BaseService } from '@venizia/ignis-kernel';\nimport type { Env } from 'hono';\nimport type { JWTPayload, JWTVerifyResult, SignJWT } from 'jose';\n\n/** Abstract base for Bearer-token services (JWS, JWKS) with optional AES payload encryption. */\nexport abstract class AbstractBearerTokenService<E extends Env = Env> extends BaseService {\n /** Standard JWT fields that are never encrypted. */\n static readonly JWT_COMMON_FIELDS = new Set<keyof JWTPayload>([\n 'iss',\n 'sub',\n 'aud',\n 'jti',\n 'nbf',\n 'exp',\n 'iat',\n ]);\n\n protected aes: AES | null = null;\n protected applicationSecret: string | null = null;\n protected fieldCodecs: Map<string, IPayloadFieldCodec> = new Map();\n\n /** Configured `iss` / `aud`. Authoritative over anything the payload carries. */\n protected signOptions: IJWTSignOptions | null = null;\n\n /** Configures AES payload encryption and field codecs. Both aesAlgorithm and applicationSecret required to activate encryption. */\n protected configurePayloadEncryption(opts: {\n aesAlgorithm?: AESAlgorithmType;\n applicationSecret?: string;\n fieldCodecs?: IPayloadFieldCodec[];\n sign?: IJWTSignOptions;\n }): void {\n const { aesAlgorithm = 'aes-256-cbc', applicationSecret, fieldCodecs, sign } = opts;\n\n this.signOptions = sign ?? null;\n\n if (fieldCodecs) {\n for (const codec of fieldCodecs) {\n this.fieldCodecs.set(codec.key, codec);\n }\n }\n\n if (!applicationSecret) {\n return;\n }\n\n this.aes = AES.withAlgorithm(aesAlgorithm);\n this.applicationSecret = applicationSecret;\n }\n\n extractCredentials(context: TContext<E, string>): { type: string; token: string } {\n const request = context.req;\n\n const authHeaderValue = request.header('Authorization');\n\n if (!authHeaderValue) {\n throw getError({\n error: AuthenticationErrors.HEADER_MISSING,\n message: 'Unauthorized user! Missing authorization header',\n });\n }\n\n if (!authHeaderValue.startsWith(Authentication.TYPE_BEARER)) {\n throw getError({\n error: AuthenticationErrors.SCHEME_INVALID,\n message: 'Unauthorized user! Invalid schema of request token!',\n });\n }\n\n const parts = authHeaderValue.split(' ');\n\n if (parts.length !== 2) {\n throw getError({\n error: AuthenticationErrors.HEADER_MALFORMED,\n message: `Authorization header value is invalid format. It must follow the pattern: 'Bearer xx.yy.zz' where xx.yy.zz is a valid JWT token.`,\n });\n }\n\n const [tokenType, tokenValue] = parts;\n\n return { type: tokenType, token: tokenValue };\n }\n\n async verify(opts: { type: string; token: string }): Promise<IJWTTokenPayload> {\n const { token } = opts;\n\n if (!token) {\n this.logger.for(this.verify.name).error('Missing token for validating request!');\n throw getError({\n error: AuthenticationErrors.TOKEN_MISSING,\n message: '[verify] Invalid request token!',\n });\n }\n\n try {\n const result = await this.doVerify(token);\n\n return result;\n } catch (error) {\n // No log here - `cause` carries the reason (JWTExpired, signature mismatch) to the error handler, which logs the request once. An expired token is the caller's problem, hence `warn`.\n throw getError({\n error: AuthenticationErrors.TOKEN_INVALID,\n message: '[verify] Invalid or expired token',\n logLevel: 'warn',\n cause: error,\n });\n }\n }\n\n async generate(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn?: TGetTokenExpiresFn;\n /** Per-token registered claims. The supported way to vary `aud` / `sub`; the payload is not. */\n claims?: IJWTIssueClaims;\n }): Promise<string> {\n const { payload, claims, getTokenExpiresFn = this.getDefaultTokenExpiresFn() } = opts;\n\n if (!payload) {\n throw getError({\n error: AuthenticationErrors.TOKEN_PAYLOAD_INVALID,\n message: '[generate] Invalid token payload!',\n });\n }\n\n const signer = await this.getSigner({ payload, getTokenExpiresFn, claims });\n\n try {\n const result = await this.getSigningKey();\n const rs = await signer.sign(result);\n\n return rs;\n } catch (error) {\n this.logger.for(this.generate.name).error('Failed to generate token | Error: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[generate] Failed to generate token',\n });\n }\n }\n\n protected serializeField(opts: { key: string; value: any }): string {\n const { key, value } = opts;\n const codec = this.fieldCodecs.get(key);\n\n if (codec) {\n return codec.serialize({ value });\n }\n\n return JSON.stringify(value);\n }\n\n async encryptPayload(payload: IJWTTokenPayload): Promise<Record<string, any>> {\n if (!this.aes || !this.applicationSecret) {\n return payload;\n }\n\n const rs: Record<string, string> = {};\n\n const keys = Object.keys(payload);\n\n for (const key of keys) {\n const value = payload[key];\n\n if (AbstractBearerTokenService.JWT_COMMON_FIELDS.has(key)) {\n rs[key] = value;\n continue;\n }\n\n // NOTE: Skip undefined or null values because they cannot be encrypted\n if (value === undefined || value === null) {\n continue;\n }\n\n const encryptedKey = await this.aes.encrypt({\n message: key,\n secret: this.applicationSecret,\n });\n\n const serialized = this.serializeField({ key, value });\n\n const encryptedValue = await this.aes.encrypt({\n message: serialized,\n secret: this.applicationSecret,\n });\n rs[encryptedKey] = encryptedValue;\n }\n\n return rs;\n }\n\n protected deserializeField(opts: { key: string; value: string }) {\n const { key, value } = opts;\n const codec = this.fieldCodecs.get(key);\n\n if (codec) {\n return codec.deserialize({ raw: value });\n }\n\n return JSON.parse(value);\n }\n\n /**\n * Stamps the configured `iss` / `aud` onto a signer, plus any per-token claims the caller passed.\n *\n * The configured value is AUTHORITATIVE. `iss` and `aud` are in `JWT_COMMON_FIELDS`, so they ride\n * through the AES envelope in the clear and an application-shaped payload can carry them - an\n * issuer identity any payload could overwrite would not be an identity. A conflicting payload\n * claim is overwritten and reported.\n *\n * Per-token audience is an explicit argument rather than a smuggled payload key, so the caller\n * that legitimately needs one says so.\n */\n protected applySignClaims(opts: {\n signer: SignJWT;\n payload: Record<string, any>;\n claims?: IJWTIssueClaims;\n }): SignJWT {\n const { signer, payload, claims } = opts;\n const configured = this.signOptions;\n\n const issuer = claims?.issuer ?? configured?.issuer;\n const audience = claims?.audience ?? configured?.audience;\n\n const logger = this.logger.for(this.applySignClaims.name);\n\n if (issuer !== undefined) {\n if (payload.iss !== undefined && payload.iss !== issuer) {\n logger.warn(\n 'Payload iss overridden by the configured issuer | payload: %s | configured: %s',\n payload.iss,\n issuer,\n );\n }\n\n signer.setIssuer(issuer);\n }\n\n if (audience !== undefined) {\n if (payload.aud !== undefined) {\n logger.warn('Payload aud overridden | payload: %j | applied: %j', payload.aud, audience);\n }\n\n signer.setAudience(audience);\n }\n\n if (claims?.subject !== undefined) {\n signer.setSubject(claims.subject);\n }\n\n if (claims?.jwtId !== undefined) {\n signer.setJti(claims.jwtId);\n }\n\n return signer;\n }\n\n async decryptPayload(opts: {\n result: JWTVerifyResult<IJWTTokenPayload>;\n }): Promise<IJWTTokenPayload> {\n const { payload, protectedHeader } = opts.result;\n\n if (!this.aes || !this.applicationSecret) {\n return payload as IJWTTokenPayload;\n }\n\n this.logger\n .for(this.decryptPayload.name)\n .debug('JWT Token | payload: %j | header: %j', payload, protectedHeader);\n\n const rs: any = {};\n\n for (const key in payload) {\n if (AbstractBearerTokenService.JWT_COMMON_FIELDS.has(key)) {\n rs[key] = payload[key];\n continue;\n }\n\n const decryptedKey = await this.aes.decrypt({\n message: key,\n secret: this.applicationSecret,\n });\n const decryptedValue = await this.aes.decrypt({\n message: payload[key],\n secret: this.applicationSecret,\n });\n\n rs[decryptedKey] = this.deserializeField({ key: decryptedKey, value: decryptedValue });\n }\n\n return rs;\n }\n\n protected abstract doVerify(token: string): Promise<IJWTTokenPayload>;\n\n abstract getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }): Promise<SignJWT>;\n\n protected abstract getSigningKey(): ValueOrPromise<Uint8Array | CryptoKey>;\n\n protected abstract getDefaultTokenExpiresFn(): TGetTokenExpiresFn;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"abstract.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/bearer/abstract.service.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,GAAG,EAAE,MAAM,wBAAwB,CAAC;AAE7C,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AAUtE,OAAO,EACL,cAAc,EACd,oBAAoB,EACpB,WAAW,EACX,gBAAgB,GACjB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAiB5C,gGAAgG;AAChG,MAAM,OAAgB,0BAAgD,SAAQ,WAAW;IAAzF;;QAYY,QAAG,GAAe,IAAI,CAAC;QACvB,sBAAiB,GAAkB,IAAI,CAAC;QACxC,gBAAW,GAAoC,IAAI,GAAG,EAAE,CAAC;QAEnE,oJAAoJ;QAC1I,iBAAY,GAA6B,IAAI,CAAC;QAExD,yFAAyF;QAC/E,kBAAa,GAA4B,IAAI,CAAC;IA4a1D,CAAC;IA/bC,oDAAoD;aACpC,sBAAiB,GAAG,IAAI,GAAG,CAAmB;QAC5D,KAAK;Q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AC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;gBACvB,SAAS;YACX,CAAC;YAED,MAAM,YAAY,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC;gBAC1C,OAAO,EAAE,GAAG;gBACZ,MAAM,EAAE,IAAI,CAAC,iBAAiB;aAC/B,CAAC,CAAC;YACH,MAAM,cAAc,GAAG,MAAM,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC;gBAC5C,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC;gBACrB,MAAM,EAAE,IAAI,CAAC,iBAAiB;aAC/B,CAAC,CAAC;YAEH,EAAE,CAAC,YAAY,CAAC,GAAG,IAAI,CAAC,gBAAgB,CAAC,EAAE,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,cAAc,EAAE,CAAC,CAAC;QACzF,CAAC;QAED,OAAO,EAAE,CAAC;IACZ,CAAC","sourcesContent":["import type { AESAlgorithmType } from '@venizia/ignis-helpers';\nimport { AES } from '@venizia/ignis-helpers';\nimport type { ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError, RecordUtility } from '@venizia/ignis-helpers/core';\nimport type {\n IJWTClaimsOptions,\n IJWTIssueClaims,\n IJWTTokenPayload,\n IJWTVerifyOptions,\n IPayloadFieldCodec,\n TContext,\n TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport {\n Authentication,\n AuthenticationErrors,\n BaseService,\n ServiceAssertion,\n} from '@venizia/ignis-kernel';\nimport type { Env } from 'hono';\nimport { JoseLoader } from '../jose-loader';\nimport type { JWTPayload, JWTVerifyOptions, JWTVerifyResult, SignJWT } from 'jose';\n\n/** What a token service is configured with for claims: the required `claims`, the `verify` checks, and the removed `sign` it refuses. */\nexport interface IClaimsConfigSource {\n claims?: unknown;\n verify?: unknown;\n /** Removed: refused with a message that points to `claims`. */\n sign?: unknown;\n}\n\n/** What {@link AbstractBearerTokenService.resolveClaimsConfig} answers: the validated claims and the verify options jose receives. */\nexport interface IResolvedClaimsConfig {\n claims: IJWTClaimsOptions;\n verify: JWTVerifyOptions & { algorithms: string[] };\n}\n\n/** Abstract base for Bearer-token services (JWS, JWKS) with optional AES payload encryption. */\nexport abstract class AbstractBearerTokenService<E extends Env = Env> extends BaseService {\n /** Standard JWT fields that are never encrypted. */\n static readonly JWT_COMMON_FIELDS = new Set<keyof JWTPayload>([\n 'iss',\n 'sub',\n 'aud',\n 'jti',\n 'nbf',\n 'exp',\n 'iat',\n ]);\n\n protected aes: AES | null = null;\n protected applicationSecret: string | null = null;\n protected fieldCodecs: Map<string, IPayloadFieldCodec> = new Map();\n\n /** Configured `iss` / `aud`: stamped on every issued token, authoritative over anything the payload carries, and required on every verified one. */\n protected claimOptions: IJWTClaimsOptions | null = null;\n\n /** What jose verifies against: the claims, the algorithm pin and the `verify` checks. */\n protected verifyOptions: JWTVerifyOptions | null = null;\n\n /** The keys a `claims` object may hold. */\n static readonly CLAIM_KEYS: ReadonlyArray<string> = ['issuer', 'audience'];\n\n /**\n * Validates the claims configuration of a token service and answers what the service uses. It throws, naming the\n * key, when `claims.issuer` is missing or empty, when `claims.audience` is present but not a non-empty string or a\n * non-empty list of them, when `claims` holds another key, when the removed `sign` or `verify.issuer` /\n * `verify.audience` is still passed, and when no algorithm is pinned. `claims.audience` is optional: without it\n * no `aud` is stamped and none is checked.\n * `pinnedAlgorithms` is what the service signs with; a verifier has none and requires `verify.algorithms`.\n * The component calls it at boot, and a service calls it when it is built, so neither can start without them.\n */\n static resolveClaimsConfig(opts: {\n scope: string;\n options: IClaimsConfigSource;\n pinnedAlgorithms?: string[];\n }): IResolvedClaimsConfig {\n const { scope, options, pinnedAlgorithms } = opts;\n const fail = (detail: string) =>\n getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${scope}] ${detail}`,\n });\n\n if (options.sign !== undefined) {\n throw fail(\n '`sign` was removed | put the issuer and the audience in `claims: { issuer, audience }`: they are stamped on every token and required on every verified one',\n );\n }\n\n if (options.verify !== undefined && !RecordUtility.isPlainRecord(options.verify)) {\n throw fail(\n 'verify must be an object | its checks (maxTokenAge, subject, ...) would be dropped silently',\n );\n }\n\n const verify = RecordUtility.isPlainRecord(options.verify) ? options.verify : {};\n\n for (const key of AbstractBearerTokenService.CLAIM_KEYS) {\n if (key in verify) {\n throw fail(\n `verify.${key} was removed | set claims.${key}: it is stamped on every token and required on every verified one`,\n );\n }\n }\n\n const { claims } = options;\n\n if (!RecordUtility.isPlainRecord(claims)) {\n throw fail(\n 'claims is required | pass claims: { issuer: string, audience: string | string[] }: a token signed with the same key for another purpose must not authenticate a request',\n );\n }\n\n const unknown = Object.keys(claims).filter(\n (key) => !AbstractBearerTokenService.CLAIM_KEYS.includes(key),\n );\n\n if (unknown.length > 0) {\n throw fail(\n `claims holds unknown keys ${JSON.stringify(unknown)} | accepted: ${AbstractBearerTokenService.CLAIM_KEYS.join(', ')}`,\n );\n }\n\n const { issuer, audience } = claims;\n const isName = (value: unknown): value is string =>\n typeof value === 'string' && value.trim().length > 0;\n\n if (!isName(issuer)) {\n throw fail('claims.issuer is required | a non-empty string');\n }\n\n // Optional, but a present value is checked: `null`, `''` and `[]` are mistakes, not \"no audience\".\n if (\n audience !== undefined &&\n !isName(audience) &&\n !(Array.isArray(audience) && audience.length > 0 && audience.every(isName))\n ) {\n throw fail(\n 'claims.audience must be a non-empty string or a non-empty list of them | or leave it out',\n );\n }\n\n const resolvedAudience = Array.isArray(audience) ? [...audience] : audience;\n\n const algorithms = verify.algorithms ?? pinnedAlgorithms;\n\n if (!Array.isArray(algorithms) || algorithms.length === 0 || !algorithms.every(isName)) {\n throw fail(\n \"verify.algorithms is required | the accepted JWS algorithms, for example ['RS256']: a verifier cannot know what the issuer signs with\",\n );\n }\n\n if (algorithms.some((algorithm) => algorithm.trim().toLowerCase() === 'none')) {\n throw fail(\"the algorithm 'none' is refused | a token with no signature verifies nothing\");\n }\n\n return {\n claims: { issuer, ...(resolvedAudience === undefined ? {} : { audience: resolvedAudience }) },\n verify: {\n ...(verify as IJWTVerifyOptions),\n issuer,\n ...(resolvedAudience === undefined ? {} : { audience: resolvedAudience }),\n algorithms: [...algorithms],\n },\n };\n }\n\n /** Validates the claims configuration (see {@link AbstractBearerTokenService.resolveClaimsConfig}) and keeps the result. */\n protected configureClaims(opts: {\n options: IClaimsConfigSource;\n pinnedAlgorithms?: string[];\n }): void {\n const resolved = AbstractBearerTokenService.resolveClaimsConfig({\n scope: this.scope,\n options: opts.options,\n pinnedAlgorithms: opts.pinnedAlgorithms,\n });\n\n this.claimOptions = resolved.claims;\n this.verifyOptions = resolved.verify;\n }\n\n /** Configures AES payload encryption and field codecs. Both aesAlgorithm and applicationSecret required to activate encryption. */\n protected configurePayloadEncryption(opts: {\n aesAlgorithm?: AESAlgorithmType;\n applicationSecret?: string;\n fieldCodecs?: IPayloadFieldCodec[];\n }): void {\n const { aesAlgorithm = 'aes-256-cbc', applicationSecret, fieldCodecs } = opts;\n\n if (fieldCodecs) {\n for (const codec of fieldCodecs) {\n this.fieldCodecs.set(codec.key, codec);\n }\n }\n\n if (!applicationSecret) {\n return;\n }\n\n this.aes = AES.withAlgorithm(aesAlgorithm);\n this.applicationSecret = applicationSecret;\n }\n\n extractCredentials(context: TContext<E, string>): { type: string; token: string } {\n const request = context.req;\n\n const authHeaderValue = request.header('Authorization');\n\n if (!authHeaderValue) {\n throw getError({\n error: AuthenticationErrors.HEADER_MISSING,\n message: 'Unauthorized user! Missing authorization header',\n });\n }\n\n if (!authHeaderValue.startsWith(Authentication.TYPE_BEARER)) {\n throw getError({\n error: AuthenticationErrors.SCHEME_INVALID,\n message: 'Unauthorized user! Invalid schema of request token!',\n });\n }\n\n const parts = authHeaderValue.split(' ');\n\n if (parts.length !== 2) {\n throw getError({\n error: AuthenticationErrors.HEADER_MALFORMED,\n message: `Authorization header value is invalid format. It must follow the pattern: 'Bearer xx.yy.zz' where xx.yy.zz is a valid JWT token.`,\n });\n }\n\n const [tokenType, tokenValue] = parts;\n\n return { type: tokenType, token: tokenValue };\n }\n\n async verify(opts: { type: string; token: string }): Promise<IJWTTokenPayload> {\n const { token } = opts;\n\n if (!token) {\n this.logger.for(this.verify.name).error('Missing token for validating request!');\n throw getError({\n error: AuthenticationErrors.TOKEN_MISSING,\n message: '[verify] Invalid request token!',\n });\n }\n\n try {\n await this.assertNotServiceAssertion({ token });\n const result = await this.doVerify(token);\n\n return result;\n } catch (error) {\n // No log here - `cause` carries the reason (JWTExpired, signature mismatch) to the error handler, which logs the request once. An expired token is the caller's problem, hence `warn`.\n throw getError({\n error: AuthenticationErrors.TOKEN_INVALID,\n message: '[verify] Invalid or expired token',\n logLevel: 'warn',\n cause: error,\n });\n }\n }\n\n /**\n * A service assertion (`typ: svc+jwt`) is not a user token. When a JWKS issuer shares the key of the service\n * assertions and the names collide, an assertion would otherwise verify here, so the user-token path refuses it.\n */\n protected async assertNotServiceAssertion(opts: { token: string }): Promise<void> {\n const { decodeProtectedHeader } = await JoseLoader.load();\n const { typ } = decodeProtectedHeader(opts.token);\n const kind = typeof typ === 'string' ? typ.toLowerCase().replace(/^application\\//, '') : '';\n\n if (kind === ServiceAssertion.TYP) {\n throw getError({\n error: AuthenticationErrors.TOKEN_INVALID,\n message: '[verify] A service assertion is not a user token',\n });\n }\n }\n\n async generate(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn?: TGetTokenExpiresFn;\n /** Per-token registered claims. The supported way to vary `aud` / `sub`; the payload is not. */\n claims?: IJWTIssueClaims;\n }): Promise<string> {\n const { payload, claims, getTokenExpiresFn = this.getDefaultTokenExpiresFn() } = opts;\n\n if (!payload) {\n throw getError({\n error: AuthenticationErrors.TOKEN_PAYLOAD_INVALID,\n message: '[generate] Invalid token payload!',\n });\n }\n\n const signer = await this.getSigner({ payload, getTokenExpiresFn, claims });\n\n try {\n const result = await this.getSigningKey();\n const rs = await signer.sign(result);\n\n return rs;\n } catch (error) {\n this.logger.for(this.generate.name).error('Failed to generate token | Error: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[generate] Failed to generate token',\n });\n }\n }\n\n /** A `null` is written as `null` whatever the field's codec is: a codec converts a value, and `null` is none. */\n protected serializeField(opts: { key: string; value: any }): string {\n const { key, value } = opts;\n const codec = value === null ? undefined : this.fieldCodecs.get(key);\n\n if (codec) {\n return codec.serialize({ value });\n }\n\n return JSON.stringify(value);\n }\n\n /**\n * With `applicationSecret` set, AES-encrypts the key and the value of every claim outside `JWT_COMMON_FIELDS`;\n * without it, returns the payload as is. A `null` claim is encrypted like any other value and decodes as `null`,\n * so the token decodes to the same payload with encryption on or off and `null` stays distinct from absent. An\n * `undefined` claim is skipped, as JSON drops it.\n */\n async encryptPayload(payload: IJWTTokenPayload): Promise<Record<string, any>> {\n if (!this.aes || !this.applicationSecret) {\n return payload;\n }\n\n const rs: Record<string, string> = {};\n\n const keys = Object.keys(payload);\n\n for (const key of keys) {\n const value = payload[key];\n\n if (AbstractBearerTokenService.JWT_COMMON_FIELDS.has(key)) {\n rs[key] = value;\n continue;\n }\n\n // Only `undefined` is skipped: JSON drops it too, so the claim is absent either way. `null` is a value, and\n // `serializeField` writes it as `null`, which `deserializeField` reads back, so an encrypted token decodes the\n // same payload as a plain one.\n if (value === undefined) {\n continue;\n }\n\n const encryptedKey = await this.aes.encrypt({\n message: key,\n secret: this.applicationSecret,\n });\n\n const serialized = this.serializeField({ key, value });\n\n const encryptedValue = await this.aes.encrypt({\n message: serialized,\n secret: this.applicationSecret,\n });\n rs[encryptedKey] = encryptedValue;\n }\n\n return rs;\n }\n\n /** The text `null` reads as `null` before any codec sees it, the other half of {@link serializeField}. */\n protected deserializeField(opts: { key: string; value: string }) {\n const { key, value } = opts;\n const codec = value === 'null' ? undefined : this.fieldCodecs.get(key);\n\n if (codec) {\n return codec.deserialize({ raw: value });\n }\n\n return JSON.parse(value);\n }\n\n /**\n * Stamps the configured `iss` / `aud` onto a signer, plus any per-token claims the caller passed.\n *\n * The configured value is AUTHORITATIVE. `iss` and `aud` are in `JWT_COMMON_FIELDS`, so they ride\n * through the AES envelope in the clear and an application-shaped payload can carry them - an\n * issuer identity any payload could overwrite would not be an identity. A conflicting payload\n * claim is overwritten and reported.\n *\n * Per-token audience is an explicit argument rather than a smuggled payload key, so the caller\n * that legitimately needs one says so.\n */\n protected applySignClaims(opts: {\n signer: SignJWT;\n payload: Record<string, any>;\n claims?: IJWTIssueClaims;\n }): SignJWT {\n const { signer, payload, claims } = opts;\n const configured = this.claimOptions;\n\n const issuer = claims?.issuer ?? configured?.issuer;\n const audience = claims?.audience ?? configured?.audience;\n\n const logger = this.logger.for(this.applySignClaims.name);\n\n if (issuer !== undefined) {\n if (payload.iss !== undefined && payload.iss !== issuer) {\n logger.warn(\n 'Payload iss overridden by the configured issuer | payload: %s | configured: %s',\n payload.iss,\n issuer,\n );\n }\n\n signer.setIssuer(issuer);\n }\n\n if (audience !== undefined) {\n if (payload.aud !== undefined) {\n logger.warn('Payload aud overridden | payload: %j | applied: %j', payload.aud, audience);\n }\n\n signer.setAudience(audience);\n }\n\n if (claims?.subject !== undefined) {\n signer.setSubject(claims.subject);\n }\n\n if (claims?.jwtId !== undefined) {\n signer.setJti(claims.jwtId);\n }\n\n return signer;\n }\n\n async decryptPayload(opts: {\n result: JWTVerifyResult<IJWTTokenPayload>;\n }): Promise<IJWTTokenPayload> {\n const { payload, protectedHeader } = opts.result;\n\n if (!this.aes || !this.applicationSecret) {\n return payload as IJWTTokenPayload;\n }\n\n this.logger\n .for(this.decryptPayload.name)\n .debug('JWT Token | payload: %j | header: %j', payload, protectedHeader);\n\n const rs: any = {};\n\n for (const key in payload) {\n if (AbstractBearerTokenService.JWT_COMMON_FIELDS.has(key)) {\n rs[key] = payload[key];\n continue;\n }\n\n const decryptedKey = await this.aes.decrypt({\n message: key,\n secret: this.applicationSecret,\n });\n const decryptedValue = await this.aes.decrypt({\n message: payload[key],\n secret: this.applicationSecret,\n });\n\n rs[decryptedKey] = this.deserializeField({ key: decryptedKey, value: decryptedValue });\n }\n\n return rs;\n }\n\n protected abstract doVerify(token: string): Promise<IJWTTokenPayload>;\n\n abstract getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }): Promise<SignJWT>;\n\n protected abstract getSigningKey(): ValueOrPromise<Uint8Array | CryptoKey>;\n\n protected abstract getDefaultTokenExpiresFn(): TGetTokenExpiresFn;\n}\n"]}
|
|
@@ -25,11 +25,11 @@ let JWKSIssuerTokenService = JWKSIssuerTokenService_1 = class JWKSIssuerTokenSer
|
|
|
25
25
|
this.privateKey = null;
|
|
26
26
|
this.publicKey = null;
|
|
27
27
|
this.jwks = null;
|
|
28
|
+
this.configureClaims({ options: this.options, pinnedAlgorithms: [this.options.algorithm] });
|
|
28
29
|
this.configurePayloadEncryption({
|
|
29
30
|
aesAlgorithm: this.options.aesAlgorithm,
|
|
30
31
|
applicationSecret: this.options.applicationSecret,
|
|
31
32
|
fieldCodecs: this.options.fieldCodecs,
|
|
32
|
-
sign: this.options.sign,
|
|
33
33
|
});
|
|
34
34
|
}
|
|
35
35
|
async initialize() {
|
|
@@ -154,7 +154,7 @@ let JWKSIssuerTokenService = JWKSIssuerTokenService_1 = class JWKSIssuerTokenSer
|
|
|
154
154
|
async doVerify(token) {
|
|
155
155
|
await this.ensureInitialized();
|
|
156
156
|
const { jwtVerify } = await JoseLoader.load();
|
|
157
|
-
const result = await jwtVerify(token, this.publicKey, this.
|
|
157
|
+
const result = await jwtVerify(token, this.publicKey, this.verifyOptions);
|
|
158
158
|
return this.decryptPayload({ result });
|
|
159
159
|
}
|
|
160
160
|
async getSigner(opts) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"issuer.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/issuer.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAu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AAY,EAAE,CAAC,CAAA;;GAN7C,sBAAsB,CAqOlC","sourcesContent":["import { HTTP, type TNullable, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSIssuerOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n JWKSKeyDrivers,\n JWKSKeyFormats,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { CryptoKey, JWK } from 'jose';\nimport { readFile } from 'node:fs/promises';\nimport { JoseLoader } from '../../jose-loader';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\n/** Signs tokens with a private key loaded from `IJWKSIssuerOptions` and exposes the matching public keys as a JWKS via `getJWKSAsync()`. */\nexport class JWKSIssuerTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected privateKey: TNullable<CryptoKey | Uint8Array> = null;\n protected publicKey: TNullable<CryptoKey | Uint8Array> = null;\n protected jwks: { keys: JWK[] } | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSIssuerOptions,\n ) {\n super({ scope: JWKSIssuerTokenService.name });\n\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n sign: this.options.sign,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { keys, algorithm } = this.options;\n\n const raw = await this.resolveKeyContent({ keys });\n const built = await this.parseKeyMaterial({ raw, algorithm, keys });\n\n this.privateKey = built.priv;\n this.publicKey = built.pub;\n\n const { exportJWK } = await JoseLoader.load();\n const publicJWK = await exportJWK(this.publicKey!);\n\n // Belt and braces. `assertPublicJWK` already refused a private JWK on the way IN, but this is\n // the exact object an unauthenticated `/certs` serves - the last place to notice a signing key\n // about to be published, whatever route the material took to get here.\n this.assertPublicJWK({ jwk: publicJWK });\n\n publicJWK.kid = this.options.kid;\n publicJWK.alg = algorithm;\n publicJWK.use = 'sig';\n\n this.jwks = { keys: [publicJWK] };\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info(\n 'JWKS issuer initialized | driver: %s | format: %s | kid: %s',\n keys.driver,\n keys.format,\n this.options.kid,\n );\n }\n\n protected async resolveKeyContent(opts: { keys: IJWKSIssuerOptions['keys'] }) {\n const { keys } = opts;\n\n switch (keys.driver) {\n case JWKSKeyDrivers.FILE: {\n const [priv, pub] = await Promise.all([\n readFile(keys.private, 'utf-8'),\n readFile(keys.public, 'utf-8'),\n ]);\n\n return { priv, pub };\n }\n case JWKSKeyDrivers.TEXT: {\n return {\n priv: keys.private,\n pub: keys.public,\n };\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key driver: ${keys.driver}`,\n });\n }\n }\n }\n\n /**\n * Refuses a JWK carrying private material where a PUBLIC key is expected.\n *\n * The `pem` format cannot reach this state - `importSPKI` rejects a private PEM outright. The\n * `jwk` format can: `importJWK` imports whatever it is handed, and a private JWK marked\n * `\"ext\": true` yields an EXTRACTABLE key, so `exportJWK` then carries `d` straight into the\n * document `/certs` serves without authentication. Measured on jose 6.2.3: with `ext: true` the\n * round trip returns `d`; without it, export throws. So the only thing standing between a\n * mis-pasted key and a published signing key was an optional flag on attacker-irrelevant input.\n *\n * Named members, not a blanket scan: `d` covers EC/OKP and RSA's private exponent, and the CRT\n * members are the rest of an RSA private key.\n */\n protected assertPublicJWK(opts: { jwk: JWK }): void {\n const PRIVATE_MEMBERS = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'k'] as const;\n\n const present = PRIVATE_MEMBERS.filter((member) => opts.jwk[member] !== undefined);\n\n if (present.length === 0) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] The public key material carries PRIVATE members (${present.join(', ')}) | this key would be published at the JWKS endpoint | pass the public half in keys.public`,\n });\n }\n\n protected async parseKeyMaterial(opts: {\n raw: { priv: string; pub: string };\n algorithm: IJWKSIssuerOptions['algorithm'];\n keys: IJWKSIssuerOptions['keys'];\n }) {\n const { raw, algorithm, keys } = opts;\n\n if (!raw.priv) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.priv key!',\n });\n }\n\n if (!raw.pub) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.pub key!',\n });\n }\n\n const { importJWK, importPKCS8, importSPKI } = await JoseLoader.load();\n\n switch (keys.format) {\n case JWKSKeyFormats.PEM: {\n const priv = await importPKCS8(raw.priv, algorithm);\n const pub = await importSPKI(raw.pub, algorithm);\n\n return { priv, pub };\n }\n case JWKSKeyFormats.JWK: {\n try {\n const parsed = {\n priv: JSON.parse(raw.priv) as JWK,\n pub: JSON.parse(raw.pub) as JWK,\n };\n\n this.assertPublicJWK({ jwk: parsed.pub });\n\n const priv = await importJWK(parsed.priv, algorithm);\n const pub = await importJWK(parsed.pub, algorithm);\n\n return { priv, pub };\n } catch (error) {\n this.logger\n .for(this.parseKeyMaterial.name)\n .error('Invalid JWK key material | Error: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid JWK key material',\n });\n }\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key format: ${keys.format}`,\n });\n }\n }\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(token, this.publicKey!, this.options.verify);\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n await this.ensureInitialized();\n const { SignJWT } = await JoseLoader.load();\n\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT({ ...encryptedPayload })\n .setProtectedHeader({ alg: this.options.algorithm, kid: this.options.kid })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array | CryptoKey> {\n if (!this.privateKey) {\n throw getError({ message: '[getSigningKey] Invalid privateKey!' });\n }\n\n return this.privateKey;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n\n getJWKS(): { keys: JWK[] } {\n if (!this.jwks) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] JWKS not initialized yet. Call getJWKSAsync() instead.',\n });\n }\n\n return this.jwks;\n }\n\n async getJWKSAsync(): Promise<{ keys: JWK[] }> {\n await this.ensureInitialized();\n\n return this.jwks!;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"issuer.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/issuer.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAuC,MAAM,+BAA+B,CAAC;AAC1F,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAIvB,MAAM,EACN,cAAc,EACd,cAAc,GAEf,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB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AE,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;aAC1E,WAAW,EAAE;aACb,iBAAiB,CAAC,GAAG,GAAG,SAAS,CAAC;aAClC,YAAY,CAAC,GAAG,CAAC,CAAC;QAErB,OAAO,IAAI,CAAC,eAAe,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IAC1F,CAAC;IAEkB,aAAa;QAC9B,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;YACrB,MAAM,QAAQ,CAAC,EAAE,OAAO,EAAE,qCAAqC,EAAE,CAAC,CAAC;QACrE,CAAC;QAED,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IAEkB,wBAAwB;QACzC,OAAO,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC;IACxC,CAAC;IAED,OAAO;QACL,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YACf,MAAM,QAAQ,CAAC;gBACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;gBACrD,OAAO,EAAE,iFAAiF;aAC3F,CAAC,CAAC;QACL,CAAC;QAED,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED,KAAK,CAAC,YAAY;QAChB,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAE/B,OAAO,IAAI,CAAC,IAAK,CAAC;IACpB,CAAC;CACF,CAAA;AArOY,sBAAsB;IAM9B,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAA;;GAN7C,sBAAsB,CAqOlC","sourcesContent":["import { HTTP, type TNullable, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSIssuerOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n JWKSKeyDrivers,\n JWKSKeyFormats,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { CryptoKey, JWK } from 'jose';\nimport { readFile } from 'node:fs/promises';\nimport { JoseLoader } from '../../jose-loader';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\n/** Signs tokens with a private key loaded from `IJWKSIssuerOptions` and exposes the matching public keys as a JWKS via `getJWKSAsync()`. */\nexport class JWKSIssuerTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected privateKey: TNullable<CryptoKey | Uint8Array> = null;\n protected publicKey: TNullable<CryptoKey | Uint8Array> = null;\n protected jwks: { keys: JWK[] } | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSIssuerOptions,\n ) {\n super({ scope: JWKSIssuerTokenService.name });\n\n this.configureClaims({ options: this.options, pinnedAlgorithms: [this.options.algorithm] });\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { keys, algorithm } = this.options;\n\n const raw = await this.resolveKeyContent({ keys });\n const built = await this.parseKeyMaterial({ raw, algorithm, keys });\n\n this.privateKey = built.priv;\n this.publicKey = built.pub;\n\n const { exportJWK } = await JoseLoader.load();\n const publicJWK = await exportJWK(this.publicKey!);\n\n // Belt and braces. `assertPublicJWK` already refused a private JWK on the way IN, but this is\n // the exact object an unauthenticated `/certs` serves - the last place to notice a signing key\n // about to be published, whatever route the material took to get here.\n this.assertPublicJWK({ jwk: publicJWK });\n\n publicJWK.kid = this.options.kid;\n publicJWK.alg = algorithm;\n publicJWK.use = 'sig';\n\n this.jwks = { keys: [publicJWK] };\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info(\n 'JWKS issuer initialized | driver: %s | format: %s | kid: %s',\n keys.driver,\n keys.format,\n this.options.kid,\n );\n }\n\n protected async resolveKeyContent(opts: { keys: IJWKSIssuerOptions['keys'] }) {\n const { keys } = opts;\n\n switch (keys.driver) {\n case JWKSKeyDrivers.FILE: {\n const [priv, pub] = await Promise.all([\n readFile(keys.private, 'utf-8'),\n readFile(keys.public, 'utf-8'),\n ]);\n\n return { priv, pub };\n }\n case JWKSKeyDrivers.TEXT: {\n return {\n priv: keys.private,\n pub: keys.public,\n };\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key driver: ${keys.driver}`,\n });\n }\n }\n }\n\n /**\n * Refuses a JWK carrying private material where a PUBLIC key is expected.\n *\n * The `pem` format cannot reach this state - `importSPKI` rejects a private PEM outright. The\n * `jwk` format can: `importJWK` imports whatever it is handed, and a private JWK marked\n * `\"ext\": true` yields an EXTRACTABLE key, so `exportJWK` then carries `d` straight into the\n * document `/certs` serves without authentication. Measured on jose 6.2.3: with `ext: true` the\n * round trip returns `d`; without it, export throws. So the only thing standing between a\n * mis-pasted key and a published signing key was an optional flag on attacker-irrelevant input.\n *\n * Named members, not a blanket scan: `d` covers EC/OKP and RSA's private exponent, and the CRT\n * members are the rest of an RSA private key.\n */\n protected assertPublicJWK(opts: { jwk: JWK }): void {\n const PRIVATE_MEMBERS = ['d', 'p', 'q', 'dp', 'dq', 'qi', 'k'] as const;\n\n const present = PRIVATE_MEMBERS.filter((member) => opts.jwk[member] !== undefined);\n\n if (present.length === 0) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] The public key material carries PRIVATE members (${present.join(', ')}) | this key would be published at the JWKS endpoint | pass the public half in keys.public`,\n });\n }\n\n protected async parseKeyMaterial(opts: {\n raw: { priv: string; pub: string };\n algorithm: IJWKSIssuerOptions['algorithm'];\n keys: IJWKSIssuerOptions['keys'];\n }) {\n const { raw, algorithm, keys } = opts;\n\n if (!raw.priv) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.priv key!',\n });\n }\n\n if (!raw.pub) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid raw.pub key!',\n });\n }\n\n const { importJWK, importPKCS8, importSPKI } = await JoseLoader.load();\n\n switch (keys.format) {\n case JWKSKeyFormats.PEM: {\n const priv = await importPKCS8(raw.priv, algorithm);\n const pub = await importSPKI(raw.pub, algorithm);\n\n return { priv, pub };\n }\n case JWKSKeyFormats.JWK: {\n try {\n const parsed = {\n priv: JSON.parse(raw.priv) as JWK,\n pub: JSON.parse(raw.pub) as JWK,\n };\n\n this.assertPublicJWK({ jwk: parsed.pub });\n\n const priv = await importJWK(parsed.priv, algorithm);\n const pub = await importJWK(parsed.pub, algorithm);\n\n return { priv, pub };\n } catch (error) {\n this.logger\n .for(this.parseKeyMaterial.name)\n .error('Invalid JWK key material | Error: %s', error);\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] Invalid JWK key material',\n });\n }\n }\n default: {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[JWKSIssuerTokenService] Unknown key format: ${keys.format}`,\n });\n }\n }\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(token, this.publicKey!, this.verifyOptions!);\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n await this.ensureInitialized();\n const { SignJWT } = await JoseLoader.load();\n\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT({ ...encryptedPayload })\n .setProtectedHeader({ alg: this.options.algorithm, kid: this.options.kid })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array | CryptoKey> {\n if (!this.privateKey) {\n throw getError({ message: '[getSigningKey] Invalid privateKey!' });\n }\n\n return this.privateKey;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n\n getJWKS(): { keys: JWK[] } {\n if (!this.jwks) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSIssuerTokenService] JWKS not initialized yet. Call getJWKSAsync() instead.',\n });\n }\n\n return this.jwks;\n }\n\n async getJWKSAsync(): Promise<{ keys: JWK[] }> {\n await this.ensureInitialized();\n\n return this.jwks!;\n }\n}\n"]}
|
|
@@ -15,6 +15,7 @@ import { HTTP } from '@venizia/ignis-helpers/common';
|
|
|
15
15
|
import { getError } from '@venizia/ignis-helpers/core';
|
|
16
16
|
import { AuthenticateBindingKeys, inject, } from '@venizia/ignis-kernel';
|
|
17
17
|
import { JoseLoader } from '../../jose-loader.js';
|
|
18
|
+
import { JWKSUrlPolicy } from '../../jwks-url-policy.js';
|
|
18
19
|
import { AbstractJWKSTokenService } from './abstract.service.js';
|
|
19
20
|
/** Verifies tokens against a remote JWKS fetched from `jwksUrl`. The key set is cached for `cacheTtlMs` (default 43_200_000 ms) with a `cooldownMs` refetch cooldown (default 30_000 ms). */
|
|
20
21
|
let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTokenService extends AbstractJWKSTokenService {
|
|
@@ -22,6 +23,7 @@ let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTo
|
|
|
22
23
|
super({ scope: JWKSVerifierTokenService_1.name });
|
|
23
24
|
this.options = options;
|
|
24
25
|
this.jwksVerifier = null;
|
|
26
|
+
this.configureClaims({ options: this.options });
|
|
25
27
|
this.configurePayloadEncryption({
|
|
26
28
|
aesAlgorithm: this.options.aesAlgorithm,
|
|
27
29
|
applicationSecret: this.options.applicationSecret,
|
|
@@ -30,7 +32,12 @@ let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTo
|
|
|
30
32
|
}
|
|
31
33
|
async initialize() {
|
|
32
34
|
const { createRemoteJWKSet } = await JoseLoader.load();
|
|
33
|
-
const jwksUrl =
|
|
35
|
+
const jwksUrl = JWKSUrlPolicy.assertUrl({
|
|
36
|
+
scope: JWKSVerifierTokenService_1.name,
|
|
37
|
+
label: 'jwksUrl',
|
|
38
|
+
url: this.options.jwksUrl,
|
|
39
|
+
hosts: this.options.jwks?.hosts?.http,
|
|
40
|
+
});
|
|
34
41
|
this.jwksVerifier = createRemoteJWKSet(jwksUrl, {
|
|
35
42
|
cacheMaxAge: this.options.cacheTtlMs ?? 43_200_000,
|
|
36
43
|
cooldownDuration: this.options.cooldownMs ?? 30_000,
|
|
@@ -38,12 +45,12 @@ let JWKSVerifierTokenService = JWKSVerifierTokenService_1 = class JWKSVerifierTo
|
|
|
38
45
|
this.initialized = true;
|
|
39
46
|
this.logger
|
|
40
47
|
.for(this.initialize.name)
|
|
41
|
-
.info('JWKS verifier initialized |
|
|
48
|
+
.info('JWKS verifier initialized | origin: %s', jwksUrl.origin);
|
|
42
49
|
}
|
|
43
50
|
async doVerify(token) {
|
|
44
51
|
await this.ensureInitialized();
|
|
45
52
|
const { jwtVerify } = await JoseLoader.load();
|
|
46
|
-
const result = await jwtVerify(token, this.jwksVerifier, this.
|
|
53
|
+
const result = await jwtVerify(token, this.jwksVerifier, this.verifyOptions);
|
|
47
54
|
return this.decryptPayload({ result });
|
|
48
55
|
}
|
|
49
56
|
async getSigner(_opts) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAGvB,MAAM,GAEP,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,wBAAwB,EAAE,MAAM,oBAAoB,CAAC;AAE9D,6LAA6L;AAC7L,IAAa,wBAAwB,gCAArC,MAAa,wBAA8C,SAAQ,wBAA2B;IAG5F,YAEE,OAAuC;QAEvC,KAAK,CAAC,EAAE,KAAK,EAAE,0BAAwB,CAAC,IAAI,EAAE,CAAC,CAAC;QAFtC,YAAO,GAAP,OAAO,CAAsB;QAJ/B,iBAAY,GAAiD,IAAI,CAAC;QAO1E,IAAI,CAAC,0BAA0B,CAAC;YAC9B,YAAY,EAAE,IAAI,CAAC,OAAO,CAAC,YAAY;YACvC,iBAAiB,EAAE,IAAI,CAAC,OAAO,CAAC,iBAAiB;YACjD,WAAW,EAAE,IAAI,CAAC,OAAO,CAAC,WAAW;SACtC,CAAC,CAAC;IACL,CAAC;IAEkB,KAAK,CAAC,UAAU;QACjC,MAAM,EAAE,kBAAkB,EAAE,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;QACvD,MAAM,OAAO,GAAG,IAAI,GAAG,
|
|
1
|
+
{"version":3,"file":"verifier.service.js","sourceRoot":"","sources":["../../../../../../../../src/components/auth/authenticate/services/bearer/jwks/verifier.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,+BAA+B,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAGvB,MAAM,GAEP,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,UAAU,EAAE,MAAM,mB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I,CAAC;QAExB,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;aACzB,IAAI,CAAC,wCAAwC,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;IACpE,CAAC;IAEkB,KAAK,CAAC,QAAQ,CAAC,KAAa;QAC7C,MAAM,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAC/B,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;QAC9C,MAAM,MAAM,GAAG,MAAM,SAAS,CAC5B,KAAK,EACL,IAAI,CAAC,YAAa,EAClB,IAAI,CAAC,aAAc,CACpB,CAAC;QAEF,OAAO,IAAI,CAAC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC;IACzC,CAAC;IAEQ,KAAK,CAAC,SAAS,CAAC,KAGxB;QACC,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,6DAA6D;SACvE,CAAC,CAAC;IACL,CAAC;IAEkB,aAAa;QAC9B,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,6DAA6D;SACvE,CAAC,CAAC;IACL,CAAC;IAEkB,wBAAwB;QACzC,MAAM,QAAQ,CAAC;YACb,UAAU,EAAE,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,mBAAmB;YACrD,OAAO,EAAE,8DAA8D;SACxE,CAAC,CAAC;IACL,CAAC;CACF,CAAA;AAvEY,wBAAwB;IAIhC,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,YAAY,EAAE,CAAC,CAAA;;GAJ7C,wBAAwB,CAuEpC","sourcesContent":["import { HTTP } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWKSVerifierOptions,\n type IJWTTokenPayload,\n inject,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport type { createRemoteJWKSet, SignJWT } from 'jose';\nimport { JoseLoader } from '../../jose-loader';\nimport { JWKSUrlPolicy } from '../../jwks-url-policy';\nimport { AbstractJWKSTokenService } from './abstract.service';\n\n/** Verifies tokens against a remote JWKS fetched from `jwksUrl`. The key set is cached for `cacheTtlMs` (default 43_200_000 ms) with a `cooldownMs` refetch cooldown (default 30_000 ms). */\nexport class JWKSVerifierTokenService<E extends Env = Env> extends AbstractJWKSTokenService<E> {\n protected jwksVerifier: ReturnType<typeof createRemoteJWKSet> | null = null;\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWKS_OPTIONS })\n protected options: IJWKSVerifierOptions,\n ) {\n super({ scope: JWKSVerifierTokenService.name });\n this.configureClaims({ options: this.options });\n this.configurePayloadEncryption({\n aesAlgorithm: this.options.aesAlgorithm,\n applicationSecret: this.options.applicationSecret,\n fieldCodecs: this.options.fieldCodecs,\n });\n }\n\n protected override async initialize(): Promise<void> {\n const { createRemoteJWKSet } = await JoseLoader.load();\n const jwksUrl = JWKSUrlPolicy.assertUrl({\n scope: JWKSVerifierTokenService.name,\n label: 'jwksUrl',\n url: this.options.jwksUrl,\n hosts: this.options.jwks?.hosts?.http,\n });\n this.jwksVerifier = createRemoteJWKSet(jwksUrl, {\n cacheMaxAge: this.options.cacheTtlMs ?? 43_200_000,\n cooldownDuration: this.options.cooldownMs ?? 30_000,\n });\n\n this.initialized = true;\n\n this.logger\n .for(this.initialize.name)\n .info('JWKS verifier initialized | origin: %s', jwksUrl.origin);\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n await this.ensureInitialized();\n const { jwtVerify } = await JoseLoader.load();\n const result = await jwtVerify<IJWTTokenPayload>(\n token,\n this.jwksVerifier!,\n this.verifyOptions!,\n );\n\n return this.decryptPayload({ result });\n }\n\n override async getSigner(_opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n }): Promise<SignJWT> {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode cannot sign tokens',\n });\n }\n\n protected override getSigningKey(): never {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode cannot sign tokens',\n });\n }\n\n protected override getDefaultTokenExpiresFn(): never {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWKSVerifierTokenService] Verifier mode has no token expiry',\n });\n }\n}\n"]}
|
|
@@ -5,7 +5,18 @@ import { AbstractBearerTokenService } from './abstract.service.js';
|
|
|
5
5
|
/** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */
|
|
6
6
|
export declare class JWSTokenService<E extends Env = Env> extends AbstractBearerTokenService<E> {
|
|
7
7
|
protected options: IJWSTokenServiceOptions;
|
|
8
|
+
/** The shortest `jwtSecret` accepted, in bytes: an HMAC key is as strong as it is long, and 32 bytes is the size of a SHA-256 output. */
|
|
9
|
+
static readonly MIN_SECRET_BYTES = 32;
|
|
8
10
|
protected jwtSecret: Uint8Array;
|
|
11
|
+
/**
|
|
12
|
+
* Refuses a `jwtSecret` shorter than {@link JWSTokenService.MIN_SECRET_BYTES} (counted in UTF-8 bytes, not
|
|
13
|
+
* characters), saying how to make one. The secret is never echoed. The component calls it at boot and the
|
|
14
|
+
* service when it is built.
|
|
15
|
+
*/
|
|
16
|
+
static assertSecretStrength(opts: {
|
|
17
|
+
scope: string;
|
|
18
|
+
secret: string;
|
|
19
|
+
}): void;
|
|
9
20
|
constructor(options: IJWSTokenServiceOptions);
|
|
10
21
|
protected doVerify(token: string): Promise<IJWTTokenPayload>;
|
|
11
22
|
getSigner(opts: {
|
|
@@ -17,7 +17,25 @@ import { AuthenticateBindingKeys, inject, } from '@venizia/ignis-kernel';
|
|
|
17
17
|
import { JoseLoader } from '../jose-loader.js';
|
|
18
18
|
import { AbstractBearerTokenService } from './abstract.service.js';
|
|
19
19
|
/** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */
|
|
20
|
-
let JWSTokenService =
|
|
20
|
+
let JWSTokenService = class JWSTokenService extends AbstractBearerTokenService {
|
|
21
|
+
static { JWSTokenService_1 = this; }
|
|
22
|
+
/** The shortest `jwtSecret` accepted, in bytes: an HMAC key is as strong as it is long, and 32 bytes is the size of a SHA-256 output. */
|
|
23
|
+
static { this.MIN_SECRET_BYTES = 32; }
|
|
24
|
+
/**
|
|
25
|
+
* Refuses a `jwtSecret` shorter than {@link JWSTokenService.MIN_SECRET_BYTES} (counted in UTF-8 bytes, not
|
|
26
|
+
* characters), saying how to make one. The secret is never echoed. The component calls it at boot and the
|
|
27
|
+
* service when it is built.
|
|
28
|
+
*/
|
|
29
|
+
static assertSecretStrength(opts) {
|
|
30
|
+
const bytes = new TextEncoder().encode(opts.secret).length;
|
|
31
|
+
if (bytes >= JWSTokenService_1.MIN_SECRET_BYTES) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
throw getError({
|
|
35
|
+
statusCode: HTTP.ResultCodes.RS_5.InternalServerError,
|
|
36
|
+
message: `[${opts.scope}] jwtSecret is too short: ${bytes} bytes, at least ${JWSTokenService_1.MIN_SECRET_BYTES} are required | Generate one with: openssl rand -base64 48`,
|
|
37
|
+
});
|
|
38
|
+
}
|
|
21
39
|
constructor(options) {
|
|
22
40
|
super({ scope: JWSTokenService_1.name });
|
|
23
41
|
this.options = options;
|
|
@@ -34,17 +52,21 @@ let JWSTokenService = JWSTokenService_1 = class JWSTokenService extends Abstract
|
|
|
34
52
|
message: '[JWSTokenService] Invalid getTokenExpiresFn',
|
|
35
53
|
});
|
|
36
54
|
}
|
|
55
|
+
this.configureClaims({
|
|
56
|
+
options,
|
|
57
|
+
pinnedAlgorithms: [options.headerAlgorithm ?? 'HS256'],
|
|
58
|
+
});
|
|
59
|
+
JWSTokenService_1.assertSecretStrength({ scope: JWSTokenService_1.name, secret: jwtSecret });
|
|
37
60
|
this.configurePayloadEncryption({
|
|
38
61
|
aesAlgorithm,
|
|
39
62
|
applicationSecret,
|
|
40
63
|
fieldCodecs: options.fieldCodecs,
|
|
41
|
-
sign: options.sign,
|
|
42
64
|
});
|
|
43
65
|
this.jwtSecret = new TextEncoder().encode(this.options.jwtSecret);
|
|
44
66
|
}
|
|
45
67
|
async doVerify(token) {
|
|
46
68
|
const { jwtVerify } = await JoseLoader.load();
|
|
47
|
-
const decodedToken = await jwtVerify(token, this.jwtSecret, this.
|
|
69
|
+
const decodedToken = await jwtVerify(token, this.jwtSecret, this.verifyOptions);
|
|
48
70
|
return this.decryptPayload({ result: decodedToken });
|
|
49
71
|
}
|
|
50
72
|
async getSigner(opts) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jws.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/bearer/jws.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAuB,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAIvB,MAAM,GAEP,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,0BAA0B,EAAE,MAAM,oBAAoB,CAAC;AAEhE,8EAA8E;AAC9E,IAAa,eAAe,
|
|
1
|
+
{"version":3,"file":"jws.service.js","sourceRoot":"","sources":["../../../../../../../src/components/auth/authenticate/services/bearer/jws.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAAA,OAAO,EAAE,IAAI,EAAuB,MAAM,+BAA+B,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,MAAM,6BAA6B,CAAC;AACvD,OAAO,EACL,uBAAuB,EAIvB,MAAM,GAEP,MAAM,uBAAuB,C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,MAAM,CAAC,EAAE,EAAE,gBAAgB,CAAC,CAAC;aAC5D,kBAAkB,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,eAAe,IAAI,OAAO,EAAE,CAAC;aACpE,WAAW,EAAE;aACb,iBAAiB,CAAC,GAAG,GAAG,SAAS,CAAC;aAClC,YAAY,CAAC,GAAG,CAAC,CAAC;QAErB,OAAO,IAAI,CAAC,eAAe,CAAC,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC;IAC1F,CAAC;IAEkB,aAAa;QAC9B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,MAAM,QAAQ,CAAC,EAAE,OAAO,EAAE,oCAAoC,EAAE,CAAC,CAAC;QACpE,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC;IACxB,CAAC;IAEkB,wBAAwB;QACzC,OAAO,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC;IACxC,CAAC;;AArGU,eAAe;IAyBvB,WAAA,MAAM,CAAC,EAAE,GAAG,EAAE,uBAAuB,CAAC,WAAW,EAAE,CAAC,CAAA;;GAzB5C,eAAe,CAsG3B","sourcesContent":["import { HTTP, type ValueOrPromise } from '@venizia/ignis-helpers/common';\nimport { getError } from '@venizia/ignis-helpers/core';\nimport {\n AuthenticateBindingKeys,\n type IJWSTokenServiceOptions,\n type IJWTIssueClaims,\n type IJWTTokenPayload,\n inject,\n type TGetTokenExpiresFn,\n} from '@venizia/ignis-kernel';\nimport { type Env } from 'hono';\nimport { JoseLoader } from '../jose-loader';\nimport { AbstractBearerTokenService } from './abstract.service';\n\n/** Symmetric JWT (JWS) token service with optional AES-encrypted payloads. */\nexport class JWSTokenService<E extends Env = Env> extends AbstractBearerTokenService<E> {\n /** The shortest `jwtSecret` accepted, in bytes: an HMAC key is as strong as it is long, and 32 bytes is the size of a SHA-256 output. */\n static readonly MIN_SECRET_BYTES = 32;\n\n protected jwtSecret: Uint8Array;\n\n /**\n * Refuses a `jwtSecret` shorter than {@link JWSTokenService.MIN_SECRET_BYTES} (counted in UTF-8 bytes, not\n * characters), saying how to make one. The secret is never echoed. The component calls it at boot and the\n * service when it is built.\n */\n static assertSecretStrength(opts: { scope: string; secret: string }): void {\n const bytes = new TextEncoder().encode(opts.secret).length;\n\n if (bytes >= JWSTokenService.MIN_SECRET_BYTES) {\n return;\n }\n\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: `[${opts.scope}] jwtSecret is too short: ${bytes} bytes, at least ${JWSTokenService.MIN_SECRET_BYTES} are required | Generate one with: openssl rand -base64 48`,\n });\n }\n\n constructor(\n @inject({ key: AuthenticateBindingKeys.JWT_OPTIONS })\n protected options: IJWSTokenServiceOptions,\n ) {\n super({ scope: JWSTokenService.name });\n\n const { aesAlgorithm, jwtSecret, applicationSecret, getTokenExpiresFn } = options ?? {};\n\n if (!jwtSecret) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWSTokenService] Invalid jwtSecret',\n });\n }\n\n if (!getTokenExpiresFn) {\n throw getError({\n statusCode: HTTP.ResultCodes.RS_5.InternalServerError,\n message: '[JWSTokenService] Invalid getTokenExpiresFn',\n });\n }\n\n this.configureClaims({\n options,\n pinnedAlgorithms: [options.headerAlgorithm ?? 'HS256'],\n });\n JWSTokenService.assertSecretStrength({ scope: JWSTokenService.name, secret: jwtSecret });\n\n this.configurePayloadEncryption({\n aesAlgorithm,\n applicationSecret,\n fieldCodecs: options.fieldCodecs,\n });\n this.jwtSecret = new TextEncoder().encode(this.options.jwtSecret);\n }\n\n protected override async doVerify(token: string): Promise<IJWTTokenPayload> {\n const { jwtVerify } = await JoseLoader.load();\n const decodedToken = await jwtVerify<IJWTTokenPayload>(\n token,\n this.jwtSecret,\n this.verifyOptions!,\n );\n\n return this.decryptPayload({ result: decodedToken });\n }\n\n override async getSigner(opts: {\n payload: IJWTTokenPayload;\n getTokenExpiresFn: TGetTokenExpiresFn;\n claims?: IJWTIssueClaims;\n }) {\n const { SignJWT } = await JoseLoader.load();\n const now = Math.floor(Date.now() / 1000);\n const expiresIn = await opts.getTokenExpiresFn();\n\n const encryptedPayload = await this.encryptPayload(opts.payload);\n\n const signer = new SignJWT(Object.assign({}, encryptedPayload))\n .setProtectedHeader({ alg: this.options.headerAlgorithm ?? 'HS256' })\n .setIssuedAt()\n .setExpirationTime(now + expiresIn)\n .setNotBefore(now);\n\n return this.applySignClaims({ signer, payload: encryptedPayload, claims: opts.claims });\n }\n\n protected override getSigningKey(): ValueOrPromise<Uint8Array> {\n if (!this.jwtSecret) {\n throw getError({ message: '[getSigningKey] Invalid jwtSecret!' });\n }\n\n return this.jwtSecret;\n }\n\n protected override getDefaultTokenExpiresFn(): TGetTokenExpiresFn {\n return this.options.getTokenExpiresFn;\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,WAAW,CAAC","sourcesContent":["export * from './basic';\nexport * from './bearer';\nexport * from './service';\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../../src/components/auth/authenticate/services/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,UAAU,CAAC;AACzB,cAAc,mBAAmB,CAAC;AAClC,cAAc,WAAW,CAAC","sourcesContent":["export * from './basic';\nexport * from './bearer';\nexport * from './jwks-url-policy';\nexport * from './service';\n"]}
|