@nage-api/core 1.0.0-beta.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/LICENSE +202 -0
- package/README.md +141 -0
- package/dist/bootstrap/bootstrap.d.ts +48 -0
- package/dist/bootstrap/bootstrap.js +255 -0
- package/dist/bootstrap/drain.d.ts +48 -0
- package/dist/bootstrap/drain.js +113 -0
- package/dist/bootstrap/lifecycle.d.ts +30 -0
- package/dist/bootstrap/lifecycle.js +64 -0
- package/dist/bootstrap/process-guards.d.ts +42 -0
- package/dist/bootstrap/process-guards.js +103 -0
- package/dist/bootstrap/query-parser.d.ts +34 -0
- package/dist/bootstrap/query-parser.js +37 -0
- package/dist/bootstrap/shutdown.d.ts +55 -0
- package/dist/bootstrap/shutdown.js +182 -0
- package/dist/constants.d.ts +32 -0
- package/dist/constants.js +48 -0
- package/dist/context/active-context.d.ts +23 -0
- package/dist/context/active-context.js +34 -0
- package/dist/context/request-context.middleware.d.ts +31 -0
- package/dist/context/request-context.middleware.js +95 -0
- package/dist/context/request-context.service.d.ts +29 -0
- package/dist/context/request-context.service.js +67 -0
- package/dist/decorators/owner.decorator.d.ts +18 -0
- package/dist/decorators/owner.decorator.js +31 -0
- package/dist/decorators/public.decorator.d.ts +13 -0
- package/dist/decorators/public.decorator.js +23 -0
- package/dist/decorators/version.decorators.d.ts +34 -0
- package/dist/decorators/version.decorators.js +40 -0
- package/dist/errors/catalog.d.ts +149 -0
- package/dist/errors/catalog.js +289 -0
- package/dist/errors/index.d.ts +3 -0
- package/dist/errors/index.js +22 -0
- package/dist/errors/nage.error.d.ts +43 -0
- package/dist/errors/nage.error.js +45 -0
- package/dist/guards/api-version.guard.d.ts +20 -0
- package/dist/guards/api-version.guard.js +73 -0
- package/dist/http/all-exceptions.filter.d.ts +25 -0
- package/dist/http/all-exceptions.filter.js +256 -0
- package/dist/http/envelope.d.ts +25 -0
- package/dist/http/envelope.js +44 -0
- package/dist/http/no-envelope.decorator.d.ts +11 -0
- package/dist/http/no-envelope.decorator.js +16 -0
- package/dist/http/request-timeout.decorators.d.ts +23 -0
- package/dist/http/request-timeout.decorators.js +29 -0
- package/dist/http/request-timeout.interceptor.d.ts +28 -0
- package/dist/http/request-timeout.interceptor.js +75 -0
- package/dist/http/response.interceptor.d.ts +19 -0
- package/dist/http/response.interceptor.js +73 -0
- package/dist/index.d.ts +38 -0
- package/dist/index.js +135 -0
- package/dist/job/job.factory.d.ts +29 -0
- package/dist/job/job.factory.js +50 -0
- package/dist/logging/json.logger.d.ts +23 -0
- package/dist/logging/json.logger.js +136 -0
- package/dist/logging/nest-logger.adapter.d.ts +20 -0
- package/dist/logging/nest-logger.adapter.js +46 -0
- package/dist/module/core.module.d.ts +40 -0
- package/dist/module/core.module.js +112 -0
- package/dist/security/audit.d.ts +42 -0
- package/dist/security/audit.js +399 -0
- package/dist/security/index.d.ts +15 -0
- package/dist/security/index.js +50 -0
- package/dist/security/legacy-scan.d.ts +24 -0
- package/dist/security/legacy-scan.js +98 -0
- package/dist/security/random.d.ts +40 -0
- package/dist/security/random.js +87 -0
- package/dist/security/rate-limit.decorators.d.ts +24 -0
- package/dist/security/rate-limit.decorators.js +25 -0
- package/dist/security/rate-limit.guard.d.ts +44 -0
- package/dist/security/rate-limit.guard.js +130 -0
- package/dist/security/rate-limit.store.d.ts +30 -0
- package/dist/security/rate-limit.store.js +63 -0
- package/dist/security/redaction.d.ts +54 -0
- package/dist/security/redaction.js +146 -0
- package/dist/security/tls.d.ts +29 -0
- package/dist/security/tls.js +48 -0
- package/dist/tokens.d.ts +60 -0
- package/dist/tokens.js +89 -0
- package/dist/version.d.ts +5 -0
- package/dist/version.js +8 -0
- package/package.json +77 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# @nage-api/core
|
|
2
|
+
|
|
3
|
+
The small mandatory layer every `@nage-api` application depends on (PLAN.md §7.2).
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
// apps/api/src/main.ts — the whole file
|
|
7
|
+
import 'reflect-metadata';
|
|
8
|
+
|
|
9
|
+
import { bootstrap } from '@nage-api/core';
|
|
10
|
+
|
|
11
|
+
import { AppModule } from './app.module.js';
|
|
12
|
+
import { EnvSchema } from './config/env.schema.js';
|
|
13
|
+
import { buildConfig } from './config/nage.config.js';
|
|
14
|
+
|
|
15
|
+
const env = EnvSchema.parse(process.env);
|
|
16
|
+
|
|
17
|
+
void bootstrap({ module: AppModule, config: buildConfig(env) });
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
A generated `main.ts` calls `@nage-api/config`'s `loadEnvOrExit(EnvSchema)` in place of
|
|
21
|
+
`parse`: same validation, but it reports every invalid variable at once and exits
|
|
22
|
+
non-zero instead of throwing on the first one.
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// apps/api/src/app.module.ts
|
|
26
|
+
import { Module } from '@nestjs/common';
|
|
27
|
+
import { NageCoreModule } from '@nage-api/core';
|
|
28
|
+
|
|
29
|
+
import { EnvSchema } from './config/env.schema.js';
|
|
30
|
+
import { buildConfig } from './config/nage.config.js';
|
|
31
|
+
import { WidgetController } from './widget/widget.controller.js';
|
|
32
|
+
|
|
33
|
+
const config = buildConfig(EnvSchema.parse(process.env));
|
|
34
|
+
|
|
35
|
+
@Module({ imports: [NageCoreModule.forRoot(config)], controllers: [WidgetController] })
|
|
36
|
+
export class AppModule {}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`forRoot` is what registers the interceptor, the filter, the guards and the
|
|
40
|
+
validation pipe. Skip it and the application still starts — with none of them, so
|
|
41
|
+
the envelope, the error catalog and the request context are simply absent.
|
|
42
|
+
|
|
43
|
+
## What it provides
|
|
44
|
+
|
|
45
|
+
| Area | Export | Notes |
|
|
46
|
+
| ----------------- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------- |
|
|
47
|
+
| Request context | `RequestContextService`, `getActiveContext()` | `AsyncLocalStorage`-backed; carries `requestId`, `user`, `tenantId` (§18) |
|
|
48
|
+
| Response envelope | `ResponseInterceptor`, `successEnvelope` | Controllers `return data`; no `@Res()` (§16.1) |
|
|
49
|
+
| Errors | `AllExceptionsFilter`, `NageError` + catalog | Stable codes, safe messages, detail logged (§17) |
|
|
50
|
+
| Decorators | `@Public`, `@Owner`, `@OptionalOwner`, `@NoEnvelope` | `@Owner()` returns a typed `AuthUser` (§13) |
|
|
51
|
+
| Versioning | `@ForVersion`, `@FromVersion`, `@TillVersion`, `@BetweenVersions`, `ApiVersionGuard` | Header `x-application-version`, retained from the legacy framework (§16.2) |
|
|
52
|
+
| Jobs | `createJob`, `paginate`, `emptyPage` | Typed `Job<TEntity>` for the Phase 5 data layer (§14.1) |
|
|
53
|
+
| Logging | `JsonLogger`, `NestLoggerAdapter` | NDJSON with redaction, behind `LoggerPort` (§18) |
|
|
54
|
+
| Security baseline | `RateLimitGuard`, `@RateLimit`, `randomToken`, `redact`, `auditSecurity` | CSPRNG, redaction, TLS policy, global throttle, boot-time audit (§12) |
|
|
55
|
+
| DI tokens | `NAGE_CONFIG`, `NAGE_LOGGER`, `repositoryToken()`, … | How feature packages collaborate without importing each other (§7.3) |
|
|
56
|
+
| Bootstrap | `bootstrap()`, `createApplication()` | helmet, CORS allow-list, compression, versioning (§21) |
|
|
57
|
+
| Lifecycle | `installShutdown`, `installProcessGuards`, `LifecycleState`, `RequestDrain` | Ordered drain, readiness phase, fatal-error policy (§21) |
|
|
58
|
+
| Request timeout | `RequestTimeoutInterceptor`, `@RequestTimeout`, `@SkipRequestTimeout` | 30 s by default; a handler that overruns is answered 504 (§21) |
|
|
59
|
+
|
|
60
|
+
## Behaviour worth knowing
|
|
61
|
+
|
|
62
|
+
**The envelope is a guarantee.** Every HTTP response is
|
|
63
|
+
`{ success, data | error, meta }`. A repository page is lifted automatically:
|
|
64
|
+
`records` becomes `data`, `pagination` goes to `meta.pagination`. The single
|
|
65
|
+
opt-out is `@NoEnvelope()`, for downloads and webhook callbacks that need an
|
|
66
|
+
exact body.
|
|
67
|
+
|
|
68
|
+
**Errors never leak.** A thrown `NageError` returns its `code` and
|
|
69
|
+
`safeMessage`; its `meta` is logged, never serialised. Anything unrecognised
|
|
70
|
+
becomes `INTERNAL_ERROR` / "Internal server error" with the real message, stack
|
|
71
|
+
and cause in the log line — keyed by the same `requestId` the caller received.
|
|
72
|
+
`ValidationPipe` failures become `VALIDATION_FAILED` (422) with field `details`.
|
|
73
|
+
|
|
74
|
+
**Correlation ids are settled once.** A caller-supplied `X-Request-Id` is
|
|
75
|
+
validated against `REQUEST_ID_PATTERN` and replaced if it does not match — it is
|
|
76
|
+
echoed into responses and log lines, so it is untrusted input. The id is in the
|
|
77
|
+
response header, in `meta.requestId`, and on every log line, for successes and
|
|
78
|
+
failures alike.
|
|
79
|
+
|
|
80
|
+
**Defaults are the safe ones.** CORS is _off_ unless an allow-list is
|
|
81
|
+
configured, because `app.enableCors()` with no arguments allowed every origin by
|
|
82
|
+
omission; a wildcard must be spelled out and is refused in production. Helmet is
|
|
83
|
+
on, HSTS in production. `forbidNonWhitelisted` makes an unexpected body property
|
|
84
|
+
an error rather than a silent drop. Throttling is global and opt-_out_: the
|
|
85
|
+
legacy framework imported a throttler and never registered a guard, so exactly
|
|
86
|
+
one endpoint was limited. A critical security finding at boot exits non-zero
|
|
87
|
+
instead of serving traffic insecurely.
|
|
88
|
+
|
|
89
|
+
**Shutdown runs in an order, and the order is the point.** `bootstrap` claims
|
|
90
|
+
`SIGTERM` and `SIGINT` itself rather than calling Nest's
|
|
91
|
+
`app.enableShutdownHooks()`, which destroys modules _before_ it closes the HTTP
|
|
92
|
+
server: measured against a 600 ms handler signalled at 200 ms, the handler's query
|
|
93
|
+
returned `pool is closed` and the caller got that as a 200. `installShutdown`
|
|
94
|
+
fails readiness first (`/health/ready` → 503, `/health/live` still 200), stops
|
|
95
|
+
accepting connections, waits out the requests it already has under
|
|
96
|
+
`drainTimeoutMs`, and only then calls `app.close()` so modules can close their
|
|
97
|
+
pools. `forceExitAfterMs` bounds the whole thing and exits non-zero on expiry —
|
|
98
|
+
before that, one handler that never returned kept a signalled process alive
|
|
99
|
+
indefinitely.
|
|
100
|
+
|
|
101
|
+
**Handlers have a deadline.** `http.requestTimeoutMs` defaults to 30 seconds and
|
|
102
|
+
answers 504 in the error envelope with the code `REQUEST_TIMEOUT`. It bounds the
|
|
103
|
+
caller's wait, not the process's work: Node cannot abort a running promise, so put
|
|
104
|
+
a deadline on the dependency as well. `@RequestTimeout(ms)` raises it for one
|
|
105
|
+
route, `@SkipRequestTimeout()` removes it for a stream.
|
|
106
|
+
|
|
107
|
+
**An uncaught exception or unhandled rejection is fatal.** That is Node's verdict
|
|
108
|
+
and it is kept; what is added is one structured `fatal` line before the process
|
|
109
|
+
goes, and one bounded attempt at the graceful shutdown above, so the reason lands
|
|
110
|
+
in the same log stream as everything else and the pools still close.
|
|
111
|
+
|
|
112
|
+
**Redaction fails closed.** `redact` masks configured field names at any depth,
|
|
113
|
+
including inside arrays. Where it cannot see — past its depth bound, or into a
|
|
114
|
+
cycle — it substitutes a marker rather than passing the value through, and the
|
|
115
|
+
human-readable log format is scrubbed exactly like the JSON one. A log call never
|
|
116
|
+
throws: an unreadable field is reported as unreadable, and the line still carries
|
|
117
|
+
its level and message.
|
|
118
|
+
|
|
119
|
+
## Dependency rule
|
|
120
|
+
|
|
121
|
+
`@nage-api/core` depends on `@nage-api/contracts` **and nothing else** — never a feature
|
|
122
|
+
package, never a project entity. Enforced by `@nage-api/eslint-config` and
|
|
123
|
+
`pnpm check:boundaries`.
|
|
124
|
+
|
|
125
|
+
## Not yet implemented
|
|
126
|
+
|
|
127
|
+
- **A shared rate-limit store.** The counters are per process, so a limit of 100
|
|
128
|
+
across four pods is 400. `RateLimitStore` is the seam, but the token
|
|
129
|
+
`forRoot` binds it to is not exported, so today there is no way to supply
|
|
130
|
+
another one. See `docs/packages/core.md`.
|
|
131
|
+
- **`http.bodyLimit`.** Declared in the config type and read by nothing; body
|
|
132
|
+
size is whatever the platform adapter defaults to.
|
|
133
|
+
- **URI versioning, `Idempotency-Key`, `Deprecation`/`Sunset` headers** — §16.2
|
|
134
|
+
asks for all three; only header versioning is built.
|
|
135
|
+
- **pino.** §18 names it as the production logger; `JsonLogger` covers structured
|
|
136
|
+
output today and `LoggerPort` is the seam it would arrive behind.
|
|
137
|
+
|
|
138
|
+
Health and readiness endpoints, metrics and tracing live in
|
|
139
|
+
`@nage-api/observability`; config loading and env validation in `@nage-api/config`.
|
|
140
|
+
|
|
141
|
+
The deeper guide is [`docs/packages/core.md`](../../docs/packages/core.md).
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `bootstrap({ module, config })` — the whole of a generated `main.ts`
|
|
3
|
+
* (PLAN.md §9.1, §21).
|
|
4
|
+
*
|
|
5
|
+
* Everything the legacy `main.ts` did by hand, with the defaults inverted to the
|
|
6
|
+
* safe side: CORS is off unless an allow-list is configured, helmet is on, and a
|
|
7
|
+
* boot failure exits non-zero instead of logging and carrying on.
|
|
8
|
+
*/
|
|
9
|
+
import { ValidationPipe, type INestApplication } from '@nestjs/common';
|
|
10
|
+
import { NestFactory } from '@nestjs/core';
|
|
11
|
+
import type { NestApplicationOptions } from '@nestjs/common';
|
|
12
|
+
import type { CorsConfig, NageCoreConfig } from '@nage-api/contracts';
|
|
13
|
+
/** Nest needs a module *class*; typed loosely to avoid depending on its internals. */
|
|
14
|
+
export type ApplicationModule = Parameters<typeof NestFactory.create>[0];
|
|
15
|
+
export interface BootstrapOptions {
|
|
16
|
+
readonly module: ApplicationModule;
|
|
17
|
+
readonly config: NageCoreConfig;
|
|
18
|
+
/** Passed through to `NestFactory.create`. */
|
|
19
|
+
readonly nestOptions?: NestApplicationOptions;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* A wildcard origin is accepted only when written out explicitly, and never in
|
|
23
|
+
* production — the legacy `app.enableCors()` with no arguments allowed every
|
|
24
|
+
* origin by omission.
|
|
25
|
+
*/
|
|
26
|
+
export declare function resolveCorsOptions(cors: CorsConfig | undefined, environment: NageCoreConfig['app']['environment']): Record<string, unknown> | false;
|
|
27
|
+
/**
|
|
28
|
+
* Build a fully configured application **without listening**. Tests and the CLI
|
|
29
|
+
* use this; `bootstrap()` adds the listen and the fail-fast wrapper.
|
|
30
|
+
*/
|
|
31
|
+
export declare function createApplication(options: BootstrapOptions): Promise<INestApplication>;
|
|
32
|
+
/**
|
|
33
|
+
* Create, configure and start the application.
|
|
34
|
+
*
|
|
35
|
+
* A failure here is fatal: the process exits non-zero rather than staying up in
|
|
36
|
+
* a half-configured state, which is what the legacy bootstrap did by only
|
|
37
|
+
* logging the error.
|
|
38
|
+
*
|
|
39
|
+
* This is also where the process-wide policy lives — signal handling and the
|
|
40
|
+
* fatal-error guards. `createApplication` deliberately installs neither: it is
|
|
41
|
+
* used by tests and by the CLI, and a test suite that built ten applications
|
|
42
|
+
* would otherwise leave ten `SIGTERM` listeners and ten `uncaughtException`
|
|
43
|
+
* handlers on one process.
|
|
44
|
+
*/
|
|
45
|
+
export declare function bootstrap(options: BootstrapOptions): Promise<INestApplication>;
|
|
46
|
+
/** Re-exported so applications can build the same pipe for a sub-app. */
|
|
47
|
+
export { ValidationPipe };
|
|
48
|
+
//# sourceMappingURL=bootstrap.d.ts.map
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* `bootstrap({ module, config })` — the whole of a generated `main.ts`
|
|
4
|
+
* (PLAN.md §9.1, §21).
|
|
5
|
+
*
|
|
6
|
+
* Everything the legacy `main.ts` did by hand, with the defaults inverted to the
|
|
7
|
+
* safe side: CORS is off unless an allow-list is configured, helmet is on, and a
|
|
8
|
+
* boot failure exits non-zero instead of logging and carrying on.
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.ValidationPipe = void 0;
|
|
12
|
+
exports.resolveCorsOptions = resolveCorsOptions;
|
|
13
|
+
exports.createApplication = createApplication;
|
|
14
|
+
exports.bootstrap = bootstrap;
|
|
15
|
+
const common_1 = require("@nestjs/common");
|
|
16
|
+
Object.defineProperty(exports, "ValidationPipe", { enumerable: true, get: function () { return common_1.ValidationPipe; } });
|
|
17
|
+
const core_1 = require("@nestjs/core");
|
|
18
|
+
const constants_js_1 = require("../constants.js");
|
|
19
|
+
const catalog_js_1 = require("../errors/catalog.js");
|
|
20
|
+
const json_logger_js_1 = require("../logging/json.logger.js");
|
|
21
|
+
const audit_js_1 = require("../security/audit.js");
|
|
22
|
+
const nest_logger_adapter_js_1 = require("../logging/nest-logger.adapter.js");
|
|
23
|
+
const drain_js_1 = require("./drain.js");
|
|
24
|
+
const lifecycle_js_1 = require("./lifecycle.js");
|
|
25
|
+
const process_guards_js_1 = require("./process-guards.js");
|
|
26
|
+
const query_parser_js_1 = require("./query-parser.js");
|
|
27
|
+
const shutdown_js_1 = require("./shutdown.js");
|
|
28
|
+
/**
|
|
29
|
+
* A wildcard origin is accepted only when written out explicitly, and never in
|
|
30
|
+
* production — the legacy `app.enableCors()` with no arguments allowed every
|
|
31
|
+
* origin by omission.
|
|
32
|
+
*/
|
|
33
|
+
function resolveCorsOptions(cors, environment) {
|
|
34
|
+
if (cors === undefined)
|
|
35
|
+
return false;
|
|
36
|
+
if (cors.origins === '*') {
|
|
37
|
+
if (environment === 'production') {
|
|
38
|
+
throw new catalog_js_1.ConfigurationError({
|
|
39
|
+
detail: 'A wildcard CORS origin is not allowed in production',
|
|
40
|
+
meta: { hint: 'Set http.cors.origins to an explicit allow-list.' },
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
if (cors.credentials === true) {
|
|
44
|
+
throw new catalog_js_1.ConfigurationError({
|
|
45
|
+
detail: 'A wildcard CORS origin cannot be combined with credentials',
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
else if (cors.origins.length === 0) {
|
|
50
|
+
throw new catalog_js_1.ConfigurationError({
|
|
51
|
+
detail: 'http.cors.origins is empty — omit `cors` to disable CORS instead',
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return {
|
|
55
|
+
origin: cors.origins === '*' ? '*' : [...cors.origins],
|
|
56
|
+
credentials: cors.credentials ?? false,
|
|
57
|
+
methods: [...(cors.methods ?? ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])],
|
|
58
|
+
allowedHeaders: [
|
|
59
|
+
...(cors.allowedHeaders ?? [
|
|
60
|
+
'content-type',
|
|
61
|
+
'authorization',
|
|
62
|
+
'x-request-id',
|
|
63
|
+
constants_js_1.API_VERSION_HEADER,
|
|
64
|
+
]),
|
|
65
|
+
],
|
|
66
|
+
exposedHeaders: [...(cors.exposedHeaders ?? ['x-request-id'])],
|
|
67
|
+
maxAge: cors.maxAge ?? 600,
|
|
68
|
+
optionsSuccessStatus: common_1.HttpStatus.NO_CONTENT,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Build a fully configured application **without listening**. Tests and the CLI
|
|
73
|
+
* use this; `bootstrap()` adds the listen and the fail-fast wrapper.
|
|
74
|
+
*/
|
|
75
|
+
async function createApplication(options) {
|
|
76
|
+
const { config } = options;
|
|
77
|
+
const bootLogger = new json_logger_js_1.JsonLogger(undefined, config);
|
|
78
|
+
// Boot-time security gate (§21): a critical finding stops the process here
|
|
79
|
+
// rather than being discovered in a pen test. Development reports and
|
|
80
|
+
// continues, so the baseline does not get switched off to get work done.
|
|
81
|
+
const findings = (0, audit_js_1.assertSecureConfig)({ config, env: process.env });
|
|
82
|
+
if (findings.length > 0) {
|
|
83
|
+
bootLogger.warn('Security findings in configuration', {
|
|
84
|
+
findings: findings.map((finding) => `${finding.code}@${finding.location}`),
|
|
85
|
+
report: (0, audit_js_1.formatFindings)(findings),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
// Nest's own boot messages go through the framework logger, so stdout carries
|
|
89
|
+
// exactly one log grammar (§18).
|
|
90
|
+
const nestOptions = {
|
|
91
|
+
logger: new nest_logger_adapter_js_1.NestLoggerAdapter(new json_logger_js_1.JsonLogger(undefined, config)),
|
|
92
|
+
...options.nestOptions,
|
|
93
|
+
};
|
|
94
|
+
const app = await core_1.NestFactory.create(options.module, nestOptions);
|
|
95
|
+
if (config.app.globalPrefix !== undefined) {
|
|
96
|
+
app.setGlobalPrefix(config.app.globalPrefix);
|
|
97
|
+
}
|
|
98
|
+
// Before anything reads a query string: Express 5 defaults to the `simple`
|
|
99
|
+
// parser, under which `?where[x]=1` never becomes an object and a filtered
|
|
100
|
+
// request quietly returns the unfiltered collection.
|
|
101
|
+
(0, query_parser_js_1.enableQueryDsl)(app);
|
|
102
|
+
// First middleware in the chain, so a request that 404s or dies in body
|
|
103
|
+
// parsing is still counted: `installShutdown` waits on this count, and
|
|
104
|
+
// anything it cannot see is a request that gets its socket cut mid-deploy.
|
|
105
|
+
const lifecycle = (0, lifecycle_js_1.processLifecycle)();
|
|
106
|
+
const drain = new drain_js_1.RequestDrain({ isDraining: () => lifecycle.draining });
|
|
107
|
+
(0, drain_js_1.registerRequestDrain)(app, drain);
|
|
108
|
+
app.use(drain.middleware());
|
|
109
|
+
// The client IP decides rate-limit buckets, so how many proxies to believe is
|
|
110
|
+
// stated explicitly — an unconfigured `x-forwarded-for` is caller-controlled.
|
|
111
|
+
if (config.http?.trustProxy !== undefined) {
|
|
112
|
+
const instance = app.getHttpAdapter().getInstance();
|
|
113
|
+
if (typeof instance.set === 'function') {
|
|
114
|
+
instance.set('trust proxy', config.http.trustProxy);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
// Secure headers first, so they apply to every later handler.
|
|
118
|
+
if (config.http?.helmet?.enabled !== false) {
|
|
119
|
+
const { default: helmet } = await import('helmet');
|
|
120
|
+
const hstsEnabled = config.app.environment === 'production' || config.http?.helmet?.hsts === true;
|
|
121
|
+
app.use(helmet({
|
|
122
|
+
// `false` disables CSP (needed only for Swagger UI); omitting the key
|
|
123
|
+
// keeps helmet's own secure default.
|
|
124
|
+
...(config.http?.helmet?.contentSecurityPolicy === false
|
|
125
|
+
? { contentSecurityPolicy: false }
|
|
126
|
+
: {}),
|
|
127
|
+
hsts: hstsEnabled ? { maxAge: 31_536_000, includeSubDomains: true, preload: false } : false,
|
|
128
|
+
crossOriginResourcePolicy: {
|
|
129
|
+
policy: config.http?.helmet?.crossOriginResourcePolicy ?? 'same-origin',
|
|
130
|
+
},
|
|
131
|
+
}));
|
|
132
|
+
}
|
|
133
|
+
if (config.http?.compression === true) {
|
|
134
|
+
const { default: compression } = await import('compression');
|
|
135
|
+
app.use(compression());
|
|
136
|
+
}
|
|
137
|
+
applyBodyLimit(app, config.http?.bodyLimit);
|
|
138
|
+
const corsOptions = resolveCorsOptions(config.http?.cors, config.app.environment);
|
|
139
|
+
if (corsOptions !== false)
|
|
140
|
+
app.enableCors(corsOptions);
|
|
141
|
+
if (config.versioning?.enabled !== false) {
|
|
142
|
+
const header = config.versioning?.header ?? constants_js_1.API_VERSION_HEADER;
|
|
143
|
+
const fallback = String(config.versioning?.defaultVersion ?? constants_js_1.DEFAULT_API_VERSION);
|
|
144
|
+
app.enableVersioning({
|
|
145
|
+
type: common_1.VersioningType.CUSTOM,
|
|
146
|
+
extractor: (request) => extractVersion(request, header) ?? fallback,
|
|
147
|
+
defaultVersion: fallback,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
return app;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Apply `http.bodyLimit` (§21).
|
|
154
|
+
*
|
|
155
|
+
* The legacy framework capped bodies at 5 MB. This option was declared in
|
|
156
|
+
* `HttpConfig` from the start and read by nothing, so every application built on
|
|
157
|
+
* it accepted a body of any size that its ingress let through — a regression
|
|
158
|
+
* against the framework it replaces, not merely a missing feature. It is applied
|
|
159
|
+
* here rather than at `NestFactory.create` because the platform adapter is what
|
|
160
|
+
* owns the parsers.
|
|
161
|
+
*
|
|
162
|
+
* `useBodyParser` is Express-specific, so a different adapter is left alone
|
|
163
|
+
* rather than being made to fail: an application on one of those still has no
|
|
164
|
+
* limit, and the alternative — throwing — would refuse to boot over a setting the
|
|
165
|
+
* adapter simply cannot express.
|
|
166
|
+
*/
|
|
167
|
+
function applyBodyLimit(app, bodyLimit) {
|
|
168
|
+
if (bodyLimit === undefined)
|
|
169
|
+
return;
|
|
170
|
+
const withParsers = app;
|
|
171
|
+
if (typeof withParsers.useBodyParser !== 'function')
|
|
172
|
+
return;
|
|
173
|
+
// Both, deliberately. Limiting `json` alone leaves a form-encoded body of any
|
|
174
|
+
// size accepted, which is the same hole reached by a different content type.
|
|
175
|
+
withParsers.useBodyParser('json', { limit: bodyLimit });
|
|
176
|
+
withParsers.useBodyParser('urlencoded', { limit: bodyLimit });
|
|
177
|
+
}
|
|
178
|
+
/** Read the version header from a platform-agnostic request object. */
|
|
179
|
+
function extractVersion(request, header) {
|
|
180
|
+
if (request === null || typeof request !== 'object')
|
|
181
|
+
return undefined;
|
|
182
|
+
const headers = request.headers;
|
|
183
|
+
const raw = headers?.[header.toLowerCase()];
|
|
184
|
+
const value = Array.isArray(raw) ? raw[0] : raw;
|
|
185
|
+
return value === undefined || value === '' ? undefined : value;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Create, configure and start the application.
|
|
189
|
+
*
|
|
190
|
+
* A failure here is fatal: the process exits non-zero rather than staying up in
|
|
191
|
+
* a half-configured state, which is what the legacy bootstrap did by only
|
|
192
|
+
* logging the error.
|
|
193
|
+
*
|
|
194
|
+
* This is also where the process-wide policy lives — signal handling and the
|
|
195
|
+
* fatal-error guards. `createApplication` deliberately installs neither: it is
|
|
196
|
+
* used by tests and by the CLI, and a test suite that built ten applications
|
|
197
|
+
* would otherwise leave ten `SIGTERM` listeners and ten `uncaughtException`
|
|
198
|
+
* handlers on one process.
|
|
199
|
+
*/
|
|
200
|
+
async function bootstrap(options) {
|
|
201
|
+
const { config } = options;
|
|
202
|
+
const logger = new json_logger_js_1.JsonLogger(undefined, config);
|
|
203
|
+
try {
|
|
204
|
+
const app = await createApplication(options);
|
|
205
|
+
const port = config.app.port ?? 3000;
|
|
206
|
+
const host = config.app.host ?? '0.0.0.0';
|
|
207
|
+
// Installed before `listen`: a signal that arrives during startup must find a
|
|
208
|
+
// handler, or the default disposition kills the process with connections
|
|
209
|
+
// already accepted. Nest's own `enableShutdownHooks()` is not used — it
|
|
210
|
+
// destroys modules *before* closing the server, so pools go while requests
|
|
211
|
+
// are still running (see shutdown.ts).
|
|
212
|
+
const shutdown = config.shutdown?.enabled === false ? undefined : (0, shutdown_js_1.installShutdown)(app, { config, logger });
|
|
213
|
+
const disposeGuards = (0, process_guards_js_1.installProcessGuards)({
|
|
214
|
+
logger,
|
|
215
|
+
...(shutdown === undefined
|
|
216
|
+
? {}
|
|
217
|
+
: {
|
|
218
|
+
onFatal: async () => {
|
|
219
|
+
await shutdown.run('fatal-error');
|
|
220
|
+
},
|
|
221
|
+
}),
|
|
222
|
+
});
|
|
223
|
+
// Both sets of listeners come off together, so an embedded application — or a
|
|
224
|
+
// test that boots several — can hand the process back the way it found it.
|
|
225
|
+
(0, shutdown_js_1.registerShutdownHandle)(app, {
|
|
226
|
+
get draining() {
|
|
227
|
+
return shutdown?.draining ?? false;
|
|
228
|
+
},
|
|
229
|
+
run: async (reason) => (await shutdown?.run(reason)) ?? 0,
|
|
230
|
+
dispose: () => {
|
|
231
|
+
shutdown?.dispose();
|
|
232
|
+
disposeGuards();
|
|
233
|
+
},
|
|
234
|
+
});
|
|
235
|
+
await app.listen(port, host);
|
|
236
|
+
(0, lifecycle_js_1.processLifecycle)().markLive();
|
|
237
|
+
logger.info('Application started', {
|
|
238
|
+
name: config.app.name,
|
|
239
|
+
environment: config.app.environment,
|
|
240
|
+
port,
|
|
241
|
+
host,
|
|
242
|
+
...(config.app.globalPrefix === undefined ? {} : { globalPrefix: config.app.globalPrefix }),
|
|
243
|
+
});
|
|
244
|
+
return app;
|
|
245
|
+
}
|
|
246
|
+
catch (error) {
|
|
247
|
+
logger.fatal('Application failed to start', {
|
|
248
|
+
name: config.app.name,
|
|
249
|
+
error: error instanceof Error ? error.message : String(error),
|
|
250
|
+
stack: error instanceof Error ? error.stack : undefined,
|
|
251
|
+
});
|
|
252
|
+
process.exit(1);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
//# sourceMappingURL=bootstrap.js.map
|