@tula-tech/core 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -1,3 +1,407 @@
1
- # Temporary Holding Version
1
+ # @tula-tech/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The headless TypeScript client for [Tula Auth](../../README.md): server-driven sign-up, sign-in
4
+ and password reset, the session, and token refresh. No UI and no framework. It runs in browsers,
5
+ Node, Bun and edge runtimes, and is what `@tula-tech/react` and `@tula-tech/nextjs` are built on.
6
+
7
+ ```sh
8
+ bun add @tula-tech/core@latest # or: npm install @tula-tech/core@latest
9
+ ```
10
+
11
+ > **Early release (0.x).** The API may change from one release to the next. It talks to a Tula API, which you host yourself
12
+ > ([docs/self-host.md](../../docs/self-host.md)); everything else is in the
13
+ > [repository](https://github.com/Tula-Solutions/tula-auth-and-user-management#readme).
14
+
15
+ ## Quickstart
16
+
17
+ ```ts
18
+ import { createTulaClient, isTulaError } from '@tula-tech/core'
19
+
20
+ const tula = createTulaClient({
21
+ publishableKey: 'tula_pk_dev_…', // safe to embed in an app
22
+ baseUrl: 'https://auth.example.com', // where the Tula API is served
23
+ onSessionChange: (state) => render(state),
24
+ })
25
+
26
+ await tula.load() // who is signed in? → 'signed-in' | 'signed-out'
27
+
28
+ const flow = await tula.signIn.start({ identifier: 'maya@northline.app' })
29
+ try {
30
+ const step = await flow.submitPassword({ password })
31
+ if (step.status === 'complete') {
32
+ const token = await tula.session.getToken() // send this to your own backend
33
+ }
34
+ } catch (error) {
35
+ if (isTulaError(error)) {
36
+ show(error.code, error.message) // 'auth.invalid_credentials', 'The email or password is incorrect.'
37
+ }
38
+ }
39
+ ```
40
+
41
+ Creating a client sends nothing. Call `load()` once when the app starts.
42
+
43
+ ## Flows
44
+
45
+ The server decides the next step; draw one screen per `step.status`. The flow object keeps the
46
+ attempt's secret to itself (in memory only) and sends it on every call.
47
+
48
+ ```ts
49
+ // Sign-up
50
+ const flow = await tula.signUp.start({ email, password, firstName: 'Maya' })
51
+ flow.step // { status: 'needs_email_verification', destination: 'm***@northline.app', strategies: ['email_code'] }
52
+ await flow.verifyEmail({ code: '123456' }) // → { status: 'complete', userId, sessionId }
53
+ await flow.resendCode()
54
+
55
+ // Sign-in
56
+ const flow = await tula.signIn.start({ identifier: email })
57
+ flow.step // { status: 'needs_password' } (or 'needs_first_factor' with strategies)
58
+ await flow.submitPassword({ password }) // → 'complete', 'needs_email_verification' or 'needs_second_factor'
59
+ await flow.verifyEmail({ code })
60
+
61
+ // Forgotten password: the code and the new password travel together
62
+ const flow = await tula.resetPassword.start({ email })
63
+ await flow.submit({ code, password: newPassword })
64
+ ```
65
+
66
+ ### Signing in by email
67
+
68
+ Where the environment enables them, a sign-in start answers `needs_first_factor` with
69
+ `email_code` and/or `email_link` among its `strategies`.
70
+
71
+ ```ts
72
+ const flow = await tula.signIn.start({ identifier: email })
73
+
74
+ // A 6-digit code
75
+ await flow.prepareFirstFactor({ strategy: 'email_code' }) // emails it; step.prepared says where to
76
+ await flow.attemptFirstFactor({ strategy: 'email_code', code }) // → 'complete' (or 'needs_second_factor')
77
+
78
+ // A link (the same email carries the code as well)
79
+ if (tula.signIn.canUseEmailLink()) {
80
+ await flow.prepareFirstFactor({
81
+ strategy: 'email_link',
82
+ redirectUrl: 'https://app.example.com/auth/link', // an allowed redirect URL, exactly, on this page's origin
83
+ })
84
+ const step = await flow.waitForEmailLink({ signal }) // resolves when the link was opened in this browser
85
+ }
86
+ flow.discard() // when the user leaves the screen: ends the attempt (later actions throw
87
+ // flow.invalid_step, a late answer signs nobody in), stops waiting,
88
+ // forgets the link's binding
89
+
90
+ // On the page the link leads to, once:
91
+ const { status } = await tula.signIn.handleEmailLink()
92
+ // 'signed_in' | 'verified' | 'different_browser' | 'expired' | 'none'
93
+ ```
94
+
95
+ - **A link works only in the browser that asked for it.** `handleEmailLink()` takes the token
96
+ out of the URL fragment (and out of the address bar), and sends it with a binding this
97
+ browser was given when it asked. In any other browser there is no binding: the answer is
98
+ `different_browser`, nothing is used up, and the user types the code where they started.
99
+ - Opening a link never signs the opening tab in by itself. The tab that started the sign-in
100
+ completes it (`waitForEmailLink`), and the landing tab then shares its session: `signed_in`.
101
+ `verified` means the link was accepted but the starting tab has not finished (it was closed,
102
+ perhaps): the user starts again.
103
+ - `waitForEmailLink()` asks the server every few seconds, at once when the landing tab says the
104
+ link was accepted, and obeys `Retry-After`. It ends when the step moves on, on `signal`,
105
+ `discard()`, sign-out or an error (an expired attempt is `flow.not_found`); nothing keeps
106
+ running afterwards. The other actions keep working while it waits.
107
+ - **The link's page must be on the same origin as the page that asks** (scheme, host and
108
+ port). The binding is kept in that origin's storage; a page elsewhere could not read it, and
109
+ the link would answer `different_browser` in the very browser that asked. In a browser,
110
+ `prepareFirstFactor` refuses such a `redirectUrl` itself with `link.cross_origin` (`status:
111
+ 0`, nothing sent); outside a browser there is no page origin and nothing is checked.
112
+ - A dead link (`expired`) leaves this browser's binding alone: the link of an older email, or
113
+ a forged one, cannot undo the email that is current.
114
+ - The answer to `prepareFirstFactor` is the same whether or not the address has an account.
115
+ - `signUp.start({ email })` without a password is accepted where the environment's config says
116
+ `signUp.password === 'optional'`.
117
+
118
+ Every step status, so that a `switch` can be exhaustive: `needs_identifier`, `needs_password`,
119
+ `needs_first_factor`, `needs_email_verification`, `needs_new_password`, `needs_second_factor`,
120
+ `needs_factor_enrolment`, `complete`. The last two before `complete` are covered under
121
+ [Two-step verification](#two-step-verification).
122
+
123
+ When a step is `complete` the client is signed in: `tula.state.status === 'signed-in'`, and
124
+ the flow object is spent (its secret is dropped; further actions are refused locally).
125
+ Disable the submit button while an action is pending: a second one is refused with `flow.busy`.
126
+ A flow cannot be resumed after a page reload; start again (attempts last ten minutes).
127
+
128
+ ## Signing in with a provider (OAuth)
129
+
130
+ ```ts
131
+ // On the sign-in page: keeps a binding for this tab and navigates to the provider.
132
+ await tula.signIn.withOAuth({ provider: 'google', redirectUrl: `${location.origin}/oauth/callback` })
133
+
134
+ // On /oauth/callback, on every load:
135
+ const outcome = await tula.signIn.handleOAuthCallback()
136
+ switch (outcome.status) {
137
+ case 'complete': // signed in
138
+ case 'needs_step': // outcome.flow.step is needs_second_factor or needs_factor_enrolment:
139
+ break // outcome.flow.submitSecondFactor({ method: 'totp', code })
140
+ case 'linked': // a link started with tula.user.identities.link(): outcome.identity
141
+ case 'different_browser': // this browser did not start it; nothing was completed
142
+ case 'error': // outcome.code: 'oauth.account_exists', 'oauth.access_denied', …
143
+ case 'none': // no OAuth answer in the address
144
+ }
145
+
146
+ await tula.user.identities.list()
147
+ await tula.user.identities.link({ provider: 'github', redirectUrl }) // needs a recent sign-in
148
+ await tula.user.identities.unlink({ identityId }) // refused for the last way in
149
+ ```
150
+
151
+ The provider returns to the API, which redirects to `redirectUrl` with a single-use, 60-second
152
+ ticket in the URL **fragment**. `handleOAuthCallback()` removes it from the address before it
153
+ sends anything and exchanges it together with the binding. The binding is the one thing kept
154
+ in `sessionStorage` (`tula.oauth.<attempt id>`): the page is replaced by the provider's, so
155
+ memory does not survive, and only the same tab may finish. It is not a token and not the
156
+ attempt's secret, it is removed on every outcome, and it expires after fifteen minutes.
157
+ `redirectUrl` must be on the page's own origin (`link.cross_origin` otherwise) and on the
158
+ environment's allow-list. `withOAuth({ navigate: false })` returns the URL instead of
159
+ navigating. No provider token ever reaches the client.
160
+
161
+ ## Session
162
+
163
+ ```ts
164
+ await tula.session.getToken() // a valid access token, refreshed first if needed; null when signed out
165
+ await tula.session.refresh() // refresh now
166
+ await tula.session.signOut()
167
+
168
+ const sessions = await tula.session.list() // the user's devices; `current` marks this one
169
+ await tula.session.revoke(sessions[1].id)
170
+ await tula.session.revokeOthers() // → how many ended
171
+
172
+ await tula.user.get() // the signed-in user (also updates tula.state)
173
+ await tula.user.changePassword({ currentPassword, newPassword })
174
+
175
+ const config = await tula.config.get() // app name, sign-in methods, password policy, mfa.policy (cached)
176
+ ```
177
+
178
+ Access tokens last about a minute. Call `getToken()` each time you need one rather than keeping
179
+ it: the call is free while the token is fresh, and any number of concurrent calls share one
180
+ refresh.
181
+
182
+ ### State
183
+
184
+ ```ts
185
+ tula.state // { status: 'loading' } | { status: 'signed-out' } | { status: 'signed-in', sessionId, user }
186
+ const stop = tula.onChange((state) => { … }) // also: the onSessionChange option
187
+ ```
188
+
189
+ The state object keeps its identity until something changes, and a token refresh is not a
190
+ change, so it can be used directly as an external-store snapshot.
191
+
192
+ ## Two-step verification
193
+
194
+ An authenticator app (TOTP) plus ten backup codes. Whether an app offers it is the
195
+ environment's `mfa.policy`: `(await tula.config.get()).mfa?.policy ?? 'off'` is `off` (hide
196
+ it), `optional` or `required`.
197
+
198
+ ```ts
199
+ // Turning it on, for the signed-in user
200
+ const { totp, backupCodes } = await tula.mfa.get() // { enabled, confirmedAt }, { remaining }
201
+ const { secret, uri } = await tula.mfa.startTotp() // show `uri` as a QR code, `secret` for typing
202
+ const { codes } = await tula.mfa.confirmTotp({ code: '123456' }) // ten backup codes, once
203
+
204
+ await tula.mfa.regenerateBackupCodes() // → { codes }: the earlier ones stop working
205
+ await tula.mfa.disableTotp()
206
+
207
+ // Signing in (and resetting a password) with it on
208
+ const flow = await tula.signIn.start({ identifier: email })
209
+ await flow.submitPassword({ password }) // → { status: 'needs_second_factor', options: ['totp', 'backup_code'] }
210
+ const { step } = await flow.submitSecondFactor({ method: 'totp', code: '123456' })
211
+ // or a backup code, which is spent:
212
+ const { step, backupCodesRemaining } = await flow.submitSecondFactor({ method: 'backup_code', code })
213
+
214
+ // Where the environment requires it and the user has none, a flow stops to enrol
215
+ if (flow.step.status === 'needs_factor_enrolment') {
216
+ const { secret, uri } = await flow.startTotpEnrolment()
217
+ const { step, backupCodes } = await flow.confirmTotpEnrolment({ code: '123456' }) // signed in
218
+ }
219
+ ```
220
+
221
+ - **The secret, its URI and the backup codes are handed to you once and kept nowhere in the
222
+ SDK**: not on the client or a flow object, not in `JSON.stringify` of either, not in storage,
223
+ not in an error. The server cannot show them again either. Put them on screen and let them go.
224
+ - `submitSecondFactor` and `confirmTotpEnrolment` answer `{ step, … }` rather than the step
225
+ alone, because they carry something for the caller: `backupCodesRemaining` after a backup
226
+ code, `backupCodes` after an enrolment. If the device cannot store the session
227
+ (`storage.failed`), `confirmTotpEnrolment` still returns the codes, with the error as
228
+ `failure` instead of throwing it: the user is signed in for as long as the app runs.
229
+ - `confirmTotp` ends the user's other sessions and refreshes this one, so that its next access
230
+ token says the second factor was proven. If that refresh cannot be made the codes are
231
+ returned all the same, and the next `getToken()` asks again.
232
+ - A wrong code is `mfa.invalid_code`; repeated wrong codes are `rate_limited` with
233
+ `retryAfterMs`. An authenticator code is accepted once: after a wrong guess wait for the app
234
+ to show the next one. `mfa.enrolment_expired` means start again (a pending enrolment lasts
235
+ ten minutes). `mfa.not_available`: the policy is `off`. `mfa.required_by_policy`: it cannot
236
+ be turned off.
237
+ - There is no emailed bypass. A user who lost both the authenticator and the backup codes is
238
+ reset by an administrator.
239
+
240
+ ## Step-up
241
+
242
+ Sensitive calls need a recent proof of who the user is: `mfa.startTotp`, `mfa.disableTotp`,
243
+ `mfa.regenerateBackupCodes`, and, for a user with two-step verification,
244
+ `user.changePassword`. When the session's last proof is older than ten minutes (or did not
245
+ include the second factor) they answer `auth.step_up_required`. The SDK never prompts and
246
+ never retries by itself; your UI does:
247
+
248
+ ```ts
249
+ import { isStepUpRequired, stepUpMethods } from '@tula-tech/core'
250
+
251
+ try {
252
+ await tula.mfa.regenerateBackupCodes()
253
+ } catch (error) {
254
+ if (!isStepUpRequired(error)) throw error
255
+ const methods = stepUpMethods(error) // ['totp', 'backup_code'], ['password'] or []
256
+ if (methods.length === 0) {
257
+ // Nothing to prove with (an account that signs in by email only): sign in again.
258
+ }
259
+ await tula.session.stepUp({ method: 'totp', code }) // or { method: 'backup_code', code }
260
+ // a user without two-step verification: { method: 'password', password }
261
+ await tula.mfa.regenerateBackupCodes() // repeat the call
262
+ }
263
+ ```
264
+
265
+ `session.stepUp` gives the **same session** a new access token. The refresh token (or cookie)
266
+ is untouched, `tula.state` does not change, and other tabs get the token too. A wrong password
267
+ is `auth.invalid_credentials`, a wrong code `mfa.invalid_code`; a method the user may not use
268
+ (a password, for a user with two-step verification) is `auth.step_up_required` again. If the
269
+ session's token was replaced while the proof was on its way (a refresh, here or in another
270
+ tab), the step-up's token is not installed over it; the client refreshes once more instead, so
271
+ the token it ends with was issued after the proof.
272
+
273
+ ## Password checklist
274
+
275
+ ```ts
276
+ import { evaluatePassword } from '@tula-tech/core'
277
+
278
+ const { password: policy } = await tula.config.get()
279
+ const { ok, checks } = evaluatePassword(policy, typed, { email })
280
+ // checks: [{ rule: 'min_length', code: 'password.too_short', passed: false, params: { min: 10 } }, …]
281
+ ```
282
+
283
+ The same function the server runs, so the checklist and the server never disagree. (The
284
+ breached-password check is server-side only.)
285
+
286
+ ## Errors
287
+
288
+ Every failed call throws a `TulaError`:
289
+
290
+ ```ts
291
+ error.code // a contract code ('password.too_short', 'rate_limited', …) or a client one
292
+ error.status // HTTP status; 0 when the request got no answer
293
+ error.message // ready to show, from the locale table
294
+ error.params // { min: 10 }
295
+ error.errors // field errors: [{ field: 'password', code: 'password.too_short', message, params }]
296
+ error.retryAfterMs // on a 429 or 503 that says when to try again
297
+ ```
298
+
299
+ Client-side codes (all `status: 0`): `network.failed`, `network.timeout`, `response.invalid`
300
+ (the answer could not be read, or a 200 was not what the API sends: check `baseUrl`),
301
+ `storage.failed`, `flow.busy` (a second action on a flow while one is still being sent), and
302
+ `link.cross_origin` (an emailed sign-in link was asked for with a page on another origin).
303
+ One contract code is also raised locally: `flow.invalid_step` with `status: 0` for an action on
304
+ a flow that has already completed. The client never retries on its own, with one exception: a refresh that got no answer is sent
305
+ once more (see the security notes). After a 429 or 503
306
+ with `Retry-After`, `getToken()` fails fast until then (at most five minutes,
307
+ `MAX_REFRESH_BACKOFF_MS`); an explicit `session.refresh()` always asks. For another language, pass messages for any subset of
308
+ codes (the rest stay English); a message may use the error's params as placeholders:
309
+
310
+ ```ts
311
+ createTulaClient({
312
+ publishableKey,
313
+ baseUrl,
314
+ messages: {
315
+ 'auth.invalid_credentials': 'El correo o la contraseña no son correctos.',
316
+ 'password.too_short': 'Usa al menos {min} caracteres.',
317
+ },
318
+ })
319
+ tula.setMessages(otherLocale) // switch later
320
+ ```
321
+
322
+ `EN_MESSAGES` is the full English table, the starting point for a translation.
323
+
324
+ ## Options
325
+
326
+ | Option | Default | |
327
+ | --- | --- | --- |
328
+ | `publishableKey` | required | `tula_pk_<env>_…`. A secret key is refused. |
329
+ | `baseUrl` | required | The API's absolute URL. |
330
+ | `client` | `web` in a browser, `server` elsewhere | `web`, `ios`, `android` or `server`: decides where the refresh token lives. |
331
+ | `storage` | `memoryStorage()` | Where a non-`web` client keeps its refresh token. Not allowed for `web`. |
332
+ | `fetch` | the global `fetch` | `(request: Request) => Promise<Response>`. |
333
+ | `onSessionChange` | none | Same as a first `onChange` listener. |
334
+ | `messages` | English | Messages by error code. |
335
+ | `timeoutMs` | `15000` | Per request. A refresh uses `min(timeoutMs, 8000)`; see the security notes. |
336
+
337
+ ## Security notes
338
+
339
+ **Where tokens live.**
340
+
341
+ - The **access token** is kept in memory only. It is never written to `localStorage`,
342
+ `sessionStorage`, a cookie or the storage adapter.
343
+ - In a browser (`client: 'web'`) the **refresh token** is an `HttpOnly` cookie set by the API.
344
+ JavaScript, this SDK included, cannot read it; requests are sent with
345
+ `credentials: 'include'`. An XSS bug in your app cannot steal it.
346
+ - Elsewhere the refresh token is held in memory and in the `storage` adapter you provide.
347
+ It is a long-lived credential: back the adapter with the platform's secure store (Keychain,
348
+ Keystore), never with `localStorage` or a plain file. The default keeps it in memory, so the
349
+ session ends with the process. A React Native secure-store adapter comes in Phase 2.
350
+ - An attempt's secret stays inside its flow object, in memory. It is not in `JSON.stringify(flow)`,
351
+ not in logs and not in errors.
352
+ - A TOTP secret, its `otpauth://` URI and backup codes pass through the SDK to the caller and
353
+ are kept nowhere: not in memory after the call returns, not in storage, not in an error.
354
+ - **The one thing this SDK puts in `localStorage`** is the binding of an emailed sign-in link
355
+ (`tula.link.<attempt id>`), because a new tab of the same browser has to read it. It is not a
356
+ token and not the attempt's secret: alone it authorizes nothing, with the emailed token it
357
+ only marks the attempt as proven, and the session still goes to the tab holding the secret.
358
+ It is removed when the link is used, when the sign-in completes and on `discard()`, and after
359
+ fifteen minutes otherwise. Where storage is missing or refused, `canUseEmailLink()` is
360
+ `false` and only the code is available.
361
+ - An emailed link's token travels in the URL **fragment**, which a browser never sends to a
362
+ server, and `handleEmailLink()` removes it from the address before it sends anything.
363
+
364
+ **The app and the API must be same-site (browsers).** The refresh cookie is `SameSite=Lax` and
365
+ belongs to the API's origin, so the browser only sends it when the page and the API are on the
366
+ same site: `app.example.com` with `auth.example.com`, or two ports on `localhost`. An app on a
367
+ different site (`myapp.com` with `auth.tula.example`) needs a first-party proxy in front of the
368
+ API; `@tula-tech/nextjs` will provide one. The page's origin must also be in the environment's
369
+ allowed origins (`urls.allowedOrigins`), or flows answer `request.origin_not_allowed`.
370
+
371
+ **Tabs.** Tabs of one app share the cookie. They take turns refreshing (Web Locks) and tell
372
+ each other the result, and a sign-out in one tab signs the others out at once
373
+ (`BroadcastChannel`). Where a browser lacks either, the server's short reuse grace period makes
374
+ the leftover race harmless.
375
+
376
+ **A lost refresh and the grace period.** Refresh tokens are single-use. If the server rotates
377
+ one but its answer never arrives, the client still holds the old token, and presenting it again
378
+ is forgiven only inside the server's reuse grace period (10 seconds by default); after that it
379
+ is treated as theft and the whole session is revoked, on every device. So a refresh gives up
380
+ after 8 seconds (`REFRESH_TIMEOUT_MS`), not the general 15, and if it got no answer at all (a
381
+ timeout or a network failure, never an HTTP answer) the client sends it **once more, at once**,
382
+ with what is left of the 10-second window (`REFRESH_RETRY_WINDOW_MS`). This is the only request
383
+ the client ever repeats by itself. If the retry also fails, `getToken()` rejects with the
384
+ network error and the session is kept; asking again later than the grace period may then sign
385
+ the user out. An operator who shortens `refresh.reuseGracePeriod` below 8 seconds removes that
386
+ margin.
387
+
388
+ **A signed-out client stays signed out.** After `signOut()` (here or in another tab), a late
389
+ 401, a refresh that was in flight, or another tab's message about the session that ended
390
+ cannot sign the client back in. Only a new sign-in, or this client's own `load()`/`refresh()`,
391
+ can.
392
+
393
+ **When a session ends.** If a refresh is refused (expired, revoked, signed out elsewhere, or a
394
+ reused refresh token), the state becomes `signed-out`, listeners are told once, and nothing is
395
+ retried.
396
+
397
+ ## Development
398
+
399
+ ```bash
400
+ bun run --filter @tula-tech/core test # unit tests (fake fetch, locks, channel, clock)
401
+ bun run --filter @tula-tech/core typecheck # also typecheck:portable: web-platform types only
402
+ bun run --filter @tula-tech/core generate # regenerate src/generated/api.gen.ts from the OpenAPI snapshot
403
+ bun test apps/api/src/sdk-journeys.test.ts # the SDK against the real API, in process
404
+ bun run playground # manual test bench in a browser (examples/core-playground)
405
+ ```
406
+
407
+ Design and reasoning: [ADR 0021](../../docs/adr/0021-core-sdk.md).