@feedb2b-dev/service-auth 0.0.1 → 0.0.2

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/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { ServiceAuthModule } from './service-auth.module';
2
- export { ServiceToken } from './service-token';
3
- export type { ServiceAuthModuleOptions } from './service-auth.options';
2
+ export { ServiceAuth } from './service-auth';
3
+ export type { ServiceAuthLogger, ServiceAuthModuleOptions, } from './service-auth.options';
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ServiceToken = exports.ServiceAuthModule = void 0;
3
+ exports.ServiceAuth = exports.ServiceAuthModule = void 0;
4
4
  var service_auth_module_1 = require("./service-auth.module");
5
5
  Object.defineProperty(exports, "ServiceAuthModule", { enumerable: true, get: function () { return service_auth_module_1.ServiceAuthModule; } });
6
- var service_token_1 = require("./service-token");
7
- Object.defineProperty(exports, "ServiceToken", { enumerable: true, get: function () { return service_token_1.ServiceToken; } });
6
+ var service_auth_1 = require("./service-auth");
7
+ Object.defineProperty(exports, "ServiceAuth", { enumerable: true, get: function () { return service_auth_1.ServiceAuth; } });
8
8
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,6DAA0D;AAAjD,wHAAA,iBAAiB,OAAA;AAC1B,iDAA+C;AAAtC,6GAAA,YAAY,OAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,6DAA0D;AAAjD,wHAAA,iBAAiB,OAAA;AAC1B,+CAA6C;AAApC,2GAAA,WAAW,OAAA"}
@@ -1,4 +1,4 @@
1
- import { type ServiceAuthModuleOptions } from './service-auth.options';
1
+ import { type ServiceAuthConfig } from './service-auth.options';
2
2
  export interface ServiceAuthTokenResponse {
3
3
  access_token: string;
4
4
  token_type: 'Bearer';
@@ -7,6 +7,6 @@ export interface ServiceAuthTokenResponse {
7
7
  export declare class ServiceAuthClient {
8
8
  private readonly options;
9
9
  private readonly http;
10
- constructor(options: ServiceAuthModuleOptions);
10
+ constructor(options: ServiceAuthConfig);
11
11
  fetchToken(): Promise<ServiceAuthTokenResponse>;
12
12
  }
@@ -48,7 +48,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
48
48
  exports.ServiceAuthClient = void 0;
49
49
  const common_1 = require("@nestjs/common");
50
50
  const axios_1 = __importStar(require("axios"));
51
- const service_auth_module_definition_1 = require("./service-auth.module-definition");
52
51
  const service_auth_options_1 = require("./service-auth.options");
53
52
  const REQUEST_TIMEOUT_MS = 10_000;
54
53
  const MAX_BODY_BYTES = 64 * 1024;
@@ -58,9 +57,8 @@ let ServiceAuthClient = class ServiceAuthClient {
58
57
  http;
59
58
  constructor(options) {
60
59
  this.options = options;
61
- (0, service_auth_options_1.assertServiceAuthOptions)(options);
62
60
  this.http = axios_1.default.create({
63
- baseURL: options.authUrl.trim().replace(/\/+$/, ''),
61
+ baseURL: options.authUrl,
64
62
  timeout: REQUEST_TIMEOUT_MS,
65
63
  maxContentLength: MAX_BODY_BYTES,
66
64
  maxBodyLength: MAX_BODY_BYTES,
@@ -88,7 +86,7 @@ let ServiceAuthClient = class ServiceAuthClient {
88
86
  exports.ServiceAuthClient = ServiceAuthClient;
89
87
  exports.ServiceAuthClient = ServiceAuthClient = __decorate([
90
88
  (0, common_1.Injectable)(),
91
- __param(0, (0, common_1.Inject)(service_auth_module_definition_1.MODULE_OPTIONS_TOKEN)),
89
+ __param(0, (0, common_1.Inject)(service_auth_options_1.SERVICE_AUTH_CONFIG)),
92
90
  __metadata("design:paramtypes", [Object])
93
91
  ], ServiceAuthClient);
94
92
  class InvalidTokenResponseError extends Error {
@@ -1 +1 @@
1
- {"version":3,"file":"service-auth.client.js","sourceRoot":"","sources":["../src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,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;IAC7E,CAAC;IACD,OAAO,8BAA8B,CAAC;AACxC,CAAC"}
@@ -0,0 +1,12 @@
1
+ export interface ServiceAuthCredentials {
2
+ token: string | null;
3
+ tokenType: string | null;
4
+ fullToken: string;
5
+ }
6
+ export declare class ServiceAuth {
7
+ constructor();
8
+ get token(): string | null;
9
+ get tokenType(): string | null;
10
+ get fullToken(): string;
11
+ }
12
+ export declare function writeServiceAuth(serviceAuth: ServiceAuth, next: ServiceAuthCredentials): void;
@@ -0,0 +1,50 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.ServiceAuth = void 0;
13
+ exports.writeServiceAuth = writeServiceAuth;
14
+ const common_1 = require("@nestjs/common");
15
+ const EMPTY_CREDENTIALS = {
16
+ token: null,
17
+ tokenType: null,
18
+ fullToken: '',
19
+ };
20
+ const credentials = new WeakMap();
21
+ let ServiceAuth = class ServiceAuth {
22
+ constructor() {
23
+ credentials.set(this, EMPTY_CREDENTIALS);
24
+ }
25
+ get token() {
26
+ return current(this).token;
27
+ }
28
+ get tokenType() {
29
+ return current(this).tokenType;
30
+ }
31
+ get fullToken() {
32
+ return current(this).fullToken;
33
+ }
34
+ };
35
+ exports.ServiceAuth = ServiceAuth;
36
+ exports.ServiceAuth = ServiceAuth = __decorate([
37
+ (0, common_1.Injectable)(),
38
+ __metadata("design:paramtypes", [])
39
+ ], ServiceAuth);
40
+ function writeServiceAuth(serviceAuth, next) {
41
+ credentials.set(serviceAuth, {
42
+ token: next.token,
43
+ tokenType: next.tokenType,
44
+ fullToken: next.fullToken,
45
+ });
46
+ }
47
+ function current(serviceAuth) {
48
+ return credentials.get(serviceAuth) ?? EMPTY_CREDENTIALS;
49
+ }
50
+ //# sourceMappingURL=service-auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service-auth.js","sourceRoot":"","sources":["../src/service-auth.ts"],"names":[],"mappings":";;;;;;;;;;;;AAmCA,4CASC;AA5CD,2CAA4C;AAQ5C,MAAM,iBAAiB,GAA2B;IAChD,KAAK,EAAE,IAAI;IACX,SAAS,EAAE,IAAI;IACf,SAAS,EAAE,EAAE;CACd,CAAC;AAEF,MAAM,WAAW,GAAG,IAAI,OAAO,EAAuC,CAAC;AAGhE,IAAM,WAAW,GAAjB,MAAM,WAAW;IACtB;QACE,WAAW,CAAC,GAAG,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;IAC3C,CAAC;IAED,IAAI,KAAK;QACP,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC;IAC7B,CAAC;IAED,IAAI,SAAS;QACX,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC;IACjC,CAAC;IAED,IAAI,SAAS;QACX,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC,SAAS,CAAC;IACjC,CAAC;CACF,CAAA;AAhBY,kCAAW;sBAAX,WAAW;IADvB,IAAA,mBAAU,GAAE;;GACA,WAAW,CAgBvB;AAED,SAAgB,gBAAgB,CAC9B,WAAwB,EACxB,IAA4B;IAE5B,WAAW,CAAC,GAAG,CAAC,WAAW,EAAE;QAC3B,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,SAAS,EAAE,IAAI,CAAC,SAAS;KAC1B,CAAC,CAAC;AACL,CAAC;AAED,SAAS,OAAO,CAAC,WAAwB;IACvC,OAAO,WAAW,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,iBAAiB,CAAC;AAC3D,CAAC"}
@@ -8,11 +8,12 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.ServiceAuthModule = void 0;
10
10
  const common_1 = require("@nestjs/common");
11
+ const service_auth_1 = require("./service-auth");
11
12
  const service_auth_client_1 = require("./service-auth.client");
12
13
  const service_auth_controller_1 = require("./service-auth.controller");
13
14
  const service_auth_module_definition_1 = require("./service-auth.module-definition");
14
15
  const service_auth_service_1 = require("./service-auth.service");
15
- const service_token_1 = require("./service-token");
16
+ const service_auth_options_1 = require("./service-auth.options");
16
17
  let ServiceAuthModule = class ServiceAuthModule extends service_auth_module_definition_1.ConfigurableModuleClass {
17
18
  };
18
19
  exports.ServiceAuthModule = ServiceAuthModule;
@@ -20,8 +21,17 @@ exports.ServiceAuthModule = ServiceAuthModule = __decorate([
20
21
  (0, common_1.Global)(),
21
22
  (0, common_1.Module)({
22
23
  controllers: [service_auth_controller_1.ServiceAuthController],
23
- providers: [service_auth_client_1.ServiceAuthClient, service_auth_service_1.ServiceAuthService, service_token_1.ServiceToken],
24
- exports: [service_token_1.ServiceToken],
24
+ providers: [
25
+ service_auth_1.ServiceAuth,
26
+ {
27
+ provide: service_auth_options_1.SERVICE_AUTH_CONFIG,
28
+ inject: [service_auth_module_definition_1.MODULE_OPTIONS_TOKEN],
29
+ useFactory: (options) => (0, service_auth_options_1.normalizeServiceAuthOptions)(options),
30
+ },
31
+ service_auth_client_1.ServiceAuthClient,
32
+ service_auth_service_1.ServiceAuthService,
33
+ ],
34
+ exports: [service_auth_1.ServiceAuth],
25
35
  })
26
36
  ], ServiceAuthModule);
27
37
  //# sourceMappingURL=service-auth.module.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"service-auth.module.js","sourceRoot":"","sources":["../src/service-auth.module.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAAgD;AAChD,+DAA0D;AAC1D,uEAAkE;AAClE,qFAA2E;AAC3E,iEAA4D;AAC5D,mDAA+C;AAQxC,IAAM,iBAAiB,GAAvB,MAAM,iBAAkB,SAAQ,wDAAuB;CAAG,CAAA;AAApD,8CAAiB;4BAAjB,iBAAiB;IAN7B,IAAA,eAAM,GAAE;IACR,IAAA,eAAM,EAAC;QACN,WAAW,EAAE,CAAC,+CAAqB,CAAC;QACpC,SAAS,EAAE,CAAC,uCAAiB,EAAE,yCAAkB,EAAE,4BAAY,CAAC;QAChE,OAAO,EAAE,CAAC,4BAAY,CAAC;KACxB,CAAC;GACW,iBAAiB,CAAmC"}
1
+ {"version":3,"file":"service-auth.module.js","sourceRoot":"","sources":["../src/service-auth.module.ts"],"names":[],"mappings":";;;;;;;;;AAAA,2CAAgD;AAChD,iDAA6C;AAC7C,+DAA0D;AAC1D,uEAAkE;AAClE,qFAG0C;AAC1C,iEAA4D;AAC5D,iEAIgC;AAkBzB,IAAM,iBAAiB,GAAvB,MAAM,iBAAkB,SAAQ,wDAAuB;CAAG,CAAA;AAApD,8CAAiB;4BAAjB,iBAAiB;IAhB7B,IAAA,eAAM,GAAE;IACR,IAAA,eAAM,EAAC;QACN,WAAW,EAAE,CAAC,+CAAqB,CAAC;QACpC,SAAS,EAAE;YACT,0BAAW;YACX;gBACE,OAAO,EAAE,0CAAmB;gBAC5B,MAAM,EAAE,CAAC,qDAAoB,CAAC;gBAC9B,UAAU,EAAE,CAAC,OAAiC,EAAE,EAAE,CAChD,IAAA,kDAA2B,EAAC,OAAO,CAAC;aACvC;YACD,uCAAiB;YACjB,yCAAkB;SACnB;QACD,OAAO,EAAE,CAAC,0BAAW,CAAC;KACvB,CAAC;GACW,iBAAiB,CAAmC"}
@@ -1,8 +1,38 @@
1
+ export declare const SERVICE_AUTH_CONFIG: unique symbol;
2
+ export declare const DEFAULT_REQUEST_INTERVAL_SECONDS: number;
3
+ export declare const MIN_REQUEST_INTERVAL_SECONDS: number;
4
+ export declare const MAX_REQUEST_INTERVAL_SECONDS: number;
5
+ export declare const MAX_RETRY_ATTEMPTS = 10;
6
+ export declare const EXPIRY_MARGIN_SECONDS = 60;
7
+ export interface ServiceAuthLogger {
8
+ log(...args: unknown[]): void;
9
+ info(...args: unknown[]): void;
10
+ warn(...args: unknown[]): void;
11
+ error(...args: unknown[]): void;
12
+ debug(...args: unknown[]): void;
13
+ verbose(...args: unknown[]): void;
14
+ }
1
15
  export interface ServiceAuthModuleOptions {
2
16
  env?: string;
3
17
  authUrl: string;
4
18
  serviceId: string;
5
19
  serviceSecret: string;
6
- shadowToken?: string;
20
+ shadowToken?: unknown;
21
+ requestInterval?: unknown;
22
+ retry?: unknown;
23
+ logger?: ServiceAuthLogger;
24
+ }
25
+ export interface ServiceAuthConfig {
26
+ env: string;
27
+ local: boolean;
28
+ authUrl: string;
29
+ serviceId: string;
30
+ serviceSecret: string;
31
+ shadowToken: string | null;
32
+ requestInterval: number;
33
+ retry: number;
34
+ logger: ServiceAuthLogger;
7
35
  }
8
- export declare function assertServiceAuthOptions(options: ServiceAuthModuleOptions): void;
36
+ export declare function normalizeServiceAuthOptions(options: ServiceAuthModuleOptions): ServiceAuthConfig;
37
+ export declare function formatDuration(seconds: number): string;
38
+ export declare function expirationTooSmallMessage(expiresIn: number, requestInterval: number): string;
@@ -1,8 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.assertServiceAuthOptions = assertServiceAuthOptions;
3
+ exports.EXPIRY_MARGIN_SECONDS = exports.MAX_RETRY_ATTEMPTS = exports.MAX_REQUEST_INTERVAL_SECONDS = exports.MIN_REQUEST_INTERVAL_SECONDS = exports.DEFAULT_REQUEST_INTERVAL_SECONDS = exports.SERVICE_AUTH_CONFIG = void 0;
4
+ exports.normalizeServiceAuthOptions = normalizeServiceAuthOptions;
5
+ exports.formatDuration = formatDuration;
6
+ exports.expirationTooSmallMessage = expirationTooSmallMessage;
7
+ const common_1 = require("@nestjs/common");
8
+ exports.SERVICE_AUTH_CONFIG = Symbol('SERVICE_AUTH_CONFIG');
9
+ exports.DEFAULT_REQUEST_INTERVAL_SECONDS = 59 * 60;
10
+ exports.MIN_REQUEST_INTERVAL_SECONDS = 5 * 60;
11
+ exports.MAX_REQUEST_INTERVAL_SECONDS = 24 * 60 * 60;
12
+ exports.MAX_RETRY_ATTEMPTS = 10;
13
+ exports.EXPIRY_MARGIN_SECONDS = 60;
4
14
  const REQUIRED_OPTIONS = ['authUrl', 'serviceId', 'serviceSecret'];
5
- function assertServiceAuthOptions(options) {
15
+ function normalizeServiceAuthOptions(options) {
6
16
  const missing = REQUIRED_OPTIONS.filter((key) => {
7
17
  const value = options?.[key];
8
18
  return typeof value !== 'string' || value.trim() === '';
@@ -10,5 +20,129 @@ function assertServiceAuthOptions(options) {
10
20
  if (missing.length > 0) {
11
21
  throw new Error(`ServiceAuthModule requires ${missing.join(', ')}`);
12
22
  }
23
+ const logger = resolveLogger(options.logger);
24
+ const env = normalizeEnv(options.env);
25
+ const requestInterval = clampInterval(parseOptionalNumber(options.requestInterval, 'requestInterval'), logger);
26
+ const retry = clampRetry(parseOptionalNumber(options.retry, 'retry'), logger);
27
+ return {
28
+ env,
29
+ local: env === 'local',
30
+ authUrl: options.authUrl.trim().replace(/\/+$/, ''),
31
+ serviceId: options.serviceId.trim(),
32
+ serviceSecret: options.serviceSecret.trim(),
33
+ shadowToken: normalizeShadowToken(options.shadowToken),
34
+ requestInterval,
35
+ retry,
36
+ logger,
37
+ };
38
+ }
39
+ function formatDuration(seconds) {
40
+ const minutes = seconds / 60;
41
+ const minuteText = Number.isInteger(minutes)
42
+ ? String(minutes)
43
+ : minutes.toFixed(2);
44
+ const minuteWord = Math.abs(minutes) === 1 ? 'minute' : 'minutes';
45
+ const secondWord = Math.abs(seconds) === 1 ? 'second' : 'seconds';
46
+ return `${minuteText} ${minuteWord} (${seconds} ${secondWord})`;
47
+ }
48
+ function expirationTooSmallMessage(expiresIn, requestInterval) {
49
+ return ('Received token expiration is too small for the current service schedule. ' +
50
+ `The expiration is ${formatDuration(expiresIn)} and the schedule interval is ${formatDuration(requestInterval)}. ` +
51
+ `The expiration must be at least ${formatDuration(exports.EXPIRY_MARGIN_SECONDS)} longer than the schedule interval.`);
52
+ }
53
+ function normalizeEnv(env) {
54
+ if (typeof env !== 'string') {
55
+ return '';
56
+ }
57
+ return env.trim().toLowerCase();
58
+ }
59
+ function normalizeShadowToken(value) {
60
+ if (isFalsyShadow(value)) {
61
+ return null;
62
+ }
63
+ if (typeof value !== 'string') {
64
+ throw new Error('ServiceAuthModule shadowToken must be a string');
65
+ }
66
+ const trimmed = value.trim();
67
+ return trimmed === '' ? null : trimmed;
68
+ }
69
+ function isFalsyShadow(value) {
70
+ return (value === undefined ||
71
+ value === null ||
72
+ value === false ||
73
+ value === 0 ||
74
+ value === '');
75
+ }
76
+ function parseOptionalNumber(value, name) {
77
+ if (value === undefined || value === null || value === '') {
78
+ return undefined;
79
+ }
80
+ const raw = typeof value === 'string' ? value.trim() : value;
81
+ if (raw === '') {
82
+ return undefined;
83
+ }
84
+ if (typeof raw !== 'number' && typeof raw !== 'string') {
85
+ throw new Error(`ServiceAuthModule ${name} must be a number`);
86
+ }
87
+ const parsed = typeof raw === 'number' ? raw : Number(raw);
88
+ if (!Number.isFinite(parsed)) {
89
+ throw new Error(`ServiceAuthModule ${name} must be a number`);
90
+ }
91
+ return Math.floor(parsed);
92
+ }
93
+ function clampInterval(value, logger) {
94
+ if (value === undefined) {
95
+ return exports.DEFAULT_REQUEST_INTERVAL_SECONDS;
96
+ }
97
+ if (value < exports.MIN_REQUEST_INTERVAL_SECONDS) {
98
+ logger.warn(`requestInterval ${formatDuration(value)} is below the minimum. Using ${formatDuration(exports.MIN_REQUEST_INTERVAL_SECONDS)}.`);
99
+ return exports.MIN_REQUEST_INTERVAL_SECONDS;
100
+ }
101
+ if (value > exports.MAX_REQUEST_INTERVAL_SECONDS) {
102
+ logger.warn(`requestInterval ${formatDuration(value)} is above the maximum. Using ${formatDuration(exports.MAX_REQUEST_INTERVAL_SECONDS)}.`);
103
+ return exports.MAX_REQUEST_INTERVAL_SECONDS;
104
+ }
105
+ return value;
106
+ }
107
+ function clampRetry(value, logger) {
108
+ if (value === undefined) {
109
+ return 0;
110
+ }
111
+ if (value < 0) {
112
+ logger.warn(`retry ${value} is below the minimum. No retry attempts will be made.`);
113
+ return 0;
114
+ }
115
+ if (value > exports.MAX_RETRY_ATTEMPTS) {
116
+ logger.warn(`retry ${value} is above the maximum. Using ${exports.MAX_RETRY_ATTEMPTS} retry attempts.`);
117
+ return exports.MAX_RETRY_ATTEMPTS;
118
+ }
119
+ return value;
120
+ }
121
+ function resolveLogger(logger) {
122
+ if (logger === undefined || logger === null) {
123
+ return nestLoggerAdapter();
124
+ }
125
+ if (typeof logger.info !== 'function' ||
126
+ typeof logger.warn !== 'function' ||
127
+ typeof logger.error !== 'function') {
128
+ throw new Error('ServiceAuthModule logger must implement info, warn, and error');
129
+ }
130
+ return logger;
131
+ }
132
+ function nestLoggerAdapter() {
133
+ const logger = new common_1.Logger('ServiceAuth');
134
+ return {
135
+ log: (...args) => logger.log(message(args)),
136
+ info: (...args) => logger.log(message(args)),
137
+ warn: (...args) => logger.warn(message(args)),
138
+ error: (...args) => logger.error(message(args)),
139
+ debug: (...args) => logger.debug(message(args)),
140
+ verbose: (...args) => logger.verbose(message(args)),
141
+ };
142
+ }
143
+ function message(args) {
144
+ return args
145
+ .map((arg) => (typeof arg === 'string' ? arg : String(arg)))
146
+ .join(' ');
13
147
  }
14
148
  //# sourceMappingURL=service-auth.options.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"service-auth.options.js","sourceRoot":"","sources":["../src/service-auth.options.ts"],"names":[],"mappings":";;AAUA,4DAUC;AAZD,MAAM,gBAAgB,GAAG,CAAC,SAAS,EAAE,WAAW,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C3C,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC5C,IAAI,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC7C,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/C,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/C,OAAO,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;KACpD,CAAC;AACJ,CAAC;AAED,SAAS,OAAO,CAAC,IAAe;IAC9B,OAAO,IAAI;SACR,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;SAC3D,IAAI,CAAC,GAAG,CAAC,CAAC;AACf,CAAC"}
@@ -1,19 +1,25 @@
1
1
  import { OnModuleDestroy, OnModuleInit } from '@nestjs/common';
2
+ import { ServiceAuth } from './service-auth';
2
3
  import { ServiceAuthClient, ServiceAuthTokenResponse } from './service-auth.client';
3
- import { ServiceToken } from './service-token';
4
+ import { type ServiceAuthConfig } from './service-auth.options';
4
5
  export declare class ServiceAuthService implements OnModuleInit, OnModuleDestroy {
6
+ private readonly config;
5
7
  private readonly client;
6
- private readonly serviceToken;
7
- private readonly logger;
8
+ private readonly serviceAuth;
8
9
  private timer?;
9
10
  private inflight?;
10
- private acquired;
11
11
  private closed;
12
- constructor(client: ServiceAuthClient, serviceToken: ServiceToken);
13
- onModuleInit(): Promise<ServiceAuthTokenResponse>;
12
+ private shadowActive;
13
+ constructor(config: ServiceAuthConfig, client: ServiceAuthClient, serviceAuth: ServiceAuth);
14
+ onModuleInit(): Promise<void>;
14
15
  onModuleDestroy(): void;
15
16
  refresh(): Promise<ServiceAuthTokenResponse>;
16
17
  private execute;
18
+ private requestWithRetries;
19
+ private store;
20
+ private applyShadow;
21
+ private logStartup;
17
22
  private scheduleNext;
18
23
  private clearTimer;
24
+ private failAndStop;
19
25
  }
@@ -8,28 +8,36 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
- var ServiceAuthService_1;
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
12
14
  Object.defineProperty(exports, "__esModule", { value: true });
13
15
  exports.ServiceAuthService = void 0;
14
16
  const common_1 = require("@nestjs/common");
17
+ const service_auth_1 = require("./service-auth");
15
18
  const service_auth_client_1 = require("./service-auth.client");
16
- const service_token_1 = require("./service-token");
17
- const MIN_DELAY_MS = 5_000;
18
- const EXPIRY_MARGIN_SECONDS = 60;
19
- let ServiceAuthService = ServiceAuthService_1 = class ServiceAuthService {
19
+ const service_auth_options_1 = require("./service-auth.options");
20
+ const RETRY_DELAY_MS = 1000;
21
+ let ServiceAuthService = class ServiceAuthService {
22
+ config;
20
23
  client;
21
- serviceToken;
22
- logger = new common_1.Logger(ServiceAuthService_1.name);
24
+ serviceAuth;
23
25
  timer;
24
26
  inflight;
25
- acquired = false;
26
27
  closed = false;
27
- constructor(client, serviceToken) {
28
+ shadowActive = false;
29
+ constructor(config, client, serviceAuth) {
30
+ this.config = config;
28
31
  this.client = client;
29
- this.serviceToken = serviceToken;
32
+ this.serviceAuth = serviceAuth;
30
33
  }
31
34
  onModuleInit() {
32
- return this.refresh();
35
+ this.logStartup();
36
+ if (this.config.local) {
37
+ this.applyShadow();
38
+ return Promise.resolve();
39
+ }
40
+ return this.refresh().then(() => undefined);
33
41
  }
34
42
  onModuleDestroy() {
35
43
  this.closed = true;
@@ -55,34 +63,96 @@ let ServiceAuthService = ServiceAuthService_1 = class ServiceAuthService {
55
63
  }
56
64
  async execute() {
57
65
  try {
58
- const response = await this.client.fetchToken();
66
+ const response = await this.requestWithRetries();
59
67
  if (this.closed) {
60
68
  return response;
61
69
  }
62
- this.serviceToken.set(response.access_token);
63
- this.acquired = true;
64
- this.scheduleNext(response.expires_in);
70
+ this.store(response);
71
+ if (!this.config.local) {
72
+ this.scheduleNext();
73
+ }
65
74
  return response;
66
75
  }
67
76
  catch (error) {
68
- const failure = toFailure(error);
69
- if (this.closed || !this.acquired) {
70
- throw failure;
77
+ if (this.closed || this.config.local) {
78
+ throw toFailure(error);
79
+ }
80
+ this.failAndStop(error);
81
+ }
82
+ }
83
+ async requestWithRetries() {
84
+ const attempts = 1 + this.config.retry;
85
+ let lastError;
86
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
87
+ if (attempt > 0) {
88
+ await delay(RETRY_DELAY_MS);
89
+ }
90
+ if (this.closed) {
91
+ throw new common_1.BadGatewayException('Service auth is stopped');
92
+ }
93
+ try {
94
+ const response = await this.client.fetchToken();
95
+ if (response.expires_in <
96
+ this.config.requestInterval + service_auth_options_1.EXPIRY_MARGIN_SECONDS) {
97
+ throw new Error((0, service_auth_options_1.expirationTooSmallMessage)(response.expires_in, this.config.requestInterval));
98
+ }
99
+ return response;
100
+ }
101
+ catch (error) {
102
+ lastError = error;
71
103
  }
72
- this.logger.error(failure.message);
73
- this.scheduleNext(undefined);
74
- throw failure;
75
104
  }
105
+ throw lastError;
106
+ }
107
+ store(response) {
108
+ const replacingShadow = this.shadowActive;
109
+ (0, service_auth_1.writeServiceAuth)(this.serviceAuth, {
110
+ token: response.access_token,
111
+ tokenType: response.token_type,
112
+ fullToken: `${response.token_type} ${response.access_token}`,
113
+ });
114
+ if (!replacingShadow) {
115
+ return;
116
+ }
117
+ this.shadowActive = false;
118
+ this.config.logger.warn('Manual token request overrode the shadow token.');
76
119
  }
77
- scheduleNext(expiresIn) {
120
+ applyShadow() {
121
+ if (!this.config.shadowToken) {
122
+ (0, service_auth_1.writeServiceAuth)(this.serviceAuth, {
123
+ token: null,
124
+ tokenType: null,
125
+ fullToken: '',
126
+ });
127
+ return;
128
+ }
129
+ (0, service_auth_1.writeServiceAuth)(this.serviceAuth, {
130
+ token: null,
131
+ tokenType: null,
132
+ fullToken: this.config.shadowToken,
133
+ });
134
+ this.shadowActive = true;
135
+ }
136
+ logStartup() {
137
+ this.config.logger.info(`Service auth retry attempts: ${this.config.retry}. Schedule interval: ${(0, service_auth_options_1.formatDuration)(this.config.requestInterval)}.`);
138
+ if (!this.config.local) {
139
+ return;
140
+ }
141
+ if (this.config.shadowToken) {
142
+ this.config.logger.info('Shadow token will be used for fullToken.');
143
+ return;
144
+ }
145
+ this.config.logger.warn('Shadow token was not provided. fullToken will be an empty string.');
146
+ }
147
+ scheduleNext() {
78
148
  this.clearTimer();
79
- if (this.closed) {
149
+ if (this.closed || this.config.local) {
80
150
  return;
81
151
  }
82
152
  this.timer = setTimeout(() => {
83
153
  this.timer = undefined;
84
154
  void this.refresh().catch(() => undefined);
85
- }, delayMsFor(expiresIn));
155
+ }, this.config.requestInterval * 1000);
86
156
  this.timer.unref();
87
157
  }
88
158
  clearTimer() {
@@ -92,26 +162,35 @@ let ServiceAuthService = ServiceAuthService_1 = class ServiceAuthService {
92
162
  clearTimeout(this.timer);
93
163
  this.timer = undefined;
94
164
  }
165
+ failAndStop(error) {
166
+ this.clearTimer();
167
+ this.config.logger.error(failureText(error));
168
+ process.exit(1);
169
+ }
95
170
  };
96
171
  exports.ServiceAuthService = ServiceAuthService;
97
- exports.ServiceAuthService = ServiceAuthService = ServiceAuthService_1 = __decorate([
172
+ exports.ServiceAuthService = ServiceAuthService = __decorate([
98
173
  (0, common_1.Injectable)(),
99
- __metadata("design:paramtypes", [service_auth_client_1.ServiceAuthClient,
100
- service_token_1.ServiceToken])
174
+ __param(0, (0, common_1.Inject)(service_auth_options_1.SERVICE_AUTH_CONFIG)),
175
+ __metadata("design:paramtypes", [Object, service_auth_client_1.ServiceAuthClient,
176
+ service_auth_1.ServiceAuth])
101
177
  ], ServiceAuthService);
102
- function delayMsFor(expiresIn) {
103
- if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn)) {
104
- return MIN_DELAY_MS;
105
- }
106
- return (Math.max(expiresIn - EXPIRY_MARGIN_SECONDS, MIN_DELAY_MS / 1000) * 1000);
178
+ function delay(ms) {
179
+ return new Promise((resolve) => {
180
+ const timer = setTimeout(resolve, ms);
181
+ timer.unref();
182
+ });
107
183
  }
108
184
  function toFailure(error) {
109
185
  if (error instanceof common_1.BadGatewayException) {
110
186
  return error;
111
187
  }
112
- const message = error instanceof Error && error.message
113
- ? error.message
114
- : 'Service token request failed';
115
- return new common_1.BadGatewayException(message);
188
+ return new common_1.BadGatewayException(failureText(error));
189
+ }
190
+ function failureText(error) {
191
+ if (error instanceof Error && error.message) {
192
+ return error.message;
193
+ }
194
+ return 'Service token request failed';
116
195
  }
117
196
  //# sourceMappingURL=service-auth.service.js.map