@veroxm/sdk 0.1.0 → 0.2.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/CHANGELOG.md +14 -0
- package/README.md +59 -3
- package/dist/auth.d.ts +122 -2
- package/dist/auth.js +190 -1
- package/dist/client.d.ts +3 -1
- package/dist/client.js +3 -3
- package/dist/errors.d.ts +5 -0
- package/dist/errors.js +2 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +1 -0
- package/dist/pkce.d.ts +8 -0
- package/dist/pkce.js +38 -0
- package/dist/token-storage.d.ts +10 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
- End-user accounts on `app.auth`: `signUp`, `verifyEmail`, `resendVerification`, `signInWithEmail`,
|
|
6
|
+
`requestPasswordReset`, `resetPassword`, `acceptInvite`, `currentUser`, `onAuthStateChange`,
|
|
7
|
+
`getAccount`, `updateAccount`, `changePassword`, `deleteAccount`.
|
|
8
|
+
- Social sign-in with PKCE: `socialProviders`, `signInWithRedirect` and `completeSignInWithRedirect`
|
|
9
|
+
in a browser, `startSocialSignIn` and `exchangeSocialCode` for apps.
|
|
10
|
+
- `signOut()` also revokes the refresh token on the server.
|
|
11
|
+
- `VeroXMApiError.code`: the API's reason, such as `email_not_verified`.
|
|
12
|
+
|
|
13
|
+
## 0.1.1
|
|
14
|
+
|
|
15
|
+
- First release published from CI with npm trusted publishing. No code changes.
|
|
16
|
+
|
|
3
17
|
## 0.1.0
|
|
4
18
|
|
|
5
19
|
- First public release on npm.
|
package/README.md
CHANGED
|
@@ -106,7 +106,8 @@ between there.
|
|
|
106
106
|
for server-to-server use where there's no per-user identity; never
|
|
107
107
|
expires, nothing to refresh.
|
|
108
108
|
- **`signInWithCredentials(username, password)`** -- the login flow from a
|
|
109
|
-
project's Authentication tab
|
|
109
|
+
project's Authentication tab (for built-in accounts, `signInWithEmail`
|
|
110
|
+
and the rest of [End-user accounts](#end-user-accounts)). Returns a 1-hour access token plus a
|
|
110
111
|
30-day refresh token; `VeroXMAuth` refreshes automatically, a little
|
|
111
112
|
before actual expiry, and again on demand if a request still comes back
|
|
112
113
|
`401` (clock skew, or a token revoked server-side). You never need to
|
|
@@ -133,6 +134,59 @@ app.auth.onTokenChange((accessToken) => {
|
|
|
133
134
|
});
|
|
134
135
|
```
|
|
135
136
|
|
|
137
|
+
## End-user accounts
|
|
138
|
+
|
|
139
|
+
When the project has built-in accounts turned on (Developer > Authentication
|
|
140
|
+
> Accounts), your app can sign people up and in without a server of its own.
|
|
141
|
+
Every way of signing in ends in the same session, refreshed automatically.
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
// Sign up. When the project wants emails confirmed, the person gets a 6-digit code.
|
|
145
|
+
const result = await app.auth.signUp({ email, password, name });
|
|
146
|
+
if ('verificationSent' in result) {
|
|
147
|
+
await app.auth.verifyEmail({ email, code }); // or { token } from the email's link
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
await app.auth.signInWithEmail(email, password);
|
|
151
|
+
app.auth.currentUser(); // { id, email, name, roles, emailVerified }
|
|
152
|
+
|
|
153
|
+
// Forgotten password
|
|
154
|
+
await app.auth.requestPasswordReset(email);
|
|
155
|
+
await app.auth.resetPassword({ email, code, password: newPassword });
|
|
156
|
+
|
|
157
|
+
// An admin's invitation
|
|
158
|
+
await app.auth.acceptInvite({ email, code, password, name });
|
|
159
|
+
|
|
160
|
+
// The signed-in person's own account
|
|
161
|
+
await app.auth.getAccount(); // also abilities, hasPassword, signInMethods
|
|
162
|
+
await app.auth.updateAccount({ name: 'Amira K' });
|
|
163
|
+
await app.auth.changePassword({ currentPassword, newPassword });
|
|
164
|
+
await app.auth.deleteAccount({ password });
|
|
165
|
+
|
|
166
|
+
app.auth.onAuthStateChange((user) => render(user));
|
|
167
|
+
await app.auth.signOut();
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### Google, Microsoft, Apple
|
|
171
|
+
|
|
172
|
+
In a browser, one call leaves for the provider, and one call on your
|
|
173
|
+
redirect page finishes. `redirectUri` must be one of the project's redirect
|
|
174
|
+
addresses. The PKCE verifier waits in `sessionStorage` meanwhile.
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
const providers = await app.auth.socialProviders(); // [{ key: 'google', name: 'Google', ... }]
|
|
178
|
+
await app.auth.signInWithRedirect('google', { redirectUri: 'https://app.example.com/auth/done' });
|
|
179
|
+
|
|
180
|
+
// on https://app.example.com/auth/done
|
|
181
|
+
const user = await app.auth.completeSignInWithRedirect();
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
In a mobile app, open the URL from `startSocialSignIn` in the system browser,
|
|
185
|
+
keep its `codeVerifier` and `state`, and when your app is opened with the
|
|
186
|
+
redirect address, check the `state` and call
|
|
187
|
+
`exchangeSocialCode(code, codeVerifier)`. React Native needs a Web Crypto
|
|
188
|
+
polyfill (such as `react-native-quick-crypto`) for the PKCE challenge.
|
|
189
|
+
|
|
136
190
|
## Visitor tracking (Experience OS)
|
|
137
191
|
|
|
138
192
|
Record page views and actions, the visitor's consent, and who they are, so
|
|
@@ -229,8 +283,10 @@ throws: an error returns an empty list with `error` set.
|
|
|
229
283
|
|
|
230
284
|
## Errors
|
|
231
285
|
|
|
232
|
-
Every non-2xx response throws `VeroXMApiError` (`.status`, `.body`,
|
|
233
|
-
`.message` extracted from whichever error shape the API used
|
|
286
|
+
Every non-2xx response throws `VeroXMApiError` (`.status`, `.body`, a
|
|
287
|
+
`.message` extracted from whichever error shape the API used, and `.code`
|
|
288
|
+
when the API gave a reason, such as `email_not_verified`, `invalid_code`,
|
|
289
|
+
`sign_up_closed` or `too_many_attempts`). A request
|
|
234
290
|
made before any sign-in call throws `VeroXMNotAuthenticatedError`.
|
|
235
291
|
|
|
236
292
|
```ts
|
package/dist/auth.d.ts
CHANGED
|
@@ -1,4 +1,36 @@
|
|
|
1
|
-
import type { TokenStorage } from './token-storage.js';
|
|
1
|
+
import type { AuthUser, TokenStorage } from './token-storage.js';
|
|
2
|
+
/** A code from an email, with the address; or the token from the email's link. */
|
|
3
|
+
export type EmailCode = {
|
|
4
|
+
email: string;
|
|
5
|
+
code: string;
|
|
6
|
+
} | {
|
|
7
|
+
token: string;
|
|
8
|
+
};
|
|
9
|
+
/** The signed-in person's account, from `getAccount()`. */
|
|
10
|
+
export interface Account extends AuthUser {
|
|
11
|
+
abilities: string[];
|
|
12
|
+
hasPassword: boolean;
|
|
13
|
+
/** How they sign in: `password`, a social provider's key such as `google`, or `identity_provider`. */
|
|
14
|
+
signInMethods: string[];
|
|
15
|
+
}
|
|
16
|
+
/** A social sign-in option to show a button for. */
|
|
17
|
+
export interface SocialProvider {
|
|
18
|
+
key: string;
|
|
19
|
+
kind: 'google' | 'microsoft' | 'apple' | 'oidc';
|
|
20
|
+
name: string;
|
|
21
|
+
}
|
|
22
|
+
/** What `startSocialSignIn` returns: send the person to `url`, keep the rest until they come back. */
|
|
23
|
+
export interface SocialSignInStart {
|
|
24
|
+
url: string;
|
|
25
|
+
codeVerifier: string;
|
|
26
|
+
state: string;
|
|
27
|
+
}
|
|
28
|
+
/** Where a sign-in in progress keeps its verifier across the redirect (sessionStorage in a browser). */
|
|
29
|
+
export interface PendingStore {
|
|
30
|
+
get(key: string): string | null;
|
|
31
|
+
set(key: string, value: string): void;
|
|
32
|
+
remove(key: string): void;
|
|
33
|
+
}
|
|
2
34
|
/**
|
|
3
35
|
* Handles both auth modes this SDK supports:
|
|
4
36
|
* - `signInWithApiKey` -- a static project API key (Sanctum-style,
|
|
@@ -9,21 +41,108 @@ import type { TokenStorage } from './token-storage.js';
|
|
|
9
41
|
* token plus a refresh token; this class refreshes silently and
|
|
10
42
|
* transparently as needed, the same "just works" feel as Firebase
|
|
11
43
|
* Auth's token refresh.
|
|
44
|
+
*
|
|
45
|
+
* And the project's built-in accounts on top of the second: sign-up, email
|
|
46
|
+
* codes, password reset, invitations, the signed-in person's own account,
|
|
47
|
+
* and social sign-in (Google, Microsoft, Apple...) with PKCE. Every way of
|
|
48
|
+
* signing in ends in the same session, refreshed the same way.
|
|
12
49
|
*/
|
|
13
50
|
export declare class VeroXMAuth {
|
|
14
51
|
private readonly apiBase;
|
|
15
52
|
private readonly storage;
|
|
53
|
+
private readonly pending;
|
|
16
54
|
private apiKey;
|
|
17
55
|
private session;
|
|
18
56
|
private loadedFromStorage;
|
|
19
57
|
private refreshInFlight;
|
|
20
58
|
private readonly listeners;
|
|
21
|
-
|
|
59
|
+
private readonly userListeners;
|
|
60
|
+
constructor(apiBase: string, storage: TokenStorage, pending?: PendingStore);
|
|
22
61
|
/** Static-key mode: no login round-trip, no expiry, no refresh token. */
|
|
23
62
|
signInWithApiKey(apiKey: string): void;
|
|
24
63
|
/** Username/password mode -- exchanges credentials for an access+refresh token pair and persists it via the configured TokenStorage. */
|
|
25
64
|
signInWithCredentials(username: string, password: string): Promise<void>;
|
|
65
|
+
/** Signs in a built-in account with its email and password. Throws VeroXMApiError with code `email_not_verified` until the email is confirmed. */
|
|
66
|
+
signInWithEmail(email: string, password: string): Promise<AuthUser | null>;
|
|
67
|
+
/** Signs out here: the refresh token is revoked on the server too (best effort), and the stored session cleared. */
|
|
26
68
|
signOut(): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Creates an account. When the project wants emails confirmed, resolves `{ verificationSent: true }` and the person
|
|
71
|
+
* gets a 6-digit code (finish with `verifyEmail`); otherwise they're signed in and it resolves `{ user }`.
|
|
72
|
+
*/
|
|
73
|
+
signUp(input: {
|
|
74
|
+
email: string;
|
|
75
|
+
password: string;
|
|
76
|
+
name?: string;
|
|
77
|
+
}): Promise<{
|
|
78
|
+
verificationSent: true;
|
|
79
|
+
} | {
|
|
80
|
+
user: AuthUser | null;
|
|
81
|
+
}>;
|
|
82
|
+
/** Confirms the email with its code (or the link's token) and signs the person in. */
|
|
83
|
+
verifyEmail(input: EmailCode): Promise<AuthUser | null>;
|
|
84
|
+
/** Sends a new confirmation code. Resolves the same whether or not the address has an account. */
|
|
85
|
+
resendVerification(email: string): Promise<void>;
|
|
86
|
+
/** Emails a password reset code. Resolves the same whether or not the address has an account. */
|
|
87
|
+
requestPasswordReset(email: string): Promise<void>;
|
|
88
|
+
/** Sets a new password with the reset code (or the link's token), signs out every other device, and signs in here. */
|
|
89
|
+
resetPassword(input: EmailCode & {
|
|
90
|
+
password: string;
|
|
91
|
+
}): Promise<AuthUser | null>;
|
|
92
|
+
/** Accepts an invitation: chooses a password (and a name) with the invitation's code or link token, and signs in. */
|
|
93
|
+
acceptInvite(input: EmailCode & {
|
|
94
|
+
password: string;
|
|
95
|
+
name?: string;
|
|
96
|
+
}): Promise<AuthUser | null>;
|
|
97
|
+
/** Who is signed in, as of the last sign-in or refresh; null when signed out or using an API key. */
|
|
98
|
+
currentUser(): AuthUser | null;
|
|
99
|
+
/** Called with the person whenever they sign in, change, or sign out (and once now). Returns an unsubscribe function. */
|
|
100
|
+
onAuthStateChange(listener: (user: AuthUser | null) => void): () => void;
|
|
101
|
+
/** Loads a stored session (from a previous visit), so currentUser() knows who's signed in. */
|
|
102
|
+
ready(): Promise<void>;
|
|
103
|
+
/** The signed-in person's account, fresh from the API. */
|
|
104
|
+
getAccount(): Promise<Account>;
|
|
105
|
+
/** Changes the signed-in person's name. */
|
|
106
|
+
updateAccount(input: {
|
|
107
|
+
name: string | null;
|
|
108
|
+
}): Promise<Account>;
|
|
109
|
+
/** Changes the password (the current one is needed when there is one). Other devices are signed out; this one stays in. */
|
|
110
|
+
changePassword(input: {
|
|
111
|
+
currentPassword?: string;
|
|
112
|
+
newPassword: string;
|
|
113
|
+
}): Promise<void>;
|
|
114
|
+
/** Deletes the signed-in person's account (their password is needed when they have one), then signs out here. */
|
|
115
|
+
deleteAccount(input?: {
|
|
116
|
+
password?: string;
|
|
117
|
+
}): Promise<void>;
|
|
118
|
+
/** The social sign-in options the project has turned on, for your buttons. */
|
|
119
|
+
socialProviders(): Promise<SocialProvider[]>;
|
|
120
|
+
/**
|
|
121
|
+
* Starts a social sign-in and returns where to send the person. `redirectUri` must be one of the project's redirect
|
|
122
|
+
* addresses (Developer > Authentication > Accounts). Keep `codeVerifier` and `state` until they come back; in a
|
|
123
|
+
* browser, `signInWithRedirect` does all of this for you.
|
|
124
|
+
*/
|
|
125
|
+
startSocialSignIn(provider: string, options: {
|
|
126
|
+
redirectUri: string;
|
|
127
|
+
state?: string;
|
|
128
|
+
}): Promise<SocialSignInStart>;
|
|
129
|
+
/** Trades the code the person came back with, and the verifier from `startSocialSignIn`, for a session. */
|
|
130
|
+
exchangeSocialCode(code: string, codeVerifier: string): Promise<AuthUser | null>;
|
|
131
|
+
/** Browser: starts a social sign-in and leaves the page for the provider. Finish on the redirect page with `completeSignInWithRedirect()`. */
|
|
132
|
+
signInWithRedirect(provider: string, options: {
|
|
133
|
+
redirectUri: string;
|
|
134
|
+
}): Promise<void>;
|
|
135
|
+
/**
|
|
136
|
+
* On the redirect page (or with the address an app was opened with): checks the `state`, trades the code, and signs the
|
|
137
|
+
* person in. Resolves null when the address has no sign-in result; throws when the provider or VeroXM refused it
|
|
138
|
+
* (the error's `code` is the `error` the page came back with, e.g. `access_denied` or `sign_up_closed`).
|
|
139
|
+
*/
|
|
140
|
+
completeSignInWithRedirect(url?: string): Promise<AuthUser | null>;
|
|
141
|
+
private signInWith;
|
|
142
|
+
private post;
|
|
143
|
+
/** A call as the signed-in person (not with an API key). */
|
|
144
|
+
private authed;
|
|
145
|
+
private updateStoredUser;
|
|
27
146
|
/** Returns the abilities (read/create/update/delete, or ['*']) the current credential carries, or null if signed out or in static-key mode (a key's abilities aren't known client-side -- only the API enforces them). */
|
|
28
147
|
currentAbilities(): string[] | null;
|
|
29
148
|
/** Notified with the current access token whenever it changes (sign-in, refresh, sign-out) -- e.g. to mirror it into your own app state. Returns an unsubscribe function. */
|
|
@@ -37,4 +156,5 @@ export declare class VeroXMAuth {
|
|
|
37
156
|
private refresh;
|
|
38
157
|
private persistSession;
|
|
39
158
|
private notify;
|
|
159
|
+
private notifyUser;
|
|
40
160
|
}
|
package/dist/auth.js
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
import { rawRequest } from './http.js';
|
|
2
2
|
import { VeroXMNotAuthenticatedError } from './errors.js';
|
|
3
|
+
import { createPkce, randomString } from './pkce.js';
|
|
4
|
+
function defaultPendingStore() {
|
|
5
|
+
try {
|
|
6
|
+
if (typeof window !== 'undefined' && window.sessionStorage) {
|
|
7
|
+
const ss = window.sessionStorage;
|
|
8
|
+
return { get: (k) => ss.getItem(k), set: (k, v) => ss.setItem(k, v), remove: (k) => ss.removeItem(k) };
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
// storage blocked: fall through to memory
|
|
13
|
+
}
|
|
14
|
+
const m = new Map();
|
|
15
|
+
return { get: (k) => m.get(k) ?? null, set: (k, v) => void m.set(k, v), remove: (k) => void m.delete(k) };
|
|
16
|
+
}
|
|
17
|
+
const PENDING_KEY = 'veroxm:social-sign-in';
|
|
3
18
|
// Refresh a little before the token actually expires, not exactly at the
|
|
4
19
|
// deadline -- covers clock skew and the time an in-flight request spends
|
|
5
20
|
// on the wire between "token looked valid" and "server received it".
|
|
@@ -14,16 +29,23 @@ const REFRESH_SKEW_MS = 30000;
|
|
|
14
29
|
* token plus a refresh token; this class refreshes silently and
|
|
15
30
|
* transparently as needed, the same "just works" feel as Firebase
|
|
16
31
|
* Auth's token refresh.
|
|
32
|
+
*
|
|
33
|
+
* And the project's built-in accounts on top of the second: sign-up, email
|
|
34
|
+
* codes, password reset, invitations, the signed-in person's own account,
|
|
35
|
+
* and social sign-in (Google, Microsoft, Apple...) with PKCE. Every way of
|
|
36
|
+
* signing in ends in the same session, refreshed the same way.
|
|
17
37
|
*/
|
|
18
38
|
export class VeroXMAuth {
|
|
19
|
-
constructor(apiBase, storage) {
|
|
39
|
+
constructor(apiBase, storage, pending = defaultPendingStore()) {
|
|
20
40
|
this.apiBase = apiBase;
|
|
21
41
|
this.storage = storage;
|
|
42
|
+
this.pending = pending;
|
|
22
43
|
this.apiKey = null;
|
|
23
44
|
this.session = null;
|
|
24
45
|
this.loadedFromStorage = false;
|
|
25
46
|
this.refreshInFlight = null;
|
|
26
47
|
this.listeners = new Set();
|
|
48
|
+
this.userListeners = new Set();
|
|
27
49
|
}
|
|
28
50
|
/** Static-key mode: no login round-trip, no expiry, no refresh token. */
|
|
29
51
|
signInWithApiKey(apiKey) {
|
|
@@ -42,12 +64,172 @@ export class VeroXMAuth {
|
|
|
42
64
|
this.apiKey = null;
|
|
43
65
|
await this.persistSession(data);
|
|
44
66
|
}
|
|
67
|
+
/** Signs in a built-in account with its email and password. Throws VeroXMApiError with code `email_not_verified` until the email is confirmed. */
|
|
68
|
+
async signInWithEmail(email, password) {
|
|
69
|
+
await this.signInWithCredentials(email, password);
|
|
70
|
+
return this.currentUser();
|
|
71
|
+
}
|
|
72
|
+
/** Signs out here: the refresh token is revoked on the server too (best effort), and the stored session cleared. */
|
|
45
73
|
async signOut() {
|
|
74
|
+
if (!this.loadedFromStorage)
|
|
75
|
+
this.session = await this.storage.get();
|
|
76
|
+
const refreshToken = this.session?.refreshToken;
|
|
46
77
|
this.apiKey = null;
|
|
47
78
|
this.session = null;
|
|
48
79
|
this.loadedFromStorage = true;
|
|
49
80
|
await this.storage.clear();
|
|
50
81
|
this.notify(null);
|
|
82
|
+
if (refreshToken)
|
|
83
|
+
await rawRequest(this.apiBase, { method: 'POST', path: '/auth/logout', json: { refreshToken } }).catch(() => undefined);
|
|
84
|
+
}
|
|
85
|
+
// ------------------------------------------------------------------ built-in accounts
|
|
86
|
+
/**
|
|
87
|
+
* Creates an account. When the project wants emails confirmed, resolves `{ verificationSent: true }` and the person
|
|
88
|
+
* gets a 6-digit code (finish with `verifyEmail`); otherwise they're signed in and it resolves `{ user }`.
|
|
89
|
+
*/
|
|
90
|
+
async signUp(input) {
|
|
91
|
+
const data = (await this.post('/auth/signup', input));
|
|
92
|
+
if ('accessToken' in data) {
|
|
93
|
+
await this.persistSession(data);
|
|
94
|
+
return { user: this.currentUser() };
|
|
95
|
+
}
|
|
96
|
+
return { verificationSent: true };
|
|
97
|
+
}
|
|
98
|
+
/** Confirms the email with its code (or the link's token) and signs the person in. */
|
|
99
|
+
async verifyEmail(input) {
|
|
100
|
+
return this.signInWith('/auth/verify', input);
|
|
101
|
+
}
|
|
102
|
+
/** Sends a new confirmation code. Resolves the same whether or not the address has an account. */
|
|
103
|
+
async resendVerification(email) {
|
|
104
|
+
await this.post('/auth/verify/resend', { email });
|
|
105
|
+
}
|
|
106
|
+
/** Emails a password reset code. Resolves the same whether or not the address has an account. */
|
|
107
|
+
async requestPasswordReset(email) {
|
|
108
|
+
await this.post('/auth/password/forgot', { email });
|
|
109
|
+
}
|
|
110
|
+
/** Sets a new password with the reset code (or the link's token), signs out every other device, and signs in here. */
|
|
111
|
+
async resetPassword(input) {
|
|
112
|
+
return this.signInWith('/auth/password/reset', input);
|
|
113
|
+
}
|
|
114
|
+
/** Accepts an invitation: chooses a password (and a name) with the invitation's code or link token, and signs in. */
|
|
115
|
+
async acceptInvite(input) {
|
|
116
|
+
return this.signInWith('/auth/invite/accept', input);
|
|
117
|
+
}
|
|
118
|
+
/** Who is signed in, as of the last sign-in or refresh; null when signed out or using an API key. */
|
|
119
|
+
currentUser() {
|
|
120
|
+
return this.session?.user ?? null;
|
|
121
|
+
}
|
|
122
|
+
/** Called with the person whenever they sign in, change, or sign out (and once now). Returns an unsubscribe function. */
|
|
123
|
+
onAuthStateChange(listener) {
|
|
124
|
+
this.userListeners.add(listener);
|
|
125
|
+
void this.ready().then(() => this.userListeners.has(listener) && listener(this.currentUser()));
|
|
126
|
+
return () => this.userListeners.delete(listener);
|
|
127
|
+
}
|
|
128
|
+
/** Loads a stored session (from a previous visit), so currentUser() knows who's signed in. */
|
|
129
|
+
async ready() {
|
|
130
|
+
if (!this.loadedFromStorage) {
|
|
131
|
+
this.session = await this.storage.get();
|
|
132
|
+
this.loadedFromStorage = true;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
/** The signed-in person's account, fresh from the API. */
|
|
136
|
+
async getAccount() {
|
|
137
|
+
const account = (await this.authed('GET', '/auth/me'));
|
|
138
|
+
await this.updateStoredUser(account);
|
|
139
|
+
return account;
|
|
140
|
+
}
|
|
141
|
+
/** Changes the signed-in person's name. */
|
|
142
|
+
async updateAccount(input) {
|
|
143
|
+
const account = (await this.authed('PATCH', '/auth/me', input));
|
|
144
|
+
await this.updateStoredUser(account);
|
|
145
|
+
return account;
|
|
146
|
+
}
|
|
147
|
+
/** Changes the password (the current one is needed when there is one). Other devices are signed out; this one stays in. */
|
|
148
|
+
async changePassword(input) {
|
|
149
|
+
const data = (await this.authed('POST', '/auth/me/password', input));
|
|
150
|
+
await this.persistSession(data);
|
|
151
|
+
}
|
|
152
|
+
/** Deletes the signed-in person's account (their password is needed when they have one), then signs out here. */
|
|
153
|
+
async deleteAccount(input = {}) {
|
|
154
|
+
await this.authed('DELETE', '/auth/me', input);
|
|
155
|
+
this.session = null;
|
|
156
|
+
await this.storage.clear();
|
|
157
|
+
this.notify(null);
|
|
158
|
+
}
|
|
159
|
+
// ------------------------------------------------------------------ social sign-in
|
|
160
|
+
/** The social sign-in options the project has turned on, for your buttons. */
|
|
161
|
+
async socialProviders() {
|
|
162
|
+
return (await rawRequest(this.apiBase, { path: '/auth/social' }));
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Starts a social sign-in and returns where to send the person. `redirectUri` must be one of the project's redirect
|
|
166
|
+
* addresses (Developer > Authentication > Accounts). Keep `codeVerifier` and `state` until they come back; in a
|
|
167
|
+
* browser, `signInWithRedirect` does all of this for you.
|
|
168
|
+
*/
|
|
169
|
+
async startSocialSignIn(provider, options) {
|
|
170
|
+
const { codeVerifier, codeChallenge } = await createPkce();
|
|
171
|
+
const state = options.state ?? (await randomString(16));
|
|
172
|
+
const base = this.apiBase.endsWith('/') ? this.apiBase : `${this.apiBase}/`;
|
|
173
|
+
const url = new URL(`auth/social/${encodeURIComponent(provider)}/start`, base);
|
|
174
|
+
url.searchParams.set('redirect_uri', options.redirectUri);
|
|
175
|
+
url.searchParams.set('state', state);
|
|
176
|
+
url.searchParams.set('code_challenge', codeChallenge);
|
|
177
|
+
url.searchParams.set('code_challenge_method', 'S256');
|
|
178
|
+
return { url: url.toString(), codeVerifier, state };
|
|
179
|
+
}
|
|
180
|
+
/** Trades the code the person came back with, and the verifier from `startSocialSignIn`, for a session. */
|
|
181
|
+
async exchangeSocialCode(code, codeVerifier) {
|
|
182
|
+
return this.signInWith('/auth/social/token', { code, codeVerifier });
|
|
183
|
+
}
|
|
184
|
+
/** Browser: starts a social sign-in and leaves the page for the provider. Finish on the redirect page with `completeSignInWithRedirect()`. */
|
|
185
|
+
async signInWithRedirect(provider, options) {
|
|
186
|
+
const start = await this.startSocialSignIn(provider, options);
|
|
187
|
+
this.pending.set(PENDING_KEY, JSON.stringify({ codeVerifier: start.codeVerifier, state: start.state }));
|
|
188
|
+
window.location.assign(start.url);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* On the redirect page (or with the address an app was opened with): checks the `state`, trades the code, and signs the
|
|
192
|
+
* person in. Resolves null when the address has no sign-in result; throws when the provider or VeroXM refused it
|
|
193
|
+
* (the error's `code` is the `error` the page came back with, e.g. `access_denied` or `sign_up_closed`).
|
|
194
|
+
*/
|
|
195
|
+
async completeSignInWithRedirect(url = typeof window !== 'undefined' ? window.location.href : '') {
|
|
196
|
+
const params = new URL(url).searchParams;
|
|
197
|
+
const raw = this.pending.get(PENDING_KEY);
|
|
198
|
+
if (!params.has('code') && !params.has('error'))
|
|
199
|
+
return null;
|
|
200
|
+
this.pending.remove(PENDING_KEY);
|
|
201
|
+
const pending = raw ? JSON.parse(raw) : null;
|
|
202
|
+
if (!pending || params.get('state') !== pending.state) {
|
|
203
|
+
throw Object.assign(new Error("This sign-in wasn't started here, or it was already finished. Start it again."), { code: 'state_mismatch' });
|
|
204
|
+
}
|
|
205
|
+
const error = params.get('error');
|
|
206
|
+
if (error)
|
|
207
|
+
throw Object.assign(new Error(params.get('error_description') ?? 'The sign-in was refused.'), { code: error });
|
|
208
|
+
return this.exchangeSocialCode(params.get('code'), pending.codeVerifier);
|
|
209
|
+
}
|
|
210
|
+
async signInWith(path, body) {
|
|
211
|
+
const data = (await this.post(path, body));
|
|
212
|
+
this.apiKey = null;
|
|
213
|
+
await this.persistSession(data);
|
|
214
|
+
return this.currentUser();
|
|
215
|
+
}
|
|
216
|
+
post(path, json) {
|
|
217
|
+
return rawRequest(this.apiBase, { method: 'POST', path, json });
|
|
218
|
+
}
|
|
219
|
+
/** A call as the signed-in person (not with an API key). */
|
|
220
|
+
async authed(method, path, json) {
|
|
221
|
+
if (this.apiKey)
|
|
222
|
+
throw new VeroXMNotAuthenticatedError();
|
|
223
|
+
const token = await this.getAccessToken();
|
|
224
|
+
return rawRequest(this.apiBase, { method, path, ...(json !== undefined ? { json } : {}), headers: { Authorization: `Bearer ${token}` } });
|
|
225
|
+
}
|
|
226
|
+
async updateStoredUser(account) {
|
|
227
|
+
if (!this.session)
|
|
228
|
+
return;
|
|
229
|
+
const user = { id: account.id, email: account.email, name: account.name, roles: account.roles, emailVerified: account.emailVerified };
|
|
230
|
+
this.session = { ...this.session, user, abilities: account.abilities };
|
|
231
|
+
await this.storage.set(this.session);
|
|
232
|
+
this.notifyUser();
|
|
51
233
|
}
|
|
52
234
|
/** Returns the abilities (read/create/update/delete, or ['*']) the current credential carries, or null if signed out or in static-key mode (a key's abilities aren't known client-side -- only the API enforces them). */
|
|
53
235
|
currentAbilities() {
|
|
@@ -110,6 +292,7 @@ export class VeroXMAuth {
|
|
|
110
292
|
refreshToken: data.refreshToken,
|
|
111
293
|
expiresAt: Date.now() + data.expiresIn * 1000,
|
|
112
294
|
abilities: data.abilities,
|
|
295
|
+
user: data.user ?? this.session?.user ?? null,
|
|
113
296
|
};
|
|
114
297
|
this.session = session;
|
|
115
298
|
this.loadedFromStorage = true;
|
|
@@ -119,5 +302,11 @@ export class VeroXMAuth {
|
|
|
119
302
|
notify(accessToken) {
|
|
120
303
|
for (const listener of this.listeners)
|
|
121
304
|
listener(accessToken);
|
|
305
|
+
this.notifyUser();
|
|
306
|
+
}
|
|
307
|
+
notifyUser() {
|
|
308
|
+
const user = this.currentUser();
|
|
309
|
+
for (const listener of this.userListeners)
|
|
310
|
+
listener(user);
|
|
122
311
|
}
|
|
123
312
|
}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type RawRequestOptions } from './http.js';
|
|
2
|
-
import { VeroXMAuth } from './auth.js';
|
|
2
|
+
import { VeroXMAuth, type PendingStore } from './auth.js';
|
|
3
3
|
import { ContentResource } from './content.js';
|
|
4
4
|
import { MediaResource } from './media.js';
|
|
5
5
|
import { type TokenStorage } from './token-storage.js';
|
|
@@ -10,6 +10,8 @@ export interface VeroXMAppOptions {
|
|
|
10
10
|
projectId: string;
|
|
11
11
|
/** Defaults to browser localStorage when available, otherwise an in-memory store that only lasts for this VeroXMApp instance's lifetime. Pass your own TokenStorage implementation for disk persistence in Node/React Native. */
|
|
12
12
|
tokenStorage?: TokenStorage;
|
|
13
|
+
/** Where a social sign-in keeps its verifier while the person is at the provider. Defaults to sessionStorage in a browser. */
|
|
14
|
+
pendingStore?: PendingStore;
|
|
13
15
|
}
|
|
14
16
|
/**
|
|
15
17
|
* The SDK's entry point -- one `initializeApp()` call, Firebase-style,
|
package/dist/client.js
CHANGED
|
@@ -16,14 +16,14 @@ function defaultTokenStorage(projectId) {
|
|
|
16
16
|
* else. See this package's README for a full quickstart.
|
|
17
17
|
*/
|
|
18
18
|
export class VeroXMApp {
|
|
19
|
-
constructor(apiBase, tokenStorage) {
|
|
19
|
+
constructor(apiBase, tokenStorage, pendingStore) {
|
|
20
20
|
this.apiBase = apiBase;
|
|
21
|
-
this.auth = new VeroXMAuth(apiBase, tokenStorage);
|
|
21
|
+
this.auth = new VeroXMAuth(apiBase, tokenStorage, pendingStore);
|
|
22
22
|
}
|
|
23
23
|
static initializeApp(options) {
|
|
24
24
|
const base = options.baseUrl.replace(/\/$/, '');
|
|
25
25
|
const apiBase = `${base}/public/v2/projects/${options.projectId}`;
|
|
26
|
-
return new VeroXMApp(apiBase, options.tokenStorage ?? defaultTokenStorage(options.projectId));
|
|
26
|
+
return new VeroXMApp(apiBase, options.tokenStorage ?? defaultTokenStorage(options.projectId), options.pendingStore);
|
|
27
27
|
}
|
|
28
28
|
/** Typed access to one content collection's entries (list/get/create/update/delete/search). */
|
|
29
29
|
content(collectionSlug) {
|
package/dist/errors.d.ts
CHANGED
|
@@ -10,6 +10,11 @@
|
|
|
10
10
|
export declare class VeroXMApiError extends Error {
|
|
11
11
|
readonly status: number;
|
|
12
12
|
readonly body: unknown;
|
|
13
|
+
/**
|
|
14
|
+
* The API's machine-readable reason, when it gave one: e.g. `email_not_verified`, `invalid_code`,
|
|
15
|
+
* `sign_up_closed`, `too_many_attempts`, `access_denied`, `function_limit`.
|
|
16
|
+
*/
|
|
17
|
+
readonly code: string | undefined;
|
|
13
18
|
constructor(status: number, body: unknown);
|
|
14
19
|
private static messageFrom;
|
|
15
20
|
}
|
package/dist/errors.js
CHANGED
|
@@ -13,6 +13,8 @@ export class VeroXMApiError extends Error {
|
|
|
13
13
|
this.name = 'VeroXMApiError';
|
|
14
14
|
this.status = status;
|
|
15
15
|
this.body = body;
|
|
16
|
+
const c = body && typeof body === 'object' ? body.code : undefined;
|
|
17
|
+
this.code = typeof c === 'string' ? c : undefined;
|
|
16
18
|
}
|
|
17
19
|
static messageFrom(status, body) {
|
|
18
20
|
if (body && typeof body === 'object') {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
export { VeroXMApp } from './client.js';
|
|
2
2
|
export type { VeroXMAppOptions } from './client.js';
|
|
3
3
|
export { VeroXMAuth } from './auth.js';
|
|
4
|
+
export type { Account, EmailCode, PendingStore, SocialProvider, SocialSignInStart } from './auth.js';
|
|
5
|
+
export { createPkce } from './pkce.js';
|
|
4
6
|
export { ContentResource } from './content.js';
|
|
5
7
|
export type { ListOptions } from './content.js';
|
|
6
8
|
export { MediaResource } from './media.js';
|
|
7
9
|
export type { MediaItem, MediaPage, UploadableFile } from './media.js';
|
|
8
10
|
export { VeroXMApiError, VeroXMNotAuthenticatedError } from './errors.js';
|
|
9
11
|
export { MemoryTokenStorage, BrowserLocalStorageTokenStorage } from './token-storage.js';
|
|
10
|
-
export type { TokenStorage, StoredSession } from './token-storage.js';
|
|
12
|
+
export type { TokenStorage, StoredSession, AuthUser } from './token-storage.js';
|
|
11
13
|
export { VeroxmTracker, createTracker } from './tracker.js';
|
|
12
14
|
export type { TrackerOptions, TrackerStorage, ConsentChoices, ConsentValue, StoredConsent, ExperienceDecision, GetExperienceOptions, Recommendations, } from './tracker.js';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { VeroXMApp } from './client.js';
|
|
2
2
|
export { VeroXMAuth } from './auth.js';
|
|
3
|
+
export { createPkce } from './pkce.js';
|
|
3
4
|
export { ContentResource } from './content.js';
|
|
4
5
|
export { MediaResource } from './media.js';
|
|
5
6
|
export { VeroXMApiError, VeroXMNotAuthenticatedError } from './errors.js';
|
package/dist/pkce.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare function base64url(bytes: Uint8Array): string;
|
|
2
|
+
/** A random URL-safe string from `bytes` random bytes. */
|
|
3
|
+
export declare function randomString(bytes?: number): Promise<string>;
|
|
4
|
+
/** A new verifier and its S256 challenge. */
|
|
5
|
+
export declare function createPkce(): Promise<{
|
|
6
|
+
codeVerifier: string;
|
|
7
|
+
codeChallenge: string;
|
|
8
|
+
}>;
|
package/dist/pkce.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// PKCE (RFC 7636) for social sign-in: a random verifier the app keeps, and
|
|
2
|
+
// its S256 challenge, sent when the sign-in starts. VeroXM only hands out
|
|
3
|
+
// tokens for the code it sends back to someone who has the verifier.
|
|
4
|
+
// Uses Web Crypto: browsers, Node 19+ and Deno have it as globalThis.crypto;
|
|
5
|
+
// Node 18 gets it from node:crypto.
|
|
6
|
+
async function webCrypto() {
|
|
7
|
+
const g = globalThis.crypto;
|
|
8
|
+
if (g?.subtle && typeof g.getRandomValues === 'function')
|
|
9
|
+
return g;
|
|
10
|
+
try {
|
|
11
|
+
const mod = (await import(/* @vite-ignore */ 'node:crypto'));
|
|
12
|
+
if (mod.webcrypto?.subtle)
|
|
13
|
+
return mod.webcrypto;
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
// not Node
|
|
17
|
+
}
|
|
18
|
+
throw new Error('Social sign-in needs Web Crypto (crypto.subtle). In React Native, add a polyfill such as react-native-quick-crypto.');
|
|
19
|
+
}
|
|
20
|
+
export function base64url(bytes) {
|
|
21
|
+
let s = '';
|
|
22
|
+
for (let i = 0; i < bytes.length; i++)
|
|
23
|
+
s += String.fromCharCode(bytes[i]);
|
|
24
|
+
const b64 = typeof btoa === 'function' ? btoa(s) : globalThis.Buffer.from(bytes).toString('base64');
|
|
25
|
+
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
26
|
+
}
|
|
27
|
+
/** A random URL-safe string from `bytes` random bytes. */
|
|
28
|
+
export async function randomString(bytes = 32) {
|
|
29
|
+
const c = await webCrypto();
|
|
30
|
+
return base64url(c.getRandomValues(new Uint8Array(bytes)));
|
|
31
|
+
}
|
|
32
|
+
/** A new verifier and its S256 challenge. */
|
|
33
|
+
export async function createPkce() {
|
|
34
|
+
const c = await webCrypto();
|
|
35
|
+
const codeVerifier = base64url(c.getRandomValues(new Uint8Array(32)));
|
|
36
|
+
const digest = await c.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier));
|
|
37
|
+
return { codeVerifier, codeChallenge: base64url(new Uint8Array(digest)) };
|
|
38
|
+
}
|
package/dist/token-storage.d.ts
CHANGED
|
@@ -1,9 +1,19 @@
|
|
|
1
|
+
/** The signed-in person, as the API last described them. */
|
|
2
|
+
export interface AuthUser {
|
|
3
|
+
id: number;
|
|
4
|
+
email: string | null;
|
|
5
|
+
name: string | null;
|
|
6
|
+
roles: string[];
|
|
7
|
+
emailVerified: boolean;
|
|
8
|
+
}
|
|
1
9
|
export interface StoredSession {
|
|
2
10
|
accessToken: string;
|
|
3
11
|
refreshToken: string | null;
|
|
4
12
|
/** Epoch ms this access token stops being valid. */
|
|
5
13
|
expiresAt: number;
|
|
6
14
|
abilities: string[];
|
|
15
|
+
/** Who signed in (built-in accounts); missing in sessions stored by older SDK versions. */
|
|
16
|
+
user?: AuthUser | null;
|
|
7
17
|
}
|
|
8
18
|
/**
|
|
9
19
|
* Where the SDK persists the current session between calls -- mirrors how
|