@azlib/identity 0.2.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 +387 -0
- package/dist/errors-BGMwaW5s.d.mts +481 -0
- package/dist/errors-BGMwaW5s.d.mts.map +1 -0
- package/dist/errors-Bcjx9o6g.cjs +111 -0
- package/dist/errors-C2xZAatu.d.cts +481 -0
- package/dist/errors-C2xZAatu.d.cts.map +1 -0
- package/dist/errors-CEmnZxIn.mjs +66 -0
- package/dist/errors-CEmnZxIn.mjs.map +1 -0
- package/dist/express.cjs +405 -0
- package/dist/express.d.cts +87 -0
- package/dist/express.d.cts.map +1 -0
- package/dist/express.d.mts +87 -0
- package/dist/express.d.mts.map +1 -0
- package/dist/express.mjs +401 -0
- package/dist/express.mjs.map +1 -0
- package/dist/identity-4eP45YIP.cjs +461 -0
- package/dist/identity-Bz9RDOvT.mjs +410 -0
- package/dist/identity-Bz9RDOvT.mjs.map +1 -0
- package/dist/identity-router-DBL20UWT.d.mts +115 -0
- package/dist/identity-router-DBL20UWT.d.mts.map +1 -0
- package/dist/identity-router-Dib30Waj.d.cts +115 -0
- package/dist/identity-router-Dib30Waj.d.cts.map +1 -0
- package/dist/identity-service-B9zrvE9z.d.mts +128 -0
- package/dist/identity-service-B9zrvE9z.d.mts.map +1 -0
- package/dist/identity-service-CLzKx8Z7.d.cts +128 -0
- package/dist/identity-service-CLzKx8Z7.d.cts.map +1 -0
- package/dist/identity-store-BRRahxcS.d.cts +272 -0
- package/dist/identity-store-BRRahxcS.d.cts.map +1 -0
- package/dist/identity-store-BRRahxcS.d.mts +272 -0
- package/dist/identity-store-BRRahxcS.d.mts.map +1 -0
- package/dist/index-CpufYgyn.d.cts +30 -0
- package/dist/index-CpufYgyn.d.cts.map +1 -0
- package/dist/index-CpufYgyn.d.mts +30 -0
- package/dist/index-CpufYgyn.d.mts.map +1 -0
- package/dist/index.cjs +18 -0
- package/dist/index.d.cts +4 -0
- package/dist/index.d.mts +4 -0
- package/dist/index.mjs +3 -0
- package/dist/logger-Be1wDzBC.cjs +48 -0
- package/dist/logger-CcCHJVVe.mjs +33 -0
- package/dist/logger-CcCHJVVe.mjs.map +1 -0
- package/dist/nestjs.cjs +516 -0
- package/dist/nestjs.d.cts +102 -0
- package/dist/nestjs.d.cts.map +1 -0
- package/dist/nestjs.d.mts +102 -0
- package/dist/nestjs.d.mts.map +1 -0
- package/dist/nestjs.mjs +500 -0
- package/dist/nestjs.mjs.map +1 -0
- package/dist/node.cjs +946 -0
- package/dist/node.d.cts +260 -0
- package/dist/node.d.cts.map +1 -0
- package/dist/node.d.mts +260 -0
- package/dist/node.d.mts.map +1 -0
- package/dist/node.mjs +890 -0
- package/dist/node.mjs.map +1 -0
- package/dist/test-utils.cjs +169 -0
- package/dist/test-utils.d.cts +12 -0
- package/dist/test-utils.d.cts.map +1 -0
- package/dist/test-utils.d.mts +12 -0
- package/dist/test-utils.d.mts.map +1 -0
- package/dist/test-utils.mjs +170 -0
- package/dist/test-utils.mjs.map +1 -0
- package/package.json +92 -0
- package/schema/model.ts +100 -0
- package/schema/mysql.sql +102 -0
- package/schema/postgres.sql +92 -0
- package/schema/prisma.schema +122 -0
- package/schema/sqlite.sql +92 -0
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 [yyyy] [name of copyright owner]
|
|
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
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
# @azlib/identity
|
|
2
|
+
|
|
3
|
+
Storage-agnostic authentication and authorization foundation for Node.js services.
|
|
4
|
+
|
|
5
|
+
`@azlib/identity` provides a shared core for registration, login, JWT access tokens,
|
|
6
|
+
rotating refresh sessions, predefined relational schema artifacts, and deny-by-default
|
|
7
|
+
authorization. Express and NestJS integrations are thin wrappers over the same core so
|
|
8
|
+
you can plug the package into your own database engine and transport layer.
|
|
9
|
+
|
|
10
|
+
## Entry points
|
|
11
|
+
|
|
12
|
+
| Import | Purpose |
|
|
13
|
+
| --- | --- |
|
|
14
|
+
| `@azlib/identity` | Framework-agnostic types, config, errors, authorization, store contract |
|
|
15
|
+
| `@azlib/identity/node` | Node runtime services (password hashing, JWT, register/login/refresh) |
|
|
16
|
+
| `@azlib/identity/express` | Express authentication and authorization middleware |
|
|
17
|
+
| `@azlib/identity/nestjs` | NestJS module, guards, and decorators |
|
|
18
|
+
| `@azlib/identity/schema/*` | Predefined SQL and Prisma schema artifacts |
|
|
19
|
+
|
|
20
|
+
## Quick start (Express)
|
|
21
|
+
|
|
22
|
+
1. Apply a schema artifact to your database, e.g. Postgres:
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
psql "$DATABASE_URL" -f node_modules/@azlib/identity/schema/postgres.sql
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
2. Implement the `IdentityStore` contract against your database (or use the bundled
|
|
29
|
+
in-memory store from `@azlib/identity/test-utils` to prototype).
|
|
30
|
+
|
|
31
|
+
3. **Mount the pre-built router** — one import, one `app.use` call:
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import express from "express";
|
|
35
|
+
import { createIdentityService } from "@azlib/identity/node";
|
|
36
|
+
import { createIdentityRouter, identityErrorHandler } from "@azlib/identity/express";
|
|
37
|
+
|
|
38
|
+
const service = createIdentityService(
|
|
39
|
+
{ accessTokenSecret: process.env.ACCESS_TOKEN_SECRET! },
|
|
40
|
+
store, // your IdentityStore
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
const app = express();
|
|
44
|
+
app.use(express.json());
|
|
45
|
+
app.use("/auth", createIdentityRouter(service));
|
|
46
|
+
app.use(identityErrorHandler); // converts IdentityError → JSON
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
That's it. The following endpoints are ready immediately:
|
|
50
|
+
|
|
51
|
+
| Method | Path | Description |
|
|
52
|
+
|--------|------|-------------|
|
|
53
|
+
| `POST` | `/auth/register` | Create a new account |
|
|
54
|
+
| `POST` | `/auth/login` | Email + password login |
|
|
55
|
+
| `POST` | `/auth/refresh` | Rotate the refresh token |
|
|
56
|
+
| `POST` | `/auth/logout` | Revoke the session |
|
|
57
|
+
| `GET` | `/auth/me` | Return the authenticated principal |
|
|
58
|
+
| `GET` | `/auth/:provider` | Start an OAuth flow *(if configured)* |
|
|
59
|
+
| `GET` | `/auth/:provider/callback` | Handle an OAuth callback *(if configured)* |
|
|
60
|
+
|
|
61
|
+
### Cookie-mode refresh tokens
|
|
62
|
+
|
|
63
|
+
Store the refresh token in an `HttpOnly` cookie instead of the response body so the
|
|
64
|
+
client never touches it directly:
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
app.use(
|
|
68
|
+
"/auth",
|
|
69
|
+
createIdentityRouter(service, {
|
|
70
|
+
refreshToken: { cookie: { name: "rt", secure: true, sameSite: "strict" } },
|
|
71
|
+
}),
|
|
72
|
+
);
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`/refresh` and `/logout` read the cookie automatically.
|
|
76
|
+
|
|
77
|
+
### OAuth with the pre-built router
|
|
78
|
+
|
|
79
|
+
```ts
|
|
80
|
+
import { createGoogleOAuthProvider } from "@azlib/identity/node";
|
|
81
|
+
|
|
82
|
+
const service = createIdentityService(
|
|
83
|
+
{
|
|
84
|
+
accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,
|
|
85
|
+
oauth: {
|
|
86
|
+
providers: [
|
|
87
|
+
createGoogleOAuthProvider({
|
|
88
|
+
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
89
|
+
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
90
|
+
}),
|
|
91
|
+
],
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
store,
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
app.use(
|
|
98
|
+
"/auth",
|
|
99
|
+
createIdentityRouter(service, {
|
|
100
|
+
oauthBaseUrl: "https://api.example.com/auth",
|
|
101
|
+
}),
|
|
102
|
+
);
|
|
103
|
+
// → GET /auth/google starts OAuth flow
|
|
104
|
+
// → GET /auth/google/callback handles callback and issues tokens
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Manual wiring (advanced)
|
|
108
|
+
|
|
109
|
+
If you need fine-grained control over individual routes, wire each handler yourself:
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { requireAuth } from "@azlib/identity/express";
|
|
113
|
+
|
|
114
|
+
app.post("/auth/register", (req, res, next) =>
|
|
115
|
+
service.register(req.body).then((r) => res.json(r), next),
|
|
116
|
+
);
|
|
117
|
+
app.get("/auth/me", requireAuth(service), (req, res) => res.json(req.identity));
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
A complete runnable example lives in
|
|
121
|
+
[`examples/express-basic`](./examples/express-basic).
|
|
122
|
+
|
|
123
|
+
## Authorization
|
|
124
|
+
|
|
125
|
+
Authorization is **deny-by-default**: a principal is only allowed when an explicit grant
|
|
126
|
+
(and any ownership policy) passes. Permissions can be granted directly to a user or
|
|
127
|
+
through an assigned role; both resolve into the principal's `permissions`.
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
import { requirePermission, requireAuthorization } from "@azlib/identity/express";
|
|
131
|
+
|
|
132
|
+
// Require a single permission.
|
|
133
|
+
app.get(
|
|
134
|
+
"/reports",
|
|
135
|
+
requireAuth(identity),
|
|
136
|
+
requirePermission(identity, "reports:read"),
|
|
137
|
+
listReports,
|
|
138
|
+
);
|
|
139
|
+
|
|
140
|
+
// Require a permission AND ownership of the target resource.
|
|
141
|
+
app.delete(
|
|
142
|
+
"/docs/:id",
|
|
143
|
+
requireAuth(identity),
|
|
144
|
+
requireAuthorization(
|
|
145
|
+
identity,
|
|
146
|
+
{
|
|
147
|
+
permission: "documents:delete",
|
|
148
|
+
policy: ({ principal, resource }) => resource.ownerId === principal.userId,
|
|
149
|
+
},
|
|
150
|
+
(req) => loadDocument(req.params.id),
|
|
151
|
+
),
|
|
152
|
+
deleteDocument,
|
|
153
|
+
);
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
Grant roles and permissions through the store contract:
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
await store.grantRolePermission({ roleId: "editor", permission: "documents:write" });
|
|
160
|
+
await store.assignRole({ userId, roleId: "editor" });
|
|
161
|
+
await store.grantDirectPermission({ userId, permission: "reports:read" });
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
For non-Express transports, evaluate requirements directly with
|
|
165
|
+
`evaluateAuthorization(requirement, context)` from `@azlib/identity`.
|
|
166
|
+
|
|
167
|
+
## NestJS
|
|
168
|
+
|
|
169
|
+
Register the module once with `routes: true` and all standard auth endpoints are
|
|
170
|
+
wired automatically — no controller to write:
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
import { Module } from "@nestjs/common";
|
|
174
|
+
import { createIdentityService } from "@azlib/identity/node";
|
|
175
|
+
import { IdentityModule } from "@azlib/identity/nestjs";
|
|
176
|
+
|
|
177
|
+
@Module({
|
|
178
|
+
imports: [
|
|
179
|
+
IdentityModule.forRoot({
|
|
180
|
+
service: createIdentityService(config, store),
|
|
181
|
+
routes: true, // registers POST /auth/register, /login, /refresh, /logout + GET /auth/me
|
|
182
|
+
}),
|
|
183
|
+
],
|
|
184
|
+
})
|
|
185
|
+
export class AppModule {}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Customise the prefix or enable cookie-mode refresh tokens:
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
IdentityModule.forRoot({
|
|
192
|
+
service,
|
|
193
|
+
routes: {
|
|
194
|
+
prefix: "v1/auth",
|
|
195
|
+
cookie: { name: "rt", secure: true },
|
|
196
|
+
},
|
|
197
|
+
})
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Guards and decorators
|
|
201
|
+
|
|
202
|
+
Use the guards and decorators on your own controllers for authorization:
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
import {
|
|
206
|
+
CurrentUser,
|
|
207
|
+
IdentityAuthGuard,
|
|
208
|
+
IdentityAuthorizationGuard,
|
|
209
|
+
RequirePermission,
|
|
210
|
+
} from "@azlib/identity/nestjs";
|
|
211
|
+
|
|
212
|
+
@Get("reports")
|
|
213
|
+
@UseGuards(IdentityAuthGuard, IdentityAuthorizationGuard)
|
|
214
|
+
@RequirePermission("reports:read")
|
|
215
|
+
listReports(@CurrentUser() user: AuthenticatedIdentity) {
|
|
216
|
+
return this.reports.findFor(user.userId);
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
A runnable NestJS app lives in [`examples/nest-basic`](./examples/nest-basic). The same
|
|
221
|
+
`IdentityService` core powers both the Express and NestJS adapters, so behavior is
|
|
222
|
+
identical across frameworks.
|
|
223
|
+
|
|
224
|
+
## Account lockout
|
|
225
|
+
|
|
226
|
+
Protect against brute-force credential attacks by automatically locking accounts after too many consecutive failed logins.
|
|
227
|
+
|
|
228
|
+
```ts
|
|
229
|
+
createIdentityService(
|
|
230
|
+
{
|
|
231
|
+
accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,
|
|
232
|
+
lockout: {
|
|
233
|
+
maxFailedAttempts: 5, // 0 = disabled (default: 10)
|
|
234
|
+
durationSeconds: 900, // 0 = permanent lock (default: 900 = 15 min)
|
|
235
|
+
},
|
|
236
|
+
},
|
|
237
|
+
store,
|
|
238
|
+
);
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Behaviour:
|
|
242
|
+
|
|
243
|
+
- Each failed `login()` call increments `failedLoginAttempts` on the user record.
|
|
244
|
+
- When `failedLoginAttempts >= maxFailedAttempts`, the user's `status` is set to
|
|
245
|
+
`"locked"` and `lockedUntil` is set to `now + durationSeconds`.
|
|
246
|
+
- A `user.account.locked` audit event is emitted once per lockout event.
|
|
247
|
+
- Once the lockout period expires, the next successful login automatically resets
|
|
248
|
+
the counter and clears `lockedUntil`.
|
|
249
|
+
- Set `maxFailedAttempts: 0` to disable lockout entirely.
|
|
250
|
+
- Set `durationSeconds: 0` for a permanent lock (requires manual admin unlock).
|
|
251
|
+
|
|
252
|
+
Your `IdentityStore` must persist `failedLoginAttempts` and `lockedUntil`. The
|
|
253
|
+
shipped schema artifacts already include these columns.
|
|
254
|
+
|
|
255
|
+
## OAuth2 / OpenID Connect
|
|
256
|
+
|
|
257
|
+
Issue sessions via OAuth2 Authorization Code Flow + OIDC. Configure one or more
|
|
258
|
+
providers when creating the service:
|
|
259
|
+
|
|
260
|
+
```ts
|
|
261
|
+
import { createIdentityService } from "@azlib/identity/node";
|
|
262
|
+
import { createGoogleOAuthProvider } from "@azlib/identity/node";
|
|
263
|
+
import { createMicrosoftOAuthProvider } from "@azlib/identity/node";
|
|
264
|
+
|
|
265
|
+
const identity = createIdentityService(
|
|
266
|
+
{
|
|
267
|
+
accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,
|
|
268
|
+
oauth: {
|
|
269
|
+
providers: [
|
|
270
|
+
createGoogleOAuthProvider({
|
|
271
|
+
clientId: process.env.GOOGLE_CLIENT_ID!,
|
|
272
|
+
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
|
|
273
|
+
}),
|
|
274
|
+
createMicrosoftOAuthProvider({
|
|
275
|
+
clientId: process.env.MS_CLIENT_ID!,
|
|
276
|
+
clientSecret: process.env.MS_CLIENT_SECRET!,
|
|
277
|
+
tenantId: "common", // or a specific tenant UUID
|
|
278
|
+
}),
|
|
279
|
+
],
|
|
280
|
+
},
|
|
281
|
+
},
|
|
282
|
+
store,
|
|
283
|
+
);
|
|
284
|
+
|
|
285
|
+
// identity.oauth is an OAuthService when providers are configured.
|
|
286
|
+
const { url, state } = identity.oauth!.buildAuthorizationUrl("google", REDIRECT_URI);
|
|
287
|
+
// …redirect the user to `url`, persist `state` in a signed cookie/session
|
|
288
|
+
|
|
289
|
+
// In the callback handler:
|
|
290
|
+
const result = await identity.oauth!.handleCallback("google", {
|
|
291
|
+
code: req.query.code as string,
|
|
292
|
+
state: req.query.state as string,
|
|
293
|
+
expectedState: req.session.oauthState,
|
|
294
|
+
redirectUri: REDIRECT_URI,
|
|
295
|
+
});
|
|
296
|
+
// result.tokens.accessToken is now ready
|
|
297
|
+
```
|
|
298
|
+
|
|
299
|
+
### Express helpers
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
import { oauthAuthorize, oauthCallback } from "@azlib/identity/express";
|
|
303
|
+
|
|
304
|
+
const options = {
|
|
305
|
+
redirectUri: `${BASE_URL}/auth/google/callback`,
|
|
306
|
+
getState: (req) => req.session?.oauthState ?? null,
|
|
307
|
+
setState: (req, _res, state) => { req.session!.oauthState = state; },
|
|
308
|
+
onSuccess: (_req, res, result) => res.json(result),
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
app.get("/auth/google", oauthAuthorize(identity.oauth!, "google", options));
|
|
312
|
+
app.get("/auth/google/callback", oauthCallback(identity.oauth!, "google", options));
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
### Callback flow
|
|
316
|
+
|
|
317
|
+
1. Verify CSRF `state` — throws `OAuthStateMismatchError` on mismatch.
|
|
318
|
+
2. Exchange the authorization `code` for tokens via the provider.
|
|
319
|
+
3. Fetch user info (email, `sub`, display name) from the provider.
|
|
320
|
+
4. If an existing OAuth link (`provider` + `providerUserId`) exists, issue a session for that user.
|
|
321
|
+
5. Otherwise if a local user with the same email exists, link the OAuth identity and issue a session.
|
|
322
|
+
6. Otherwise provision a new user, create the OAuth link, and issue a session.
|
|
323
|
+
|
|
324
|
+
Your `IdentityStore` should implement the optional `findUserByOAuthId`, `createOAuthLink`, and
|
|
325
|
+
`listOAuthLinks` methods for full OAuth support. The shipped schema artifacts include the
|
|
326
|
+
`identity_oauth_linked_accounts` table.
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
The package never talks to a database directly — you provide an `IdentityStore`. Two
|
|
331
|
+
adoption paths:
|
|
332
|
+
|
|
333
|
+
1. **Use a shipped schema artifact.** Apply one of `@azlib/identity/schema/{postgres,mysql,sqlite}.sql`
|
|
334
|
+
(or `prisma.schema`) and implement `IdentityStore` over those tables. The artifacts
|
|
335
|
+
cover users, credentials, sessions, roles, permissions, grants, and audit events.
|
|
336
|
+
2. **Adapt an existing schema.** Implement `IdentityStore` against your own tables. Only
|
|
337
|
+
the method contract matters; column and table names are yours. Email lookups must be
|
|
338
|
+
case-insensitive and email must be unique.
|
|
339
|
+
|
|
340
|
+
Migration notes for adopters:
|
|
341
|
+
|
|
342
|
+
- Store only the refresh-token **hash** (`refreshTokenHash`); never the raw token.
|
|
343
|
+
- `authVersion` must be persisted per user and returned by `findUserById`; bump it to
|
|
344
|
+
invalidate all outstanding tokens (e.g. on password reset).
|
|
345
|
+
- `recordEvent` is optional. Omit it to skip persistence; the `overrides.onEvent`
|
|
346
|
+
lifecycle hook can forward events to external logging regardless.
|
|
347
|
+
- To rotate token policy (TTLs, issuer, secret) safely, change config and let existing
|
|
348
|
+
access tokens expire; refresh tokens rotate on next use.
|
|
349
|
+
|
|
350
|
+
## Configuration overrides
|
|
351
|
+
|
|
352
|
+
```ts
|
|
353
|
+
createIdentityService(
|
|
354
|
+
{
|
|
355
|
+
accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,
|
|
356
|
+
accessTokenTtlSeconds: 900,
|
|
357
|
+
refreshTokenTtlSeconds: 60 * 60 * 24 * 14,
|
|
358
|
+
issuer: "my-service",
|
|
359
|
+
audience: "my-clients",
|
|
360
|
+
overrides: {
|
|
361
|
+
now: () => new Date(),
|
|
362
|
+
generateId: () => crypto.randomUUID(),
|
|
363
|
+
onEvent: (event) => metrics.record(event),
|
|
364
|
+
},
|
|
365
|
+
},
|
|
366
|
+
store,
|
|
367
|
+
);
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
## Security model
|
|
371
|
+
|
|
372
|
+
- Passwords are hashed with scrypt; only algorithm-tagged hashes are stored.
|
|
373
|
+
- Access tokens are short-lived HS256 JWTs (default 15 minutes).
|
|
374
|
+
- Refresh tokens are opaque and rotated on every use; only their SHA-256 hash is stored,
|
|
375
|
+
and reuse of a rotated token revokes the session.
|
|
376
|
+
- Login returns a single generic error for both unknown email and wrong password to
|
|
377
|
+
mitigate account enumeration, and pays the hash-verification cost even for unknown users.
|
|
378
|
+
- Tokens carry an `authVersion`; bump a user's version to invalidate all outstanding tokens.
|
|
379
|
+
|
|
380
|
+
## Status
|
|
381
|
+
|
|
382
|
+
This package is under active implementation. See
|
|
383
|
+
[`specs/009-identity-package`](../../specs/009-identity-package) for the plan and tasks.
|
|
384
|
+
|
|
385
|
+
## License
|
|
386
|
+
|
|
387
|
+
MIT
|