@nexartis/sentinel-sdk 1.6.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/LICENSE +201 -0
- package/README.md +215 -0
- package/dist/core/auth-utils.d.ts +31 -0
- package/dist/core/auth-utils.d.ts.map +1 -0
- package/dist/core/auth-utils.js +128 -0
- package/dist/core/auth-utils.js.map +1 -0
- package/dist/core/client.d.ts +22 -0
- package/dist/core/client.d.ts.map +1 -0
- package/dist/core/client.js +137 -0
- package/dist/core/client.js.map +1 -0
- package/dist/core/errors.d.ts +47 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/errors.js +69 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/index.d.ts +8 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +6 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/logger.d.ts +30 -0
- package/dist/core/logger.d.ts.map +1 -0
- package/dist/core/logger.js +54 -0
- package/dist/core/logger.js.map +1 -0
- package/dist/core/types.d.ts +269 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +2 -0
- package/dist/core/types.js.map +1 -0
- package/dist/sveltekit/client/index.d.ts +36 -0
- package/dist/sveltekit/client/index.d.ts.map +1 -0
- package/dist/sveltekit/client/index.js +121 -0
- package/dist/sveltekit/client/index.js.map +1 -0
- package/dist/sveltekit/cookies.d.ts +54 -0
- package/dist/sveltekit/cookies.d.ts.map +1 -0
- package/dist/sveltekit/cookies.js +64 -0
- package/dist/sveltekit/cookies.js.map +1 -0
- package/dist/sveltekit/handle.d.ts +20 -0
- package/dist/sveltekit/handle.d.ts.map +1 -0
- package/dist/sveltekit/handle.js +146 -0
- package/dist/sveltekit/handle.js.map +1 -0
- package/dist/sveltekit/handlers/index.d.ts +29 -0
- package/dist/sveltekit/handlers/index.d.ts.map +1 -0
- package/dist/sveltekit/handlers/index.js +536 -0
- package/dist/sveltekit/handlers/index.js.map +1 -0
- package/dist/sveltekit/index.d.ts +6 -0
- package/dist/sveltekit/index.d.ts.map +1 -0
- package/dist/sveltekit/index.js +5 -0
- package/dist/sveltekit/index.js.map +1 -0
- package/dist/sveltekit/pages/index.d.ts +68 -0
- package/dist/sveltekit/pages/index.d.ts.map +1 -0
- package/dist/sveltekit/pages/index.js +207 -0
- package/dist/sveltekit/pages/index.js.map +1 -0
- package/dist/sveltekit/utils.d.ts +17 -0
- package/dist/sveltekit/utils.d.ts.map +1 -0
- package/dist/sveltekit/utils.js +34 -0
- package/dist/sveltekit/utils.js.map +1 -0
- package/package.json +99 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
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 describing the origin of the Work and
|
|
141
|
+
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 Support. While redistributing the Work or
|
|
166
|
+
Derivative Works thereof, You may choose to offer, and charge a
|
|
167
|
+
fee for, acceptance of support, warranty, indemnity, or other
|
|
168
|
+
liability obligations and/or rights consistent with this License.
|
|
169
|
+
However, in accepting such obligations, You may act only on Your
|
|
170
|
+
own behalf and on Your sole responsibility, not on behalf of any
|
|
171
|
+
other Contributor, and only if You agree to indemnify, defend,
|
|
172
|
+
and hold each Contributor harmless for any liability incurred by,
|
|
173
|
+
or claims asserted against, such Contributor by reason of your
|
|
174
|
+
accepting any such warranty or support.
|
|
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 2026 Nexartis LLC
|
|
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.
|
package/README.md
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# @nexartis/sentinel-sdk
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@nexartis/sentinel-sdk)
|
|
4
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
5
|
+
[](https://nodejs.org)
|
|
6
|
+
|
|
7
|
+
> **Passwordless, magic-link authentication for SvelteKit.** A batteries-included client SDK for the hosted Nexartis **Sentinel** auth backend — five lines in `hooks.server.ts`, three lines in your auth route, and you're done.
|
|
8
|
+
|
|
9
|
+
Sentinel is a passwordless authentication service: users sign in with a one-time magic link delivered to their email, the SDK handles JWT issuance, secure cookie storage, automatic token refresh, and route protection. No passwords. No sessions to reap. No boilerplate.
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Table of contents
|
|
14
|
+
|
|
15
|
+
- [What you get](#what-you-get)
|
|
16
|
+
- [Install](#install)
|
|
17
|
+
- [Configure](#configure)
|
|
18
|
+
- [Quickstart](#quickstart)
|
|
19
|
+
- [Subpath exports](#subpath-exports)
|
|
20
|
+
- [Hosted Sentinel (optional)](#hosted-sentinel-optional)
|
|
21
|
+
- [Framework support](#framework-support)
|
|
22
|
+
- [Versioning](#versioning)
|
|
23
|
+
- [License](#license)
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
## What you get
|
|
28
|
+
|
|
29
|
+
- **Framework-agnostic core** — `SentinelClient`, local JWT decode, expiry checks, structured errors, retry classification.
|
|
30
|
+
- **SvelteKit `handle` hook** — JWT validation, automatic refresh on stale access tokens, route protection, `event.locals.user` hydration.
|
|
31
|
+
- **Drop-in API handlers** — `createAuthHandlers()` mounts login / register / poll / claim / refresh / logout on a single catch-all `+server.ts`.
|
|
32
|
+
- **Page handlers** — `handleMagicLink`, `handleVerifyEmail`, `handleVerified` for the browser-side magic-link flow.
|
|
33
|
+
- **Authenticated fetch** — `authFetch` / `authFetchJson` for long-running client operations with transparent token refresh.
|
|
34
|
+
- **Launch primitives** — `onBeforeLogin` gating, `resolveRedirect` for role-aware post-login destinations, configurable `logoutRedirect`.
|
|
35
|
+
- **Cookie management** — HTTP-only, `Secure`, `SameSite=Lax` cookies with rotation on refresh.
|
|
36
|
+
- **TypeScript-first** — ships `.d.ts` and sourcemaps.
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pnpm add @nexartis/sentinel-sdk
|
|
44
|
+
# or
|
|
45
|
+
npm install @nexartis/sentinel-sdk
|
|
46
|
+
# or
|
|
47
|
+
yarn add @nexartis/sentinel-sdk
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
**Requirements**
|
|
51
|
+
|
|
52
|
+
- Node.js **≥ 20**
|
|
53
|
+
- SvelteKit **≥ 2.0** *(optional peer — only needed for the `/sveltekit*` subpath exports)*
|
|
54
|
+
- A running Sentinel backend (self-hosted, or the free hosted tier — see [below](#hosted-sentinel-optional)).
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## Configure
|
|
59
|
+
|
|
60
|
+
The SDK does not bake in any backend URL. Every request is directed at the URL **you** configure. Two values drive everything:
|
|
61
|
+
|
|
62
|
+
| Name | Purpose |
|
|
63
|
+
|------|---------|
|
|
64
|
+
| `apiUrl` | Base URL of the Sentinel auth backend (e.g. `https://auth.example.com`). |
|
|
65
|
+
| `baseUrl` | Public base URL of your own app (e.g. `https://app.example.com`) — used when constructing magic-link callback URLs. |
|
|
66
|
+
|
|
67
|
+
Expose them via SvelteKit environment (`$env/static/private` for `apiUrl`, `$env/static/public` for the browser-visible base URL) and pass them into `createSentinelHandle` / `createAuthHandlers`.
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
# .env
|
|
71
|
+
SENTINEL_API_URL="https://auth.example.com"
|
|
72
|
+
PUBLIC_BASE_URL="https://app.example.com"
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Quickstart
|
|
78
|
+
|
|
79
|
+
### 1. Protect routes with the SvelteKit hook
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
// src/hooks.server.ts
|
|
83
|
+
import { createSentinelHandle } from '@nexartis/sentinel-sdk/sveltekit';
|
|
84
|
+
import { SENTINEL_API_URL } from '$env/static/private';
|
|
85
|
+
import { PUBLIC_BASE_URL } from '$env/static/public';
|
|
86
|
+
|
|
87
|
+
export const handle = createSentinelHandle({
|
|
88
|
+
config: { apiUrl: SENTINEL_API_URL, baseUrl: PUBLIC_BASE_URL },
|
|
89
|
+
protectedRoutes: ['/dashboard', '/admin'],
|
|
90
|
+
loginRedirect: '/auth'
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
After this hook runs, `event.locals.user` is populated on every request with `{ isAuthenticated, id, email, roles }`.
|
|
95
|
+
|
|
96
|
+
### 2. Mount the auth API
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
// src/routes/api/auth/[...path]/+server.ts
|
|
100
|
+
import { createAuthHandlers } from '@nexartis/sentinel-sdk/sveltekit/handlers';
|
|
101
|
+
|
|
102
|
+
export const { GET, POST } = createAuthHandlers({
|
|
103
|
+
// Optional: gate logins BEFORE the magic link is dispatched.
|
|
104
|
+
onBeforeLogin: async (_event, { email }) => {
|
|
105
|
+
if (await isBlocked(email)) {
|
|
106
|
+
return { error: 'not_allowed', status: 403, redirect: '/waitlist' };
|
|
107
|
+
}
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
// Optional: role-aware post-login destination.
|
|
111
|
+
resolveRedirect: async (_event, { user, requestedRedirect, defaultRedirect }) =>
|
|
112
|
+
user.roles.includes('admin') ? '/admin' : (requestedRedirect || defaultRedirect),
|
|
113
|
+
|
|
114
|
+
// Optional: where to land after logout.
|
|
115
|
+
logoutRedirect: '/'
|
|
116
|
+
});
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### 3. Handle the magic link
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
// src/routes/auth/magic/+page.server.ts
|
|
123
|
+
import { handleMagicLink } from '@nexartis/sentinel-sdk/sveltekit/pages';
|
|
124
|
+
export const load = handleMagicLink();
|
|
125
|
+
|
|
126
|
+
// src/routes/auth/verify/+page.server.ts
|
|
127
|
+
import { handleVerifyEmail } from '@nexartis/sentinel-sdk/sveltekit/pages';
|
|
128
|
+
export const load = handleVerifyEmail();
|
|
129
|
+
|
|
130
|
+
// src/routes/auth/verified/+page.server.ts
|
|
131
|
+
import { handleVerified } from '@nexartis/sentinel-sdk/sveltekit/pages';
|
|
132
|
+
export const load = handleVerified();
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### 4. Call your own APIs with automatic refresh
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
// Any client component
|
|
139
|
+
import { authFetchJson } from '@nexartis/sentinel-sdk/sveltekit/client';
|
|
140
|
+
|
|
141
|
+
const profile = await authFetchJson<UserProfile>('/api/me');
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
`authFetch` / `authFetchJson` transparently refresh the access token if it has expired mid-request, so long-running client operations don't fall over on a stale JWT.
|
|
145
|
+
|
|
146
|
+
---
|
|
147
|
+
|
|
148
|
+
## Subpath exports
|
|
149
|
+
|
|
150
|
+
The package ships one framework-agnostic core and one SvelteKit adapter, split into focused subpaths so you only pay for what you import.
|
|
151
|
+
|
|
152
|
+
| Export | Purpose |
|
|
153
|
+
|--------|---------|
|
|
154
|
+
| `@nexartis/sentinel-sdk/core` | Framework-agnostic client: `SentinelClient`, `decodeTokenLocally`, `validateToken`, `isTokenExpired`, `SentinelError`, `SentinelCode`, `createLogger`, plus every response type. |
|
|
155
|
+
| `@nexartis/sentinel-sdk/sveltekit` | `createSentinelHandle` and cookie utilities (`setSessionCookies`, `getSessionCookies`, `clearAuthCookies`, `COOKIE_NAMES`). |
|
|
156
|
+
| `@nexartis/sentinel-sdk/sveltekit/handlers` | `createAuthHandlers()` — the catch-all API route. |
|
|
157
|
+
| `@nexartis/sentinel-sdk/sveltekit/pages` | `handleMagicLink`, `handleVerifyEmail`, `handleVerified` for browser-side flows. |
|
|
158
|
+
| `@nexartis/sentinel-sdk/sveltekit/client` | `authFetch`, `authFetchJson` for authenticated client-side requests. |
|
|
159
|
+
|
|
160
|
+
### Framework-agnostic core in action
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
import { SentinelClient, decodeTokenLocally, isTokenExpired } from '@nexartis/sentinel-sdk/core';
|
|
164
|
+
|
|
165
|
+
const client = new SentinelClient({
|
|
166
|
+
apiUrl: 'https://auth.example.com',
|
|
167
|
+
baseUrl: 'https://app.example.com',
|
|
168
|
+
timeoutMs: 8000,
|
|
169
|
+
maxRetries: 1
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
const decoded = decodeTokenLocally(accessToken);
|
|
173
|
+
if (isTokenExpired(accessToken)) {
|
|
174
|
+
// ... refresh via client.refresh(refreshToken)
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
---
|
|
179
|
+
|
|
180
|
+
## Hosted Sentinel (optional)
|
|
181
|
+
|
|
182
|
+
**Nexartis operates a hosted Sentinel backend so you don't have to.**
|
|
183
|
+
|
|
184
|
+
- 🆓 **Free tier** for reasonable use — hobby projects, small teams, side projects, indie apps.
|
|
185
|
+
- 🏢 **Enterprise support** available for higher volumes, SLAs, custom domains, dedicated infrastructure, and compliance workloads.
|
|
186
|
+
|
|
187
|
+
Either way, this SDK is fully self-service and works against any Sentinel-compatible backend, including your own.
|
|
188
|
+
|
|
189
|
+
👉 **Learn more and get in touch: <https://cubicube.com>**
|
|
190
|
+
|
|
191
|
+
---
|
|
192
|
+
|
|
193
|
+
## Framework support
|
|
194
|
+
|
|
195
|
+
| Framework | Status |
|
|
196
|
+
|-----------|--------|
|
|
197
|
+
| SvelteKit ≥ 2.0 (Svelte 5) | ✅ First-class |
|
|
198
|
+
| Framework-agnostic core | ✅ Use anywhere — Node, Bun, Cloudflare Workers, browsers |
|
|
199
|
+
| Next.js / Remix / Nuxt / SolidStart | Roadmap — core is designed to make new adapters straightforward |
|
|
200
|
+
|
|
201
|
+
Contributions of new adapters are welcome under the same Apache-2.0 license.
|
|
202
|
+
|
|
203
|
+
---
|
|
204
|
+
|
|
205
|
+
## Versioning
|
|
206
|
+
|
|
207
|
+
This SDK follows [Semantic Versioning](https://semver.org/) and a strict **never-break-minor** policy: minor and patch releases are always safe to auto-update; breaking changes are reserved for majors and preceded by at least one deprecation cycle. See [`VERSIONING.md`](./VERSIONING.md) and [`CHANGELOG.md`](./CHANGELOG.md).
|
|
208
|
+
|
|
209
|
+
---
|
|
210
|
+
|
|
211
|
+
## License
|
|
212
|
+
|
|
213
|
+
Licensed under the [Apache License 2.0](./LICENSE). Copyright © Nexartis LLC.
|
|
214
|
+
|
|
215
|
+
You may use, modify, and redistribute this SDK freely in commercial and non-commercial projects. The Sentinel hosted backend is a separate service governed by its own terms — see <https://cubicube.com>.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { DecodedToken, SentinelConfig } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Validates a JWT access token using Sentinel API
|
|
4
|
+
* @param accessToken - The JWT access token to validate
|
|
5
|
+
* @param fetchFn - Fetch function (for server-side requests)
|
|
6
|
+
* @param config - Sentinel configuration
|
|
7
|
+
* @returns Decoded token data if valid, null if invalid
|
|
8
|
+
*/
|
|
9
|
+
export declare function validateToken(accessToken: string, fetchFn: typeof globalThis.fetch, config: SentinelConfig): Promise<DecodedToken | null>;
|
|
10
|
+
/**
|
|
11
|
+
* Decode JWT payload locally without API validation.
|
|
12
|
+
* Used for per-request user extraction after local expiry check passes.
|
|
13
|
+
*
|
|
14
|
+
* Security model: tokens live in httpOnly/secure cookies and are validated
|
|
15
|
+
* by the Sentinel API at issuance (claim) and refresh. The per-request
|
|
16
|
+
* decode simply extracts the already-validated user info. A structurally
|
|
17
|
+
* invalid or expired token falls through to the refresh path which does
|
|
18
|
+
* a full API-validated exchange.
|
|
19
|
+
*
|
|
20
|
+
* @param token - JWT access token
|
|
21
|
+
* @returns Decoded token payload if structurally valid and has required fields, null otherwise
|
|
22
|
+
*/
|
|
23
|
+
export declare function decodeTokenLocally(token: string): DecodedToken | null;
|
|
24
|
+
/**
|
|
25
|
+
* Check token expiration locally (saves API call)
|
|
26
|
+
* @param token - JWT token to check
|
|
27
|
+
* @param bufferSeconds - Seconds before actual expiry to consider expired (default: 30)
|
|
28
|
+
* @returns true if token is expired or will expire within buffer, false otherwise
|
|
29
|
+
*/
|
|
30
|
+
export declare function isTokenExpired(token: string, bufferSeconds?: number): boolean;
|
|
31
|
+
//# sourceMappingURL=auth-utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-utils.d.ts","sourceRoot":"","sources":["../../src/core/auth-utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAuB,YAAY,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAsBpF;;;;;;GAMG;AACH,wBAAsB,aAAa,CAClC,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,OAAO,UAAU,CAAC,KAAK,EAChC,MAAM,EAAE,cAAc,GACpB,OAAO,CAAC,YAAY,GAAG,IAAI,CAAC,CAwB9B;AAiBD;;;;;;;;;;;;GAYG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAyBrE;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,aAAa,GAAE,MAAW,GAAG,OAAO,CAkBjF"}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { SentinelClient } from './client.js';
|
|
2
|
+
function normalizeRoles(profile) {
|
|
3
|
+
if (Array.isArray(profile.roles)) {
|
|
4
|
+
return profile.roles.filter((role) => typeof role === 'string' && role.length > 0);
|
|
5
|
+
}
|
|
6
|
+
return typeof profile.role === 'string' && profile.role.length > 0 ? [profile.role] : [];
|
|
7
|
+
}
|
|
8
|
+
function hydrateTokenFromCurrentUser(payload, profile) {
|
|
9
|
+
const roles = normalizeRoles(profile);
|
|
10
|
+
return {
|
|
11
|
+
...payload,
|
|
12
|
+
sub: typeof profile.id === 'string' && profile.id.length > 0 ? profile.id : payload.sub,
|
|
13
|
+
email: typeof profile.email === 'string' && profile.email.length > 0 ? profile.email : payload.email,
|
|
14
|
+
roles: roles.length > 0 ? roles : payload.roles
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Validates a JWT access token using Sentinel API
|
|
19
|
+
* @param accessToken - The JWT access token to validate
|
|
20
|
+
* @param fetchFn - Fetch function (for server-side requests)
|
|
21
|
+
* @param config - Sentinel configuration
|
|
22
|
+
* @returns Decoded token data if valid, null if invalid
|
|
23
|
+
*/
|
|
24
|
+
export async function validateToken(accessToken, fetchFn, config) {
|
|
25
|
+
try {
|
|
26
|
+
const sentinel = new SentinelClient(config, fetchFn);
|
|
27
|
+
const result = await sentinel.validateToken(accessToken);
|
|
28
|
+
if (result.code === 0 && result.valid && result.payload) {
|
|
29
|
+
const payload = result.payload;
|
|
30
|
+
if (config.hydrateUserProfile !== true) {
|
|
31
|
+
return payload;
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
const currentUser = await sentinel.getCurrentUser(accessToken);
|
|
35
|
+
return hydrateTokenFromCurrentUser(payload, currentUser);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return payload;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
console.error('Token validation error:', error);
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Decode a base64url-encoded string (JWT standard encoding).
|
|
50
|
+
* Converts base64url → base64, adds padding, then decodes.
|
|
51
|
+
*/
|
|
52
|
+
function base64UrlDecode(str) {
|
|
53
|
+
let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
|
|
54
|
+
const pad = base64.length % 4;
|
|
55
|
+
if (pad)
|
|
56
|
+
base64 += '='.repeat(4 - pad);
|
|
57
|
+
// Decode via Uint8Array + TextDecoder for proper UTF-8 handling.
|
|
58
|
+
// atob() returns a binary string that corrupts multi-byte characters.
|
|
59
|
+
const binary = atob(base64);
|
|
60
|
+
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
61
|
+
return new TextDecoder('utf-8').decode(bytes);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Decode JWT payload locally without API validation.
|
|
65
|
+
* Used for per-request user extraction after local expiry check passes.
|
|
66
|
+
*
|
|
67
|
+
* Security model: tokens live in httpOnly/secure cookies and are validated
|
|
68
|
+
* by the Sentinel API at issuance (claim) and refresh. The per-request
|
|
69
|
+
* decode simply extracts the already-validated user info. A structurally
|
|
70
|
+
* invalid or expired token falls through to the refresh path which does
|
|
71
|
+
* a full API-validated exchange.
|
|
72
|
+
*
|
|
73
|
+
* @param token - JWT access token
|
|
74
|
+
* @returns Decoded token payload if structurally valid and has required fields, null otherwise
|
|
75
|
+
*/
|
|
76
|
+
export function decodeTokenLocally(token) {
|
|
77
|
+
try {
|
|
78
|
+
const parts = token.split('.');
|
|
79
|
+
if (parts.length !== 3)
|
|
80
|
+
return null;
|
|
81
|
+
const payload = JSON.parse(base64UrlDecode(parts[1]));
|
|
82
|
+
// Require sub and email to be strings (not just truthy) per DecodedToken contract
|
|
83
|
+
if (typeof payload.sub !== 'string' || !payload.sub)
|
|
84
|
+
return null;
|
|
85
|
+
if (typeof payload.email !== 'string' || !payload.email)
|
|
86
|
+
return null;
|
|
87
|
+
if (typeof payload.exp !== 'number' || isNaN(payload.exp))
|
|
88
|
+
return null;
|
|
89
|
+
// Validate iat is numeric (required by DecodedToken contract)
|
|
90
|
+
if (typeof payload.iat !== 'number' || isNaN(payload.iat))
|
|
91
|
+
return null;
|
|
92
|
+
return {
|
|
93
|
+
sub: payload.sub,
|
|
94
|
+
email: payload.email,
|
|
95
|
+
roles: Array.isArray(payload.roles) ? payload.roles.filter((r) => typeof r === 'string') : [],
|
|
96
|
+
exp: payload.exp,
|
|
97
|
+
iat: payload.iat
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Check token expiration locally (saves API call)
|
|
106
|
+
* @param token - JWT token to check
|
|
107
|
+
* @param bufferSeconds - Seconds before actual expiry to consider expired (default: 30)
|
|
108
|
+
* @returns true if token is expired or will expire within buffer, false otherwise
|
|
109
|
+
*/
|
|
110
|
+
export function isTokenExpired(token, bufferSeconds = 30) {
|
|
111
|
+
try {
|
|
112
|
+
const parts = token.split('.');
|
|
113
|
+
if (parts.length !== 3) {
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
const payload = JSON.parse(base64UrlDecode(parts[1]));
|
|
117
|
+
if (typeof payload.exp !== 'number' || isNaN(payload.exp)) {
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
const expiresAt = payload.exp * 1000;
|
|
121
|
+
const bufferMs = bufferSeconds * 1000;
|
|
122
|
+
return Date.now() >= expiresAt - bufferMs;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return true; // Treat malformed tokens as expired
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
//# sourceMappingURL=auth-utils.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth-utils.js","sourceRoot":"","sources":["../../src/core/auth-utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,SAAS,cAAc,CAAC,OAA4B;IACnD,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;QAClC,OAAO,OAAO,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAkB,EAAE,CAAC,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACpG,CAAC;IAED,OAAO,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1F,CAAC;AAED,SAAS,2BAA2B,CAAC,OAAqB,EAAE,OAA4B;IACvF,MAAM,KAAK,GAAG,cAAc,CAAC,OAAO,CAAC,CAAC;IAEtC,OAAO;QACN,GAAG,OAAO;QACV,GAAG,EAAE,OAAO,OAAO,CAAC,EAAE,KAAK,QAAQ,IAAI,OAAO,CAAC,EAAE,CAAC,MAAM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,IAAI,CAAC;QACrC,MAAM,QAAQ,GAAG,aAAa,GAAG,IAAI,CAAC;QAEtC,OAAO,IAAI,CAAC,GAAG,EAAE,IAAI,SAAS,GAAG,QAAQ,CAAC;IAC3C,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,IAAI,CAAC,CAAC,oCAAoC;IAClD,CAAC;AACF,CAAC","sourcesContent":["// src/core/auth-utils.ts\nimport type { CurrentUserResponse, DecodedToken, SentinelConfig } from './types.js';\nimport { SentinelClient } from './client.js';\n\nfunction normalizeRoles(profile: CurrentUserResponse): string[] {\n\tif (Array.isArray(profile.roles)) {\n\t\treturn profile.roles.filter((role): role is string => typeof role === 'string' && role.length > 0);\n\t}\n\n\treturn typeof profile.role === 'string' && profile.role.length > 0 ? [profile.role] : [];\n}\n\nfunction hydrateTokenFromCurrentUser(payload: DecodedToken, profile: CurrentUserResponse): DecodedToken {\n\tconst roles = normalizeRoles(profile);\n\n\treturn {\n\t\t...payload,\n\t\tsub: typeof profile.id === 'string' && profile.id.length > 0 ? profile.id : payload.sub,\n\t\temail: typeof profile.email === 'string' && profile.email.length > 0 ? profile.email : payload.email,\n\t\troles: roles.length > 0 ? roles : payload.roles\n\t};\n}\n\n/**\n * Validates a JWT access token using Sentinel API\n * @param accessToken - The JWT access token to validate\n * @param fetchFn - Fetch function (for server-side requests)\n * @param config - Sentinel configuration\n * @returns Decoded token data if valid, null if invalid\n */\nexport async function validateToken(\n\taccessToken: string,\n\tfetchFn: typeof globalThis.fetch,\n\tconfig: SentinelConfig\n): Promise<DecodedToken | null> {\n\ttry {\n\t\tconst sentinel = new SentinelClient(config, fetchFn);\n\t\tconst result = await sentinel.validateToken(accessToken);\n\n\t\tif (result.code === 0 && result.valid && result.payload) {\n\t\t\tconst payload = result.payload as DecodedToken;\n\t\t\tif (config.hydrateUserProfile !== true) {\n\t\t\t\treturn payload;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tconst currentUser = await sentinel.getCurrentUser(accessToken);\n\t\t\t\treturn hydrateTokenFromCurrentUser(payload, currentUser);\n\t\t\t} catch {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t} catch (error) {\n\t\tconsole.error('Token validation error:', error);\n\t\treturn null;\n\t}\n}\n\n/**\n * Decode a base64url-encoded string (JWT standard encoding).\n * Converts base64url → base64, adds padding, then decodes.\n */\nfunction base64UrlDecode(str: string): string {\n\tlet base64 = str.replace(/-/g, '+').replace(/_/g, '/');\n\tconst pad = base64.length % 4;\n\tif (pad) base64 += '='.repeat(4 - pad);\n\t// Decode via Uint8Array + TextDecoder for proper UTF-8 handling.\n\t// atob() returns a binary string that corrupts multi-byte characters.\n\tconst binary = atob(base64);\n\tconst bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));\n\treturn new TextDecoder('utf-8').decode(bytes);\n}\n\n/**\n * Decode JWT payload locally without API validation.\n * Used for per-request user extraction after local expiry check passes.\n *\n * Security model: tokens live in httpOnly/secure cookies and are validated\n * by the Sentinel API at issuance (claim) and refresh. The per-request\n * decode simply extracts the already-validated user info. A structurally\n * invalid or expired token falls through to the refresh path which does\n * a full API-validated exchange.\n *\n * @param token - JWT access token\n * @returns Decoded token payload if structurally valid and has required fields, null otherwise\n */\nexport function decodeTokenLocally(token: string): DecodedToken | null {\n\ttry {\n\t\tconst parts = token.split('.');\n\t\tif (parts.length !== 3) return null;\n\n\t\tconst payload = JSON.parse(base64UrlDecode(parts[1]));\n\n\t\t// Require sub and email to be strings (not just truthy) per DecodedToken contract\n\t\tif (typeof payload.sub !== 'string' || !payload.sub) return null;\n\t\tif (typeof payload.email !== 'string' || !payload.email) return null;\n\t\tif (typeof payload.exp !== 'number' || isNaN(payload.exp)) return null;\n\n\t\t// Validate iat is numeric (required by DecodedToken contract)\n\t\tif (typeof payload.iat !== 'number' || isNaN(payload.iat)) return null;\n\n\t\treturn {\n\t\t\tsub: payload.sub,\n\t\t\temail: payload.email,\n\t\t\troles: Array.isArray(payload.roles) ? payload.roles.filter((r: unknown): r is string => typeof r === 'string') : [],\n\t\t\texp: payload.exp,\n\t\t\tiat: payload.iat\n\t\t};\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/**\n * Check token expiration locally (saves API call)\n * @param token - JWT token to check\n * @param bufferSeconds - Seconds before actual expiry to consider expired (default: 30)\n * @returns true if token is expired or will expire within buffer, false otherwise\n */\nexport function isTokenExpired(token: string, bufferSeconds: number = 30): boolean {\n\ttry {\n\t\tconst parts = token.split('.');\n\t\tif (parts.length !== 3) {\n\t\t\treturn true;\n\t\t}\n\n\t\tconst payload = JSON.parse(base64UrlDecode(parts[1]));\n\t\tif (typeof payload.exp !== 'number' || isNaN(payload.exp)) {\n\t\t\treturn true;\n\t\t}\n\t\tconst expiresAt = payload.exp * 1000;\n\t\tconst bufferMs = bufferSeconds * 1000;\n\n\t\treturn Date.now() >= expiresAt - bufferMs;\n\t} catch {\n\t\treturn true; // Treat malformed tokens as expired\n\t}\n}\n\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { SentinelConfig, StartLoginResponse, PollResponse, ClaimResponse, RefreshResponse, ValidateResponse, CurrentUserResponse, RegisterResponse, VerifyResponse, CompletePasswordlessResponse } from './types.js';
|
|
2
|
+
export declare class SentinelClient {
|
|
3
|
+
private config;
|
|
4
|
+
private fetch;
|
|
5
|
+
private timeoutMs;
|
|
6
|
+
private maxRetries;
|
|
7
|
+
private log;
|
|
8
|
+
constructor(config: SentinelConfig, fetchFn?: typeof globalThis.fetch);
|
|
9
|
+
private request;
|
|
10
|
+
/** Exponential backoff: 1s, 2s, 4s, ... */
|
|
11
|
+
private backoff;
|
|
12
|
+
startLogin(email: string): Promise<StartLoginResponse>;
|
|
13
|
+
pollStatus(transactionId: string): Promise<PollResponse>;
|
|
14
|
+
claimTokens(transactionId: string, clientToken: string): Promise<ClaimResponse>;
|
|
15
|
+
register(email: string): Promise<RegisterResponse>;
|
|
16
|
+
verifyEmail(token: string): Promise<VerifyResponse>;
|
|
17
|
+
completePasswordless(magicToken: string): Promise<CompletePasswordlessResponse>;
|
|
18
|
+
refreshToken(refreshToken: string): Promise<RefreshResponse>;
|
|
19
|
+
validateToken(accessToken: string): Promise<ValidateResponse>;
|
|
20
|
+
getCurrentUser(accessToken: string): Promise<CurrentUserResponse>;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/core/client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,cAAc,EACd,kBAAkB,EAClB,YAAY,EACZ,aAAa,EACb,eAAe,EACf,gBAAgB,EAChB,mBAAmB,EACnB,gBAAgB,EAChB,cAAc,EACd,4BAA4B,EAC5B,MAAM,YAAY,CAAC;AAOpB,qBAAa,cAAc;IAC1B,OAAO,CAAC,MAAM,CAAiB;IAC/B,OAAO,CAAC,KAAK,CAA0B;IACvC,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,GAAG,CAAiB;gBAEhB,MAAM,EAAE,cAAc,EAAE,OAAO,GAAE,OAAO,UAAU,CAAC,KAAa;YAQ9D,OAAO;IA0DrB,2CAA2C;IAC3C,OAAO,CAAC,OAAO;IAKT,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC;IAUtD,UAAU,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAOxD,WAAW,CAAC,aAAa,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,aAAa,CAAC;IAO/E,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC;IAUlD,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC;IAOnD,oBAAoB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,4B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