@haatlabs-core/nest-common 0.0.0-stage → 0.10.0
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 +201 -0
- package/README.md +30 -2
- package/dist/auth-metadata.d.ts +10 -0
- package/dist/auth-metadata.js +11 -0
- package/dist/auth-metadata.js.map +1 -0
- package/dist/cjs/auth-metadata.d.ts +10 -0
- package/dist/cjs/auth-metadata.js +34 -0
- package/dist/cjs/error.filter.d.ts +20 -0
- package/dist/cjs/error.filter.js +111 -0
- package/dist/cjs/fastify-app.d.ts +16 -0
- package/dist/cjs/fastify-app.js +109 -0
- package/dist/cjs/feature-gate.d.ts +28 -0
- package/dist/cjs/feature-gate.js +50 -0
- package/dist/cjs/health.d.ts +36 -0
- package/dist/cjs/health.js +107 -0
- package/dist/cjs/html-problem.filter.d.ts +32 -0
- package/dist/cjs/html-problem.filter.js +112 -0
- package/dist/cjs/index.d.ts +17 -0
- package/dist/cjs/index.js +101 -0
- package/dist/cjs/package.json +8 -0
- package/dist/cjs/period.d.ts +6 -0
- package/dist/cjs/period.js +34 -0
- package/dist/cjs/shutdown.d.ts +13 -0
- package/dist/cjs/shutdown.js +46 -0
- package/dist/cjs/tokens.d.ts +15 -0
- package/dist/cjs/tokens.js +61 -0
- package/dist/cjs/warn-auth.d.ts +4 -0
- package/dist/cjs/warn-auth.js +34 -0
- package/dist/cjs/zod.pipe.d.ts +11 -0
- package/dist/cjs/zod.pipe.js +41 -0
- package/dist/error.filter.d.ts +20 -0
- package/dist/error.filter.js +108 -0
- package/dist/error.filter.js.map +1 -0
- package/dist/fastify-app.d.ts +16 -0
- package/dist/fastify-app.js +97 -0
- package/dist/fastify-app.js.map +1 -0
- package/dist/feature-gate.d.ts +28 -0
- package/dist/feature-gate.js +27 -0
- package/dist/feature-gate.js.map +1 -0
- package/dist/health.d.ts +36 -0
- package/dist/health.js +79 -0
- package/dist/health.js.map +1 -0
- package/dist/html-problem.filter.d.ts +32 -0
- package/dist/html-problem.filter.js +97 -0
- package/dist/html-problem.filter.js.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/period.d.ts +6 -0
- package/dist/period.js +14 -0
- package/dist/period.js.map +1 -0
- package/dist/shutdown.d.ts +13 -0
- package/dist/shutdown.js +31 -0
- package/dist/shutdown.js.map +1 -0
- package/dist/tokens.d.ts +15 -0
- package/dist/tokens.js +20 -0
- package/dist/tokens.js.map +1 -0
- package/dist/warn-auth.d.ts +4 -0
- package/dist/warn-auth.js +10 -0
- package/dist/warn-auth.js.map +1 -0
- package/dist/zod.pipe.d.ts +11 -0
- package/dist/zod.pipe.js +22 -0
- package/dist/zod.pipe.js.map +1 -0
- package/package.json +82 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Haatlabs
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,31 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @haatlabs-core/nest-common
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
What every app's NestJS API shares, below authentication.
|
|
4
|
+
|
|
5
|
+
- **Tokens** (`CONFIG`, `LOGGER`, `APP_DB`, `SYSTEM_DB`, `REDIS`, `RATE_LIMITER`, `METRICS`,
|
|
6
|
+
`PLAIN_FETCH`, `FETCH`, `MAILER`, `TOKEN_CIPHER`, `STORE_TOKENS`): registered symbols, so
|
|
7
|
+
two installed copies name the same provider. An app's `infra/tokens.ts` re-exports them
|
|
8
|
+
beside its own.
|
|
9
|
+
- `AppExceptionFilter`: every error as `{ error: { code, message, requestId } }`; a fault of
|
|
10
|
+
ours is INTERNAL, logged without SQL or bound values, and never shown.
|
|
11
|
+
- `HtmlProblemFilter` with the provider `HTML_PROBLEM_OPTIONS`: a page, not JSON, for a
|
|
12
|
+
refusal a person's browser was sent to.
|
|
13
|
+
- `ZodPipe`, `Public` / `OptionalAuth` (the auth mode nest-auth's guard reads).
|
|
14
|
+
- `MAILER` is bound by the app to `@haatlabs-core/mailer`'s `mailerFromConfig(config.mail)`.
|
|
15
|
+
- `requireFeature` / `requireFeatureFor` over a `FeatureSource`, with `FEATURE_ERRORS`
|
|
16
|
+
(spread into `defineErrors` by an app with plans).
|
|
17
|
+
- `HealthController` (`/health/live`, `/health/ready`) over the provider `HEALTH_CHECKS`,
|
|
18
|
+
with `postgresCheck` and `redisCheck`; a check may be `advisory` and cached (`cacheMs`).
|
|
19
|
+
- `createFastifyApp(module, options)`: request IDs, a span per request, metrics by route
|
|
20
|
+
pattern, helmet, cookies, CORS and the OpenAPI document. `installShutdown` and
|
|
21
|
+
`warnAuthMisconfig` for the app's main. `oneMonthAfter`. `observeHttp` is given before the
|
|
22
|
+
app exists, so an app makes its metrics in `main` (with `@haatlabs-core/observability/metrics`)
|
|
23
|
+
and hands the same object to its module as `METRICS`.
|
|
24
|
+
|
|
25
|
+
Every `@nestjs/*` package, `fastify`, `ioredis`, `drizzle-orm` and `zod` are peers.
|
|
26
|
+
|
|
27
|
+
## Install
|
|
28
|
+
|
|
29
|
+
pnpm add @haatlabs-core/nest-common
|
|
30
|
+
|
|
31
|
+
It leaves these packages to your app, so the app holds one copy: `@fastify/cookie`, `@fastify/helmet`, `@nestjs/common`, `@nestjs/core`, `@nestjs/platform-fastify`, `@nestjs/swagger`, `drizzle-orm`, `fastify`, `ioredis`, `reflect-metadata`, `rxjs`, `zod`.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a route needs a signed-in principal. Kept here, below the auth package, so that
|
|
3
|
+
* shared controllers (health) can be public; nest-auth's guard reads the same key.
|
|
4
|
+
*/
|
|
5
|
+
export declare const AUTH_MODE = "auth:mode";
|
|
6
|
+
export type AuthMode = 'required' | 'optional' | 'public';
|
|
7
|
+
/** No authentication is attempted (login, OAuth callback, webhooks, health). */
|
|
8
|
+
export declare const Public: () => MethodDecorator & ClassDecorator;
|
|
9
|
+
/** Authenticates when credentials are present but allows anonymous requests. */
|
|
10
|
+
export declare const OptionalAuth: () => MethodDecorator & ClassDecorator;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { SetMetadata } from '@nestjs/common';
|
|
2
|
+
/**
|
|
3
|
+
* Whether a route needs a signed-in principal. Kept here, below the auth package, so that
|
|
4
|
+
* shared controllers (health) can be public; nest-auth's guard reads the same key.
|
|
5
|
+
*/
|
|
6
|
+
export const AUTH_MODE = 'auth:mode';
|
|
7
|
+
/** No authentication is attempted (login, OAuth callback, webhooks, health). */
|
|
8
|
+
export const Public = () => SetMetadata(AUTH_MODE, 'public');
|
|
9
|
+
/** Authenticates when credentials are present but allows anonymous requests. */
|
|
10
|
+
export const OptionalAuth = () => SetMetadata(AUTH_MODE, 'optional');
|
|
11
|
+
//# sourceMappingURL=auth-metadata.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-metadata.js","sourceRoot":"","sources":["../src/auth-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE7C;;;GAGG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,WAAW,CAAC;AAGrC,gFAAgF;AAChF,MAAM,CAAC,MAAM,MAAM,GAAG,GAAqC,EAAE,CAC3D,WAAW,CAAC,SAAS,EAAE,QAA2B,CAAC,CAAC;AACtD,gFAAgF;AAChF,MAAM,CAAC,MAAM,YAAY,GAAG,GAAqC,EAAE,CACjE,WAAW,CAAC,SAAS,EAAE,UAA6B,CAAC,CAAC"}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether a route needs a signed-in principal. Kept here, below the auth package, so that
|
|
3
|
+
* shared controllers (health) can be public; nest-auth's guard reads the same key.
|
|
4
|
+
*/
|
|
5
|
+
export declare const AUTH_MODE = "auth:mode";
|
|
6
|
+
export type AuthMode = 'required' | 'optional' | 'public';
|
|
7
|
+
/** No authentication is attempted (login, OAuth callback, webhooks, health). */
|
|
8
|
+
export declare const Public: () => MethodDecorator & ClassDecorator;
|
|
9
|
+
/** Authenticates when credentials are present but allows anonymous requests. */
|
|
10
|
+
export declare const OptionalAuth: () => MethodDecorator & ClassDecorator;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var auth_metadata_exports = {};
|
|
19
|
+
__export(auth_metadata_exports, {
|
|
20
|
+
AUTH_MODE: () => AUTH_MODE,
|
|
21
|
+
OptionalAuth: () => OptionalAuth,
|
|
22
|
+
Public: () => Public
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(auth_metadata_exports);
|
|
25
|
+
var import_common = require("@nestjs/common");
|
|
26
|
+
const AUTH_MODE = "auth:mode";
|
|
27
|
+
const Public = () => (0, import_common.SetMetadata)(AUTH_MODE, "public");
|
|
28
|
+
const OptionalAuth = () => (0, import_common.SetMetadata)(AUTH_MODE, "optional");
|
|
29
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
30
|
+
0 && (module.exports = {
|
|
31
|
+
AUTH_MODE,
|
|
32
|
+
OptionalAuth,
|
|
33
|
+
Public
|
|
34
|
+
});
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ArgumentsHost, ExceptionFilter } from '@nestjs/common';
|
|
2
|
+
import type { Logger } from '@haatlabs-core/logger';
|
|
3
|
+
/** The body of every error answer. */
|
|
4
|
+
export interface ErrorEnvelope {
|
|
5
|
+
error: {
|
|
6
|
+
code: string;
|
|
7
|
+
message: string;
|
|
8
|
+
requestId: string;
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Every error an app's API answers, as `{ error: { code, message, requestId } }`. An
|
|
13
|
+
* AppError keeps its code and status; a fault of ours is INTERNAL, logged without SQL or
|
|
14
|
+
* bound values, and never shown.
|
|
15
|
+
*/
|
|
16
|
+
export declare class AppExceptionFilter implements ExceptionFilter {
|
|
17
|
+
private readonly logger;
|
|
18
|
+
constructor(logger: Logger);
|
|
19
|
+
catch(exception: unknown, host: ArgumentsHost): void;
|
|
20
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var error_filter_exports = {};
|
|
19
|
+
__export(error_filter_exports, {
|
|
20
|
+
AppExceptionFilter: () => AppExceptionFilter
|
|
21
|
+
});
|
|
22
|
+
module.exports = __toCommonJS(error_filter_exports);
|
|
23
|
+
var import_common = require("@nestjs/common");
|
|
24
|
+
var import_errors = require("@haatlabs-core/errors");
|
|
25
|
+
var import_tokens = require("./tokens.js");
|
|
26
|
+
var __decorate = function(decorators, target, key, desc) {
|
|
27
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
28
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
29
|
+
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;
|
|
30
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
31
|
+
};
|
|
32
|
+
var __param = function(paramIndex, decorator) {
|
|
33
|
+
return function(target, key) {
|
|
34
|
+
decorator(target, key, paramIndex);
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
const MS_PER_SECOND = 1e3;
|
|
38
|
+
const SERVER_ERROR_MIN = 500;
|
|
39
|
+
const CLIENT_ERROR_MIN = 400;
|
|
40
|
+
const HTTP_ERROR_MAX = 599;
|
|
41
|
+
const INTERNAL_STATUS = 500;
|
|
42
|
+
const HTTP_STATUS_CODES = {
|
|
43
|
+
400: "VALIDATION_FAILED",
|
|
44
|
+
401: "UNAUTHENTICATED",
|
|
45
|
+
403: "FORBIDDEN",
|
|
46
|
+
404: "NOT_FOUND",
|
|
47
|
+
409: "CONFLICT",
|
|
48
|
+
413: "VALIDATION_FAILED",
|
|
49
|
+
429: "RATE_LIMITED"
|
|
50
|
+
};
|
|
51
|
+
const isHttpErrorStatus = (status) => Number.isInteger(status) && status >= CLIENT_ERROR_MIN && status <= HTTP_ERROR_MAX;
|
|
52
|
+
const codeForStatus = (status) => status >= SERVER_ERROR_MIN ? "INTERNAL" : HTTP_STATUS_CODES[status] ?? "VALIDATION_FAILED";
|
|
53
|
+
function isFastifyClientError(exception) {
|
|
54
|
+
if (typeof exception !== "object" || exception === null)
|
|
55
|
+
return false;
|
|
56
|
+
const { code, statusCode } = exception;
|
|
57
|
+
return typeof code === "string" && code.startsWith("FST_") && typeof statusCode === "number" && Number.isInteger(statusCode) && statusCode >= CLIENT_ERROR_MIN && statusCode < SERVER_ERROR_MIN;
|
|
58
|
+
}
|
|
59
|
+
let AppExceptionFilter = class AppExceptionFilter2 {
|
|
60
|
+
logger;
|
|
61
|
+
constructor(logger) {
|
|
62
|
+
this.logger = logger;
|
|
63
|
+
}
|
|
64
|
+
catch(exception, host) {
|
|
65
|
+
const http = host.switchToHttp();
|
|
66
|
+
const request = http.getRequest();
|
|
67
|
+
const reply = http.getResponse();
|
|
68
|
+
const requestId = String(request.id);
|
|
69
|
+
let status = INTERNAL_STATUS;
|
|
70
|
+
let code = "INTERNAL";
|
|
71
|
+
let message = "Internal server error";
|
|
72
|
+
if (exception instanceof import_errors.AppError) {
|
|
73
|
+
status = exception.httpStatus;
|
|
74
|
+
code = exception.code;
|
|
75
|
+
if (status !== INTERNAL_STATUS)
|
|
76
|
+
message = exception.message;
|
|
77
|
+
if (exception.retryAfterMs !== void 0)
|
|
78
|
+
reply.header("Retry-After", Math.ceil(exception.retryAfterMs / MS_PER_SECOND));
|
|
79
|
+
} else if (exception instanceof import_common.HttpException) {
|
|
80
|
+
const httpStatus = exception.getStatus();
|
|
81
|
+
if (isHttpErrorStatus(httpStatus)) {
|
|
82
|
+
status = httpStatus;
|
|
83
|
+
code = codeForStatus(status);
|
|
84
|
+
if (status < SERVER_ERROR_MIN)
|
|
85
|
+
message = exception.message;
|
|
86
|
+
}
|
|
87
|
+
} else if (isFastifyClientError(exception)) {
|
|
88
|
+
status = exception.statusCode;
|
|
89
|
+
code = codeForStatus(status);
|
|
90
|
+
message = "Request could not be processed";
|
|
91
|
+
}
|
|
92
|
+
if (status >= SERVER_ERROR_MIN) {
|
|
93
|
+
const safeMessage = (0, import_errors.safeErrorMessage)(exception);
|
|
94
|
+
const isQueryFailure = exception instanceof Error && safeMessage !== exception.message;
|
|
95
|
+
this.logger.error({
|
|
96
|
+
requestId,
|
|
97
|
+
err: exception instanceof Error ? { message: safeMessage, ...isQueryFailure ? {} : { stack: exception.stack } } : safeMessage
|
|
98
|
+
}, "Unhandled error");
|
|
99
|
+
}
|
|
100
|
+
const body = { error: { code, message, requestId } };
|
|
101
|
+
void reply.status(status).send(body);
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
AppExceptionFilter = __decorate([
|
|
105
|
+
(0, import_common.Catch)(),
|
|
106
|
+
__param(0, (0, import_common.Inject)(import_tokens.LOGGER))
|
|
107
|
+
], AppExceptionFilter);
|
|
108
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
109
|
+
0 && (module.exports = {
|
|
110
|
+
AppExceptionFilter
|
|
111
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
import type { DynamicModule, Type } from '@nestjs/common';
|
|
3
|
+
import type { NestFastifyApplication } from '@nestjs/platform-fastify';
|
|
4
|
+
export interface FastifyAppOptions {
|
|
5
|
+
/** Reverse proxies whose X-Forwarded-For is trusted; 0 trusts none. */
|
|
6
|
+
trustProxyHops: number;
|
|
7
|
+
corsOrigins: string[];
|
|
8
|
+
bodyLimit?: number;
|
|
9
|
+
/** The longest a path parameter may be; a longer one is answered 414. Fastify's 100 by default. */
|
|
10
|
+
maxParamLength?: number;
|
|
11
|
+
/** The OpenAPI document served at `/api/docs`; none when not given. */
|
|
12
|
+
openApi?: () => object;
|
|
13
|
+
/** Called once per response, with the route's pattern (never the address asked for). */
|
|
14
|
+
observeHttp?: (method: string, route: string, status: number, seconds: number) => void;
|
|
15
|
+
}
|
|
16
|
+
export declare function createFastifyApp(module: Type<unknown> | DynamicModule, options: FastifyAppOptions): Promise<NestFastifyApplication>;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
21
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
22
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
23
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
25
|
+
mod
|
|
26
|
+
));
|
|
27
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
28
|
+
var fastify_app_exports = {};
|
|
29
|
+
__export(fastify_app_exports, {
|
|
30
|
+
createFastifyApp: () => createFastifyApp
|
|
31
|
+
});
|
|
32
|
+
module.exports = __toCommonJS(fastify_app_exports);
|
|
33
|
+
var import_reflect_metadata = require("reflect-metadata");
|
|
34
|
+
var import_node_crypto = require("node:crypto");
|
|
35
|
+
var import_cookie = __toESM(require("@fastify/cookie"));
|
|
36
|
+
var import_helmet = __toESM(require("@fastify/helmet"));
|
|
37
|
+
var import_core = require("@nestjs/core");
|
|
38
|
+
var import_platform_fastify = require("@nestjs/platform-fastify");
|
|
39
|
+
var import_swagger = require("@nestjs/swagger");
|
|
40
|
+
var import_observability = require("@haatlabs-core/observability");
|
|
41
|
+
const DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024;
|
|
42
|
+
const DEFAULT_MAX_PARAM_LENGTH = 100;
|
|
43
|
+
const BAD_REQUEST = 400;
|
|
44
|
+
const URI_TOO_LONG = 414;
|
|
45
|
+
const TOO_LONG_MESSAGE = "The address is too long.";
|
|
46
|
+
const BAD_ADDRESS_MESSAGE = "The address is not valid.";
|
|
47
|
+
const MS_PER_SECOND = 1e3;
|
|
48
|
+
const REQUEST_ID_HEADER = "x-request-id";
|
|
49
|
+
const REQUEST_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
|
|
50
|
+
const HTTP_SPAN = Symbol("haatlabs.httpSpan");
|
|
51
|
+
async function createFastifyApp(module2, options) {
|
|
52
|
+
const adapter = new import_platform_fastify.FastifyAdapter({
|
|
53
|
+
// Only as many X-Forwarded-For hops as are configured; a direct client cannot forge request.ip.
|
|
54
|
+
// Fastify 5 treats a numeric trustProxy as "trust nothing", so the hop count is a function.
|
|
55
|
+
trustProxy: options.trustProxyHops === 0 ? false : (_address, hop) => hop < options.trustProxyHops,
|
|
56
|
+
bodyLimit: options.bodyLimit ?? DEFAULT_BODY_LIMIT_BYTES,
|
|
57
|
+
maxParamLength: options.maxParamLength ?? DEFAULT_MAX_PARAM_LENGTH,
|
|
58
|
+
// What the router refuses before any hook or filter runs (an address it cannot decode, a
|
|
59
|
+
// parameter over maxParamLength) is answered in the platform's envelope too, with its ID.
|
|
60
|
+
frameworkErrors: (error, request, reply) => {
|
|
61
|
+
const status = typeof error.statusCode === "number" && error.statusCode >= BAD_REQUEST ? error.statusCode : BAD_REQUEST;
|
|
62
|
+
const requestId = String(request.id);
|
|
63
|
+
void reply.code(status).header(REQUEST_ID_HEADER, requestId).send({
|
|
64
|
+
error: {
|
|
65
|
+
code: "VALIDATION_FAILED",
|
|
66
|
+
message: status === URI_TOO_LONG ? TOO_LONG_MESSAGE : BAD_ADDRESS_MESSAGE,
|
|
67
|
+
requestId
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
// An inbound ID is reused only if it is safe to write to logs and headers.
|
|
72
|
+
genReqId: (request) => {
|
|
73
|
+
const inbound = request.headers[REQUEST_ID_HEADER];
|
|
74
|
+
return typeof inbound === "string" && REQUEST_ID_PATTERN.test(inbound) ? inbound : (0, import_node_crypto.randomUUID)();
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
const app = await import_core.NestFactory.create(module2, adapter, {
|
|
78
|
+
rawBody: true,
|
|
79
|
+
logger: false
|
|
80
|
+
});
|
|
81
|
+
const fastify = app.getHttpAdapter().getInstance();
|
|
82
|
+
fastify.addHook("onRequest", async (request, reply) => {
|
|
83
|
+
reply.header(REQUEST_ID_HEADER, String(request.id));
|
|
84
|
+
});
|
|
85
|
+
fastify.decorateRequest(HTTP_SPAN, null);
|
|
86
|
+
fastify.addHook("onRequest", (request, _reply, done) => {
|
|
87
|
+
const span = (0, import_observability.startHttpSpan)(request.method, { requestId: String(request.id) });
|
|
88
|
+
request[HTTP_SPAN] = span;
|
|
89
|
+
span.run(done);
|
|
90
|
+
});
|
|
91
|
+
fastify.addHook("onResponse", async (request, reply) => {
|
|
92
|
+
const route = request.is404 ? "" : request.routeOptions.url ?? "";
|
|
93
|
+
options.observeHttp?.(request.method, route, reply.statusCode, reply.elapsedTime / MS_PER_SECOND);
|
|
94
|
+
request[HTTP_SPAN]?.end(route, reply.statusCode);
|
|
95
|
+
});
|
|
96
|
+
await app.register(import_helmet.default, { contentSecurityPolicy: false });
|
|
97
|
+
await app.register(import_cookie.default);
|
|
98
|
+
app.enableCors({ origin: options.corsOrigins, credentials: true });
|
|
99
|
+
if (options.openApi) {
|
|
100
|
+
import_swagger.SwaggerModule.setup("api/docs", app, options.openApi());
|
|
101
|
+
}
|
|
102
|
+
await app.init();
|
|
103
|
+
await fastify.ready();
|
|
104
|
+
return app;
|
|
105
|
+
}
|
|
106
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
107
|
+
0 && (module.exports = {
|
|
108
|
+
createFastifyApp
|
|
109
|
+
});
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { TenantContext } from '@haatlabs-core/db-core';
|
|
2
|
+
/** The code a feature gate refuses with: an app with plans spreads it into defineErrors. */
|
|
3
|
+
export declare const FEATURE_ERRORS: {
|
|
4
|
+
readonly FEATURE_DISABLED: {
|
|
5
|
+
readonly httpStatus: 403;
|
|
6
|
+
readonly transient: false;
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
/** Shown when the plan, not an administrator, is why something is not available. */
|
|
10
|
+
export declare const NOT_IN_PLAN_MESSAGE = "Your plan does not include this. See the plans to add it.";
|
|
11
|
+
/** Shown to a merchant whenever a feature that is off stops something. */
|
|
12
|
+
export declare const FEATURE_OFF_MESSAGE = "This is not available for your account. Contact support to have it turned on.";
|
|
13
|
+
/** Where an app's feature switches are read from: its plans and an administrator's overrides. */
|
|
14
|
+
export interface FeatureSource<F extends string = string> {
|
|
15
|
+
detail(ctx: TenantContext): Promise<{
|
|
16
|
+
features: Record<F, boolean>;
|
|
17
|
+
overridden: F[];
|
|
18
|
+
}>;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Stops new work of a kind the organization may not start. Only for routes that start
|
|
22
|
+
* something: reviewing, applying and rolling back what there is must stay open.
|
|
23
|
+
*/
|
|
24
|
+
export declare function requireFeature<F extends string>(source: FeatureSource<F>, principal: {
|
|
25
|
+
organizationId: string;
|
|
26
|
+
}, feature: F): Promise<void>;
|
|
27
|
+
/** The same, where there is an organization and no principal yet (an API key being checked). */
|
|
28
|
+
export declare function requireFeatureFor<F extends string>(source: FeatureSource<F>, ctx: TenantContext, feature: F): Promise<void>;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var feature_gate_exports = {};
|
|
19
|
+
__export(feature_gate_exports, {
|
|
20
|
+
FEATURE_ERRORS: () => FEATURE_ERRORS,
|
|
21
|
+
FEATURE_OFF_MESSAGE: () => FEATURE_OFF_MESSAGE,
|
|
22
|
+
NOT_IN_PLAN_MESSAGE: () => NOT_IN_PLAN_MESSAGE,
|
|
23
|
+
requireFeature: () => requireFeature,
|
|
24
|
+
requireFeatureFor: () => requireFeatureFor
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(feature_gate_exports);
|
|
27
|
+
var import_errors = require("@haatlabs-core/errors");
|
|
28
|
+
const FEATURE_ERRORS = {
|
|
29
|
+
FEATURE_DISABLED: { httpStatus: 403, transient: false }
|
|
30
|
+
};
|
|
31
|
+
const featureErrors = (0, import_errors.domainErrors)(FEATURE_ERRORS);
|
|
32
|
+
const NOT_IN_PLAN_MESSAGE = "Your plan does not include this. See the plans to add it.";
|
|
33
|
+
const FEATURE_OFF_MESSAGE = "This is not available for your account. Contact support to have it turned on.";
|
|
34
|
+
async function requireFeature(source, principal, feature) {
|
|
35
|
+
await requireFeatureFor(source, { organizationId: principal.organizationId }, feature);
|
|
36
|
+
}
|
|
37
|
+
async function requireFeatureFor(source, ctx, feature) {
|
|
38
|
+
const { features: on, overridden } = await source.detail(ctx);
|
|
39
|
+
if (on[feature])
|
|
40
|
+
return;
|
|
41
|
+
throw featureErrors.create("FEATURE_DISABLED", overridden.includes(feature) ? FEATURE_OFF_MESSAGE : NOT_IN_PLAN_MESSAGE);
|
|
42
|
+
}
|
|
43
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
44
|
+
0 && (module.exports = {
|
|
45
|
+
FEATURE_ERRORS,
|
|
46
|
+
FEATURE_OFF_MESSAGE,
|
|
47
|
+
NOT_IN_PLAN_MESSAGE,
|
|
48
|
+
requireFeature,
|
|
49
|
+
requireFeatureFor
|
|
50
|
+
});
|