@molecule/api-resource-user 1.7.5 → 1.8.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 +250 -30
- package/dist/handlers/create.d.ts.map +1 -1
- package/dist/handlers/create.js +5 -5
- package/dist/handlers/create.js.map +1 -1
- package/dist/index.d.ts +42 -29
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +42 -29
- package/dist/index.js.map +1 -1
- package/dist/provisioning.d.ts +245 -0
- package/dist/provisioning.d.ts.map +1 -0
- package/dist/provisioning.js +585 -0
- package/dist/provisioning.js.map +1 -0
- package/dist/schema.d.ts +11 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +11 -0
- package/dist/schema.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Programmatic user provisioning for trusted server code.
|
|
3
|
+
*
|
|
4
|
+
* `provisionUser(resource, input)` writes the `users` row AND its same-id `usersSecrets` row
|
|
5
|
+
* through the bonded database and password providers, so a seed script, a migration, or a
|
|
6
|
+
* service-account bootstrap never hand-writes the two-table credential plumbing:
|
|
7
|
+
*
|
|
8
|
+
* - **One id keys BOTH rows.** `usersSecrets.id` IS the user's id. A credential row written
|
|
9
|
+
* under another id inserts fine and is then never found again — login answers "invalid
|
|
10
|
+
* credentials" while `GET /users/me` still answers 200.
|
|
11
|
+
* - **Props are validated ONCE, before the identity lookup.** The resource schema does the
|
|
12
|
+
* parsing, including any `transform`/`default` a caller's schema adds
|
|
13
|
+
* (`createSchema().extend({ username: z.string().toLowerCase() })`). The account is looked up
|
|
14
|
+
* by the value the schema actually produces, and that same value is what gets stored — so two
|
|
15
|
+
* `EDITOR` provisioning calls find one `editor` account instead of inserting a second row.
|
|
16
|
+
* - **No session.** No device row, no JWT, no `authorization.set`: provisioning an account
|
|
17
|
+
* never signs anyone in, and the caller keeps whatever auth flow it already has.
|
|
18
|
+
* - **No password unless you supply one.** Omit `password` for a content author or service
|
|
19
|
+
* account that must not be able to log in — the credential row is written WITHOUT a
|
|
20
|
+
* `passwordHash` (the OAuth-only shape `logIn` refuses a password for). Nothing is generated,
|
|
21
|
+
* nothing is returned, and there is no default password.
|
|
22
|
+
* - **Idempotent by username or email.** An account that already exists is answered
|
|
23
|
+
* `{ status: 'existing' }` and nothing is written — credentials included: a supplied password
|
|
24
|
+
* is applied only to the row THIS call creates, never to an existing account. (A seed whose
|
|
25
|
+
* email matches a real user's must never hand over that account.)
|
|
26
|
+
* - **Atomic where the database supports it.** The two writes run inside
|
|
27
|
+
* `withTransaction()`, so a bond with interactive transactions (SQLite, PostgreSQL, MySQL)
|
|
28
|
+
* commits both rows or neither. On a bond without them (Cloudflare D1, where
|
|
29
|
+
* `pool.transaction` is absent) the writes are sequential and a failed second write leaves the
|
|
30
|
+
* user row in place; that case is answered by a distinct `{ status: 'partial', id, recovery }`
|
|
31
|
+
* result, and `provisionUser(resource, { props, password, completeId: id })` completes it. A
|
|
32
|
+
* retry WITHOUT `completeId` answers `existing` and does NOT repair anything (password reset
|
|
33
|
+
* cannot either: it updates the `usersSecrets` row, which does not exist).
|
|
34
|
+
*
|
|
35
|
+
* TRUSTED SERVER CALLERS ONLY. This is not a request handler: it takes props directly and
|
|
36
|
+
* validates them against the resource schema, so mounting it on a route would be a
|
|
37
|
+
* mass-assignment hole. Create accounts from a seed or migration on the server — never from a
|
|
38
|
+
* public endpoint.
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```ts
|
|
42
|
+
* import { provisionUser } from '@molecule/api-resource-user'
|
|
43
|
+
*
|
|
44
|
+
* // A content-only author: no password is stored and no login is possible.
|
|
45
|
+
* const author = await provisionUser(
|
|
46
|
+
* { name: 'User', tableName: 'users' },
|
|
47
|
+
* { props: { username: 'editor', name: 'Editorial Team' } },
|
|
48
|
+
* )
|
|
49
|
+
* if (author.status === 'failed') throw new Error(author.error)
|
|
50
|
+
* if (author.status === 'partial') {
|
|
51
|
+
* // The id is the proof of ownership; the props identify the same account.
|
|
52
|
+
* await provisionUser(
|
|
53
|
+
* { name: 'User', tableName: 'users' },
|
|
54
|
+
* { props: { username: 'editor' }, completeId: author.id },
|
|
55
|
+
* )
|
|
56
|
+
* }
|
|
57
|
+
* const authorId = author.id // stable across re-runs: the second call says 'existing'
|
|
58
|
+
*
|
|
59
|
+
* // A service account that may actually sign in (password from the environment, never a literal).
|
|
60
|
+
* await provisionUser(
|
|
61
|
+
* { name: 'User', tableName: 'users' },
|
|
62
|
+
* { props: { username: 'sync-service', email: 'sync@example.com' }, password: process.env.SYNC_PASSWORD },
|
|
63
|
+
* )
|
|
64
|
+
* ```
|
|
65
|
+
*
|
|
66
|
+
* @module
|
|
67
|
+
*/
|
|
68
|
+
import type * as types from './types.js';
|
|
69
|
+
/** The sanitized user props a result carries (secret columns removed). */
|
|
70
|
+
type SafeProps = types.Props & Record<string, unknown>;
|
|
71
|
+
/**
|
|
72
|
+
* Safe user props accepted by {@link provisionUser} — the `users` table's columns without the
|
|
73
|
+
* server-controlled `id` / `createdAt` / `updatedAt` (this call sets those).
|
|
74
|
+
*
|
|
75
|
+
* The index signature lets an app pass the extra columns of its OWN resource schema
|
|
76
|
+
* (`handlerResource.schema`); the schema still decides what is kept.
|
|
77
|
+
*/
|
|
78
|
+
export type ProvisionUserProps = Omit<types.Props, 'createdAt' | 'id' | 'updatedAt'> & Record<string, unknown>;
|
|
79
|
+
/**
|
|
80
|
+
* Input accepted by {@link provisionUser}.
|
|
81
|
+
*/
|
|
82
|
+
export interface ProvisionUserInput {
|
|
83
|
+
/**
|
|
84
|
+
* The account's SAFE props (`username`, `name`, `email`, `bio`, …). Validated by the
|
|
85
|
+
* resource schema; never a secret column. At least one of `username` / `email` is required —
|
|
86
|
+
* that pair is what makes repeated provisioning find the account it created.
|
|
87
|
+
*/
|
|
88
|
+
props: ProvisionUserProps;
|
|
89
|
+
/**
|
|
90
|
+
* Optional plaintext password for an account that must be able to sign in. OMIT it for a
|
|
91
|
+
* content author or service account that must not log in: no hash is written, and `logIn`
|
|
92
|
+
* refuses password authentication for the account. The value is hashed through the bonded
|
|
93
|
+
* password provider and never stored, logged, or returned.
|
|
94
|
+
*/
|
|
95
|
+
password?: string;
|
|
96
|
+
/**
|
|
97
|
+
* Completes a provisioning that returned `{ status: 'partial' }`: the exact `id` from that
|
|
98
|
+
* result, which is the proof that this caller created the account. The supplied `props` must
|
|
99
|
+
* identify that same account, it must not be OAuth-linked, and it must not already carry a
|
|
100
|
+
* stored password (an existing password is never overwritten). A concurrent completion or a
|
|
101
|
+
* password reset that already wrote a hash is reported as `existing`, never replaced. Omit this
|
|
102
|
+
* for a normal call.
|
|
103
|
+
*/
|
|
104
|
+
completeId?: string;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Why {@link provisionUser} could not complete.
|
|
108
|
+
*/
|
|
109
|
+
export type ProvisionUserFailureReason =
|
|
110
|
+
/** Neither `props.username` nor `props.email` was supplied, so no account can be found on a re-run. */
|
|
111
|
+
'identityRequired'
|
|
112
|
+
/** `props.username` breaks the signup rule (letters, digits, dots, hyphens, underscores). */
|
|
113
|
+
| 'invalidUsername'
|
|
114
|
+
/** `password` is outside the signup bounds (8–1024 characters). */
|
|
115
|
+
| 'invalidPassword'
|
|
116
|
+
/** The datastore could not answer "does this account already exist" (or could not read its credentials). */
|
|
117
|
+
| 'lookupFailed'
|
|
118
|
+
/** `username` and `email` resolve to two DIFFERENT existing accounts. */
|
|
119
|
+
| 'conflict'
|
|
120
|
+
/** The props failed the resource schema, so nothing was written. */
|
|
121
|
+
| 'invalidProps'
|
|
122
|
+
/** The `users` insert reported no affected row and no racing account was found. */
|
|
123
|
+
| 'userNotCreated'
|
|
124
|
+
/** The user row was written but its `usersSecrets` row (or the password hash) failed. */
|
|
125
|
+
| 'credentialsFailed'
|
|
126
|
+
/** `completeId` names no account in this resource's table. */
|
|
127
|
+
| 'completeTargetMissing'
|
|
128
|
+
/** The supplied username/email does not identify the account named by `completeId`. */
|
|
129
|
+
| 'completeIdentityMismatch'
|
|
130
|
+
/** The account named by `completeId` has an OAuth identity, so its credentials are not ours to add. */
|
|
131
|
+
| 'completeNotOwned';
|
|
132
|
+
/**
|
|
133
|
+
* The outcome of a {@link provisionUser} call.
|
|
134
|
+
*
|
|
135
|
+
* `created`, `completed` and `existing` carry the account's id (the value of `usersSecrets.id`)
|
|
136
|
+
* and its sanitized `users` row. `partial` says the user row was written and its credential row
|
|
137
|
+
* was not; `failed` says the call did not complete (and carries `id` only when a user row it
|
|
138
|
+
* wrote may still exist).
|
|
139
|
+
*/
|
|
140
|
+
export type ProvisionUserResult = {
|
|
141
|
+
/** The account was created by this call. */
|
|
142
|
+
status: 'created';
|
|
143
|
+
/** The user id — the same value stored as `usersSecrets.id`. */
|
|
144
|
+
id: string;
|
|
145
|
+
/** The sanitized user row (`users` columns; secret columns stripped). */
|
|
146
|
+
props: SafeProps;
|
|
147
|
+
/** Whether a password credential was stored for this new account. */
|
|
148
|
+
hasPassword: boolean;
|
|
149
|
+
} | {
|
|
150
|
+
/** A partial provisioning named by `completeId` was finished by this call. */
|
|
151
|
+
status: 'completed';
|
|
152
|
+
/** The existing account's id. */
|
|
153
|
+
id: string;
|
|
154
|
+
/** The existing account's sanitized user row. */
|
|
155
|
+
props: SafeProps;
|
|
156
|
+
/** Whether a password credential is stored for the account now. */
|
|
157
|
+
hasPassword: boolean;
|
|
158
|
+
} | {
|
|
159
|
+
/** The account already existed for the supplied username/email; nothing was written. */
|
|
160
|
+
status: 'existing';
|
|
161
|
+
/** The existing account's id. */
|
|
162
|
+
id: string;
|
|
163
|
+
/** The existing account's sanitized user row. */
|
|
164
|
+
props: SafeProps;
|
|
165
|
+
/** Whether the EXISTING account has a stored password hash (never the hash itself). */
|
|
166
|
+
hasPassword: boolean;
|
|
167
|
+
} | {
|
|
168
|
+
/** The user row was written; its credential row was not. */
|
|
169
|
+
status: 'partial';
|
|
170
|
+
/** The step that failed. */
|
|
171
|
+
reason: 'credentialsFailed';
|
|
172
|
+
/** A stable, translated key for the failure (switch on `reason`, not on `error`). */
|
|
173
|
+
errorKey: string;
|
|
174
|
+
/** Diagnostic text for the server log — not a client-facing string. */
|
|
175
|
+
error: string;
|
|
176
|
+
/** The id of the account this call created. Pass it back as `completeId` to finish it. */
|
|
177
|
+
id: string;
|
|
178
|
+
/**
|
|
179
|
+
* What completing the row needs: whether the original call supplied a password (so the
|
|
180
|
+
* caller knows to supply it again — the plaintext was never stored).
|
|
181
|
+
*/
|
|
182
|
+
recovery: {
|
|
183
|
+
id: string;
|
|
184
|
+
passwordRequired: boolean;
|
|
185
|
+
};
|
|
186
|
+
} | {
|
|
187
|
+
/** Provisioning did not complete and left no row this call wrote. */
|
|
188
|
+
status: 'failed';
|
|
189
|
+
/** Which step failed. */
|
|
190
|
+
reason: ProvisionUserFailureReason;
|
|
191
|
+
/** A stable, translated key for the failure (switch on `reason`, not on `error`). */
|
|
192
|
+
errorKey: string;
|
|
193
|
+
/** Diagnostic text for the server log — not a client-facing string. */
|
|
194
|
+
error: string;
|
|
195
|
+
/**
|
|
196
|
+
* Present when a user row this call wrote may still exist, or when this call was completing
|
|
197
|
+
* the account named by `completeId` (so the caller can retry the same id).
|
|
198
|
+
*/
|
|
199
|
+
id?: string;
|
|
200
|
+
};
|
|
201
|
+
/**
|
|
202
|
+
* Creates a user record and its same-id credential record for a trusted server caller, without
|
|
203
|
+
* creating a session.
|
|
204
|
+
*
|
|
205
|
+
* The props are validated ONCE by the resource schema — this package's `propsSchema` unless
|
|
206
|
+
* `schema` is supplied — before the existing-account lookup, so any `transform`/`default` in a
|
|
207
|
+
* caller's schema decides the stored and the looked-up username/email. The user row and its
|
|
208
|
+
* `usersSecrets` row are then written under ONE freshly minted id, inside a transaction when the
|
|
209
|
+
* bonded database supports one. With no `password`, the credential row carries no `passwordHash`
|
|
210
|
+
* at all — the account cannot log in, and there is no default, generated, or returned password.
|
|
211
|
+
*
|
|
212
|
+
* Existing accounts are found by `username` or `email` and returned unchanged (`status:
|
|
213
|
+
* 'existing'`), which makes re-running a seed safe; a supplied password is never applied to an
|
|
214
|
+
* existing account. Where the bond has no interactive transactions and the credential write
|
|
215
|
+
* fails, the result is `{ status: 'partial', id, recovery }` — pass that id back as `completeId`
|
|
216
|
+
* (with the same identity props and the same password) to finish it.
|
|
217
|
+
*
|
|
218
|
+
* Use {@link createResource} when the app constrains or extends user props; omit it otherwise.
|
|
219
|
+
* The `tableName` convention is the one every handler in this package uses: the credential table
|
|
220
|
+
* is `${tableName}Secrets`.
|
|
221
|
+
*
|
|
222
|
+
* @param resource - The user resource configuration: `{ name, tableName, schema? }`.
|
|
223
|
+
* @param resource.name - The resource name used in error messages.
|
|
224
|
+
* @param resource.tableName - The database table for users.
|
|
225
|
+
* @param resource.schema - Optional schema validated before the write. Defaults to `propsSchema`.
|
|
226
|
+
* @param input - The account to provision.
|
|
227
|
+
* @param input.props - The SAFE user props to store (never a secret column).
|
|
228
|
+
* @param input.password - Optional plaintext password to hash into the credential row. Omit it
|
|
229
|
+
* for a content-only author, which then has no password and cannot log in.
|
|
230
|
+
* @param input.completeId - The id from an earlier `partial` result; finishes that provisioning.
|
|
231
|
+
* @returns `{ status: 'created' | 'completed' | 'existing', id, props, hasPassword }` on success,
|
|
232
|
+
* `{ status: 'partial', reason, errorKey, error, id, recovery }` when a user row was written but
|
|
233
|
+
* its credentials were not, or `{ status: 'failed', reason, errorKey, error, id? }` otherwise.
|
|
234
|
+
* @example
|
|
235
|
+
* ```ts
|
|
236
|
+
* const author = await provisionUser({ name: 'User', tableName: 'users' }, {
|
|
237
|
+
* props: { username: 'editor', name: 'Editorial Team' },
|
|
238
|
+
* })
|
|
239
|
+
* if (author.status === 'failed') throw new Error(author.error)
|
|
240
|
+
* await create('articles', { id: articleId, authorId: author.id, title, body })
|
|
241
|
+
* ```
|
|
242
|
+
*/
|
|
243
|
+
export declare const provisionUser: ({ name, tableName, schema }: types.HandlerResource, { props, password, completeId }: ProvisionUserInput) => Promise<ProvisionUserResult>;
|
|
244
|
+
export {};
|
|
245
|
+
//# sourceMappingURL=provisioning.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provisioning.d.ts","sourceRoot":"","sources":["../src/provisioning.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkEG;AAqBH,OAAO,KAAK,KAAK,KAAK,MAAM,YAAY,CAAA;AAgBxC,0EAA0E;AAC1E,KAAK,SAAS,GAAG,KAAK,CAAC,KAAK,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAEtD;;;;;;GAMG;AACH,MAAM,MAAM,kBAAkB,GAAG,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI,GAAG,WAAW,CAAC,GAClF,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAEzB;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,KAAK,EAAE,kBAAkB,CAAA;IACzB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB;;;;;;;OAOG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED;;GAEG;AACH,MAAM,MAAM,0BAA0B;AACpC,uGAAuG;AACrG,kBAAkB;AACpB,6FAA6F;GAC3F,iBAAiB;AACnB,mEAAmE;GACjE,iBAAiB;AACnB,4GAA4G;GAC1G,cAAc;AAChB,yEAAyE;GACvE,UAAU;AACZ,oEAAoE;GAClE,cAAc;AAChB,mFAAmF;GACjF,gBAAgB;AAClB,yFAAyF;GACvF,mBAAmB;AACrB,8DAA8D;GAC5D,uBAAuB;AACzB,uFAAuF;GACrF,0BAA0B;AAC5B,uGAAuG;GACrG,kBAAkB,CAAA;AAEtB;;;;;;;GAOG;AACH,MAAM,MAAM,mBAAmB,GAC3B;IACE,4CAA4C;IAC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