@feedb2b-dev/service-auth 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,98 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ [circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
6
+ [circleci-url]: https://circleci.com/gh/nestjs/nest
7
+
8
+ <p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
9
+ <p align="center">
10
+ <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
11
+ <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
12
+ <a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
13
+ <a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
14
+ <a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
15
+ <a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
16
+ <a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
17
+ <a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
18
+ <a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
19
+ <a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
20
+ </p>
21
+ <!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
22
+ [![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
23
+
24
+ ## Description
25
+
26
+ [Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
27
+
28
+ ## Project setup
29
+
30
+ ```bash
31
+ $ npm install
32
+ ```
33
+
34
+ ## Compile and run the project
35
+
36
+ ```bash
37
+ # development
38
+ $ npm run start
39
+
40
+ # watch mode
41
+ $ npm run start:dev
42
+
43
+ # production mode
44
+ $ npm run start:prod
45
+ ```
46
+
47
+ ## Run tests
48
+
49
+ ```bash
50
+ # unit tests
51
+ $ npm run test
52
+
53
+ # e2e tests
54
+ $ npm run test:e2e
55
+
56
+ # test coverage
57
+ $ npm run test:cov
58
+ ```
59
+
60
+ ## Deployment
61
+
62
+ When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
63
+
64
+ If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
65
+
66
+ ```bash
67
+ $ npm install -g @nestjs/mau
68
+ $ mau deploy
69
+ ```
70
+
71
+ With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
72
+
73
+ ## Resources
74
+
75
+ Check out a few resources that may come in handy when working with NestJS:
76
+
77
+ - Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
78
+ - For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
79
+ - To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
80
+ - Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
81
+ - Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
82
+ - Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
83
+ - To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
84
+ - Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
85
+
86
+ ## Support
87
+
88
+ Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
89
+
90
+ ## Stay in touch
91
+
92
+ - Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
93
+ - Website - [https://nestjs.com](https://nestjs.com/)
94
+ - Twitter - [@nestframework](https://twitter.com/nestframework)
95
+
96
+ ## License
97
+
98
+ Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
@@ -0,0 +1,3 @@
1
+ export { ServiceAuthModule } from './service-auth.module';
2
+ export { ServiceAuth } from './service-auth';
3
+ export type { ServiceAuthLogger, ServiceAuthModuleOptions, } from './service-auth.options';
package/dist/index.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ServiceAuth = exports.ServiceAuthModule = void 0;
4
+ var service_auth_module_1 = require("./service-auth.module");
5
+ Object.defineProperty(exports, "ServiceAuthModule", { enumerable: true, get: function () { return service_auth_module_1.ServiceAuthModule; } });
6
+ var service_auth_1 = require("./service-auth");
7
+ Object.defineProperty(exports, "ServiceAuth", { enumerable: true, get: function () { return service_auth_1.ServiceAuth; } });
8
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
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"}
@@ -0,0 +1,12 @@
1
+ import { type ServiceAuthConfig } from './service-auth.options';
2
+ export interface ServiceAuthTokenResponse {
3
+ access_token: string;
4
+ token_type: 'Bearer';
5
+ expires_in: number;
6
+ }
7
+ export declare class ServiceAuthClient {
8
+ private readonly options;
9
+ private readonly http;
10
+ constructor(options: ServiceAuthConfig);
11
+ fetchToken(): Promise<ServiceAuthTokenResponse>;
12
+ }
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ 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;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
45
+ return function (target, key) { decorator(target, key, paramIndex); }
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.ServiceAuthClient = void 0;
49
+ const common_1 = require("@nestjs/common");
50
+ const axios_1 = __importStar(require("axios"));
51
+ const service_auth_options_1 = require("./service-auth.options");
52
+ const REQUEST_TIMEOUT_MS = 10_000;
53
+ const MAX_BODY_BYTES = 64 * 1024;
54
+ const MICROSERVICE_AUDIENCE = 'microservice';
55
+ let ServiceAuthClient = class ServiceAuthClient {
56
+ options;
57
+ http;
58
+ constructor(options) {
59
+ this.options = options;
60
+ this.http = axios_1.default.create({
61
+ baseURL: options.authUrl,
62
+ timeout: REQUEST_TIMEOUT_MS,
63
+ maxContentLength: MAX_BODY_BYTES,
64
+ maxBodyLength: MAX_BODY_BYTES,
65
+ headers: { 'Content-Type': 'application/json' },
66
+ });
67
+ }
68
+ async fetchToken() {
69
+ try {
70
+ const response = await this.http.post('/oauth/token', {
71
+ grant_type: 'client_credentials',
72
+ audience: MICROSERVICE_AUDIENCE,
73
+ client_id: this.options.serviceId,
74
+ client_secret: this.options.serviceSecret,
75
+ });
76
+ return parseTokenResponse(response.data);
77
+ }
78
+ catch (error) {
79
+ if (error instanceof InvalidTokenResponseError) {
80
+ throw error;
81
+ }
82
+ throw new Error(failureMessage(error));
83
+ }
84
+ }
85
+ };
86
+ exports.ServiceAuthClient = ServiceAuthClient;
87
+ exports.ServiceAuthClient = ServiceAuthClient = __decorate([
88
+ (0, common_1.Injectable)(),
89
+ __param(0, (0, common_1.Inject)(service_auth_options_1.SERVICE_AUTH_CONFIG)),
90
+ __metadata("design:paramtypes", [Object])
91
+ ], ServiceAuthClient);
92
+ class InvalidTokenResponseError extends Error {
93
+ constructor() {
94
+ super('Auth service returned an invalid token response');
95
+ }
96
+ }
97
+ function parseTokenResponse(data) {
98
+ if (!isRecord(data)) {
99
+ throw new InvalidTokenResponseError();
100
+ }
101
+ const accessToken = data.access_token;
102
+ const tokenType = data.token_type;
103
+ const expiresIn = data.expires_in;
104
+ if (typeof accessToken !== 'string' ||
105
+ accessToken.length === 0 ||
106
+ tokenType !== 'Bearer' ||
107
+ typeof expiresIn !== 'number' ||
108
+ !Number.isFinite(expiresIn)) {
109
+ throw new InvalidTokenResponseError();
110
+ }
111
+ return {
112
+ access_token: accessToken,
113
+ token_type: 'Bearer',
114
+ expires_in: expiresIn,
115
+ };
116
+ }
117
+ function isRecord(value) {
118
+ return typeof value === 'object' && value !== null;
119
+ }
120
+ function failureMessage(error) {
121
+ if ((0, axios_1.isAxiosError)(error) && typeof error.response?.status === 'number') {
122
+ return `Service token request failed with status ${error.response.status}`;
123
+ }
124
+ return 'Service token request failed';
125
+ }
126
+ //# sourceMappingURL=service-auth.client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service-auth.client.js","sourceRoot":"","sources":["../src/service-auth.client.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,7 @@
1
+ import { ServiceAuthTokenResponse } from './service-auth.client';
2
+ import { ServiceAuthService } from './service-auth.service';
3
+ export declare class ServiceAuthController {
4
+ private readonly serviceAuth;
5
+ constructor(serviceAuth: ServiceAuthService);
6
+ token(): Promise<ServiceAuthTokenResponse>;
7
+ }
@@ -0,0 +1,35 @@
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.ServiceAuthController = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ const service_auth_service_1 = require("./service-auth.service");
15
+ let ServiceAuthController = class ServiceAuthController {
16
+ serviceAuth;
17
+ constructor(serviceAuth) {
18
+ this.serviceAuth = serviceAuth;
19
+ }
20
+ token() {
21
+ return this.serviceAuth.refresh();
22
+ }
23
+ };
24
+ exports.ServiceAuthController = ServiceAuthController;
25
+ __decorate([
26
+ (0, common_1.Post)('token'),
27
+ __metadata("design:type", Function),
28
+ __metadata("design:paramtypes", []),
29
+ __metadata("design:returntype", Promise)
30
+ ], ServiceAuthController.prototype, "token", null);
31
+ exports.ServiceAuthController = ServiceAuthController = __decorate([
32
+ (0, common_1.Controller)('serviceAuth'),
33
+ __metadata("design:paramtypes", [service_auth_service_1.ServiceAuthService])
34
+ ], ServiceAuthController);
35
+ //# sourceMappingURL=service-auth.controller.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service-auth.controller.js","sourceRoot":"","sources":["../src/service-auth.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2CAAkD;AAElD,iEAA4D;AAGrD,IAAM,qBAAqB,GAA3B,MAAM,qBAAqB;IACH;IAA7B,YAA6B,WAA+B;QAA/B,gBAAW,GAAX,WAAW,CAAoB;IAAG,CAAC;IAGhE,KAAK;QACH,OAAO,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC;IACpC,CAAC;CACF,CAAA;AAPY,sDAAqB;AAIhC;IADC,IAAA,aAAI,EAAC,OAAO,CAAC;;;;kDAGb;gCANU,qBAAqB;IADjC,IAAA,mBAAU,EAAC,aAAa,CAAC;qCAEkB,yCAAkB;GADjD,qBAAqB,CAOjC"}
@@ -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"}
@@ -0,0 +1,2 @@
1
+ import { ServiceAuthModuleOptions } from './service-auth.options';
2
+ export declare const ConfigurableModuleClass: import("@nestjs/common").ConfigurableModuleCls<ServiceAuthModuleOptions, "register", "create", {}>, MODULE_OPTIONS_TOKEN: string | symbol;
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ var _a;
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.MODULE_OPTIONS_TOKEN = exports.ConfigurableModuleClass = void 0;
5
+ const common_1 = require("@nestjs/common");
6
+ _a = new common_1.ConfigurableModuleBuilder({
7
+ moduleName: 'ServiceAuth',
8
+ })
9
+ .setClassMethodName('register')
10
+ .setExtras({}, (definition) => ({
11
+ ...definition,
12
+ global: true,
13
+ }))
14
+ .build(), exports.ConfigurableModuleClass = _a.ConfigurableModuleClass, exports.MODULE_OPTIONS_TOKEN = _a.MODULE_OPTIONS_TOKEN;
15
+ //# sourceMappingURL=service-auth.module-definition.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service-auth.module-definition.js","sourceRoot":"","sources":["../src/service-auth.module-definition.ts"],"names":[],"mappings":";;;;AAAA,2CAA2D;AAG9C,KACX,IAAI,kCAAyB,CAA2B;IACtD,UAAU,EAAE,aAAa;CAC1B,CAAC;KACC,kBAAkB,CAAC,UAAU,CAAC;KAC9B,SAAS,CAAC,EAAE,EAAE,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IAC9B,GAAG,UAAU;IACb,MAAM,EAAE,IAAI;CACb,CAAC,CAAC;KACF,KAAK,EAAE,EATG,+BAAuB,+BAAE,4BAAoB,2BAS/C"}
@@ -0,0 +1,3 @@
1
+ import { ConfigurableModuleClass } from './service-auth.module-definition';
2
+ export declare class ServiceAuthModule extends ConfigurableModuleClass {
3
+ }
@@ -0,0 +1,37 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.ServiceAuthModule = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const service_auth_1 = require("./service-auth");
12
+ const service_auth_client_1 = require("./service-auth.client");
13
+ const service_auth_controller_1 = require("./service-auth.controller");
14
+ const service_auth_module_definition_1 = require("./service-auth.module-definition");
15
+ const service_auth_service_1 = require("./service-auth.service");
16
+ const service_auth_options_1 = require("./service-auth.options");
17
+ let ServiceAuthModule = class ServiceAuthModule extends service_auth_module_definition_1.ConfigurableModuleClass {
18
+ };
19
+ exports.ServiceAuthModule = ServiceAuthModule;
20
+ exports.ServiceAuthModule = ServiceAuthModule = __decorate([
21
+ (0, common_1.Global)(),
22
+ (0, common_1.Module)({
23
+ controllers: [service_auth_controller_1.ServiceAuthController],
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],
35
+ })
36
+ ], ServiceAuthModule);
37
+ //# sourceMappingURL=service-auth.module.js.map
@@ -0,0 +1 @@
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"}
@@ -0,0 +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
+ }
15
+ export interface ServiceAuthModuleOptions {
16
+ env?: string;
17
+ authUrl: string;
18
+ serviceId: string;
19
+ serviceSecret: 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;
35
+ }
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;
@@ -0,0 +1,148 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
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;
14
+ const REQUIRED_OPTIONS = ['authUrl', 'serviceId', 'serviceSecret'];
15
+ function normalizeServiceAuthOptions(options) {
16
+ const missing = REQUIRED_OPTIONS.filter((key) => {
17
+ const value = options?.[key];
18
+ return typeof value !== 'string' || value.trim() === '';
19
+ });
20
+ if (missing.length > 0) {
21
+ throw new Error(`ServiceAuthModule requires ${missing.join(', ')}`);
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(' ');
147
+ }
148
+ //# sourceMappingURL=service-auth.options.js.map