@nage-api/auth 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 +176 -0
- package/dist/api-key.service.d.ts +50 -0
- package/dist/api-key.service.js +110 -0
- package/dist/auth.controller.d.ts +48 -0
- package/dist/auth.controller.js +185 -0
- package/dist/auth.dto.d.ts +37 -0
- package/dist/auth.dto.js +117 -0
- package/dist/auth.guard.d.ts +29 -0
- package/dist/auth.guard.js +122 -0
- package/dist/auth.module.d.ts +61 -0
- package/dist/auth.module.js +226 -0
- package/dist/auth.service.d.ts +82 -0
- package/dist/auth.service.js +269 -0
- package/dist/authorization.guard.d.ts +24 -0
- package/dist/authorization.guard.js +107 -0
- package/dist/config.d.ts +71 -0
- package/dist/config.js +151 -0
- package/dist/decorators.d.ts +51 -0
- package/dist/decorators.js +70 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +96 -0
- package/dist/jwt.d.ts +50 -0
- package/dist/jwt.js +163 -0
- package/dist/lockout.service.d.ts +43 -0
- package/dist/lockout.service.js +94 -0
- package/dist/memory-stores.d.ts +84 -0
- package/dist/memory-stores.js +246 -0
- package/dist/otp.service.d.ts +47 -0
- package/dist/otp.service.js +137 -0
- package/dist/password.d.ts +51 -0
- package/dist/password.js +122 -0
- package/dist/policy.d.ts +44 -0
- package/dist/policy.js +61 -0
- package/dist/ports.d.ts +175 -0
- package/dist/ports.js +17 -0
- package/dist/principal.resolver.d.ts +52 -0
- package/dist/principal.resolver.js +125 -0
- package/dist/session.service.d.ts +71 -0
- package/dist/session.service.js +175 -0
- package/dist/tokens.d.ts +22 -0
- package/dist/tokens.js +23 -0
- package/package.json +66 -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,176 @@
|
|
|
1
|
+
# @nage-api/auth
|
|
2
|
+
|
|
3
|
+
Authentication and authorization (PLAN.md §15). Opt-in, engine-agnostic, and
|
|
4
|
+
**globally enforced**: importing the module protects every route, and opening
|
|
5
|
+
one is a decision you have to write down.
|
|
6
|
+
|
|
7
|
+
The legacy framework wired guards per controller, so a new file started life
|
|
8
|
+
unauthenticated. Here `NageAuthModule.forRoot` registers `AuthGuard` and
|
|
9
|
+
`AuthorizationGuard` as `APP_GUARD`s, and `@Public()` is the only way out.
|
|
10
|
+
|
|
11
|
+
## What it provides
|
|
12
|
+
|
|
13
|
+
| Area | Export | Notes |
|
|
14
|
+
| -------------- | ----------------------------------------------------- | ------------------------------------------------------------ |
|
|
15
|
+
| Access tokens | `JoseTokenSigner`, `buildClaims`, `parseClaims` | RS256, algorithm pinned, issuer and audience checked |
|
|
16
|
+
| Sessions | `SessionService` | Opaque refresh token, HMAC-stored, rotated, reuse-detected |
|
|
17
|
+
| Passwords | `Argon2PasswordHasher`, `assertPasswordPolicy` | argon2id (19 MiB, t=2) with a pepper; opportunistic re-hash |
|
|
18
|
+
| One-time codes | `OtpService` | CSPRNG, HMAC-stored, TTL + attempt ceiling + resend cooldown |
|
|
19
|
+
| API keys | `ApiKeyService` | `nage_<prefix>_<secret>`, hashed, scoped, opt-in per route |
|
|
20
|
+
| Lockout | `LockoutService` | Per-identity failure counting, temporary lock |
|
|
21
|
+
| Authorization | `@Roles`, `@Permissions`, `@Policy`, `PolicyRegistry` | RBAC by default, ABAC when you want it |
|
|
22
|
+
| Principal | `PrincipalResolver` | Roles from the store, not the token; revocation is immediate |
|
|
23
|
+
| Audit | `AuthAuditSink` | Typed security events, never containing a credential |
|
|
24
|
+
|
|
25
|
+
## Endpoints
|
|
26
|
+
|
|
27
|
+
The legacy surface is retained, so existing clients keep working:
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
POST /auth/local email + password → token pair
|
|
31
|
+
POST /auth/token refresh token → rotated token pair
|
|
32
|
+
POST /auth/logout refresh token → 204
|
|
33
|
+
POST /auth/password/forgot email → 202, always
|
|
34
|
+
POST /auth/password/reset email + code + password → 204
|
|
35
|
+
POST /auth/otp/send email → 202, always
|
|
36
|
+
POST /auth/otp/verify email + code → token pair
|
|
37
|
+
POST /auth/user admin impersonation → token pair
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Wiring it up
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { NageAuthModule, ownershipPolicy } from '@nage-api/auth';
|
|
44
|
+
import type { AuthUserStore, SessionStore } from '@nage-api/auth';
|
|
45
|
+
import type { NodeEnvironment } from '@nage-api/contracts';
|
|
46
|
+
|
|
47
|
+
// Validated by `@nage-api/config` at boot. None of the peppers has a default: a
|
|
48
|
+
// default secret is the same defect as the `admin@admin.com` seed user (§12).
|
|
49
|
+
declare const env: {
|
|
50
|
+
NODE_ENV: NodeEnvironment;
|
|
51
|
+
JWT_PRIVATE_KEY: string;
|
|
52
|
+
JWT_PUBLIC_KEY: string;
|
|
53
|
+
PASSWORD_PEPPER: string;
|
|
54
|
+
SESSION_PEPPER: string;
|
|
55
|
+
OTP_PEPPER: string;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// Your implementations, bound to whichever driver the application uses.
|
|
59
|
+
declare const users: AuthUserStore;
|
|
60
|
+
declare const sessions: SessionStore;
|
|
61
|
+
|
|
62
|
+
export const authModule = NageAuthModule.forRoot({
|
|
63
|
+
environment: env.NODE_ENV,
|
|
64
|
+
auth: {
|
|
65
|
+
jwt: { issuer: 'https://auth.example.com', audience: 'https://api.example.com' },
|
|
66
|
+
},
|
|
67
|
+
roles: {
|
|
68
|
+
admin: ['user:read', 'user:write', 'order:read', 'order:write'],
|
|
69
|
+
editor: ['order:read', 'order:write'],
|
|
70
|
+
},
|
|
71
|
+
policies: { 'owns-order': ownershipPolicy('id') },
|
|
72
|
+
secrets: {
|
|
73
|
+
jwtPrivateKey: env.JWT_PRIVATE_KEY,
|
|
74
|
+
jwtPublicKey: env.JWT_PUBLIC_KEY,
|
|
75
|
+
passwordPepper: env.PASSWORD_PEPPER,
|
|
76
|
+
sessionPepper: env.SESSION_PEPPER,
|
|
77
|
+
otpPepper: env.OTP_PEPPER,
|
|
78
|
+
},
|
|
79
|
+
users,
|
|
80
|
+
sessions,
|
|
81
|
+
// …otpStore, otpChannel, lockout
|
|
82
|
+
});
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Feature packages may not import each other (§7.2), so auth declares narrow
|
|
86
|
+
ports — `AuthUserStore`, `SessionStore`, `OtpStore`, `OtpChannel`,
|
|
87
|
+
`ApiKeyStore`, `LockoutStore` — and an application binds them to its own
|
|
88
|
+
driver. Each has an in-memory implementation with real semantics, so the module
|
|
89
|
+
works before a database exists and the ports have an executable specification.
|
|
90
|
+
|
|
91
|
+
_Defaulting_ to the in-memory stores in production or staging is refused at
|
|
92
|
+
boot, for the four that hold state a restart must not lose (`users`,
|
|
93
|
+
`sessions`, `otpStore`, `lockout`): they are per-process, so otherwise the
|
|
94
|
+
mistake surfaces months later as "users are randomly logged out". Passing one
|
|
95
|
+
explicitly is still allowed — the check is against forgetting, not against
|
|
96
|
+
deliberate choice.
|
|
97
|
+
|
|
98
|
+
## The four decisions worth knowing
|
|
99
|
+
|
|
100
|
+
**Refresh tokens rotate, and replay revokes the family.** Every refresh issues
|
|
101
|
+
a new token and marks the old one spent. A spent token coming back means
|
|
102
|
+
someone replayed a token the real client already used — and there is no way to
|
|
103
|
+
tell which party it was — so the whole session family is revoked. A silent
|
|
104
|
+
theft becomes a visible re-login.
|
|
105
|
+
|
|
106
|
+
**Claims are identity, not authority.** A signed token proves _who_ you are; it
|
|
107
|
+
does not prove what you may still do. `PrincipalResolver` reads roles and
|
|
108
|
+
permissions from the store on every request, so a demotion or a disabled
|
|
109
|
+
account takes effect immediately rather than whenever the access token happens
|
|
110
|
+
to expire. A token carrying `roles: ["admin"]` that the store does not back
|
|
111
|
+
grants nothing.
|
|
112
|
+
|
|
113
|
+
**Revocation is immediate.** The access token carries the session _family_ id,
|
|
114
|
+
and a revoked family is refused, so a logout logs you out instead of leaving a
|
|
115
|
+
15-minute window. Both lookups sit behind a short TTL cache — the default is 5
|
|
116
|
+
seconds, and the tests run with it at 0.
|
|
117
|
+
|
|
118
|
+
**Everything fails closed.** An unknown policy name denies. A route marked both
|
|
119
|
+
`@Public()` and `@Roles()` is refused rather than opened. An API key works only
|
|
120
|
+
where a route has `@AllowApiKey()`. Nothing here resolves an ambiguity towards
|
|
121
|
+
access.
|
|
122
|
+
|
|
123
|
+
## Enumeration and timing
|
|
124
|
+
|
|
125
|
+
Whether an email is registered is not something an unauthenticated caller may
|
|
126
|
+
learn:
|
|
127
|
+
|
|
128
|
+
- a login against an unknown address still performs a hash verification, so it
|
|
129
|
+
takes the same time as a wrong password;
|
|
130
|
+
- wrong password, unknown address and disabled account all raise
|
|
131
|
+
`AUTH_INVALID_CREDENTIALS`;
|
|
132
|
+
- `password/forgot` and `otp/send` answer 202 either way;
|
|
133
|
+
- an authorization failure never names the role or permission that was missing.
|
|
134
|
+
|
|
135
|
+
Peppers are required, not optional: passwords, refresh tokens, OTP codes and
|
|
136
|
+
API keys are all stored under a key held outside the database, so a dumped
|
|
137
|
+
table is useless on its own.
|
|
138
|
+
|
|
139
|
+
## Testing against it
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
import { Argon2PasswordHasher, MemoryAuthUserStore, MemorySessionStore } from '@nage-api/auth';
|
|
143
|
+
|
|
144
|
+
// Sixteen characters minimum, checked in the constructor: anything shorter
|
|
145
|
+
// cannot carry enough entropy to be a pepper.
|
|
146
|
+
const pepper = 'pepper-for-passwords-0123456789';
|
|
147
|
+
|
|
148
|
+
// argon2id at its cheapest — the algorithm is real, the work factor is not.
|
|
149
|
+
const hasher = new Argon2PasswordHasher({ pepper, memoryCost: 8, timeCost: 1, parallelism: 1 });
|
|
150
|
+
|
|
151
|
+
const users = new MemoryAuthUserStore([
|
|
152
|
+
{
|
|
153
|
+
id: 'u1',
|
|
154
|
+
email: 'ada@example.test',
|
|
155
|
+
roles: ['viewer'],
|
|
156
|
+
passwordHash: await hasher.hash('Correct-Horse-9'),
|
|
157
|
+
},
|
|
158
|
+
]);
|
|
159
|
+
const sessions = new MemorySessionStore();
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Inject a `Clock` to drive expiry and lockout windows without waiting, and a
|
|
163
|
+
`MemoryOtpChannel` to read the code a flow just sent. `docs/packages/auth.md`
|
|
164
|
+
walks through the whole graph.
|
|
165
|
+
|
|
166
|
+
## Not yet implemented
|
|
167
|
+
|
|
168
|
+
- OAuth / external providers (Google, Apple, Facebook, Firebase) — §15.1 lists
|
|
169
|
+
them as opt-in adapters; the `AuthUserStore` port is where they will attach.
|
|
170
|
+
- Redis-backed revocation lists; today revocation is a `SessionStore` query
|
|
171
|
+
behind the resolver's cache.
|
|
172
|
+
- `nage add auth` adds the dependency and records the feature in the workspace
|
|
173
|
+
manifest, and prints what to do next. It writes neither the config block, the
|
|
174
|
+
environment variables (only `nage create --auth jwt` extends the env schema
|
|
175
|
+
with the key pair and the peppers) nor the store implementations, which depend
|
|
176
|
+
on the project's own user model.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* API keys for service-to-service callers (PLAN.md §15.1).
|
|
3
|
+
*
|
|
4
|
+
* A key is `nage_<prefix>_<secret>`: the prefix is a non-secret lookup handle,
|
|
5
|
+
* the secret is 32 CSPRNG bytes stored only as an HMAC. That split is what lets
|
|
6
|
+
* verification be a single indexed read followed by one constant-time compare,
|
|
7
|
+
* instead of hashing the candidate against every row.
|
|
8
|
+
*
|
|
9
|
+
* The visible prefix also makes keys revocable by eye — it can be shown in a
|
|
10
|
+
* dashboard, logged, and matched by secret scanners, none of which is safe to
|
|
11
|
+
* do with the key itself.
|
|
12
|
+
*/
|
|
13
|
+
import type { Id, Permission } from '@nage-api/contracts';
|
|
14
|
+
import type { ApiKeyRecord, ApiKeyStore, AuthAuditSink, Clock } from './ports.js';
|
|
15
|
+
/** Recognisable in a log or a leak report, and greppable by secret scanners. */
|
|
16
|
+
export declare const API_KEY_PREFIX = "nage";
|
|
17
|
+
export interface ApiKeyServiceOptions {
|
|
18
|
+
readonly store: ApiKeyStore;
|
|
19
|
+
readonly pepper: string;
|
|
20
|
+
readonly clock?: Clock;
|
|
21
|
+
readonly audit?: AuthAuditSink;
|
|
22
|
+
}
|
|
23
|
+
export interface CreateApiKeyInput {
|
|
24
|
+
readonly name: string;
|
|
25
|
+
readonly userId?: Id;
|
|
26
|
+
readonly roles?: readonly string[];
|
|
27
|
+
readonly permissions?: readonly Permission[];
|
|
28
|
+
readonly expiresAt?: number;
|
|
29
|
+
}
|
|
30
|
+
export interface CreatedApiKey {
|
|
31
|
+
readonly record: ApiKeyRecord;
|
|
32
|
+
/** Shown once, at creation. Not recoverable afterwards. */
|
|
33
|
+
readonly key: string;
|
|
34
|
+
}
|
|
35
|
+
export declare class ApiKeyService {
|
|
36
|
+
#private;
|
|
37
|
+
constructor(options: ApiKeyServiceOptions);
|
|
38
|
+
create(input: CreateApiKeyInput): Promise<CreatedApiKey>;
|
|
39
|
+
/**
|
|
40
|
+
* Verify a presented key.
|
|
41
|
+
*
|
|
42
|
+
* Every failure — bad shape, unknown prefix, wrong secret, revoked, expired —
|
|
43
|
+
* raises the same error, so the response cannot be used to enumerate which
|
|
44
|
+
* prefixes exist.
|
|
45
|
+
*/
|
|
46
|
+
verify(presented: string): Promise<ApiKeyRecord>;
|
|
47
|
+
revoke(id: string): Promise<void>;
|
|
48
|
+
hashSecret(secret: string): string;
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=api-key.service.d.ts.map
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* API keys for service-to-service callers (PLAN.md §15.1).
|
|
4
|
+
*
|
|
5
|
+
* A key is `nage_<prefix>_<secret>`: the prefix is a non-secret lookup handle,
|
|
6
|
+
* the secret is 32 CSPRNG bytes stored only as an HMAC. That split is what lets
|
|
7
|
+
* verification be a single indexed read followed by one constant-time compare,
|
|
8
|
+
* instead of hashing the candidate against every row.
|
|
9
|
+
*
|
|
10
|
+
* The visible prefix also makes keys revocable by eye — it can be shown in a
|
|
11
|
+
* dashboard, logged, and matched by secret scanners, none of which is safe to
|
|
12
|
+
* do with the key itself.
|
|
13
|
+
*/
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.ApiKeyService = exports.API_KEY_PREFIX = void 0;
|
|
16
|
+
const node_crypto_1 = require("node:crypto");
|
|
17
|
+
const core_1 = require("@nage-api/core");
|
|
18
|
+
/** Recognisable in a log or a leak report, and greppable by secret scanners. */
|
|
19
|
+
exports.API_KEY_PREFIX = 'nage';
|
|
20
|
+
const MIN_PEPPER_LENGTH = 16;
|
|
21
|
+
const PREFIX_LENGTH = 8;
|
|
22
|
+
class ApiKeyService {
|
|
23
|
+
#store;
|
|
24
|
+
#pepper;
|
|
25
|
+
#clock;
|
|
26
|
+
#audit;
|
|
27
|
+
constructor(options) {
|
|
28
|
+
if (options.pepper.length < MIN_PEPPER_LENGTH) {
|
|
29
|
+
throw new core_1.ConfigurationError({
|
|
30
|
+
detail: `The API-key pepper must be at least ${String(MIN_PEPPER_LENGTH)} characters`,
|
|
31
|
+
meta: { setting: 'API_KEY_PEPPER' },
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
this.#store = options.store;
|
|
35
|
+
this.#pepper = options.pepper;
|
|
36
|
+
this.#clock = options.clock ?? { now: () => Date.now() };
|
|
37
|
+
this.#audit = options.audit;
|
|
38
|
+
}
|
|
39
|
+
async create(input) {
|
|
40
|
+
const prefix = (0, core_1.randomString)(PREFIX_LENGTH).toLowerCase();
|
|
41
|
+
const secret = (0, core_1.randomToken)(32);
|
|
42
|
+
const record = {
|
|
43
|
+
id: (0, core_1.randomId)(),
|
|
44
|
+
prefix,
|
|
45
|
+
hashedKey: this.hashSecret(secret),
|
|
46
|
+
name: input.name,
|
|
47
|
+
...(input.userId === undefined ? {} : { userId: input.userId }),
|
|
48
|
+
roles: input.roles ?? [],
|
|
49
|
+
permissions: input.permissions ?? [],
|
|
50
|
+
createdAt: this.#clock.now(),
|
|
51
|
+
...(input.expiresAt === undefined ? {} : { expiresAt: input.expiresAt }),
|
|
52
|
+
};
|
|
53
|
+
await this.#store.create(record);
|
|
54
|
+
return { record, key: `${exports.API_KEY_PREFIX}_${prefix}_${secret}` };
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Verify a presented key.
|
|
58
|
+
*
|
|
59
|
+
* Every failure — bad shape, unknown prefix, wrong secret, revoked, expired —
|
|
60
|
+
* raises the same error, so the response cannot be used to enumerate which
|
|
61
|
+
* prefixes exist.
|
|
62
|
+
*/
|
|
63
|
+
async verify(presented) {
|
|
64
|
+
// Matched rather than split: the secret is base64url, whose alphabet
|
|
65
|
+
// includes the `_` separator, so splitting would reject a valid key
|
|
66
|
+
// whenever the random half happened to contain one.
|
|
67
|
+
const match = new RegExp(`^${exports.API_KEY_PREFIX}_([a-z0-9]+)_(.+)$`).exec(presented);
|
|
68
|
+
const prefix = match?.[1];
|
|
69
|
+
const secret = match?.[2];
|
|
70
|
+
if (prefix === undefined || secret === undefined) {
|
|
71
|
+
throw new core_1.AuthenticationError('AUTH_TOKEN_INVALID', { detail: 'Malformed API key' });
|
|
72
|
+
}
|
|
73
|
+
const record = await this.#store.findByPrefix(prefix);
|
|
74
|
+
if (record === undefined) {
|
|
75
|
+
throw new core_1.AuthenticationError('AUTH_TOKEN_INVALID', {
|
|
76
|
+
detail: `No API key with prefix ${prefix}`,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
if (!(0, core_1.secureCompare)(record.hashedKey, this.hashSecret(secret))) {
|
|
80
|
+
throw new core_1.AuthenticationError('AUTH_TOKEN_INVALID', {
|
|
81
|
+
detail: `API key ${prefix} presented an incorrect secret`,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
const now = this.#clock.now();
|
|
85
|
+
if (record.revokedAt !== undefined) {
|
|
86
|
+
throw new core_1.AuthenticationError('AUTH_SESSION_REVOKED', {
|
|
87
|
+
detail: `API key ${prefix} was revoked`,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
if (record.expiresAt !== undefined && record.expiresAt <= now) {
|
|
91
|
+
throw new core_1.AuthenticationError('AUTH_TOKEN_EXPIRED', { detail: `API key ${prefix} expired` });
|
|
92
|
+
}
|
|
93
|
+
await this.#store.touch(record.id, now);
|
|
94
|
+
await this.#audit?.record({
|
|
95
|
+
name: 'api-key.used',
|
|
96
|
+
at: now,
|
|
97
|
+
...(record.userId === undefined ? {} : { userId: record.userId }),
|
|
98
|
+
meta: { prefix, name: record.name },
|
|
99
|
+
});
|
|
100
|
+
return record;
|
|
101
|
+
}
|
|
102
|
+
async revoke(id) {
|
|
103
|
+
await this.#store.revoke(id, this.#clock.now());
|
|
104
|
+
}
|
|
105
|
+
hashSecret(secret) {
|
|
106
|
+
return (0, node_crypto_1.createHmac)('sha256', this.#pepper).update(secret, 'utf8').digest('base64url');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
exports.ApiKeyService = ApiKeyService;
|
|
110
|
+
//# sourceMappingURL=api-key.service.js.map
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The retained auth endpoint surface (PLAN.md §15.1).
|
|
3
|
+
*
|
|
4
|
+
* Same paths as the legacy framework so existing clients keep working; the
|
|
5
|
+
* hardening is behind them. Three things are worth noticing here:
|
|
6
|
+
*
|
|
7
|
+
* - the login and OTP routes are `@Public()` **and** rate-limited harder than
|
|
8
|
+
* the global default, because they are the ones worth brute-forcing;
|
|
9
|
+
* - `forgot` and `send` always answer 202, whatever the address;
|
|
10
|
+
* - nothing in this file touches a password, a hash or a code — it parses a
|
|
11
|
+
* body, calls a service and returns a token pair.
|
|
12
|
+
*/
|
|
13
|
+
import type { AuthUser, TokenPair } from '@nage-api/contracts';
|
|
14
|
+
import { AuthService } from './auth.service.js';
|
|
15
|
+
import { ForgotPasswordDto, ImpersonateDto, LoginDto, RefreshTokenDto, ResetPasswordDto, SendOtpDto, VerifyOtpDto } from './auth.dto.js';
|
|
16
|
+
interface RequestLike {
|
|
17
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
18
|
+
ip?: string;
|
|
19
|
+
socket?: {
|
|
20
|
+
remoteAddress?: string;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export declare class AuthController {
|
|
24
|
+
private readonly auth;
|
|
25
|
+
constructor(auth: AuthService);
|
|
26
|
+
login(body: LoginDto, request: RequestLike): Promise<TokenPair>;
|
|
27
|
+
refresh(body: RefreshTokenDto, request: RequestLike): Promise<TokenPair>;
|
|
28
|
+
/**
|
|
29
|
+
* Public because a caller whose access token has already expired must still
|
|
30
|
+
* be able to log out; the refresh token in the body is the credential.
|
|
31
|
+
*/
|
|
32
|
+
logout(body: RefreshTokenDto): Promise<void>;
|
|
33
|
+
forgotPassword(body: ForgotPasswordDto): Promise<void>;
|
|
34
|
+
resetPassword(body: ResetPasswordDto): Promise<void>;
|
|
35
|
+
sendOtp(body: SendOtpDto): Promise<void>;
|
|
36
|
+
verifyOtp(body: VerifyOtpDto, request: RequestLike): Promise<TokenPair>;
|
|
37
|
+
/**
|
|
38
|
+
* Administrative impersonation, retained from the legacy `/auth/user`.
|
|
39
|
+
*
|
|
40
|
+
* Not decorated with `@Roles`: which roles may impersonate is configuration
|
|
41
|
+
* (`auth.impersonation.allowedRoles`), and the service enforces it. Putting
|
|
42
|
+
* the role list in a decorator here would freeze one deployment's answer into
|
|
43
|
+
* the framework.
|
|
44
|
+
*/
|
|
45
|
+
impersonate(body: ImpersonateDto, actor: AuthUser, request: RequestLike): Promise<TokenPair>;
|
|
46
|
+
}
|
|
47
|
+
export {};
|
|
48
|
+
//# sourceMappingURL=auth.controller.d.ts.map
|