@molecule/api-resource-user 1.8.8 → 1.9.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/README.md +247 -12
- package/dist/accounts.d.ts +162 -0
- package/dist/accounts.d.ts.map +1 -0
- package/dist/accounts.js +209 -0
- package/dist/accounts.js.map +1 -0
- package/dist/index.d.ts +16 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +16 -11
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -3,7 +3,7 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
|
|
|
3
3
|
Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
|
|
4
4
|
Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
|
|
5
5
|
To change this document, edit the module-level JSDoc in src/index.ts.
|
|
6
|
-
Generated: 2026-11-
|
|
6
|
+
Generated: 2026-11-11T21:16:10.547Z
|
|
7
7
|
-->
|
|
8
8
|
|
|
9
9
|
# @molecule/api-resource-user
|
|
@@ -39,16 +39,20 @@ finish it with `provisionUser(..., { props, completeId: id })` — a retry witho
|
|
|
39
39
|
answers `existing` and repairs nothing. **TRUSTED SERVER CALLERS ONLY:** it takes props
|
|
40
40
|
directly, so a public endpoint built on it is a mass-assignment hole.
|
|
41
41
|
|
|
42
|
-
|
|
43
|
-
`
|
|
44
|
-
|
|
45
|
-
|
|
42
|
+
**Your own sign-up and sign-in routes call
|
|
43
|
+
`createAccount({ username, email, password }, { req, res })` and {@link signIn}:** each
|
|
44
|
+
resolves to `{ ok, user, token }`, and `token` is the session.
|
|
45
|
+
Never call `sign()`, `hash()` or `compare()` for accounts yourself.
|
|
46
46
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
47
|
+
HTTP path: `handlers.create`, `handlers.logIn`, `handlers.updatePassword`. One secret:
|
|
48
|
+
`findById('usersSecrets', userId)`.
|
|
49
|
+
|
|
50
|
+
**Token API (`Authorization: Token <jwt>`)? CONFIGURATION,
|
|
51
|
+
never a credentials table of your own** (`usersSecrets.passwordHash` is the store): set
|
|
52
|
+
`AUTH_SCHEME=Token` (or `verifyMiddleware({ scheme: 'Token' })`) — every route accepts it,
|
|
53
|
+
`logIn`/`create` return `accessToken`, `GET /users/me` echoes it, and a password change
|
|
54
|
+
revokes every OTHER device but keeps the
|
|
55
|
+
caller's own session.
|
|
52
56
|
|
|
53
57
|
**Generated full-stack apps:** mlcl derives the app-auth composition root from this API contract; keep that bond and use its shared HTTP client.
|
|
54
58
|
|
|
@@ -115,8 +119,8 @@ import { createRequestHandler } from '@molecule/api-resource'
|
|
|
115
119
|
import { createResource, handlers } from '@molecule/api-resource-user'
|
|
116
120
|
|
|
117
121
|
// Omit `schema`: create() validates new users with this package's propsSchema.
|
|
118
|
-
const
|
|
119
|
-
const
|
|
122
|
+
const signUpRoute = createRequestHandler(handlers.create({ name: 'User', tableName: 'users' }))
|
|
123
|
+
const signInRoute = createRequestHandler(handlers.logIn({ name: 'User', tableName: 'users' }))
|
|
120
124
|
|
|
121
125
|
// A constrained schema, when the app restricts oauthServer / planKey.
|
|
122
126
|
const users = createResource({ oauthServers: ['google', 'github'] as const })
|
|
@@ -229,6 +233,86 @@ npm install @molecule/api-resource-user @molecule/api-bond @molecule/api-config
|
|
|
229
233
|
|
|
230
234
|
### Interfaces
|
|
231
235
|
|
|
236
|
+
#### `SessionContext`
|
|
237
|
+
|
|
238
|
+
The request a session is being issued in. The session's `Authorization` response header (and
|
|
239
|
+
its cookie, where the mount allows one) is set on `res`.
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
interface SessionContext {
|
|
243
|
+
req: MoleculeRequest
|
|
244
|
+
res: MoleculeResponse
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
#### `AccountSession`
|
|
249
|
+
|
|
250
|
+
A signed-in account: the safe user row and its session token.
|
|
251
|
+
|
|
252
|
+
```typescript
|
|
253
|
+
interface AccountSession {
|
|
254
|
+
ok: true
|
|
255
|
+
/** The user's row with every secret column stripped — safe to send to the client. */
|
|
256
|
+
user: types.Props
|
|
257
|
+
/**
|
|
258
|
+
* The session token, signed by the bonded JWT provider and bound to a device row. The client
|
|
259
|
+
* sends it back as `Authorization: <scheme> <token>`; `verifyMiddleware` accepts it.
|
|
260
|
+
*/
|
|
261
|
+
token: string
|
|
262
|
+
}
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
#### `AccountFailure`
|
|
266
|
+
|
|
267
|
+
An account call that signed no one in, as values an app maps to its own error body.
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
270
|
+
interface AccountFailure {
|
|
271
|
+
ok: false
|
|
272
|
+
/** The cause, for a `switch`. */
|
|
273
|
+
reason: AccountFailureReason
|
|
274
|
+
/** The input field the cause is about, or null when it is not about one field. */
|
|
275
|
+
field: 'username' | 'email' | 'password' | 'twoFactorToken' | null
|
|
276
|
+
/** A sentence for the person, in the request's locale. */
|
|
277
|
+
message: string
|
|
278
|
+
/** The status this package's own route answers with, as a starting point. */
|
|
279
|
+
statusCode: number
|
|
280
|
+
/** This package's stable error key (`user.error.usernameUnavailable`). */
|
|
281
|
+
errorKey: string
|
|
282
|
+
}
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
#### `CreateAccountInput`
|
|
286
|
+
|
|
287
|
+
The fields a person may choose when signing up. Anything else is ignored, never stored.
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
interface CreateAccountInput {
|
|
291
|
+
username?: string
|
|
292
|
+
email?: string
|
|
293
|
+
name?: string
|
|
294
|
+
password: string
|
|
295
|
+
/** A label for the session's device row ("Chrome on macOS"). */
|
|
296
|
+
deviceName?: string
|
|
297
|
+
}
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
#### `SignInInput`
|
|
301
|
+
|
|
302
|
+
What a person signs in with: a username or an email, and the password.
|
|
303
|
+
|
|
304
|
+
```typescript
|
|
305
|
+
interface SignInInput {
|
|
306
|
+
username?: string
|
|
307
|
+
email?: string
|
|
308
|
+
password: string
|
|
309
|
+
/** The current code, when the account has two-factor on. */
|
|
310
|
+
twoFactorToken?: string
|
|
311
|
+
/** A label for the session's device row. */
|
|
312
|
+
deviceName?: string
|
|
313
|
+
}
|
|
314
|
+
```
|
|
315
|
+
|
|
232
316
|
#### `ProvisionUserInput`
|
|
233
317
|
|
|
234
318
|
Input accepted by {@link provisionUser}.
|
|
@@ -305,6 +389,34 @@ interface UserRequestHandlerMap {
|
|
|
305
389
|
|
|
306
390
|
### Types
|
|
307
391
|
|
|
392
|
+
#### `AccountFailureReason`
|
|
393
|
+
|
|
394
|
+
Why an account call did not sign anyone in.
|
|
395
|
+
|
|
396
|
+
```typescript
|
|
397
|
+
type AccountFailureReason =
|
|
398
|
+
| 'username-invalid'
|
|
399
|
+
| 'username-taken'
|
|
400
|
+
| 'email-invalid'
|
|
401
|
+
| 'email-taken'
|
|
402
|
+
| 'password-required'
|
|
403
|
+
| 'password-too-short'
|
|
404
|
+
| 'password-too-long'
|
|
405
|
+
| 'invalid-credentials'
|
|
406
|
+
| 'two-factor-required'
|
|
407
|
+
| 'two-factor-invalid'
|
|
408
|
+
| 'invalid'
|
|
409
|
+
| 'unavailable'
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
#### `AccountResult`
|
|
413
|
+
|
|
414
|
+
What {@link createAccount} and {@link signIn} resolve to.
|
|
415
|
+
|
|
416
|
+
```typescript
|
|
417
|
+
type AccountResult = AccountSession | AccountFailure
|
|
418
|
+
```
|
|
419
|
+
|
|
308
420
|
#### `ProvisionUserProps`
|
|
309
421
|
|
|
310
422
|
Safe user props accepted by {@link provisionUser} — the `users` table's columns without the
|
|
@@ -519,6 +631,129 @@ type Session = z.infer<typeof sessionSchema>
|
|
|
519
631
|
|
|
520
632
|
### Functions
|
|
521
633
|
|
|
634
|
+
#### `createAccount(input, context, resource)`
|
|
635
|
+
|
|
636
|
+
Creates an account from a sign-up form and signs it in.
|
|
637
|
+
|
|
638
|
+
Call it from a route of your own when the API's contract is not this package's
|
|
639
|
+
(`POST /users` with a `{ user: … }` envelope, say), and map the result:
|
|
640
|
+
|
|
641
|
+
```typescript
|
|
642
|
+
import { createAccount } from '@molecule/api-resource-user'
|
|
643
|
+
|
|
644
|
+
router.post('/users', async (req, res) => {
|
|
645
|
+
const { username, email, password } = req.body.user ?? {}
|
|
646
|
+
const account = await createAccount({ username, email, password }, { req, res })
|
|
647
|
+
if (!account.ok)
|
|
648
|
+
return res.status(422).json({ errors: { [account.field ?? 'account']: [account.message] } })
|
|
649
|
+
res.status(201).json({ user: { ...account.user, token: account.token } })
|
|
650
|
+
})
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
It is `handlers.create` as a function: only `username`, `email` and `name` are taken from the
|
|
654
|
+
input (nothing a caller adds is stored), the password is length-checked and hashed by the bonded
|
|
655
|
+
`@molecule/api-password` provider into `usersSecrets`, a device row is created and the token is
|
|
656
|
+
signed by the bonded `@molecule/api-jwt` provider — so it is a session `verifyMiddleware`
|
|
657
|
+
accepts. The `Authorization` response header (and the session cookie, where the mount allows
|
|
658
|
+
one) is set on `res` as the mounted route sets it.
|
|
659
|
+
|
|
660
|
+
```typescript
|
|
661
|
+
function createAccount(
|
|
662
|
+
input: CreateAccountInput,
|
|
663
|
+
context: SessionContext,
|
|
664
|
+
resource?: types.HandlerResource,
|
|
665
|
+
): Promise<AccountResult>
|
|
666
|
+
```
|
|
667
|
+
|
|
668
|
+
- `input` — What the person entered.
|
|
669
|
+
- `context` — The current `{ req, res }`; the session header is set on `res`.
|
|
670
|
+
- `resource` — The users resource, when the app renamed the table. Defaults to `users`.
|
|
671
|
+
|
|
672
|
+
**Returns:** The signed-in account, or why none was created.
|
|
673
|
+
|
|
674
|
+
#### `signIn(input, context, resource)`
|
|
675
|
+
|
|
676
|
+
Checks a username or email and password, and signs the person in.
|
|
677
|
+
|
|
678
|
+
```typescript
|
|
679
|
+
import { signIn } from '@molecule/api-resource-user'
|
|
680
|
+
|
|
681
|
+
router.post('/users/login', async (req, res) => {
|
|
682
|
+
const { email, password } = req.body.user ?? {}
|
|
683
|
+
const account = await signIn({ email, password }, { req, res })
|
|
684
|
+
if (!account.ok) return res.status(401).json({ errors: { credentials: ['invalid'] } })
|
|
685
|
+
res.json({ user: { ...account.user, token: account.token } })
|
|
686
|
+
})
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
It is `handlers.logIn` as a function, with nothing weakened: an unknown account and a wrong
|
|
690
|
+
password take the same time and give the same `invalid-credentials`, the comparison is the
|
|
691
|
+
bonded hasher's, an account with two-factor on answers `two-factor-required` until
|
|
692
|
+
`twoFactorToken` is sent, and the session is device-bound, so sign-out and a password change
|
|
693
|
+
revoke it. A password-reset token is not accepted here; use the reset routes for that.
|
|
694
|
+
|
|
695
|
+
```typescript
|
|
696
|
+
function signIn(
|
|
697
|
+
input: SignInInput,
|
|
698
|
+
context: SessionContext,
|
|
699
|
+
resource?: types.HandlerResource,
|
|
700
|
+
): Promise<AccountResult>
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
- `input` — The credentials.
|
|
704
|
+
- `context` — The current `{ req, res }`; the session header is set on `res`.
|
|
705
|
+
- `resource` — The users resource, when the app renamed the table. Defaults to `users`.
|
|
706
|
+
|
|
707
|
+
**Returns:** The signed-in account, or why no one was signed in.
|
|
708
|
+
|
|
709
|
+
#### `checkPassword(userId, password, resource)`
|
|
710
|
+
|
|
711
|
+
Whether `password` is the account's current password — for a step that re-asks for it
|
|
712
|
+
(confirming a deletion, changing an email in a route of your own).
|
|
713
|
+
|
|
714
|
+
The comparison is the bonded `@molecule/api-password` provider's, against the hash in
|
|
715
|
+
`usersSecrets`. An account with no password (OAuth-only) and an unknown id answer `false` after
|
|
716
|
+
a comparison against a throwaway hash, so the answer's timing does not say which it was.
|
|
717
|
+
Never compare hashes or passwords yourself.
|
|
718
|
+
|
|
719
|
+
```typescript
|
|
720
|
+
function checkPassword(
|
|
721
|
+
userId: string,
|
|
722
|
+
password: string,
|
|
723
|
+
resource?: types.HandlerResource,
|
|
724
|
+
): Promise<boolean>
|
|
725
|
+
```
|
|
726
|
+
|
|
727
|
+
- `userId` — The account's id (`users.id`, which is also its `usersSecrets.id`).
|
|
728
|
+
- `password` — The password the person entered.
|
|
729
|
+
- `resource` — The users resource, when the app renamed the table. Defaults to `users`.
|
|
730
|
+
|
|
731
|
+
**Returns:** True only when the password matches.
|
|
732
|
+
|
|
733
|
+
#### `issueSession(userId, context, options)`
|
|
734
|
+
|
|
735
|
+
Signs in an account you have ALREADY authenticated some other way (a verified invite link, a
|
|
736
|
+
single sign-on callback) and returns its session token.
|
|
737
|
+
|
|
738
|
+
It creates the device row and has the bonded JWT provider sign a token bound to it — the two
|
|
739
|
+
steps a session is. A token signed any other way names no device and is answered 401 by
|
|
740
|
+
`verifyMiddleware` on every request. For a username or email and password use {@link signIn},
|
|
741
|
+
which checks them first; this function checks nothing.
|
|
742
|
+
|
|
743
|
+
```typescript
|
|
744
|
+
function issueSession(
|
|
745
|
+
userId: string,
|
|
746
|
+
context: SessionContext,
|
|
747
|
+
options?: { deviceName?: string },
|
|
748
|
+
): Promise<string>
|
|
749
|
+
```
|
|
750
|
+
|
|
751
|
+
- `userId` — The authenticated account's id.
|
|
752
|
+
- `context` — The current `{ req, res }`; the session header is set on `res`.
|
|
753
|
+
- `options` — An optional label for the session's device row.
|
|
754
|
+
|
|
755
|
+
**Returns:** The session token.
|
|
756
|
+
|
|
522
757
|
#### `provisionUser(resource, input)`
|
|
523
758
|
|
|
524
759
|
Creates a user record and its same-id credential record for a trusted server caller, without
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plain account and session functions for routes an app writes itself.
|
|
3
|
+
*
|
|
4
|
+
* `handlers.*` answer HTTP (`{ statusCode, body }`) in this package's own wire shape. An API with
|
|
5
|
+
* its own contract — its own paths, envelopes, status codes or error bodies — needs the same work
|
|
6
|
+
* as values it can map: {@link createAccount}, {@link signIn}, {@link checkPassword} and
|
|
7
|
+
* {@link issueSession}. They run the SAME code the mounted routes run (validation, the bonded
|
|
8
|
+
* password hasher and its constant-time comparison, two-factor, the device-bound session signed
|
|
9
|
+
* through the bonded JWT provider), so an app never hashes a password, compares one, or signs a
|
|
10
|
+
* token itself.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import type { MoleculeRequest, MoleculeResponse } from '@molecule/api-resource';
|
|
15
|
+
import type * as types from './types.js';
|
|
16
|
+
/** Why an account call did not sign anyone in. */
|
|
17
|
+
export type AccountFailureReason = 'username-invalid' | 'username-taken' | 'email-invalid' | 'email-taken' | 'password-required' | 'password-too-short' | 'password-too-long' | 'invalid-credentials' | 'two-factor-required' | 'two-factor-invalid' | 'invalid' | 'unavailable';
|
|
18
|
+
/**
|
|
19
|
+
* The request a session is being issued in. The session's `Authorization` response header (and
|
|
20
|
+
* its cookie, where the mount allows one) is set on `res`.
|
|
21
|
+
*/
|
|
22
|
+
export interface SessionContext {
|
|
23
|
+
req: MoleculeRequest;
|
|
24
|
+
res: MoleculeResponse;
|
|
25
|
+
}
|
|
26
|
+
/** A signed-in account: the safe user row and its session token. */
|
|
27
|
+
export interface AccountSession {
|
|
28
|
+
ok: true;
|
|
29
|
+
/** The user's row with every secret column stripped — safe to send to the client. */
|
|
30
|
+
user: types.Props;
|
|
31
|
+
/**
|
|
32
|
+
* The session token, signed by the bonded JWT provider and bound to a device row. The client
|
|
33
|
+
* sends it back as `Authorization: <scheme> <token>`; `verifyMiddleware` accepts it.
|
|
34
|
+
*/
|
|
35
|
+
token: string;
|
|
36
|
+
}
|
|
37
|
+
/** An account call that signed no one in, as values an app maps to its own error body. */
|
|
38
|
+
export interface AccountFailure {
|
|
39
|
+
ok: false;
|
|
40
|
+
/** The cause, for a `switch`. */
|
|
41
|
+
reason: AccountFailureReason;
|
|
42
|
+
/** The input field the cause is about, or null when it is not about one field. */
|
|
43
|
+
field: 'username' | 'email' | 'password' | 'twoFactorToken' | null;
|
|
44
|
+
/** A sentence for the person, in the request's locale. */
|
|
45
|
+
message: string;
|
|
46
|
+
/** The status this package's own route answers with, as a starting point. */
|
|
47
|
+
statusCode: number;
|
|
48
|
+
/** This package's stable error key (`user.error.usernameUnavailable`). */
|
|
49
|
+
errorKey: string;
|
|
50
|
+
}
|
|
51
|
+
/** What {@link createAccount} and {@link signIn} resolve to. */
|
|
52
|
+
export type AccountResult = AccountSession | AccountFailure;
|
|
53
|
+
/** The fields a person may choose when signing up. Anything else is ignored, never stored. */
|
|
54
|
+
export interface CreateAccountInput {
|
|
55
|
+
username?: string;
|
|
56
|
+
email?: string;
|
|
57
|
+
name?: string;
|
|
58
|
+
password: string;
|
|
59
|
+
/** A label for the session's device row ("Chrome on macOS"). */
|
|
60
|
+
deviceName?: string;
|
|
61
|
+
}
|
|
62
|
+
/** What a person signs in with: a username or an email, and the password. */
|
|
63
|
+
export interface SignInInput {
|
|
64
|
+
username?: string;
|
|
65
|
+
email?: string;
|
|
66
|
+
password: string;
|
|
67
|
+
/** The current code, when the account has two-factor on. */
|
|
68
|
+
twoFactorToken?: string;
|
|
69
|
+
/** A label for the session's device row. */
|
|
70
|
+
deviceName?: string;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Creates an account from a sign-up form and signs it in.
|
|
74
|
+
*
|
|
75
|
+
* Call it from a route of your own when the API's contract is not this package's
|
|
76
|
+
* (`POST /users` with a `{ user: … }` envelope, say), and map the result:
|
|
77
|
+
*
|
|
78
|
+
* ```typescript
|
|
79
|
+
* import { createAccount } from '@molecule/api-resource-user'
|
|
80
|
+
*
|
|
81
|
+
* router.post('/users', async (req, res) => {
|
|
82
|
+
* const { username, email, password } = req.body.user ?? {}
|
|
83
|
+
* const account = await createAccount({ username, email, password }, { req, res })
|
|
84
|
+
* if (!account.ok)
|
|
85
|
+
* return res.status(422).json({ errors: { [account.field ?? 'account']: [account.message] } })
|
|
86
|
+
* res.status(201).json({ user: { ...account.user, token: account.token } })
|
|
87
|
+
* })
|
|
88
|
+
* ```
|
|
89
|
+
*
|
|
90
|
+
* It is `handlers.create` as a function: only `username`, `email` and `name` are taken from the
|
|
91
|
+
* input (nothing a caller adds is stored), the password is length-checked and hashed by the bonded
|
|
92
|
+
* `@molecule/api-password` provider into `usersSecrets`, a device row is created and the token is
|
|
93
|
+
* signed by the bonded `@molecule/api-jwt` provider — so it is a session `verifyMiddleware`
|
|
94
|
+
* accepts. The `Authorization` response header (and the session cookie, where the mount allows
|
|
95
|
+
* one) is set on `res` as the mounted route sets it.
|
|
96
|
+
*
|
|
97
|
+
* @param input - What the person entered.
|
|
98
|
+
* @param context - The current `{ req, res }`; the session header is set on `res`.
|
|
99
|
+
* @param resource - The users resource, when the app renamed the table. Defaults to `users`.
|
|
100
|
+
* @returns The signed-in account, or why none was created.
|
|
101
|
+
*/
|
|
102
|
+
export declare function createAccount(input: CreateAccountInput, context: SessionContext, resource?: types.HandlerResource): Promise<AccountResult>;
|
|
103
|
+
/**
|
|
104
|
+
* Checks a username or email and password, and signs the person in.
|
|
105
|
+
*
|
|
106
|
+
* ```typescript
|
|
107
|
+
* import { signIn } from '@molecule/api-resource-user'
|
|
108
|
+
*
|
|
109
|
+
* router.post('/users/login', async (req, res) => {
|
|
110
|
+
* const { email, password } = req.body.user ?? {}
|
|
111
|
+
* const account = await signIn({ email, password }, { req, res })
|
|
112
|
+
* if (!account.ok) return res.status(401).json({ errors: { credentials: ['invalid'] } })
|
|
113
|
+
* res.json({ user: { ...account.user, token: account.token } })
|
|
114
|
+
* })
|
|
115
|
+
* ```
|
|
116
|
+
*
|
|
117
|
+
* It is `handlers.logIn` as a function, with nothing weakened: an unknown account and a wrong
|
|
118
|
+
* password take the same time and give the same `invalid-credentials`, the comparison is the
|
|
119
|
+
* bonded hasher's, an account with two-factor on answers `two-factor-required` until
|
|
120
|
+
* `twoFactorToken` is sent, and the session is device-bound, so sign-out and a password change
|
|
121
|
+
* revoke it. A password-reset token is not accepted here; use the reset routes for that.
|
|
122
|
+
*
|
|
123
|
+
* @param input - The credentials.
|
|
124
|
+
* @param context - The current `{ req, res }`; the session header is set on `res`.
|
|
125
|
+
* @param resource - The users resource, when the app renamed the table. Defaults to `users`.
|
|
126
|
+
* @returns The signed-in account, or why no one was signed in.
|
|
127
|
+
*/
|
|
128
|
+
export declare function signIn(input: SignInInput, context: SessionContext, resource?: types.HandlerResource): Promise<AccountResult>;
|
|
129
|
+
/**
|
|
130
|
+
* Whether `password` is the account's current password — for a step that re-asks for it
|
|
131
|
+
* (confirming a deletion, changing an email in a route of your own).
|
|
132
|
+
*
|
|
133
|
+
* The comparison is the bonded `@molecule/api-password` provider's, against the hash in
|
|
134
|
+
* `usersSecrets`. An account with no password (OAuth-only) and an unknown id answer `false` after
|
|
135
|
+
* a comparison against a throwaway hash, so the answer's timing does not say which it was.
|
|
136
|
+
* Never compare hashes or passwords yourself.
|
|
137
|
+
*
|
|
138
|
+
* @param userId - The account's id (`users.id`, which is also its `usersSecrets.id`).
|
|
139
|
+
* @param password - The password the person entered.
|
|
140
|
+
* @param resource - The users resource, when the app renamed the table. Defaults to `users`.
|
|
141
|
+
* @returns True only when the password matches.
|
|
142
|
+
*/
|
|
143
|
+
export declare function checkPassword(userId: string, password: string, resource?: types.HandlerResource): Promise<boolean>;
|
|
144
|
+
/**
|
|
145
|
+
* Signs in an account you have ALREADY authenticated some other way (a verified invite link, a
|
|
146
|
+
* single sign-on callback) and returns its session token.
|
|
147
|
+
*
|
|
148
|
+
* It creates the device row and has the bonded JWT provider sign a token bound to it — the two
|
|
149
|
+
* steps a session is. A token signed any other way names no device and is answered 401 by
|
|
150
|
+
* `verifyMiddleware` on every request. For a username or email and password use {@link signIn},
|
|
151
|
+
* which checks them first; this function checks nothing.
|
|
152
|
+
*
|
|
153
|
+
* @param userId - The authenticated account's id.
|
|
154
|
+
* @param context - The current `{ req, res }`; the session header is set on `res`.
|
|
155
|
+
* @param options - An optional label for the session's device row.
|
|
156
|
+
* @returns The session token.
|
|
157
|
+
* @throws {Error} When no device service is bonded or the device row cannot be written.
|
|
158
|
+
*/
|
|
159
|
+
export declare function issueSession(userId: string, context: SessionContext, options?: {
|
|
160
|
+
deviceName?: string;
|
|
161
|
+
}): Promise<string>;
|
|
162
|
+
//# sourceMappingURL=accounts.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accounts.d.ts","sourceRoot":"","sources":["../src/accounts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAMH,OAAO,KAAK,EAAE,eAAe,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAA;AAM/E,OAAO,KAAK,KAAK,KAAK,MAAM,YAAY,CAAA;AAOxC,kDAAkD;AAClD,MAAM,MAAM,oBAAoB,GAC5B,kBAAkB,GAClB,gBAAgB,GAChB,eAAe,GACf,aAAa,GACb,mBAAmB,GACnB,oBAAoB,GACpB,mBAAmB,GACnB,qBAAqB,GACrB,qBAAqB,GACrB,oBAAoB,GACpB,SAAS,GACT,aAAa,CAAA;AAEjB;;;GAGG;AACH,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,eAAe,CAAA;IACpB,GAAG,EAAE,gBAAgB,CAAA;CACtB;AAED,oEAAoE;AACpE,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,IAAI,CAAA;IACR,qFAAqF;IACrF,IAAI,EAAE,KAAK,CAAC,KAAK,CAAA;IACjB;;;OAGG;IACH,KAAK,EAAE,MAAM,CAAA;CACd;AAED,0FAA0F;AAC1F,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,KAAK,CAAA;IACT,iCAAiC;IACjC,MAAM,EAAE,oBAAoB,CAAA;IAC5B,kFAAkF;IAClF,KAAK,EAAE,UAAU,GAAG,OAAO,GAAG,UAAU,GAAG,gBAAgB,GAAG,IAAI,CAAA;IAClE,0DAA0D;IAC1D,OAAO,EAAE,MAAM,CAAA;IACf,6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AsB,YAAY,CAChC,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,cAAc,EACvB,OAAO,CAAC,EAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE,GAChC,OAAO,CAAC,MAAM,CAAC,CAajB"}
|
package/dist/accounts.js
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Plain account and session functions for routes an app writes itself.
|
|
3
|
+
*
|
|
4
|
+
* `handlers.*` answer HTTP (`{ statusCode, body }`) in this package's own wire shape. An API with
|
|
5
|
+
* its own contract — its own paths, envelopes, status codes or error bodies — needs the same work
|
|
6
|
+
* as values it can map: {@link createAccount}, {@link signIn}, {@link checkPassword} and
|
|
7
|
+
* {@link issueSession}. They run the SAME code the mounted routes run (validation, the bonded
|
|
8
|
+
* password hasher and its constant-time comparison, two-factor, the device-bound session signed
|
|
9
|
+
* through the bonded JWT provider), so an app never hashes a password, compares one, or signs a
|
|
10
|
+
* token itself.
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
import { get, getLogger } from '@molecule/api-bond';
|
|
15
|
+
import { findById } from '@molecule/api-database';
|
|
16
|
+
import { t } from '@molecule/api-i18n';
|
|
17
|
+
import { compare, hash } from '@molecule/api-password';
|
|
18
|
+
import * as authorization from './authorization.js';
|
|
19
|
+
import { create } from './handlers/create.js';
|
|
20
|
+
import { logIn } from './handlers/logIn.js';
|
|
21
|
+
const logger = getLogger();
|
|
22
|
+
/** The users table the functions use unless told otherwise — the one this package's routes use. */
|
|
23
|
+
const USERS = { name: 'User', tableName: 'users' };
|
|
24
|
+
const FAILURES = {
|
|
25
|
+
'user.error.usernameInvalid': { reason: 'username-invalid', field: 'username' },
|
|
26
|
+
'user.error.usernameUnavailable': { reason: 'username-taken', field: 'username' },
|
|
27
|
+
'user.error.emailInvalid': { reason: 'email-invalid', field: 'email' },
|
|
28
|
+
'user.error.emailAlreadyRegistered': { reason: 'email-taken', field: 'email' },
|
|
29
|
+
'user.error.passwordRequired': { reason: 'password-required', field: 'password' },
|
|
30
|
+
'user.error.passwordTooShort': { reason: 'password-too-short', field: 'password' },
|
|
31
|
+
'user.error.passwordTooLong': { reason: 'password-too-long', field: 'password' },
|
|
32
|
+
'user.error.invalidCredentials': { reason: 'invalid-credentials', field: null },
|
|
33
|
+
'user.error.invalidTwoFactorToken': { reason: 'two-factor-invalid', field: 'twoFactorToken' },
|
|
34
|
+
};
|
|
35
|
+
/** The request the handler reads, with only the fields this call names as its body. */
|
|
36
|
+
function withBody(req, body) {
|
|
37
|
+
// The prototype chain is kept: the session writer reads the real request.
|
|
38
|
+
return Object.create(req, {
|
|
39
|
+
body: { value: body, enumerable: true, writable: true, configurable: true },
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/** A handler's answer as an {@link AccountResult}. */
|
|
43
|
+
function asResult(answer) {
|
|
44
|
+
const body = (answer.body ?? {});
|
|
45
|
+
if (typeof body.accessToken === 'string' && body.props && typeof body.props === 'object')
|
|
46
|
+
return { ok: true, user: body.props, token: body.accessToken };
|
|
47
|
+
if (answer.statusCode === 206 || body.twoFactorRequired === true)
|
|
48
|
+
return {
|
|
49
|
+
ok: false,
|
|
50
|
+
reason: 'two-factor-required',
|
|
51
|
+
field: 'twoFactorToken',
|
|
52
|
+
message: t('user.error.twoFactorRequired', undefined, {
|
|
53
|
+
defaultValue: 'A two-factor code is required.',
|
|
54
|
+
}),
|
|
55
|
+
statusCode: 206,
|
|
56
|
+
errorKey: 'user.twoFactorRequired',
|
|
57
|
+
};
|
|
58
|
+
const errorKey = typeof body.errorKey === 'string' ? body.errorKey : '';
|
|
59
|
+
const known = FAILURES[errorKey];
|
|
60
|
+
return {
|
|
61
|
+
ok: false,
|
|
62
|
+
reason: known?.reason ?? (answer.statusCode >= 500 ? 'unavailable' : 'invalid'),
|
|
63
|
+
field: known?.field ?? null,
|
|
64
|
+
message: typeof body.error === 'string' ? body.error : '',
|
|
65
|
+
statusCode: answer.statusCode,
|
|
66
|
+
errorKey,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Creates an account from a sign-up form and signs it in.
|
|
71
|
+
*
|
|
72
|
+
* Call it from a route of your own when the API's contract is not this package's
|
|
73
|
+
* (`POST /users` with a `{ user: … }` envelope, say), and map the result:
|
|
74
|
+
*
|
|
75
|
+
* ```typescript
|
|
76
|
+
* import { createAccount } from '@molecule/api-resource-user'
|
|
77
|
+
*
|
|
78
|
+
* router.post('/users', async (req, res) => {
|
|
79
|
+
* const { username, email, password } = req.body.user ?? {}
|
|
80
|
+
* const account = await createAccount({ username, email, password }, { req, res })
|
|
81
|
+
* if (!account.ok)
|
|
82
|
+
* return res.status(422).json({ errors: { [account.field ?? 'account']: [account.message] } })
|
|
83
|
+
* res.status(201).json({ user: { ...account.user, token: account.token } })
|
|
84
|
+
* })
|
|
85
|
+
* ```
|
|
86
|
+
*
|
|
87
|
+
* It is `handlers.create` as a function: only `username`, `email` and `name` are taken from the
|
|
88
|
+
* input (nothing a caller adds is stored), the password is length-checked and hashed by the bonded
|
|
89
|
+
* `@molecule/api-password` provider into `usersSecrets`, a device row is created and the token is
|
|
90
|
+
* signed by the bonded `@molecule/api-jwt` provider — so it is a session `verifyMiddleware`
|
|
91
|
+
* accepts. The `Authorization` response header (and the session cookie, where the mount allows
|
|
92
|
+
* one) is set on `res` as the mounted route sets it.
|
|
93
|
+
*
|
|
94
|
+
* @param input - What the person entered.
|
|
95
|
+
* @param context - The current `{ req, res }`; the session header is set on `res`.
|
|
96
|
+
* @param resource - The users resource, when the app renamed the table. Defaults to `users`.
|
|
97
|
+
* @returns The signed-in account, or why none was created.
|
|
98
|
+
*/
|
|
99
|
+
export async function createAccount(input, context, resource = USERS) {
|
|
100
|
+
const { req, res } = context;
|
|
101
|
+
const body = {
|
|
102
|
+
...(input.username === undefined ? {} : { username: input.username }),
|
|
103
|
+
...(input.email === undefined ? {} : { email: input.email }),
|
|
104
|
+
...(input.name === undefined ? {} : { name: input.name }),
|
|
105
|
+
...(input.deviceName === undefined ? {} : { deviceName: input.deviceName }),
|
|
106
|
+
password: input.password,
|
|
107
|
+
};
|
|
108
|
+
return asResult(await create(resource)(withBody(req, body), res));
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Checks a username or email and password, and signs the person in.
|
|
112
|
+
*
|
|
113
|
+
* ```typescript
|
|
114
|
+
* import { signIn } from '@molecule/api-resource-user'
|
|
115
|
+
*
|
|
116
|
+
* router.post('/users/login', async (req, res) => {
|
|
117
|
+
* const { email, password } = req.body.user ?? {}
|
|
118
|
+
* const account = await signIn({ email, password }, { req, res })
|
|
119
|
+
* if (!account.ok) return res.status(401).json({ errors: { credentials: ['invalid'] } })
|
|
120
|
+
* res.json({ user: { ...account.user, token: account.token } })
|
|
121
|
+
* })
|
|
122
|
+
* ```
|
|
123
|
+
*
|
|
124
|
+
* It is `handlers.logIn` as a function, with nothing weakened: an unknown account and a wrong
|
|
125
|
+
* password take the same time and give the same `invalid-credentials`, the comparison is the
|
|
126
|
+
* bonded hasher's, an account with two-factor on answers `two-factor-required` until
|
|
127
|
+
* `twoFactorToken` is sent, and the session is device-bound, so sign-out and a password change
|
|
128
|
+
* revoke it. A password-reset token is not accepted here; use the reset routes for that.
|
|
129
|
+
*
|
|
130
|
+
* @param input - The credentials.
|
|
131
|
+
* @param context - The current `{ req, res }`; the session header is set on `res`.
|
|
132
|
+
* @param resource - The users resource, when the app renamed the table. Defaults to `users`.
|
|
133
|
+
* @returns The signed-in account, or why no one was signed in.
|
|
134
|
+
*/
|
|
135
|
+
export async function signIn(input, context, resource = USERS) {
|
|
136
|
+
const { req, res } = context;
|
|
137
|
+
const body = {
|
|
138
|
+
...(input.username === undefined ? {} : { username: input.username }),
|
|
139
|
+
...(input.email === undefined ? {} : { email: input.email }),
|
|
140
|
+
...(input.twoFactorToken === undefined ? {} : { twoFactorToken: input.twoFactorToken }),
|
|
141
|
+
...(input.deviceName === undefined ? {} : { deviceName: input.deviceName }),
|
|
142
|
+
password: input.password,
|
|
143
|
+
};
|
|
144
|
+
return asResult(await logIn(resource)(withBody(req, body), res));
|
|
145
|
+
}
|
|
146
|
+
let dummyHash;
|
|
147
|
+
/**
|
|
148
|
+
* Whether `password` is the account's current password — for a step that re-asks for it
|
|
149
|
+
* (confirming a deletion, changing an email in a route of your own).
|
|
150
|
+
*
|
|
151
|
+
* The comparison is the bonded `@molecule/api-password` provider's, against the hash in
|
|
152
|
+
* `usersSecrets`. An account with no password (OAuth-only) and an unknown id answer `false` after
|
|
153
|
+
* a comparison against a throwaway hash, so the answer's timing does not say which it was.
|
|
154
|
+
* Never compare hashes or passwords yourself.
|
|
155
|
+
*
|
|
156
|
+
* @param userId - The account's id (`users.id`, which is also its `usersSecrets.id`).
|
|
157
|
+
* @param password - The password the person entered.
|
|
158
|
+
* @param resource - The users resource, when the app renamed the table. Defaults to `users`.
|
|
159
|
+
* @returns True only when the password matches.
|
|
160
|
+
*/
|
|
161
|
+
export async function checkPassword(userId, password, resource = USERS) {
|
|
162
|
+
if (typeof password !== 'string' || password === '')
|
|
163
|
+
return false;
|
|
164
|
+
let stored = null;
|
|
165
|
+
try {
|
|
166
|
+
const secrets = await findById(`${resource.tableName}Secrets`, userId);
|
|
167
|
+
stored = typeof secrets?.passwordHash === 'string' ? secrets.passwordHash : null;
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
logger.error('checkPassword: the credential row could not be read', error);
|
|
171
|
+
}
|
|
172
|
+
if (stored !== null)
|
|
173
|
+
return compare(password, stored);
|
|
174
|
+
try {
|
|
175
|
+
dummyHash ??= hash('molecule-dummy-password');
|
|
176
|
+
await compare(password, await dummyHash);
|
|
177
|
+
}
|
|
178
|
+
catch (_error) {
|
|
179
|
+
// The throwaway comparison only equalises timing; its failure changes no answer.
|
|
180
|
+
dummyHash = undefined;
|
|
181
|
+
}
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Signs in an account you have ALREADY authenticated some other way (a verified invite link, a
|
|
186
|
+
* single sign-on callback) and returns its session token.
|
|
187
|
+
*
|
|
188
|
+
* It creates the device row and has the bonded JWT provider sign a token bound to it — the two
|
|
189
|
+
* steps a session is. A token signed any other way names no device and is answered 401 by
|
|
190
|
+
* `verifyMiddleware` on every request. For a username or email and password use {@link signIn},
|
|
191
|
+
* which checks them first; this function checks nothing.
|
|
192
|
+
*
|
|
193
|
+
* @param userId - The authenticated account's id.
|
|
194
|
+
* @param context - The current `{ req, res }`; the session header is set on `res`.
|
|
195
|
+
* @param options - An optional label for the session's device row.
|
|
196
|
+
* @returns The session token.
|
|
197
|
+
* @throws {Error} When no device service is bonded or the device row cannot be written.
|
|
198
|
+
*/
|
|
199
|
+
export async function issueSession(userId, context, options) {
|
|
200
|
+
const { req, res } = context;
|
|
201
|
+
const deviceId = await get('device')?.createOrUpdate(userId, options?.deviceName || 'Unknown');
|
|
202
|
+
if (!deviceId)
|
|
203
|
+
throw new Error('issueSession: the session device could not be created (is the device service bonded?)');
|
|
204
|
+
const token = authorization.set(req, res, { userId, deviceId });
|
|
205
|
+
if (!token)
|
|
206
|
+
throw new Error('issueSession: the bonded JWT provider signed no token');
|
|
207
|
+
return token;
|
|
208
|
+
}
|
|
209
|
+
//# sourceMappingURL=accounts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"accounts.js","sourceRoot":"","sources":["../src/accounts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAA;AACnD,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAA;AACjD,OAAO,EAAE,CAAC,EAAE,MAAM,oBAAoB,CAAA;AACtC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAA;AAItD,OAAO,KAAK,aAAa,MAAM,oBAAoB,CAAA;AACnD,OAAO,EAAE,MAA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CAAA;IAClF,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,KAAK,CAAC,qDAAqD,EAAE,KAAK,CAAC,CAAA;IAC5E,CAAC;IACD,IAAI,MAAM,KAAK,IAAI;QAAE,OAAO,OAAO,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAA;IACrD,IAAI,CAAC;QACH,SAAS,KAAK,IAAI,CAAC,yBAAyB,CAAC,CAAA;QAC7C,MAAM,OAAO,CAAC,QAAQ,EAAE,MAAM,SAAS,CAAC,CAAA;IAC1C,CAAC;IAAC,OAAO,MAAM,EAAE,CAAC;QAChB,iFAAiF;QACjF,SAAS,GAAG,SAAS,CAAA;IACvB,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,KAAK,UAAU,YAAY,CAChC,MAAc,EACd,OAAuB,EACvB,OAAiC;IAEjC,MAAM,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,OAAO,CAAA;IAC5B,MAAM,QAAQ,GAAG,MAAM,GAAG,CAAgB,QAAQ,CAAC,EAAE,cAAc,CACjE,MAAM,EACN,OAAO,EAAE,UAAU,IAAI,SAAS,CACjC,CAAA;IACD,IAAI,CAAC,QAAQ;QACX,MAAM,IAAI,KAAK,CACb,uFAAuF,CACxF,CAAA;IACH,MAAM,KAAK,GAAG,aAAa,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAA;IAC/D,IAAI,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAA;IACpF,OAAO,KAAK,CAAA;AACd,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -29,16 +29,20 @@
|
|
|
29
29
|
* answers `existing` and repairs nothing. **TRUSTED SERVER CALLERS ONLY:** it takes props
|
|
30
30
|
* directly, so a public endpoint built on it is a mass-assignment hole.
|
|
31
31
|
*
|
|
32
|
-
*
|
|
33
|
-
* `
|
|
34
|
-
*
|
|
35
|
-
*
|
|
32
|
+
* **Your own sign-up and sign-in routes call
|
|
33
|
+
* `createAccount({ username, email, password }, { req, res })` and {@link signIn}:** each
|
|
34
|
+
* resolves to `{ ok, user, token }`, and `token` is the session.
|
|
35
|
+
* Never call `sign()`, `hash()` or `compare()` for accounts yourself.
|
|
36
36
|
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
37
|
+
* HTTP path: `handlers.create`, `handlers.logIn`, `handlers.updatePassword`. One secret:
|
|
38
|
+
* `findById('usersSecrets', userId)`.
|
|
39
|
+
*
|
|
40
|
+
* **Token API (`Authorization: Token <jwt>`)? CONFIGURATION,
|
|
41
|
+
* never a credentials table of your own** (`usersSecrets.passwordHash` is the store): set
|
|
42
|
+
* `AUTH_SCHEME=Token` (or `verifyMiddleware({ scheme: 'Token' })`) — every route accepts it,
|
|
43
|
+
* `logIn`/`create` return `accessToken`, `GET /users/me` echoes it, and a password change
|
|
44
|
+
* revokes every OTHER device but keeps the
|
|
45
|
+
* caller's own session.
|
|
42
46
|
*
|
|
43
47
|
* **Generated full-stack apps:** mlcl derives the app-auth composition root from this API contract; keep that bond and use its shared HTTP client.
|
|
44
48
|
*
|
|
@@ -105,8 +109,8 @@
|
|
|
105
109
|
* import { createResource, handlers } from '@molecule/api-resource-user'
|
|
106
110
|
*
|
|
107
111
|
* // Omit `schema`: create() validates new users with this package's propsSchema.
|
|
108
|
-
* const
|
|
109
|
-
* const
|
|
112
|
+
* const signUpRoute = createRequestHandler(handlers.create({ name: 'User', tableName: 'users' }))
|
|
113
|
+
* const signInRoute = createRequestHandler(handlers.logIn({ name: 'User', tableName: 'users' }))
|
|
110
114
|
*
|
|
111
115
|
* // A constrained schema, when the app restricts oauthServer / planKey.
|
|
112
116
|
* const users = createResource({ oauthServers: ['google', 'github'] as const })
|
|
@@ -324,6 +328,7 @@
|
|
|
324
328
|
*
|
|
325
329
|
* @module
|
|
326
330
|
*/
|
|
331
|
+
export * from './accounts.js';
|
|
327
332
|
export * as authorization from './authorization.js';
|
|
328
333
|
export * as authorizers from './authorizers/index.js';
|
|
329
334
|
export * from './browser-guard.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyUG;AAEH,cAAc,eAAe,CAAA;AAC7B,OAAO,KAAK,aAAa,MAAM,oBAAoB,CAAA;AACnD,OAAO,KAAK,WAAW,MAAM,wBAAwB,CAAA;AACrD,cAAc,oBAAoB,CAAA;AAClC,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAA;AAC/C,cAAc,WAAW,CAAA;AACzB,cAAc,mBAAmB,CAAA;AACjC,cAAc,wBAAwB,CAAA;AACtC,cAAc,eAAe,CAAA;AAC7B,cAAc,aAAa,CAAA;AAC3B,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -29,16 +29,20 @@
|
|
|
29
29
|
* answers `existing` and repairs nothing. **TRUSTED SERVER CALLERS ONLY:** it takes props
|
|
30
30
|
* directly, so a public endpoint built on it is a mass-assignment hole.
|
|
31
31
|
*
|
|
32
|
-
*
|
|
33
|
-
* `
|
|
34
|
-
*
|
|
35
|
-
*
|
|
32
|
+
* **Your own sign-up and sign-in routes call
|
|
33
|
+
* `createAccount({ username, email, password }, { req, res })` and {@link signIn}:** each
|
|
34
|
+
* resolves to `{ ok, user, token }`, and `token` is the session.
|
|
35
|
+
* Never call `sign()`, `hash()` or `compare()` for accounts yourself.
|
|
36
36
|
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
37
|
+
* HTTP path: `handlers.create`, `handlers.logIn`, `handlers.updatePassword`. One secret:
|
|
38
|
+
* `findById('usersSecrets', userId)`.
|
|
39
|
+
*
|
|
40
|
+
* **Token API (`Authorization: Token <jwt>`)? CONFIGURATION,
|
|
41
|
+
* never a credentials table of your own** (`usersSecrets.passwordHash` is the store): set
|
|
42
|
+
* `AUTH_SCHEME=Token` (or `verifyMiddleware({ scheme: 'Token' })`) — every route accepts it,
|
|
43
|
+
* `logIn`/`create` return `accessToken`, `GET /users/me` echoes it, and a password change
|
|
44
|
+
* revokes every OTHER device but keeps the
|
|
45
|
+
* caller's own session.
|
|
42
46
|
*
|
|
43
47
|
* **Generated full-stack apps:** mlcl derives the app-auth composition root from this API contract; keep that bond and use its shared HTTP client.
|
|
44
48
|
*
|
|
@@ -105,8 +109,8 @@
|
|
|
105
109
|
* import { createResource, handlers } from '@molecule/api-resource-user'
|
|
106
110
|
*
|
|
107
111
|
* // Omit `schema`: create() validates new users with this package's propsSchema.
|
|
108
|
-
* const
|
|
109
|
-
* const
|
|
112
|
+
* const signUpRoute = createRequestHandler(handlers.create({ name: 'User', tableName: 'users' }))
|
|
113
|
+
* const signInRoute = createRequestHandler(handlers.logIn({ name: 'User', tableName: 'users' }))
|
|
110
114
|
*
|
|
111
115
|
* // A constrained schema, when the app restricts oauthServer / planKey.
|
|
112
116
|
* const users = createResource({ oauthServers: ['google', 'github'] as const })
|
|
@@ -324,6 +328,7 @@
|
|
|
324
328
|
*
|
|
325
329
|
* @module
|
|
326
330
|
*/
|
|
331
|
+
export * from './accounts.js';
|
|
327
332
|
export * as authorization from './authorization.js';
|
|
328
333
|
export * as authorizers from './authorizers/index.js';
|
|
329
334
|
export * from './browser-guard.js';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyUG;AAEH,cAAc,eAAe,CAAA;AAC7B,OAAO,KAAK,aAAa,MAAM,oBAAoB,CAAA;AACnD,OAAO,KAAK,WAAW,MAAM,wBAAwB,CAAA;AACrD,cAAc,oBAAoB,CAAA;AAClC,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAA;AAC/C,cAAc,WAAW,CAAA;AACzB,cAAc,mBAAmB,CAAA;AACjC,cAAc,wBAAwB,CAAA;AACtC,cAAc,eAAe,CAAA;AAC7B,cAAc,aAAa,CAAA;AAC3B,cAAc,aAAa,CAAA;AAC3B,cAAc,cAAc,CAAA;AAC5B,OAAO,KAAK,KAAK,MAAM,YAAY,CAAA;AACnC,OAAO,KAAK,SAAS,MAAM,sBAAsB,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@molecule/api-resource-user",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.9.0",
|
|
4
4
|
"description": "User resource types and schema for molecule.dev.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
"devDependencies": {
|
|
36
36
|
"@molecule/api-bond": "1.0.4",
|
|
37
37
|
"@molecule/api-config": "1.0.4",
|
|
38
|
-
"@molecule/api-locales-user": "1.1.
|
|
38
|
+
"@molecule/api-locales-user": "1.1.1",
|
|
39
39
|
"@molecule/api-locales-user-payments": "1.0.3",
|
|
40
40
|
"@molecule/api-payments": "1.2.3",
|
|
41
41
|
"@molecule/api-push-notifications": "1.0.3",
|