auth-vir 0.0.0 → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-CC0 +121 -0
- package/LICENSE-MIT +21 -0
- package/README.md +322 -0
- package/bin.js +8 -0
- package/dist/auth.d.ts +79 -0
- package/dist/auth.js +101 -0
- package/dist/cookie.d.ts +50 -0
- package/dist/cookie.js +38 -0
- package/dist/csrf-token.d.ts +12 -0
- package/dist/csrf-token.js +15 -0
- package/dist/hash.d.ts +35 -0
- package/dist/hash.js +51 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/jwt-keys.d.ts +44 -0
- package/dist/jwt-keys.js +57 -0
- package/dist/jwt-keys.script.d.ts +1 -0
- package/dist/jwt-keys.script.js +2 -0
- package/dist/jwt.d.ts +83 -0
- package/dist/jwt.js +61 -0
- package/dist/mock-local-storage.d.ts +33 -0
- package/dist/mock-local-storage.js +56 -0
- package/dist/user-jwt.d.ts +38 -0
- package/dist/user-jwt.js +41 -0
- package/package.json +66 -11
- package/src/auth.ts +168 -0
- package/src/cookie.ts +85 -0
- package/src/csrf-token.ts +17 -0
- package/src/hash.ts +65 -0
- package/src/index.ts +8 -0
- package/src/jwt-keys.script.ts +3 -0
- package/src/jwt-keys.ts +111 -0
- package/src/jwt.ts +160 -0
- package/src/mock-local-storage.ts +72 -0
- package/src/user-jwt.ts +60 -0
package/LICENSE-CC0
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
CC0 1.0 Universal
|
|
2
|
+
|
|
3
|
+
Creative Commons Legal Code
|
|
4
|
+
|
|
5
|
+
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
|
|
6
|
+
LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
|
|
7
|
+
ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
|
|
8
|
+
INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
|
|
9
|
+
REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
|
|
10
|
+
PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
|
|
11
|
+
THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
|
|
12
|
+
HEREUNDER.
|
|
13
|
+
|
|
14
|
+
Statement of Purpose
|
|
15
|
+
|
|
16
|
+
The laws of most jurisdictions throughout the world automatically confer
|
|
17
|
+
exclusive Copyright and Related Rights (defined below) upon the creator
|
|
18
|
+
and subsequent owner(s) (each and all, an "owner") of an original work of
|
|
19
|
+
authorship and/or a database (each, a "Work").
|
|
20
|
+
|
|
21
|
+
Certain owners wish to permanently relinquish those rights to a Work for
|
|
22
|
+
the purpose of contributing to a commons of creative, cultural and
|
|
23
|
+
scientific works ("Commons") that the public can reliably and without fear
|
|
24
|
+
of later claims of infringement build upon, modify, incorporate in other
|
|
25
|
+
works, reuse and redistribute as freely as possible in any form whatsoever
|
|
26
|
+
and for any purposes, including without limitation commercial purposes.
|
|
27
|
+
These owners may contribute to the Commons to promote the ideal of a free
|
|
28
|
+
culture and the further production of creative, cultural and scientific
|
|
29
|
+
works, or to gain reputation or greater distribution for their Work in
|
|
30
|
+
part through the use and efforts of others.
|
|
31
|
+
|
|
32
|
+
For these and/or other purposes and motivations, and without any
|
|
33
|
+
expectation of additional consideration or compensation, the person
|
|
34
|
+
associating CC0 with a Work (the "Affirmer"), to the extent that he or she
|
|
35
|
+
is an owner of Copyright and Related Rights in the Work, voluntarily
|
|
36
|
+
elects to apply CC0 to the Work and publicly distribute the Work under its
|
|
37
|
+
terms, with knowledge of his or her Copyright and Related Rights in the
|
|
38
|
+
Work and the meaning and intended legal effect of CC0 on those rights.
|
|
39
|
+
|
|
40
|
+
1. Copyright and Related Rights. A Work made available under CC0 may be
|
|
41
|
+
protected by copyright and related or neighboring rights ("Copyright and
|
|
42
|
+
Related Rights"). Copyright and Related Rights include, but are not
|
|
43
|
+
limited to, the following:
|
|
44
|
+
|
|
45
|
+
i. the right to reproduce, adapt, distribute, perform, display,
|
|
46
|
+
communicate, and translate a Work;
|
|
47
|
+
ii. moral rights retained by the original author(s) and/or performer(s);
|
|
48
|
+
iii. publicity and privacy rights pertaining to a person's image or
|
|
49
|
+
likeness depicted in a Work;
|
|
50
|
+
iv. rights protecting against unfair competition in regards to a Work,
|
|
51
|
+
subject to the limitations in paragraph 4(a), below;
|
|
52
|
+
v. rights protecting the extraction, dissemination, use and reuse of data
|
|
53
|
+
in a Work;
|
|
54
|
+
vi. database rights (such as those arising under Directive 96/9/EC of the
|
|
55
|
+
European Parliament and of the Council of 11 March 1996 on the legal
|
|
56
|
+
protection of databases, and under any national implementation
|
|
57
|
+
thereof, including any amended or successor version of such
|
|
58
|
+
directive); and
|
|
59
|
+
vii. other similar, equivalent or corresponding rights throughout the
|
|
60
|
+
world based on applicable law or treaty, and any national
|
|
61
|
+
implementations thereof.
|
|
62
|
+
|
|
63
|
+
2. Waiver. To the greatest extent permitted by, but not in contravention
|
|
64
|
+
of, applicable law, Affirmer hereby overtly, fully, permanently,
|
|
65
|
+
irrevocably and unconditionally waives, abandons, and surrenders all of
|
|
66
|
+
Affirmer's Copyright and Related Rights and associated claims and causes
|
|
67
|
+
of action, whether now known or unknown (including existing as well as
|
|
68
|
+
future claims and causes of action), in the Work (i) in all territories
|
|
69
|
+
worldwide, (ii) for the maximum duration provided by applicable law or
|
|
70
|
+
treaty (including future time extensions), (iii) in any current or future
|
|
71
|
+
medium and for any number of copies, and (iv) for any purpose whatsoever,
|
|
72
|
+
including without limitation commercial, advertising or promotional
|
|
73
|
+
purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
|
|
74
|
+
member of the public at large and to the detriment of Affirmer's heirs and
|
|
75
|
+
successors, fully intending that such Waiver shall not be subject to
|
|
76
|
+
revocation, rescission, cancellation, termination, or any other legal or
|
|
77
|
+
equitable action to disrupt the quiet enjoyment of the Work by the public
|
|
78
|
+
as contemplated by Affirmer's express Statement of Purpose.
|
|
79
|
+
|
|
80
|
+
3. Public License Fallback. Should any part of the Waiver for any reason
|
|
81
|
+
be judged legally invalid or ineffective under applicable law, then the
|
|
82
|
+
Waiver shall be preserved to the maximum extent permitted taking into
|
|
83
|
+
account Affirmer's express Statement of Purpose. In addition, to the
|
|
84
|
+
extent the Waiver is so judged Affirmer hereby grants to each affected
|
|
85
|
+
person a royalty-free, non transferable, non sublicensable, non exclusive,
|
|
86
|
+
irrevocable and unconditional license to exercise Affirmer's Copyright and
|
|
87
|
+
Related Rights in the Work (i) in all territories worldwide, (ii) for the
|
|
88
|
+
maximum duration provided by applicable law or treaty (including future
|
|
89
|
+
time extensions), (iii) in any current or future medium and for any number
|
|
90
|
+
of copies, and (iv) for any purpose whatsoever, including without
|
|
91
|
+
limitation commercial, advertising or promotional purposes (the
|
|
92
|
+
"License"). The License shall be deemed effective as of the date CC0 was
|
|
93
|
+
applied by Affirmer to the Work. Should any part of the License for any
|
|
94
|
+
reason be judged legally invalid or ineffective under applicable law, such
|
|
95
|
+
partial invalidity or ineffectiveness shall not invalidate the remainder
|
|
96
|
+
of the License, and in such case Affirmer hereby affirms that he or she
|
|
97
|
+
will not (i) exercise any of his or her remaining Copyright and Related
|
|
98
|
+
Rights in the Work or (ii) assert any associated claims and causes of
|
|
99
|
+
action with respect to the Work, in either case contrary to Affirmer's
|
|
100
|
+
express Statement of Purpose.
|
|
101
|
+
|
|
102
|
+
4. Limitations and Disclaimers.
|
|
103
|
+
|
|
104
|
+
a. No trademark or patent rights held by Affirmer are waived, abandoned,
|
|
105
|
+
surrendered, licensed or otherwise affected by this document.
|
|
106
|
+
b. Affirmer offers the Work as-is and makes no representations or
|
|
107
|
+
warranties of any kind concerning the Work, express, implied,
|
|
108
|
+
statutory or otherwise, including without limitation warranties of
|
|
109
|
+
title, merchantability, fitness for a particular purpose, non
|
|
110
|
+
infringement, or the absence of latent or other defects, accuracy, or
|
|
111
|
+
the present or absence of errors, whether or not discoverable, all to
|
|
112
|
+
the greatest extent permissible under applicable law.
|
|
113
|
+
c. Affirmer disclaims responsibility for clearing rights of other persons
|
|
114
|
+
that may apply to the Work or any use thereof, including without
|
|
115
|
+
limitation any person's Copyright and Related Rights in the Work.
|
|
116
|
+
Further, Affirmer disclaims responsibility for obtaining any necessary
|
|
117
|
+
consents, permissions or other rights required for any use of the
|
|
118
|
+
Work.
|
|
119
|
+
d. Affirmer understands and acknowledges that Creative Commons is not a
|
|
120
|
+
party to this document and has no duty or obligation with respect to
|
|
121
|
+
this CC0 or use of the Work.
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 electrovir
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
# auth-vir
|
|
2
|
+
|
|
3
|
+
Auth made easy and secure via JWT cookies, CSRF tokens, and password hashing helpers. ESM and browser friendly.
|
|
4
|
+
|
|
5
|
+
- Reference docs: https://electrovir.github.io/auth-vir
|
|
6
|
+
- Clone and run the demo: https://github.com/electrovir/auth-vir/blob/dev/packages/demo
|
|
7
|
+
|
|
8
|
+
# Install
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm i auth-vir
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
# Usage
|
|
15
|
+
|
|
16
|
+
## Password hashing
|
|
17
|
+
|
|
18
|
+
- Hash a user created password:
|
|
19
|
+
<!-- example-link: ./src/examples/password-hash.example.ts -->
|
|
20
|
+
|
|
21
|
+
```TypeScript
|
|
22
|
+
import {hashPassword} from 'auth-vir';
|
|
23
|
+
|
|
24
|
+
/** When a user creates or resets their password, hash it before storing it in your database. */
|
|
25
|
+
|
|
26
|
+
const hashedPassword = await hashPassword('user input password');
|
|
27
|
+
|
|
28
|
+
if (!hashedPassword) {
|
|
29
|
+
/** This happens if the user password is too long for the bcrypt algorithm. */
|
|
30
|
+
throw new Error('Password too long.');
|
|
31
|
+
}
|
|
32
|
+
/** Now store `hashedPassword` in your database. */
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
- Compare a stored password hash for login checking:
|
|
36
|
+
<!-- example-link: ./src/examples/password-compare.example.ts -->
|
|
37
|
+
|
|
38
|
+
```TypeScript
|
|
39
|
+
import {doesPasswordMatchHash} from 'auth-vir';
|
|
40
|
+
|
|
41
|
+
if (
|
|
42
|
+
!(await doesPasswordMatchHash({
|
|
43
|
+
hash: 'hash from database',
|
|
44
|
+
password: 'user input password for login',
|
|
45
|
+
}))
|
|
46
|
+
) {
|
|
47
|
+
throw new Error('Login failure.');
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Session auth
|
|
52
|
+
|
|
53
|
+
### Host / server / backend side
|
|
54
|
+
|
|
55
|
+
Use this on your host / server / backend to authenticate client / frontend requests.
|
|
56
|
+
|
|
57
|
+
1. Expose the [`csrfTokenHeaderName`](https://electrovir.github.io/auth-vir/variables/csrfTokenHeaderName.html) (or just `'csrf-token'`) header via CORS headers with either of the following options:
|
|
58
|
+
1. Set `customHeaders: [csrfTokenHeaderName]` in `implementService` from [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service).
|
|
59
|
+
2. Set the header `Access-Control-Allow-Headers` to (at least) `csrfTokenHeaderName`.
|
|
60
|
+
2. Set the `Access-Control-Allow-Origin` header (it cannot be `*`) and properly implement CORS headers and responses.
|
|
61
|
+
3. Generate JWT signing and encryption keys with one of the following:
|
|
62
|
+
- Run `npx auth-vir`: the generated keys will be printed to your console.
|
|
63
|
+
- Run [`await generateNewJwtKeys()`](https://electrovir.github.io/auth-vir/functions/generateNewJwtKeys.html) (imported from this package) in your code.
|
|
64
|
+
4. Securely store the generated keys in a secret place. Do not commit them. They should not be shared with anyone or any other host, client, or service.
|
|
65
|
+
5. In your application code, load the string keys from step 1 into [`parseJwtKeys`](https://electrovir.github.io/auth-vir/functions/parseUserJwt.html): `await parseJwtKeys(stringKeys)`.
|
|
66
|
+
6. Use the output of [`parseJwtKeys`](https://electrovir.github.io/auth-vir/functions/parseUserJwt.html) in all auth functionality:
|
|
67
|
+
- [`generateSuccessfulLoginHeaders`](https://electrovir.github.io/auth-vir/functions/generateSuccessfulLoginHeaders.html): after a user successfully logs in, run this function and attach the output headers to the `Response` object.
|
|
68
|
+
- [`extractUserIdFromRequestHeaders`](https://electrovir.github.io/auth-vir/functions/extractUserIdFromRequestHeaders.html): to verify an authenticated user `Request` object (make sure to properly attach all auth in the client by following the below [Client / frontend side](#client--frontend-side) guide).
|
|
69
|
+
|
|
70
|
+
Here's a full example of how to use all host / server / backend side auth functionality:
|
|
71
|
+
|
|
72
|
+
<!-- example-link: ./src/examples/full-backend.example.ts -->
|
|
73
|
+
|
|
74
|
+
```TypeScript
|
|
75
|
+
import {type ClientRequest, type ServerResponse} from 'node:http';
|
|
76
|
+
import {
|
|
77
|
+
doesPasswordMatchHash,
|
|
78
|
+
extractUserIdFromRequestHeaders,
|
|
79
|
+
generateNewJwtKeys,
|
|
80
|
+
generateSuccessfulLoginHeaders,
|
|
81
|
+
hashPassword,
|
|
82
|
+
parseJwtKeys,
|
|
83
|
+
type CookieParams,
|
|
84
|
+
type CreateJwtParams,
|
|
85
|
+
} from 'auth-vir';
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Use this for a /login endpoint.
|
|
89
|
+
*
|
|
90
|
+
* This verifies a user's login credentials and generate the auth cookie and CSRF token.
|
|
91
|
+
*/
|
|
92
|
+
export async function handleLogin(
|
|
93
|
+
userRequestData: Readonly<{username: string; password: string}>,
|
|
94
|
+
response: ServerResponse,
|
|
95
|
+
) {
|
|
96
|
+
const user = findUserInDatabaseByUsername(userRequestData.username);
|
|
97
|
+
|
|
98
|
+
if (
|
|
99
|
+
!(await doesPasswordMatchHash({
|
|
100
|
+
hash: user.hashedPassword,
|
|
101
|
+
password: userRequestData.password,
|
|
102
|
+
}))
|
|
103
|
+
) {
|
|
104
|
+
throw new Error('Credentials mismatch.');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const authHeaders = await generateSuccessfulLoginHeaders(user.id, cookieParams);
|
|
108
|
+
response.setHeaders(new Headers(authHeaders));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Use this for a /sign-up endpoint.
|
|
113
|
+
*
|
|
114
|
+
* This creates a new user, stores their securely hashed password in the database, and generates the
|
|
115
|
+
* auth cookie and CSRF token.
|
|
116
|
+
*/
|
|
117
|
+
export async function createUser(
|
|
118
|
+
userRequestData: Readonly<{username: string; password: string}>,
|
|
119
|
+
response: ServerResponse,
|
|
120
|
+
) {
|
|
121
|
+
const newUser = await createUserInDatabase(userRequestData);
|
|
122
|
+
|
|
123
|
+
const authHeaders = await generateSuccessfulLoginHeaders(newUser.id, cookieParams);
|
|
124
|
+
response.setHeaders(new Headers(authHeaders));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Use this all endpoints that require an authenticated user.
|
|
129
|
+
*
|
|
130
|
+
* This loads the current user from their auth cookie and CSRF token.
|
|
131
|
+
*/
|
|
132
|
+
export async function getAuthenticatedUser(request: ClientRequest) {
|
|
133
|
+
const userId = await extractUserIdFromRequestHeaders(request.getHeaders(), jwtParams);
|
|
134
|
+
const user = userId ? findUserInDatabaseById(userId) : undefined;
|
|
135
|
+
|
|
136
|
+
if (!userId || !user) {
|
|
137
|
+
throw new Error('Unauthorized.');
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
return user;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* # ===========
|
|
145
|
+
*
|
|
146
|
+
* Helpers
|
|
147
|
+
*
|
|
148
|
+
* # ===========
|
|
149
|
+
*/
|
|
150
|
+
|
|
151
|
+
async function loadSecretJwtKeys() {
|
|
152
|
+
/**
|
|
153
|
+
* This should load your saved JWT keys from a non-committed config file or a secrets manager
|
|
154
|
+
* (like AWS Secrets Manager).
|
|
155
|
+
*/
|
|
156
|
+
return await generateNewJwtKeys();
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const jwtParams: Readonly<CreateJwtParams> = {
|
|
160
|
+
audience: 'server context',
|
|
161
|
+
jwtDuration: {
|
|
162
|
+
hours: 2,
|
|
163
|
+
},
|
|
164
|
+
issuer: 'server login',
|
|
165
|
+
jwtKeys: await parseJwtKeys(await loadSecretJwtKeys()),
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const cookieParams: CookieParams = {
|
|
169
|
+
cookieDuration: {
|
|
170
|
+
hours: 2,
|
|
171
|
+
},
|
|
172
|
+
hostOrigin: 'https://your-backend-origin.example.com',
|
|
173
|
+
jwtParams,
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
function findUserInDatabaseByUsername(username: string) {
|
|
177
|
+
/** This should connect to your database and find a user matching the given username. */
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
/** This should be retrieved from your database. */
|
|
181
|
+
id: 'some id',
|
|
182
|
+
username,
|
|
183
|
+
/** This should be retrieved from your database. */
|
|
184
|
+
hashedPassword: 'hash retrieved from database',
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function findUserInDatabaseById(userId: string): undefined | {id: string; username: string} {
|
|
189
|
+
/** This should connect to your database and find a user matching the given user id. */
|
|
190
|
+
|
|
191
|
+
return {
|
|
192
|
+
id: userId,
|
|
193
|
+
/** This should be retrieved from your database. */
|
|
194
|
+
username: 'some username',
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function createUserInDatabase(
|
|
199
|
+
userRequestData: Readonly<{username: string; password: string}>,
|
|
200
|
+
) {
|
|
201
|
+
const hashedPassword = await hashPassword(userRequestData.password);
|
|
202
|
+
|
|
203
|
+
if (!hashedPassword) {
|
|
204
|
+
throw new Error('Password too long.');
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Store the new username and hashedPassword in your database and return the new user id.
|
|
209
|
+
*
|
|
210
|
+
* @example
|
|
211
|
+
*
|
|
212
|
+
* // using the Prisma ORM:
|
|
213
|
+
* return (
|
|
214
|
+
* await prismaClient.user.create({
|
|
215
|
+
* data: {
|
|
216
|
+
* username: userRequestData.username,
|
|
217
|
+
* hashedPassword,
|
|
218
|
+
* },
|
|
219
|
+
* select: {
|
|
220
|
+
* id: true,
|
|
221
|
+
* },
|
|
222
|
+
* })
|
|
223
|
+
* ).id;
|
|
224
|
+
*/
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
id: 'some new id',
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
### Client / frontend side
|
|
233
|
+
|
|
234
|
+
Use this on your client / frontend for storing and sending session authorization.
|
|
235
|
+
|
|
236
|
+
1. Send a login fetch request to your host / server / backend with `{credentials: 'include'}` set on the request.
|
|
237
|
+
2. Pass the `Response` from step 1 into [`handleAuthResponse`](https://electrovir.github.io/auth-vir/functions/handleAuthResponse.html).
|
|
238
|
+
3. In all subsequent fetch requests to the host / server / backend, set `{credentials: 'include'}` and include `{headers: {[csrfTokenHeaderName]: getCurrentCsrfToken()}}`.
|
|
239
|
+
4. Upon user logout, call [`wipeCurrentCsrfToken()`](https://electrovir.github.io/auth-vir/functions/wipeCurrentCsrfToken.html)
|
|
240
|
+
|
|
241
|
+
Here's a full example of how to use all the client / frontend side auth functionality:
|
|
242
|
+
|
|
243
|
+
<!-- example-link: ./src/examples/full-frontend.example.ts -->
|
|
244
|
+
|
|
245
|
+
```TypeScript
|
|
246
|
+
import {HttpStatus} from '@augment-vir/common';
|
|
247
|
+
import {
|
|
248
|
+
csrfTokenHeaderName,
|
|
249
|
+
getCurrentCsrfToken,
|
|
250
|
+
handleAuthResponse,
|
|
251
|
+
wipeCurrentCsrfToken,
|
|
252
|
+
} from 'auth-vir';
|
|
253
|
+
|
|
254
|
+
/** Call this when the user logs in for the first time this session. */
|
|
255
|
+
export async function sendLoginRequest(
|
|
256
|
+
userLoginData: {username: string; password: string},
|
|
257
|
+
loginUrl: string,
|
|
258
|
+
) {
|
|
259
|
+
if (getCurrentCsrfToken()) {
|
|
260
|
+
throw new Error('Already logged in.');
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const response = await fetch(loginUrl, {
|
|
264
|
+
method: 'post',
|
|
265
|
+
body: JSON.stringify(userLoginData),
|
|
266
|
+
credentials: 'include',
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
handleAuthResponse(response);
|
|
270
|
+
|
|
271
|
+
return response;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Call this when the user needs to send any authenticated request after already having logged in. */
|
|
275
|
+
export async function sendAuthenticatedRequest(
|
|
276
|
+
requestUrl: string,
|
|
277
|
+
requestInit: Omit<RequestInit, 'headers'> = {},
|
|
278
|
+
headers: Record<string, string> = {},
|
|
279
|
+
) {
|
|
280
|
+
const csrfToken = getCurrentCsrfToken();
|
|
281
|
+
|
|
282
|
+
if (!csrfToken) {
|
|
283
|
+
throw new Error('Not authenticated.');
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const response = await fetch(requestUrl, {
|
|
287
|
+
...requestInit,
|
|
288
|
+
credentials: 'include',
|
|
289
|
+
headers: {
|
|
290
|
+
...headers,
|
|
291
|
+
[csrfTokenHeaderName]: csrfToken,
|
|
292
|
+
},
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* This indicates the user is no longer authorized and thus needs to login again. (This likely
|
|
297
|
+
* means that their session timed out or they clicked a "log out" button onr your website in
|
|
298
|
+
* another tab.)
|
|
299
|
+
*/
|
|
300
|
+
if (response.status === HttpStatus.Unauthorized) {
|
|
301
|
+
wipeCurrentCsrfToken();
|
|
302
|
+
throw new Error(`User no longer logged in.`);
|
|
303
|
+
} else {
|
|
304
|
+
return response;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Call this when the user explicitly clicks a "log out" button. */
|
|
309
|
+
export function logout() {
|
|
310
|
+
wipeCurrentCsrfToken();
|
|
311
|
+
}
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
# Requirements
|
|
315
|
+
|
|
316
|
+
All of these configurations must be set for the auth exports in this package to function properly:
|
|
317
|
+
|
|
318
|
+
- Expose the [`csrfTokenHeaderName`](https://electrovir.github.io/auth-vir/variables/csrfTokenHeaderName.html) (or just `'csrf-token'`) header via CORS headers with either of the following options:
|
|
319
|
+
1. Set `customHeaders: [csrfTokenHeaderName]` in `implementService` from [`@rest-vir/implement-service`](https://www.npmjs.com/package/@rest-vir/implement-service).
|
|
320
|
+
2. Set the header `Access-Control-Allow-Headers` to (at least) `csrfTokenHeaderName`.
|
|
321
|
+
- Set `credentials: include` in all fetch requests on the client that need to use or set the auth cookie.
|
|
322
|
+
- Server CORS should set `Access-Control-Allow-Origin` (it cannot be `*`).
|
package/bin.js
ADDED
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { CookieParams } from './cookie.js';
|
|
2
|
+
import { ParseJwtParams } from './jwt.js';
|
|
3
|
+
/**
|
|
4
|
+
* All possible headers container types supported by {@link extractUserIdFromRequestHeaders}.
|
|
5
|
+
*
|
|
6
|
+
* @category Internal
|
|
7
|
+
*/
|
|
8
|
+
export type HeaderContainer = Record<string, string[] | undefined | string | number> | Headers;
|
|
9
|
+
/**
|
|
10
|
+
* Extract the user id from a request by checking both the request cookie and CSRF token. This is
|
|
11
|
+
* used by host (backend) code to help verify a request. After extracting the user id using this,
|
|
12
|
+
* you should compare it to users stored in your database.
|
|
13
|
+
*
|
|
14
|
+
* @category Auth : Host
|
|
15
|
+
* @returns The extracted user id or `undefined` if no valid auth headers exist.
|
|
16
|
+
*/
|
|
17
|
+
export declare function extractUserIdFromRequestHeaders(headers: HeaderContainer, jwtParams: Readonly<ParseJwtParams>): Promise<string | undefined>;
|
|
18
|
+
/**
|
|
19
|
+
* Used by host (backend) code to set headers on a response object.
|
|
20
|
+
*
|
|
21
|
+
* @category Auth : Host
|
|
22
|
+
*/
|
|
23
|
+
export declare function generateSuccessfulLoginHeaders(userId: string,
|
|
24
|
+
/** The id from your database of the user you're authenticating. */
|
|
25
|
+
cookieConfig: Readonly<CookieParams>): Promise<{
|
|
26
|
+
'set-cookie': string;
|
|
27
|
+
"csrf-token": string;
|
|
28
|
+
}>;
|
|
29
|
+
/**
|
|
30
|
+
* Store auth data on a client (frontend) after receiving an auth response from the host (backend).
|
|
31
|
+
* Specifically, this stores the CSRF token into local storage (which doesn't need to be a secret).
|
|
32
|
+
* Alternatively, if the given response failed, this will wipe the existing (if anyone) stored CSRF
|
|
33
|
+
* token.
|
|
34
|
+
*
|
|
35
|
+
* @category Auth : Client
|
|
36
|
+
* @throws Error if no CSRF token header is found.
|
|
37
|
+
*/
|
|
38
|
+
export declare function handleAuthResponse(response: Readonly<Pick<Response, 'ok' | 'headers'>>, overrides?: {
|
|
39
|
+
/**
|
|
40
|
+
* Allows mocking or overriding the global `localStorage`.
|
|
41
|
+
*
|
|
42
|
+
* @default globalThis.localStorage
|
|
43
|
+
*/
|
|
44
|
+
localStorage?: Pick<Storage, 'setItem' | 'removeItem'>;
|
|
45
|
+
/** Override the default CSRF token header name. */
|
|
46
|
+
csrfHeaderName?: string;
|
|
47
|
+
}): void;
|
|
48
|
+
/**
|
|
49
|
+
* Used in client (frontend) code to retrieve the current CSRF token in order to send it with
|
|
50
|
+
* requests to the host (backend).
|
|
51
|
+
*
|
|
52
|
+
* @category Auth : Client
|
|
53
|
+
*/
|
|
54
|
+
export declare function getCurrentCsrfToken(overrides?: {
|
|
55
|
+
/**
|
|
56
|
+
* Allows mocking or overriding the global `localStorage`.
|
|
57
|
+
*
|
|
58
|
+
* @default globalThis.localStorage
|
|
59
|
+
*/
|
|
60
|
+
localStorage?: Pick<Storage, 'getItem'>;
|
|
61
|
+
/** Override the default CSRF token header name. */
|
|
62
|
+
csrfHeaderName?: string;
|
|
63
|
+
}): string | undefined;
|
|
64
|
+
/**
|
|
65
|
+
* Wipes the current stored CSRF token. This should be used by client (frontend) code to logout a
|
|
66
|
+
* user or react to a session timeout.
|
|
67
|
+
*
|
|
68
|
+
* @category Auth : Client
|
|
69
|
+
*/
|
|
70
|
+
export declare function wipeCurrentCsrfToken(overrides?: {
|
|
71
|
+
/**
|
|
72
|
+
* Allows mocking or overriding the global `localStorage`.
|
|
73
|
+
*
|
|
74
|
+
* @default globalThis.localStorage
|
|
75
|
+
*/
|
|
76
|
+
localStorage?: Pick<Storage, 'removeItem'>;
|
|
77
|
+
/** Override the default CSRF token header name. */
|
|
78
|
+
csrfHeaderName?: string;
|
|
79
|
+
}): void;
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { extractCookieJwt, generateCookie } from './cookie.js';
|
|
2
|
+
import { csrfTokenHeaderName, generateCsrfToken } from './csrf-token.js';
|
|
3
|
+
function readHeader(headers, headerName) {
|
|
4
|
+
if (headers instanceof Headers) {
|
|
5
|
+
return headers.get(headerName) || undefined;
|
|
6
|
+
}
|
|
7
|
+
else {
|
|
8
|
+
const value = headers[headerName];
|
|
9
|
+
if (value == undefined) {
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
else if (Array.isArray(value)) {
|
|
13
|
+
return value[0];
|
|
14
|
+
}
|
|
15
|
+
else {
|
|
16
|
+
return String(value);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Extract the user id from a request by checking both the request cookie and CSRF token. This is
|
|
22
|
+
* used by host (backend) code to help verify a request. After extracting the user id using this,
|
|
23
|
+
* you should compare it to users stored in your database.
|
|
24
|
+
*
|
|
25
|
+
* @category Auth : Host
|
|
26
|
+
* @returns The extracted user id or `undefined` if no valid auth headers exist.
|
|
27
|
+
*/
|
|
28
|
+
export async function extractUserIdFromRequestHeaders(headers, jwtParams) {
|
|
29
|
+
try {
|
|
30
|
+
const csrfToken = readHeader(headers, csrfTokenHeaderName);
|
|
31
|
+
const cookie = readHeader(headers, 'cookie');
|
|
32
|
+
if (!cookie || !csrfToken) {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
const jwt = await extractCookieJwt(cookie, jwtParams);
|
|
36
|
+
if (!jwt || jwt.csrfToken !== csrfToken) {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
return jwt.userId;
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Used by host (backend) code to set headers on a response object.
|
|
47
|
+
*
|
|
48
|
+
* @category Auth : Host
|
|
49
|
+
*/
|
|
50
|
+
export async function generateSuccessfulLoginHeaders(userId,
|
|
51
|
+
/** The id from your database of the user you're authenticating. */
|
|
52
|
+
cookieConfig) {
|
|
53
|
+
const csrfToken = generateCsrfToken();
|
|
54
|
+
return {
|
|
55
|
+
'set-cookie': await generateCookie({
|
|
56
|
+
csrfToken,
|
|
57
|
+
userId,
|
|
58
|
+
}, cookieConfig),
|
|
59
|
+
[csrfTokenHeaderName]: csrfToken,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Store auth data on a client (frontend) after receiving an auth response from the host (backend).
|
|
64
|
+
* Specifically, this stores the CSRF token into local storage (which doesn't need to be a secret).
|
|
65
|
+
* Alternatively, if the given response failed, this will wipe the existing (if anyone) stored CSRF
|
|
66
|
+
* token.
|
|
67
|
+
*
|
|
68
|
+
* @category Auth : Client
|
|
69
|
+
* @throws Error if no CSRF token header is found.
|
|
70
|
+
*/
|
|
71
|
+
export function handleAuthResponse(response, overrides = {}) {
|
|
72
|
+
if (!response.ok) {
|
|
73
|
+
wipeCurrentCsrfToken(overrides);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const headerName = overrides.csrfHeaderName || csrfTokenHeaderName;
|
|
77
|
+
const csrfToken = response.headers.get(headerName);
|
|
78
|
+
if (!csrfToken) {
|
|
79
|
+
wipeCurrentCsrfToken(overrides);
|
|
80
|
+
throw new Error('Did not receive any CSRF token.');
|
|
81
|
+
}
|
|
82
|
+
(overrides.localStorage || globalThis.localStorage).setItem(headerName, csrfToken);
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Used in client (frontend) code to retrieve the current CSRF token in order to send it with
|
|
86
|
+
* requests to the host (backend).
|
|
87
|
+
*
|
|
88
|
+
* @category Auth : Client
|
|
89
|
+
*/
|
|
90
|
+
export function getCurrentCsrfToken(overrides = {}) {
|
|
91
|
+
return ((overrides.localStorage || globalThis.localStorage).getItem(overrides.csrfHeaderName || csrfTokenHeaderName) || undefined);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Wipes the current stored CSRF token. This should be used by client (frontend) code to logout a
|
|
95
|
+
* user or react to a session timeout.
|
|
96
|
+
*
|
|
97
|
+
* @category Auth : Client
|
|
98
|
+
*/
|
|
99
|
+
export function wipeCurrentCsrfToken(overrides = {}) {
|
|
100
|
+
return (overrides.localStorage || globalThis.localStorage).removeItem(overrides.csrfHeaderName || csrfTokenHeaderName);
|
|
101
|
+
}
|