@tula-tech/core 0.0.0-stage → 0.1.0-alpha.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 +202 -0
- package/README.md +407 -2
- package/dist/index.d.ts +2759 -0
- package/dist/index.js +2290 -0
- package/package.json +38 -4
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,408 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tula-tech/core
|
|
2
2
|
|
|
3
|
-
|
|
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@alpha # or: npm install @tula-tech/core@alpha
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
> **Alpha.** Released under the `alpha` dist-tag: the API may change from one alpha to the
|
|
12
|
+
> next. It talks to a Tula API, which you host yourself
|
|
13
|
+
> ([docs/self-host.md](../../docs/self-host.md)); everything else is in the
|
|
14
|
+
> [repository](https://github.com/Tula-Solutions/tula-auth-and-user-management#readme).
|
|
15
|
+
|
|
16
|
+
## Quickstart
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { createTulaClient, isTulaError } from '@tula-tech/core'
|
|
20
|
+
|
|
21
|
+
const tula = createTulaClient({
|
|
22
|
+
publishableKey: 'tula_pk_dev_…', // safe to embed in an app
|
|
23
|
+
baseUrl: 'https://auth.example.com', // where the Tula API is served
|
|
24
|
+
onSessionChange: (state) => render(state),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
await tula.load() // who is signed in? → 'signed-in' | 'signed-out'
|
|
28
|
+
|
|
29
|
+
const flow = await tula.signIn.start({ identifier: 'maya@northline.app' })
|
|
30
|
+
try {
|
|
31
|
+
const step = await flow.submitPassword({ password })
|
|
32
|
+
if (step.status === 'complete') {
|
|
33
|
+
const token = await tula.session.getToken() // send this to your own backend
|
|
34
|
+
}
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (isTulaError(error)) {
|
|
37
|
+
show(error.code, error.message) // 'auth.invalid_credentials', 'The email or password is incorrect.'
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Creating a client sends nothing. Call `load()` once when the app starts.
|
|
43
|
+
|
|
44
|
+
## Flows
|
|
45
|
+
|
|
46
|
+
The server decides the next step; draw one screen per `step.status`. The flow object keeps the
|
|
47
|
+
attempt's secret to itself (in memory only) and sends it on every call.
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
// Sign-up
|
|
51
|
+
const flow = await tula.signUp.start({ email, password, firstName: 'Maya' })
|
|
52
|
+
flow.step // { status: 'needs_email_verification', destination: 'm***@northline.app', strategies: ['email_code'] }
|
|
53
|
+
await flow.verifyEmail({ code: '123456' }) // → { status: 'complete', userId, sessionId }
|
|
54
|
+
await flow.resendCode()
|
|
55
|
+
|
|
56
|
+
// Sign-in
|
|
57
|
+
const flow = await tula.signIn.start({ identifier: email })
|
|
58
|
+
flow.step // { status: 'needs_password' } (or 'needs_first_factor' with strategies)
|
|
59
|
+
await flow.submitPassword({ password }) // → 'complete', 'needs_email_verification' or 'needs_second_factor'
|
|
60
|
+
await flow.verifyEmail({ code })
|
|
61
|
+
|
|
62
|
+
// Forgotten password: the code and the new password travel together
|
|
63
|
+
const flow = await tula.resetPassword.start({ email })
|
|
64
|
+
await flow.submit({ code, password: newPassword })
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Signing in by email
|
|
68
|
+
|
|
69
|
+
Where the environment enables them, a sign-in start answers `needs_first_factor` with
|
|
70
|
+
`email_code` and/or `email_link` among its `strategies`.
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
const flow = await tula.signIn.start({ identifier: email })
|
|
74
|
+
|
|
75
|
+
// A 6-digit code
|
|
76
|
+
await flow.prepareFirstFactor({ strategy: 'email_code' }) // emails it; step.prepared says where to
|
|
77
|
+
await flow.attemptFirstFactor({ strategy: 'email_code', code }) // → 'complete' (or 'needs_second_factor')
|
|
78
|
+
|
|
79
|
+
// A link (the same email carries the code as well)
|
|
80
|
+
if (tula.signIn.canUseEmailLink()) {
|
|
81
|
+
await flow.prepareFirstFactor({
|
|
82
|
+
strategy: 'email_link',
|
|
83
|
+
redirectUrl: 'https://app.example.com/auth/link', // an allowed redirect URL, exactly, on this page's origin
|
|
84
|
+
})
|
|
85
|
+
const step = await flow.waitForEmailLink({ signal }) // resolves when the link was opened in this browser
|
|
86
|
+
}
|
|
87
|
+
flow.discard() // when the user leaves the screen: ends the attempt (later actions throw
|
|
88
|
+
// flow.invalid_step, a late answer signs nobody in), stops waiting,
|
|
89
|
+
// forgets the link's binding
|
|
90
|
+
|
|
91
|
+
// On the page the link leads to, once:
|
|
92
|
+
const { status } = await tula.signIn.handleEmailLink()
|
|
93
|
+
// 'signed_in' | 'verified' | 'different_browser' | 'expired' | 'none'
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
- **A link works only in the browser that asked for it.** `handleEmailLink()` takes the token
|
|
97
|
+
out of the URL fragment (and out of the address bar), and sends it with a binding this
|
|
98
|
+
browser was given when it asked. In any other browser there is no binding: the answer is
|
|
99
|
+
`different_browser`, nothing is used up, and the user types the code where they started.
|
|
100
|
+
- Opening a link never signs the opening tab in by itself. The tab that started the sign-in
|
|
101
|
+
completes it (`waitForEmailLink`), and the landing tab then shares its session: `signed_in`.
|
|
102
|
+
`verified` means the link was accepted but the starting tab has not finished (it was closed,
|
|
103
|
+
perhaps): the user starts again.
|
|
104
|
+
- `waitForEmailLink()` asks the server every few seconds, at once when the landing tab says the
|
|
105
|
+
link was accepted, and obeys `Retry-After`. It ends when the step moves on, on `signal`,
|
|
106
|
+
`discard()`, sign-out or an error (an expired attempt is `flow.not_found`); nothing keeps
|
|
107
|
+
running afterwards. The other actions keep working while it waits.
|
|
108
|
+
- **The link's page must be on the same origin as the page that asks** (scheme, host and
|
|
109
|
+
port). The binding is kept in that origin's storage; a page elsewhere could not read it, and
|
|
110
|
+
the link would answer `different_browser` in the very browser that asked. In a browser,
|
|
111
|
+
`prepareFirstFactor` refuses such a `redirectUrl` itself with `link.cross_origin` (`status:
|
|
112
|
+
0`, nothing sent); outside a browser there is no page origin and nothing is checked.
|
|
113
|
+
- A dead link (`expired`) leaves this browser's binding alone: the link of an older email, or
|
|
114
|
+
a forged one, cannot undo the email that is current.
|
|
115
|
+
- The answer to `prepareFirstFactor` is the same whether or not the address has an account.
|
|
116
|
+
- `signUp.start({ email })` without a password is accepted where the environment's config says
|
|
117
|
+
`signUp.password === 'optional'`.
|
|
118
|
+
|
|
119
|
+
Every step status, so that a `switch` can be exhaustive: `needs_identifier`, `needs_password`,
|
|
120
|
+
`needs_first_factor`, `needs_email_verification`, `needs_new_password`, `needs_second_factor`,
|
|
121
|
+
`needs_factor_enrolment`, `complete`. The last two before `complete` are covered under
|
|
122
|
+
[Two-step verification](#two-step-verification).
|
|
123
|
+
|
|
124
|
+
When a step is `complete` the client is signed in: `tula.state.status === 'signed-in'`, and
|
|
125
|
+
the flow object is spent (its secret is dropped; further actions are refused locally).
|
|
126
|
+
Disable the submit button while an action is pending: a second one is refused with `flow.busy`.
|
|
127
|
+
A flow cannot be resumed after a page reload; start again (attempts last ten minutes).
|
|
128
|
+
|
|
129
|
+
## Signing in with a provider (OAuth)
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
// On the sign-in page: keeps a binding for this tab and navigates to the provider.
|
|
133
|
+
await tula.signIn.withOAuth({ provider: 'google', redirectUrl: `${location.origin}/oauth/callback` })
|
|
134
|
+
|
|
135
|
+
// On /oauth/callback, on every load:
|
|
136
|
+
const outcome = await tula.signIn.handleOAuthCallback()
|
|
137
|
+
switch (outcome.status) {
|
|
138
|
+
case 'complete': // signed in
|
|
139
|
+
case 'needs_step': // outcome.flow.step is needs_second_factor or needs_factor_enrolment:
|
|
140
|
+
break // outcome.flow.submitSecondFactor({ method: 'totp', code })
|
|
141
|
+
case 'linked': // a link started with tula.user.identities.link(): outcome.identity
|
|
142
|
+
case 'different_browser': // this browser did not start it; nothing was completed
|
|
143
|
+
case 'error': // outcome.code: 'oauth.account_exists', 'oauth.access_denied', …
|
|
144
|
+
case 'none': // no OAuth answer in the address
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
await tula.user.identities.list()
|
|
148
|
+
await tula.user.identities.link({ provider: 'github', redirectUrl }) // needs a recent sign-in
|
|
149
|
+
await tula.user.identities.unlink({ identityId }) // refused for the last way in
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
The provider returns to the API, which redirects to `redirectUrl` with a single-use, 60-second
|
|
153
|
+
ticket in the URL **fragment**. `handleOAuthCallback()` removes it from the address before it
|
|
154
|
+
sends anything and exchanges it together with the binding. The binding is the one thing kept
|
|
155
|
+
in `sessionStorage` (`tula.oauth.<attempt id>`): the page is replaced by the provider's, so
|
|
156
|
+
memory does not survive, and only the same tab may finish. It is not a token and not the
|
|
157
|
+
attempt's secret, it is removed on every outcome, and it expires after fifteen minutes.
|
|
158
|
+
`redirectUrl` must be on the page's own origin (`link.cross_origin` otherwise) and on the
|
|
159
|
+
environment's allow-list. `withOAuth({ navigate: false })` returns the URL instead of
|
|
160
|
+
navigating. No provider token ever reaches the client.
|
|
161
|
+
|
|
162
|
+
## Session
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
await tula.session.getToken() // a valid access token, refreshed first if needed; null when signed out
|
|
166
|
+
await tula.session.refresh() // refresh now
|
|
167
|
+
await tula.session.signOut()
|
|
168
|
+
|
|
169
|
+
const sessions = await tula.session.list() // the user's devices; `current` marks this one
|
|
170
|
+
await tula.session.revoke(sessions[1].id)
|
|
171
|
+
await tula.session.revokeOthers() // → how many ended
|
|
172
|
+
|
|
173
|
+
await tula.user.get() // the signed-in user (also updates tula.state)
|
|
174
|
+
await tula.user.changePassword({ currentPassword, newPassword })
|
|
175
|
+
|
|
176
|
+
const config = await tula.config.get() // app name, sign-in methods, password policy, mfa.policy (cached)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Access tokens last about a minute. Call `getToken()` each time you need one rather than keeping
|
|
180
|
+
it: the call is free while the token is fresh, and any number of concurrent calls share one
|
|
181
|
+
refresh.
|
|
182
|
+
|
|
183
|
+
### State
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
tula.state // { status: 'loading' } | { status: 'signed-out' } | { status: 'signed-in', sessionId, user }
|
|
187
|
+
const stop = tula.onChange((state) => { … }) // also: the onSessionChange option
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
The state object keeps its identity until something changes, and a token refresh is not a
|
|
191
|
+
change, so it can be used directly as an external-store snapshot.
|
|
192
|
+
|
|
193
|
+
## Two-step verification
|
|
194
|
+
|
|
195
|
+
An authenticator app (TOTP) plus ten backup codes. Whether an app offers it is the
|
|
196
|
+
environment's `mfa.policy`: `(await tula.config.get()).mfa?.policy ?? 'off'` is `off` (hide
|
|
197
|
+
it), `optional` or `required`.
|
|
198
|
+
|
|
199
|
+
```ts
|
|
200
|
+
// Turning it on, for the signed-in user
|
|
201
|
+
const { totp, backupCodes } = await tula.mfa.get() // { enabled, confirmedAt }, { remaining }
|
|
202
|
+
const { secret, uri } = await tula.mfa.startTotp() // show `uri` as a QR code, `secret` for typing
|
|
203
|
+
const { codes } = await tula.mfa.confirmTotp({ code: '123456' }) // ten backup codes, once
|
|
204
|
+
|
|
205
|
+
await tula.mfa.regenerateBackupCodes() // → { codes }: the earlier ones stop working
|
|
206
|
+
await tula.mfa.disableTotp()
|
|
207
|
+
|
|
208
|
+
// Signing in (and resetting a password) with it on
|
|
209
|
+
const flow = await tula.signIn.start({ identifier: email })
|
|
210
|
+
await flow.submitPassword({ password }) // → { status: 'needs_second_factor', options: ['totp', 'backup_code'] }
|
|
211
|
+
const { step } = await flow.submitSecondFactor({ method: 'totp', code: '123456' })
|
|
212
|
+
// or a backup code, which is spent:
|
|
213
|
+
const { step, backupCodesRemaining } = await flow.submitSecondFactor({ method: 'backup_code', code })
|
|
214
|
+
|
|
215
|
+
// Where the environment requires it and the user has none, a flow stops to enrol
|
|
216
|
+
if (flow.step.status === 'needs_factor_enrolment') {
|
|
217
|
+
const { secret, uri } = await flow.startTotpEnrolment()
|
|
218
|
+
const { step, backupCodes } = await flow.confirmTotpEnrolment({ code: '123456' }) // signed in
|
|
219
|
+
}
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
- **The secret, its URI and the backup codes are handed to you once and kept nowhere in the
|
|
223
|
+
SDK**: not on the client or a flow object, not in `JSON.stringify` of either, not in storage,
|
|
224
|
+
not in an error. The server cannot show them again either. Put them on screen and let them go.
|
|
225
|
+
- `submitSecondFactor` and `confirmTotpEnrolment` answer `{ step, … }` rather than the step
|
|
226
|
+
alone, because they carry something for the caller: `backupCodesRemaining` after a backup
|
|
227
|
+
code, `backupCodes` after an enrolment. If the device cannot store the session
|
|
228
|
+
(`storage.failed`), `confirmTotpEnrolment` still returns the codes, with the error as
|
|
229
|
+
`failure` instead of throwing it: the user is signed in for as long as the app runs.
|
|
230
|
+
- `confirmTotp` ends the user's other sessions and refreshes this one, so that its next access
|
|
231
|
+
token says the second factor was proven. If that refresh cannot be made the codes are
|
|
232
|
+
returned all the same, and the next `getToken()` asks again.
|
|
233
|
+
- A wrong code is `mfa.invalid_code`; repeated wrong codes are `rate_limited` with
|
|
234
|
+
`retryAfterMs`. An authenticator code is accepted once: after a wrong guess wait for the app
|
|
235
|
+
to show the next one. `mfa.enrolment_expired` means start again (a pending enrolment lasts
|
|
236
|
+
ten minutes). `mfa.not_available`: the policy is `off`. `mfa.required_by_policy`: it cannot
|
|
237
|
+
be turned off.
|
|
238
|
+
- There is no emailed bypass. A user who lost both the authenticator and the backup codes is
|
|
239
|
+
reset by an administrator.
|
|
240
|
+
|
|
241
|
+
## Step-up
|
|
242
|
+
|
|
243
|
+
Sensitive calls need a recent proof of who the user is: `mfa.startTotp`, `mfa.disableTotp`,
|
|
244
|
+
`mfa.regenerateBackupCodes`, and, for a user with two-step verification,
|
|
245
|
+
`user.changePassword`. When the session's last proof is older than ten minutes (or did not
|
|
246
|
+
include the second factor) they answer `auth.step_up_required`. The SDK never prompts and
|
|
247
|
+
never retries by itself; your UI does:
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
import { isStepUpRequired, stepUpMethods } from '@tula-tech/core'
|
|
251
|
+
|
|
252
|
+
try {
|
|
253
|
+
await tula.mfa.regenerateBackupCodes()
|
|
254
|
+
} catch (error) {
|
|
255
|
+
if (!isStepUpRequired(error)) throw error
|
|
256
|
+
const methods = stepUpMethods(error) // ['totp', 'backup_code'], ['password'] or []
|
|
257
|
+
if (methods.length === 0) {
|
|
258
|
+
// Nothing to prove with (an account that signs in by email only): sign in again.
|
|
259
|
+
}
|
|
260
|
+
await tula.session.stepUp({ method: 'totp', code }) // or { method: 'backup_code', code }
|
|
261
|
+
// a user without two-step verification: { method: 'password', password }
|
|
262
|
+
await tula.mfa.regenerateBackupCodes() // repeat the call
|
|
263
|
+
}
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
`session.stepUp` gives the **same session** a new access token. The refresh token (or cookie)
|
|
267
|
+
is untouched, `tula.state` does not change, and other tabs get the token too. A wrong password
|
|
268
|
+
is `auth.invalid_credentials`, a wrong code `mfa.invalid_code`; a method the user may not use
|
|
269
|
+
(a password, for a user with two-step verification) is `auth.step_up_required` again. If the
|
|
270
|
+
session's token was replaced while the proof was on its way (a refresh, here or in another
|
|
271
|
+
tab), the step-up's token is not installed over it; the client refreshes once more instead, so
|
|
272
|
+
the token it ends with was issued after the proof.
|
|
273
|
+
|
|
274
|
+
## Password checklist
|
|
275
|
+
|
|
276
|
+
```ts
|
|
277
|
+
import { evaluatePassword } from '@tula-tech/core'
|
|
278
|
+
|
|
279
|
+
const { password: policy } = await tula.config.get()
|
|
280
|
+
const { ok, checks } = evaluatePassword(policy, typed, { email })
|
|
281
|
+
// checks: [{ rule: 'min_length', code: 'password.too_short', passed: false, params: { min: 10 } }, …]
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
The same function the server runs, so the checklist and the server never disagree. (The
|
|
285
|
+
breached-password check is server-side only.)
|
|
286
|
+
|
|
287
|
+
## Errors
|
|
288
|
+
|
|
289
|
+
Every failed call throws a `TulaError`:
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
error.code // a contract code ('password.too_short', 'rate_limited', …) or a client one
|
|
293
|
+
error.status // HTTP status; 0 when the request got no answer
|
|
294
|
+
error.message // ready to show, from the locale table
|
|
295
|
+
error.params // { min: 10 }
|
|
296
|
+
error.errors // field errors: [{ field: 'password', code: 'password.too_short', message, params }]
|
|
297
|
+
error.retryAfterMs // on a 429 or 503 that says when to try again
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
Client-side codes (all `status: 0`): `network.failed`, `network.timeout`, `response.invalid`
|
|
301
|
+
(the answer could not be read, or a 200 was not what the API sends: check `baseUrl`),
|
|
302
|
+
`storage.failed`, `flow.busy` (a second action on a flow while one is still being sent), and
|
|
303
|
+
`link.cross_origin` (an emailed sign-in link was asked for with a page on another origin).
|
|
304
|
+
One contract code is also raised locally: `flow.invalid_step` with `status: 0` for an action on
|
|
305
|
+
a flow that has already completed. The client never retries on its own, with one exception: a refresh that got no answer is sent
|
|
306
|
+
once more (see the security notes). After a 429 or 503
|
|
307
|
+
with `Retry-After`, `getToken()` fails fast until then (at most five minutes,
|
|
308
|
+
`MAX_REFRESH_BACKOFF_MS`); an explicit `session.refresh()` always asks. For another language, pass messages for any subset of
|
|
309
|
+
codes (the rest stay English); a message may use the error's params as placeholders:
|
|
310
|
+
|
|
311
|
+
```ts
|
|
312
|
+
createTulaClient({
|
|
313
|
+
publishableKey,
|
|
314
|
+
baseUrl,
|
|
315
|
+
messages: {
|
|
316
|
+
'auth.invalid_credentials': 'El correo o la contraseña no son correctos.',
|
|
317
|
+
'password.too_short': 'Usa al menos {min} caracteres.',
|
|
318
|
+
},
|
|
319
|
+
})
|
|
320
|
+
tula.setMessages(otherLocale) // switch later
|
|
321
|
+
```
|
|
322
|
+
|
|
323
|
+
`EN_MESSAGES` is the full English table, the starting point for a translation.
|
|
324
|
+
|
|
325
|
+
## Options
|
|
326
|
+
|
|
327
|
+
| Option | Default | |
|
|
328
|
+
| --- | --- | --- |
|
|
329
|
+
| `publishableKey` | required | `tula_pk_<env>_…`. A secret key is refused. |
|
|
330
|
+
| `baseUrl` | required | The API's absolute URL. |
|
|
331
|
+
| `client` | `web` in a browser, `server` elsewhere | `web`, `ios`, `android` or `server`: decides where the refresh token lives. |
|
|
332
|
+
| `storage` | `memoryStorage()` | Where a non-`web` client keeps its refresh token. Not allowed for `web`. |
|
|
333
|
+
| `fetch` | the global `fetch` | `(request: Request) => Promise<Response>`. |
|
|
334
|
+
| `onSessionChange` | none | Same as a first `onChange` listener. |
|
|
335
|
+
| `messages` | English | Messages by error code. |
|
|
336
|
+
| `timeoutMs` | `15000` | Per request. A refresh uses `min(timeoutMs, 8000)`; see the security notes. |
|
|
337
|
+
|
|
338
|
+
## Security notes
|
|
339
|
+
|
|
340
|
+
**Where tokens live.**
|
|
341
|
+
|
|
342
|
+
- The **access token** is kept in memory only. It is never written to `localStorage`,
|
|
343
|
+
`sessionStorage`, a cookie or the storage adapter.
|
|
344
|
+
- In a browser (`client: 'web'`) the **refresh token** is an `HttpOnly` cookie set by the API.
|
|
345
|
+
JavaScript, this SDK included, cannot read it; requests are sent with
|
|
346
|
+
`credentials: 'include'`. An XSS bug in your app cannot steal it.
|
|
347
|
+
- Elsewhere the refresh token is held in memory and in the `storage` adapter you provide.
|
|
348
|
+
It is a long-lived credential: back the adapter with the platform's secure store (Keychain,
|
|
349
|
+
Keystore), never with `localStorage` or a plain file. The default keeps it in memory, so the
|
|
350
|
+
session ends with the process. A React Native secure-store adapter comes in Phase 2.
|
|
351
|
+
- An attempt's secret stays inside its flow object, in memory. It is not in `JSON.stringify(flow)`,
|
|
352
|
+
not in logs and not in errors.
|
|
353
|
+
- A TOTP secret, its `otpauth://` URI and backup codes pass through the SDK to the caller and
|
|
354
|
+
are kept nowhere: not in memory after the call returns, not in storage, not in an error.
|
|
355
|
+
- **The one thing this SDK puts in `localStorage`** is the binding of an emailed sign-in link
|
|
356
|
+
(`tula.link.<attempt id>`), because a new tab of the same browser has to read it. It is not a
|
|
357
|
+
token and not the attempt's secret: alone it authorizes nothing, with the emailed token it
|
|
358
|
+
only marks the attempt as proven, and the session still goes to the tab holding the secret.
|
|
359
|
+
It is removed when the link is used, when the sign-in completes and on `discard()`, and after
|
|
360
|
+
fifteen minutes otherwise. Where storage is missing or refused, `canUseEmailLink()` is
|
|
361
|
+
`false` and only the code is available.
|
|
362
|
+
- An emailed link's token travels in the URL **fragment**, which a browser never sends to a
|
|
363
|
+
server, and `handleEmailLink()` removes it from the address before it sends anything.
|
|
364
|
+
|
|
365
|
+
**The app and the API must be same-site (browsers).** The refresh cookie is `SameSite=Lax` and
|
|
366
|
+
belongs to the API's origin, so the browser only sends it when the page and the API are on the
|
|
367
|
+
same site: `app.example.com` with `auth.example.com`, or two ports on `localhost`. An app on a
|
|
368
|
+
different site (`myapp.com` with `auth.tula.example`) needs a first-party proxy in front of the
|
|
369
|
+
API; `@tula-tech/nextjs` will provide one. The page's origin must also be in the environment's
|
|
370
|
+
allowed origins (`urls.allowedOrigins`), or flows answer `request.origin_not_allowed`.
|
|
371
|
+
|
|
372
|
+
**Tabs.** Tabs of one app share the cookie. They take turns refreshing (Web Locks) and tell
|
|
373
|
+
each other the result, and a sign-out in one tab signs the others out at once
|
|
374
|
+
(`BroadcastChannel`). Where a browser lacks either, the server's short reuse grace period makes
|
|
375
|
+
the leftover race harmless.
|
|
376
|
+
|
|
377
|
+
**A lost refresh and the grace period.** Refresh tokens are single-use. If the server rotates
|
|
378
|
+
one but its answer never arrives, the client still holds the old token, and presenting it again
|
|
379
|
+
is forgiven only inside the server's reuse grace period (10 seconds by default); after that it
|
|
380
|
+
is treated as theft and the whole session is revoked, on every device. So a refresh gives up
|
|
381
|
+
after 8 seconds (`REFRESH_TIMEOUT_MS`), not the general 15, and if it got no answer at all (a
|
|
382
|
+
timeout or a network failure, never an HTTP answer) the client sends it **once more, at once**,
|
|
383
|
+
with what is left of the 10-second window (`REFRESH_RETRY_WINDOW_MS`). This is the only request
|
|
384
|
+
the client ever repeats by itself. If the retry also fails, `getToken()` rejects with the
|
|
385
|
+
network error and the session is kept; asking again later than the grace period may then sign
|
|
386
|
+
the user out. An operator who shortens `refresh.reuseGracePeriod` below 8 seconds removes that
|
|
387
|
+
margin.
|
|
388
|
+
|
|
389
|
+
**A signed-out client stays signed out.** After `signOut()` (here or in another tab), a late
|
|
390
|
+
401, a refresh that was in flight, or another tab's message about the session that ended
|
|
391
|
+
cannot sign the client back in. Only a new sign-in, or this client's own `load()`/`refresh()`,
|
|
392
|
+
can.
|
|
393
|
+
|
|
394
|
+
**When a session ends.** If a refresh is refused (expired, revoked, signed out elsewhere, or a
|
|
395
|
+
reused refresh token), the state becomes `signed-out`, listeners are told once, and nothing is
|
|
396
|
+
retried.
|
|
397
|
+
|
|
398
|
+
## Development
|
|
399
|
+
|
|
400
|
+
```bash
|
|
401
|
+
bun run --filter @tula-tech/core test # unit tests (fake fetch, locks, channel, clock)
|
|
402
|
+
bun run --filter @tula-tech/core typecheck # also typecheck:portable: web-platform types only
|
|
403
|
+
bun run --filter @tula-tech/core generate # regenerate src/generated/api.gen.ts from the OpenAPI snapshot
|
|
404
|
+
bun test apps/api/src/sdk-journeys.test.ts # the SDK against the real API, in process
|
|
405
|
+
bun run playground # manual test bench in a browser (examples/core-playground)
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
Design and reasoning: [ADR 0021](../../docs/adr/0021-core-sdk.md).
|