usebecky 0.0.0-stage → 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/README.md +701 -2
- package/dist/analytics/client.d.ts +219 -0
- package/dist/analytics/client.js +923 -0
- package/dist/analytics/cmp.d.ts +20 -0
- package/dist/analytics/cmp.js +166 -0
- package/dist/analytics/context.d.ts +29 -0
- package/dist/analytics/context.js +97 -0
- package/dist/auth/client.d.ts +401 -0
- package/dist/auth/client.js +1081 -0
- package/dist/auth/webauthn.d.ts +18 -0
- package/dist/auth/webauthn.js +138 -0
- package/dist/cli/ai.d.ts +54 -0
- package/dist/cli/ai.js +202 -0
- package/dist/cli/analytics.d.ts +53 -0
- package/dist/cli/analytics.js +357 -0
- package/dist/cli/config.d.ts +75 -0
- package/dist/cli/config.js +718 -0
- package/dist/cli/db.d.ts +48 -0
- package/dist/cli/db.js +215 -0
- package/dist/cli/deploy-api.d.ts +168 -0
- package/dist/cli/deploy-api.js +177 -0
- package/dist/cli/deploy-ci.d.ts +15 -0
- package/dist/cli/deploy-ci.js +54 -0
- package/dist/cli/deploy-detect.d.ts +64 -0
- package/dist/cli/deploy-detect.js +249 -0
- package/dist/cli/deploy-files.d.ts +112 -0
- package/dist/cli/deploy-files.js +778 -0
- package/dist/cli/deploy.d.ts +10 -0
- package/dist/cli/deploy.js +430 -0
- package/dist/cli/emails.d.ts +29 -0
- package/dist/cli/emails.js +122 -0
- package/dist/cli/framework.d.ts +135 -0
- package/dist/cli/framework.js +459 -0
- package/dist/cli/functions.d.ts +59 -0
- package/dist/cli/functions.js +426 -0
- package/dist/cli/hosting.d.ts +4 -0
- package/dist/cli/hosting.js +532 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +9 -0
- package/dist/cli/payments.d.ts +35 -0
- package/dist/cli/payments.js +176 -0
- package/dist/cli/push.d.ts +36 -0
- package/dist/cli/push.js +172 -0
- package/dist/cli/run.d.ts +65 -0
- package/dist/cli/run.js +850 -0
- package/dist/cli/social.d.ts +52 -0
- package/dist/cli/social.js +532 -0
- package/dist/cli/tokens.d.ts +28 -0
- package/dist/cli/tokens.js +114 -0
- package/dist/cli/ui.d.ts +38 -0
- package/dist/cli/ui.js +140 -0
- package/dist/client.d.ts +94 -0
- package/dist/client.js +156 -0
- package/dist/db/query.d.ts +162 -0
- package/dist/db/query.js +336 -0
- package/dist/db/types.d.ts +93 -0
- package/dist/db/types.js +4 -0
- package/dist/forms/client.d.ts +65 -0
- package/dist/forms/client.js +106 -0
- package/dist/functions/client.d.ts +37 -0
- package/dist/functions/client.js +76 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +16 -0
- package/dist/lib/dashboard-paths.d.ts +4 -0
- package/dist/lib/dashboard-paths.js +8 -0
- package/dist/lib/env.d.ts +9 -0
- package/dist/lib/env.js +55 -0
- package/dist/lib/errors.d.ts +22 -0
- package/dist/lib/errors.js +90 -0
- package/dist/lib/hosted.d.ts +2 -0
- package/dist/lib/hosted.js +7 -0
- package/dist/lib/http.d.ts +59 -0
- package/dist/lib/http.js +172 -0
- package/dist/lib/jwt.d.ts +1 -0
- package/dist/lib/jwt.js +31 -0
- package/dist/lib/locale.d.ts +12 -0
- package/dist/lib/locale.js +51 -0
- package/dist/lib/pkce.d.ts +20 -0
- package/dist/lib/pkce.js +124 -0
- package/dist/lib/storage-adapter.d.ts +15 -0
- package/dist/lib/storage-adapter.js +91 -0
- package/dist/lib/types.d.ts +339 -0
- package/dist/lib/types.js +1 -0
- package/dist/newsletter/client.d.ts +140 -0
- package/dist/newsletter/client.js +85 -0
- package/dist/payments/client.d.ts +352 -0
- package/dist/payments/client.js +323 -0
- package/dist/push/client.d.ts +110 -0
- package/dist/push/client.js +179 -0
- package/dist/realtime/client.d.ts +131 -0
- package/dist/realtime/client.js +513 -0
- package/dist/server/analytics.d.ts +176 -0
- package/dist/server/analytics.js +49 -0
- package/dist/server/cache.d.ts +74 -0
- package/dist/server/cache.js +154 -0
- package/dist/server/emails.d.ts +142 -0
- package/dist/server/emails.js +123 -0
- package/dist/server/events.d.ts +357 -0
- package/dist/server/events.js +219 -0
- package/dist/server/functions.d.ts +40 -0
- package/dist/server/functions.js +1 -0
- package/dist/server/http-utils.d.ts +10 -0
- package/dist/server/http-utils.js +115 -0
- package/dist/server/index.d.ts +195 -0
- package/dist/server/index.js +314 -0
- package/dist/server/payments.d.ts +218 -0
- package/dist/server/payments.js +150 -0
- package/dist/server/push.d.ts +85 -0
- package/dist/server/push.js +37 -0
- package/dist/server/usage.d.ts +43 -0
- package/dist/server/usage.js +8 -0
- package/dist/storage/client.d.ts +143 -0
- package/dist/storage/client.js +224 -0
- package/package.json +52 -4
- package/skill/usebecky/SKILL.md +339 -0
- package/skill/usebecky/references/access-rules.md +307 -0
- package/skill/usebecky/references/addons.md +68 -0
- package/skill/usebecky/references/analytics.md +166 -0
- package/skill/usebecky/references/android.md +434 -0
- package/skill/usebecky/references/auth.md +379 -0
- package/skill/usebecky/references/cache.md +51 -0
- package/skill/usebecky/references/components.md +127 -0
- package/skill/usebecky/references/emails.md +105 -0
- package/skill/usebecky/references/expo.md +147 -0
- package/skill/usebecky/references/functions.md +99 -0
- package/skill/usebecky/references/hosting.md +119 -0
- package/skill/usebecky/references/http-api.md +233 -0
- package/skill/usebecky/references/ios.md +355 -0
- package/skill/usebecky/references/payments.md +493 -0
- package/skill/usebecky/references/realtime.md +143 -0
- package/skill/usebecky/references/scheduled-jobs.md +82 -0
- package/skill/usebecky/references/sdk.md +838 -0
- package/skill/usebecky/references/storage.md +210 -0
- package/skill/usebecky/references/templates.md +191 -0
- package/skill/usebecky/references/wordpress.md +87 -0
|
@@ -0,0 +1,1081 @@
|
|
|
1
|
+
import { UseBeckyError } from "../lib/errors.js";
|
|
2
|
+
import { decodeJwt } from "../lib/jwt.js";
|
|
3
|
+
import { localeField } from "../lib/locale.js";
|
|
4
|
+
import { createPkcePair } from "../lib/pkce.js";
|
|
5
|
+
import { createCredential, forgetUnknownPasskey, getCredential } from "./webauthn.js";
|
|
6
|
+
const COOKIE_NAME = 'ub-access-token';
|
|
7
|
+
const RETRY_DELAYS = [2_000, 5_000, 10_000, 30_000, 60_000];
|
|
8
|
+
/** Query parameters the server adds to redirect_to in the PKCE flow (removed from the address bar afterwards). */
|
|
9
|
+
const PKCE_REDIRECT_PARAMS = ['code', 'error', 'error_code', 'error_description'];
|
|
10
|
+
let warnedNoPkce = false;
|
|
11
|
+
const g = globalThis;
|
|
12
|
+
function nowSec() {
|
|
13
|
+
return Math.floor(Date.now() / 1000);
|
|
14
|
+
}
|
|
15
|
+
function inBrowser() {
|
|
16
|
+
return typeof g.window === 'object' && g.window !== null && typeof g.document === 'object' && g.document !== null;
|
|
17
|
+
}
|
|
18
|
+
/** Build a minimal user from access-token claims (used until the full user is fetched). */
|
|
19
|
+
function userFromToken(token) {
|
|
20
|
+
const c = decodeJwt(token) ?? {};
|
|
21
|
+
return {
|
|
22
|
+
id: c.sub ?? '',
|
|
23
|
+
email: c.email ?? null,
|
|
24
|
+
email_confirmed_at: null,
|
|
25
|
+
phone: c.phone ?? null,
|
|
26
|
+
created_at: '',
|
|
27
|
+
updated_at: '',
|
|
28
|
+
last_sign_in_at: null,
|
|
29
|
+
app_metadata: c.app_metadata ?? {},
|
|
30
|
+
user_metadata: c.user_metadata ?? {},
|
|
31
|
+
identities: [],
|
|
32
|
+
factors: [],
|
|
33
|
+
banned_until: null,
|
|
34
|
+
is_anonymous: !!c.is_anonymous,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Normalize a session from the API (fills expires_at, user). */
|
|
38
|
+
export function normalizeSession(raw) {
|
|
39
|
+
if (!raw || typeof raw !== 'object' || typeof raw.access_token !== 'string' || !raw.access_token)
|
|
40
|
+
return null;
|
|
41
|
+
const claims = decodeJwt(raw.access_token);
|
|
42
|
+
const expiresIn = Number(raw.expires_in) || (claims?.exp && claims?.iat ? claims.exp - claims.iat : 3600);
|
|
43
|
+
const expiresAt = Number(raw.expires_at) || claims?.exp || nowSec() + expiresIn;
|
|
44
|
+
return {
|
|
45
|
+
access_token: raw.access_token,
|
|
46
|
+
token_type: raw.token_type ?? 'bearer',
|
|
47
|
+
expires_in: expiresIn,
|
|
48
|
+
expires_at: expiresAt,
|
|
49
|
+
refresh_token: raw.refresh_token ?? '',
|
|
50
|
+
user: raw.user && typeof raw.user === 'object' ? raw.user : userFromToken(raw.access_token),
|
|
51
|
+
...(raw.mfa_required === true || raw.mfa_required === 'true' ? { mfa_required: true } : {}),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export class AuthClient {
|
|
55
|
+
http;
|
|
56
|
+
consentRef;
|
|
57
|
+
storage;
|
|
58
|
+
storageKey;
|
|
59
|
+
autoRefresh;
|
|
60
|
+
cookie;
|
|
61
|
+
session = null;
|
|
62
|
+
listeners = new Set();
|
|
63
|
+
refreshPromise = null;
|
|
64
|
+
refreshTimer = null;
|
|
65
|
+
retryCount = 0;
|
|
66
|
+
urlError = null;
|
|
67
|
+
/** Resolves when the stored session (and any session in the URL) has been loaded. */
|
|
68
|
+
ready;
|
|
69
|
+
/** MFA (TOTP authenticator apps). */
|
|
70
|
+
mfa;
|
|
71
|
+
/**
|
|
72
|
+
* Passkeys of the signed-in user (Face ID, fingerprint, device PIN or a password manager). Turn them on in
|
|
73
|
+
* Dashboard → Auth → Sign-in methods → Passkeys. Sign in with one: `baas.auth.signInWithPasskey()`.
|
|
74
|
+
*/
|
|
75
|
+
passkeys;
|
|
76
|
+
constructor(opts) {
|
|
77
|
+
this.http = opts.http;
|
|
78
|
+
this.consentRef = opts.consent ?? (() => Promise.resolve(undefined));
|
|
79
|
+
this.storage = opts.storage;
|
|
80
|
+
this.storageKey = opts.storageKey;
|
|
81
|
+
this.autoRefresh = opts.autoRefresh;
|
|
82
|
+
this.cookie = opts.cookie && inBrowser();
|
|
83
|
+
this.mfa = {
|
|
84
|
+
enroll: (o) => this.mfaEnroll(o),
|
|
85
|
+
verify: (id, code) => this.mfaVerify(id, code),
|
|
86
|
+
unenroll: (id) => this.mfaUnenroll(id),
|
|
87
|
+
listFactors: () => this.mfaListFactors(),
|
|
88
|
+
getAssuranceLevel: () => this.assuranceLevel(),
|
|
89
|
+
};
|
|
90
|
+
this.passkeys = {
|
|
91
|
+
register: (o) => this.passkeyRegister(o),
|
|
92
|
+
list: () => this.passkeyList(),
|
|
93
|
+
rename: (id, name) => this.passkeyRename(id, name),
|
|
94
|
+
remove: (id) => this.passkeyRemove(id),
|
|
95
|
+
};
|
|
96
|
+
const init = this.initialize(opts.detectSessionInUrl);
|
|
97
|
+
this.ready = init.then(() => undefined);
|
|
98
|
+
// Emit the redirect event after INITIAL_SESSION has reached listeners added right after createClient().
|
|
99
|
+
void init.then((event) => {
|
|
100
|
+
if (event)
|
|
101
|
+
queueMicrotask(() => this.emit(event));
|
|
102
|
+
});
|
|
103
|
+
this.watchOtherTabs();
|
|
104
|
+
}
|
|
105
|
+
// ---- initialization ---------------------------------------------------------------------
|
|
106
|
+
async initialize(detectInUrl) {
|
|
107
|
+
// Load synchronously when the storage is synchronous, so getSession() works right away.
|
|
108
|
+
try {
|
|
109
|
+
const raw = this.storage.getItem(this.storageKey);
|
|
110
|
+
const value = typeof raw?.then === 'function' ? await raw : raw;
|
|
111
|
+
if (typeof value === 'string')
|
|
112
|
+
this.session = normalizeSession(safeParse(value));
|
|
113
|
+
}
|
|
114
|
+
catch { }
|
|
115
|
+
let urlEvent = null;
|
|
116
|
+
if (detectInUrl) {
|
|
117
|
+
// #access_token=... is read synchronously (getSession() works right away); a PKCE ?code= needs a request.
|
|
118
|
+
urlEvent = this.readSessionFromLocation();
|
|
119
|
+
if (!urlEvent && this.locationHasPkceParams())
|
|
120
|
+
urlEvent = await this.readCodeFromLocation();
|
|
121
|
+
}
|
|
122
|
+
if (urlEvent) {
|
|
123
|
+
await this.persist();
|
|
124
|
+
await this.fetchFullUser();
|
|
125
|
+
}
|
|
126
|
+
else if (this.session) {
|
|
127
|
+
this.writeCookie();
|
|
128
|
+
}
|
|
129
|
+
if (this.session) {
|
|
130
|
+
if (this.session.expires_at - nowSec() < 10 && this.autoRefresh)
|
|
131
|
+
void this.refreshSession();
|
|
132
|
+
else
|
|
133
|
+
this.scheduleRefresh();
|
|
134
|
+
}
|
|
135
|
+
return urlEvent;
|
|
136
|
+
}
|
|
137
|
+
/** Parse `#access_token=...` after an OAuth / magic link / recovery redirect, then clean the URL. */
|
|
138
|
+
readSessionFromLocation() {
|
|
139
|
+
const loc = g.location;
|
|
140
|
+
if (!loc || typeof loc.hash !== 'string' || loc.hash.length < 2)
|
|
141
|
+
return null;
|
|
142
|
+
// Hash routers can produce "#/route#access_token=..." — keep the route, read the rest.
|
|
143
|
+
const raw = loc.hash.slice(1);
|
|
144
|
+
const inner = raw.lastIndexOf('#');
|
|
145
|
+
const route = inner >= 0 ? `#${raw.slice(0, inner)}` : '';
|
|
146
|
+
const params = new URLSearchParams(inner >= 0 ? raw.slice(inner + 1) : raw);
|
|
147
|
+
if (!params.has('access_token') && !params.has('error') && !params.has('error_description'))
|
|
148
|
+
return null;
|
|
149
|
+
const result = this.sessionFromParams(params);
|
|
150
|
+
try {
|
|
151
|
+
g.history?.replaceState?.(g.history.state, '', `${loc.pathname}${loc.search}${route}`);
|
|
152
|
+
}
|
|
153
|
+
catch { }
|
|
154
|
+
if (result.error) {
|
|
155
|
+
this.urlError = result.error;
|
|
156
|
+
try {
|
|
157
|
+
g.console?.warn?.(`[usebecky] ${result.error.message}`);
|
|
158
|
+
}
|
|
159
|
+
catch { }
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
this.session = result.session;
|
|
163
|
+
return result.type === 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN';
|
|
164
|
+
}
|
|
165
|
+
locationHasPkceParams() {
|
|
166
|
+
const search = g.location?.search;
|
|
167
|
+
if (typeof search !== 'string' || search.length < 2)
|
|
168
|
+
return false;
|
|
169
|
+
const params = new URLSearchParams(search);
|
|
170
|
+
return params.has('code') || params.has('error') || params.has('error_description');
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* PKCE: after a social sign-in the page comes back with `?code=...` (or `?error=...`). Swap the code for a
|
|
174
|
+
* session with the verifier signInWith() saved, then clean the URL. A `?code=` that this client didn't
|
|
175
|
+
* start (no saved verifier, e.g. your app's own parameter) is left alone.
|
|
176
|
+
*/
|
|
177
|
+
async readCodeFromLocation() {
|
|
178
|
+
const loc = g.location;
|
|
179
|
+
const verifier = await this.readVerifier();
|
|
180
|
+
if (!verifier)
|
|
181
|
+
return null;
|
|
182
|
+
const params = new URLSearchParams(loc.search);
|
|
183
|
+
const code = params.get('code');
|
|
184
|
+
let error = redirectError(params);
|
|
185
|
+
for (const k of PKCE_REDIRECT_PARAMS)
|
|
186
|
+
params.delete(k);
|
|
187
|
+
const rest = params.toString();
|
|
188
|
+
try {
|
|
189
|
+
g.history?.replaceState?.(g.history.state, '', `${loc.pathname}${rest ? `?${rest}` : ''}${loc.hash ?? ''}`);
|
|
190
|
+
}
|
|
191
|
+
catch { }
|
|
192
|
+
if (!error && code) {
|
|
193
|
+
const res = await this.exchangeCode(code, verifier);
|
|
194
|
+
if (res.session) {
|
|
195
|
+
this.session = res.session;
|
|
196
|
+
return 'SIGNED_IN';
|
|
197
|
+
}
|
|
198
|
+
error = res.error;
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
await this.removeVerifier();
|
|
202
|
+
}
|
|
203
|
+
if (error) {
|
|
204
|
+
this.urlError = error;
|
|
205
|
+
try {
|
|
206
|
+
g.console?.warn?.(`[usebecky] ${error.message}`);
|
|
207
|
+
}
|
|
208
|
+
catch { }
|
|
209
|
+
}
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
get verifierKey() {
|
|
213
|
+
return `${this.storageKey}-code-verifier`;
|
|
214
|
+
}
|
|
215
|
+
async readVerifier() {
|
|
216
|
+
try {
|
|
217
|
+
const v = await this.storage.getItem(this.verifierKey);
|
|
218
|
+
return typeof v === 'string' && v ? v : null;
|
|
219
|
+
}
|
|
220
|
+
catch {
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
async removeVerifier() {
|
|
225
|
+
try {
|
|
226
|
+
await this.storage.removeItem(this.verifierKey);
|
|
227
|
+
await this.storage.removeItem(this.linkKey);
|
|
228
|
+
}
|
|
229
|
+
catch { }
|
|
230
|
+
}
|
|
231
|
+
/** Set while a linkIdentity() redirect is under way: its code is finished with the signed-in user's token. */
|
|
232
|
+
get linkKey() {
|
|
233
|
+
return `${this.storageKey}-link`;
|
|
234
|
+
}
|
|
235
|
+
/** The access token for finishing a link (refreshed when about to expire; never waits for `ready`). */
|
|
236
|
+
async linkToken() {
|
|
237
|
+
let marker = null;
|
|
238
|
+
try {
|
|
239
|
+
marker = await this.storage.getItem(this.linkKey);
|
|
240
|
+
}
|
|
241
|
+
catch { }
|
|
242
|
+
if (marker !== '1' || !this.session)
|
|
243
|
+
return null;
|
|
244
|
+
if (this.session.expires_at - nowSec() < 30) {
|
|
245
|
+
const r = await this.refreshSession();
|
|
246
|
+
return r.data?.session?.access_token ?? null;
|
|
247
|
+
}
|
|
248
|
+
return this.session.access_token;
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* POST /auth/v1/token?grant_type=pkce. The verifier is forgotten afterwards unless the request never
|
|
252
|
+
* reached the server (offline: try again with the same code). The visitor's consent state goes along: the server
|
|
253
|
+
* uses it only when this sign-in created the account (sign_up for a server-side tagging extension).
|
|
254
|
+
*/
|
|
255
|
+
async exchangeCode(code, verifier) {
|
|
256
|
+
// A linkIdentity() code only works with the access token of the user who started the link (server: link.ts).
|
|
257
|
+
const linkToken = await this.linkToken();
|
|
258
|
+
const consent = linkToken ? undefined : await this.consentRef();
|
|
259
|
+
const res = await this.http.request('/auth/v1/token', { method: 'POST', query: { grant_type: 'pkce' }, token: linkToken, body: { auth_code: code, code_verifier: verifier, consent } });
|
|
260
|
+
if (!(res.error && res.error.status === 0))
|
|
261
|
+
await this.removeVerifier();
|
|
262
|
+
if (res.error)
|
|
263
|
+
return { session: null, error: res.error };
|
|
264
|
+
const session = normalizeSession(res.data);
|
|
265
|
+
if (!session)
|
|
266
|
+
return { session: null, error: new UseBeckyError({ code: 'invalid_response', message: 'The server did not return a session.', status: 500 }) };
|
|
267
|
+
return { session, error: null };
|
|
268
|
+
}
|
|
269
|
+
sessionFromParams(params) {
|
|
270
|
+
const error = redirectError(params);
|
|
271
|
+
if (error)
|
|
272
|
+
return { session: null, type: null, error };
|
|
273
|
+
const session = normalizeSession({
|
|
274
|
+
access_token: params.get('access_token'),
|
|
275
|
+
refresh_token: params.get('refresh_token'),
|
|
276
|
+
expires_in: params.get('expires_in'),
|
|
277
|
+
expires_at: params.get('expires_at'),
|
|
278
|
+
token_type: params.get('token_type'),
|
|
279
|
+
mfa_required: params.get('mfa_required'),
|
|
280
|
+
});
|
|
281
|
+
if (!session)
|
|
282
|
+
return { session: null, type: null, error: new UseBeckyError({ code: 'invalid_redirect', message: 'The sign-in link did not contain a session.', status: 400 }) };
|
|
283
|
+
return { session, type: params.get('type'), error: null };
|
|
284
|
+
}
|
|
285
|
+
async fetchFullUser() {
|
|
286
|
+
if (!this.session)
|
|
287
|
+
return;
|
|
288
|
+
const res = await this.http.request('/auth/v1/user', { token: this.session.access_token });
|
|
289
|
+
if (res.data && this.session) {
|
|
290
|
+
this.session = { ...this.session, user: res.data };
|
|
291
|
+
await this.persist();
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
// ---- session state ----------------------------------------------------------------------
|
|
295
|
+
/** The current session from memory (no network). `null` when signed out. */
|
|
296
|
+
getSession() {
|
|
297
|
+
return { data: { session: this.session }, error: this.urlError };
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Listen for sign-in, sign-out and token refreshes. Called once right away with
|
|
301
|
+
* `INITIAL_SESSION`. Returns a function that stops listening.
|
|
302
|
+
*/
|
|
303
|
+
onAuthStateChange(callback) {
|
|
304
|
+
const listener = (e, s) => callback(e, s);
|
|
305
|
+
this.listeners.add(listener);
|
|
306
|
+
let active = true;
|
|
307
|
+
void this.ready.then(() => {
|
|
308
|
+
if (active)
|
|
309
|
+
safeCall(callback, 'INITIAL_SESSION', this.session);
|
|
310
|
+
});
|
|
311
|
+
return () => {
|
|
312
|
+
active = false;
|
|
313
|
+
this.listeners.delete(listener);
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
emit(event) {
|
|
317
|
+
for (const l of [...this.listeners])
|
|
318
|
+
safeCall(l, event, this.session);
|
|
319
|
+
}
|
|
320
|
+
/** Access token for API calls; refreshes it first when it is about to expire. */
|
|
321
|
+
async getAccessToken() {
|
|
322
|
+
await this.ready;
|
|
323
|
+
const s = this.session;
|
|
324
|
+
if (!s)
|
|
325
|
+
return null;
|
|
326
|
+
if (s.expires_at - nowSec() < 15) {
|
|
327
|
+
const r = await this.refreshSession();
|
|
328
|
+
return r.data?.session?.access_token ?? this.session?.access_token ?? null;
|
|
329
|
+
}
|
|
330
|
+
return s.access_token;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* @internal The server said `token` is expired/invalid. Refresh (once, shared) and return the
|
|
334
|
+
* new token, or the current one if another call already refreshed.
|
|
335
|
+
*/
|
|
336
|
+
async handleRejectedToken(token) {
|
|
337
|
+
if (!this.session)
|
|
338
|
+
return null;
|
|
339
|
+
if (this.session.access_token !== token)
|
|
340
|
+
return this.session.access_token;
|
|
341
|
+
const r = await this.refreshSession();
|
|
342
|
+
return r.data?.session?.access_token ?? null;
|
|
343
|
+
}
|
|
344
|
+
async setSession(session, event) {
|
|
345
|
+
this.session = session;
|
|
346
|
+
this.urlError = null;
|
|
347
|
+
await this.persist();
|
|
348
|
+
this.scheduleRefresh();
|
|
349
|
+
if (event)
|
|
350
|
+
this.emit(event);
|
|
351
|
+
}
|
|
352
|
+
async persist() {
|
|
353
|
+
try {
|
|
354
|
+
if (this.session)
|
|
355
|
+
await this.storage.setItem(this.storageKey, JSON.stringify(this.session));
|
|
356
|
+
else
|
|
357
|
+
await this.storage.removeItem(this.storageKey);
|
|
358
|
+
}
|
|
359
|
+
catch { }
|
|
360
|
+
this.writeCookie();
|
|
361
|
+
}
|
|
362
|
+
writeCookie() {
|
|
363
|
+
if (!this.cookie)
|
|
364
|
+
return;
|
|
365
|
+
try {
|
|
366
|
+
const secure = g.location?.protocol === 'https:' ? '; Secure' : '';
|
|
367
|
+
if (this.session) {
|
|
368
|
+
const maxAge = Math.max(0, this.session.expires_at - nowSec());
|
|
369
|
+
g.document.cookie = `${COOKIE_NAME}=${encodeURIComponent(this.session.access_token)}; Path=/; Max-Age=${maxAge}; SameSite=Lax${secure}`;
|
|
370
|
+
}
|
|
371
|
+
else {
|
|
372
|
+
g.document.cookie = `${COOKIE_NAME}=; Path=/; Max-Age=0; SameSite=Lax${secure}`;
|
|
373
|
+
}
|
|
374
|
+
// Remove the cookie name used before the rename to usebecky.
|
|
375
|
+
if (/(?:^|;\s*)yb-access-token=/.test(String(g.document.cookie)))
|
|
376
|
+
g.document.cookie = `yb-access-token=; Path=/; Max-Age=0; SameSite=Lax${secure}`;
|
|
377
|
+
}
|
|
378
|
+
catch { }
|
|
379
|
+
}
|
|
380
|
+
async readStored() {
|
|
381
|
+
try {
|
|
382
|
+
const v = await this.storage.getItem(this.storageKey);
|
|
383
|
+
return typeof v === 'string' ? normalizeSession(safeParse(v)) : null;
|
|
384
|
+
}
|
|
385
|
+
catch {
|
|
386
|
+
return this.session;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/** Keep tabs in sync: another tab signed in, refreshed or signed out. */
|
|
390
|
+
watchOtherTabs() {
|
|
391
|
+
if (!inBrowser() || typeof g.addEventListener !== 'function')
|
|
392
|
+
return;
|
|
393
|
+
try {
|
|
394
|
+
g.addEventListener('storage', (e) => {
|
|
395
|
+
if (e.key !== this.storageKey)
|
|
396
|
+
return;
|
|
397
|
+
const next = typeof e.newValue === 'string' ? normalizeSession(safeParse(e.newValue)) : null;
|
|
398
|
+
const prev = this.session;
|
|
399
|
+
if (!next && prev) {
|
|
400
|
+
this.session = null;
|
|
401
|
+
this.clearTimer();
|
|
402
|
+
this.writeCookie();
|
|
403
|
+
this.emit('SIGNED_OUT');
|
|
404
|
+
}
|
|
405
|
+
else if (next && next.access_token !== prev?.access_token) {
|
|
406
|
+
this.session = next;
|
|
407
|
+
this.scheduleRefresh();
|
|
408
|
+
this.writeCookie();
|
|
409
|
+
this.emit(prev && prev.user?.id === next.user?.id ? 'TOKEN_REFRESHED' : 'SIGNED_IN');
|
|
410
|
+
}
|
|
411
|
+
});
|
|
412
|
+
g.document?.addEventListener?.('visibilitychange', () => {
|
|
413
|
+
if (g.document.visibilityState === 'visible' && this.session && this.autoRefresh && this.session.expires_at - nowSec() < 60)
|
|
414
|
+
void this.refreshSession();
|
|
415
|
+
});
|
|
416
|
+
}
|
|
417
|
+
catch { }
|
|
418
|
+
}
|
|
419
|
+
// ---- refresh ------------------------------------------------------------------------------
|
|
420
|
+
clearTimer() {
|
|
421
|
+
if (this.refreshTimer)
|
|
422
|
+
clearTimeout(this.refreshTimer);
|
|
423
|
+
this.refreshTimer = null;
|
|
424
|
+
}
|
|
425
|
+
scheduleRefresh(delayMs) {
|
|
426
|
+
this.clearTimer();
|
|
427
|
+
if (!this.autoRefresh || !this.session)
|
|
428
|
+
return;
|
|
429
|
+
let ms = delayMs;
|
|
430
|
+
if (ms === undefined) {
|
|
431
|
+
const lifetime = Math.max(1, this.session.expires_in || 3600) * 1000;
|
|
432
|
+
const margin = Math.min(60_000, lifetime / 4);
|
|
433
|
+
ms = this.session.expires_at * 1000 - Date.now() - margin;
|
|
434
|
+
}
|
|
435
|
+
this.refreshTimer = setTimeout(() => void this.refreshSession(), Math.max(0, Math.min(ms, 2_147_000_000)));
|
|
436
|
+
this.refreshTimer?.unref?.();
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Get a new access token now. Concurrent calls share one request, and only one browser tab
|
|
440
|
+
* refreshes at a time (the others pick up its result).
|
|
441
|
+
*/
|
|
442
|
+
refreshSession() {
|
|
443
|
+
if (this.refreshPromise)
|
|
444
|
+
return this.refreshPromise;
|
|
445
|
+
this.refreshPromise = this.withLock(() => this.doRefresh()).finally(() => {
|
|
446
|
+
this.refreshPromise = null;
|
|
447
|
+
});
|
|
448
|
+
return this.refreshPromise;
|
|
449
|
+
}
|
|
450
|
+
async withLock(fn) {
|
|
451
|
+
const locks = g.navigator?.locks;
|
|
452
|
+
if (!locks || typeof locks.request !== 'function')
|
|
453
|
+
return fn();
|
|
454
|
+
let ran = false;
|
|
455
|
+
try {
|
|
456
|
+
const signal = typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function' ? AbortSignal.timeout(10_000) : undefined;
|
|
457
|
+
return await locks.request(`ub-auth-refresh:${this.storageKey}`, signal ? { signal } : {}, () => {
|
|
458
|
+
ran = true;
|
|
459
|
+
return fn();
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
catch (err) {
|
|
463
|
+
if (ran)
|
|
464
|
+
throw err;
|
|
465
|
+
return fn(); // lock unavailable or timed out: refresh anyway
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
async doRefresh() {
|
|
469
|
+
const current = this.session;
|
|
470
|
+
if (!current)
|
|
471
|
+
return { data: { session: null }, error: null };
|
|
472
|
+
// Another tab (sharing storage) may have refreshed or signed out already.
|
|
473
|
+
const stored = await this.readStored();
|
|
474
|
+
if (stored !== current && JSON.stringify(stored) !== JSON.stringify(current)) {
|
|
475
|
+
if (!stored) {
|
|
476
|
+
this.session = null;
|
|
477
|
+
this.clearTimer();
|
|
478
|
+
this.writeCookie();
|
|
479
|
+
this.emit('SIGNED_OUT');
|
|
480
|
+
return { data: { session: null }, error: null };
|
|
481
|
+
}
|
|
482
|
+
if (stored.refresh_token !== current.refresh_token && stored.expires_at - nowSec() > 30) {
|
|
483
|
+
this.session = stored;
|
|
484
|
+
this.scheduleRefresh();
|
|
485
|
+
this.writeCookie();
|
|
486
|
+
this.emit('TOKEN_REFRESHED');
|
|
487
|
+
return { data: { session: stored }, error: null };
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
const res = await this.http.request('/auth/v1/token', {
|
|
491
|
+
method: 'POST',
|
|
492
|
+
query: { grant_type: 'refresh_token' },
|
|
493
|
+
body: { refresh_token: current.refresh_token },
|
|
494
|
+
token: null,
|
|
495
|
+
});
|
|
496
|
+
if (res.error) {
|
|
497
|
+
if (res.error.status === 0 || res.error.status >= 500 || res.error.status === 429) {
|
|
498
|
+
// Offline or server hiccup: keep the session and try again later.
|
|
499
|
+
const delay = RETRY_DELAYS[Math.min(this.retryCount, RETRY_DELAYS.length - 1)];
|
|
500
|
+
this.retryCount++;
|
|
501
|
+
this.scheduleRefresh(delay);
|
|
502
|
+
return { data: null, error: res.error };
|
|
503
|
+
}
|
|
504
|
+
this.retryCount = 0;
|
|
505
|
+
await this.setSession(null, 'SIGNED_OUT');
|
|
506
|
+
return { data: null, error: res.error };
|
|
507
|
+
}
|
|
508
|
+
this.retryCount = 0;
|
|
509
|
+
const session = normalizeSession(res.data);
|
|
510
|
+
if (!session)
|
|
511
|
+
return { data: null, error: new UseBeckyError({ code: 'invalid_response', message: 'The server returned an unexpected response while refreshing the session.', status: res.status }) };
|
|
512
|
+
await this.setSession(session, 'TOKEN_REFRESHED');
|
|
513
|
+
return { data: { session }, error: null };
|
|
514
|
+
}
|
|
515
|
+
// ---- sign in / out -------------------------------------------------------------------------
|
|
516
|
+
async sessionResult(res, event) {
|
|
517
|
+
if (res.error)
|
|
518
|
+
return { data: null, error: res.error };
|
|
519
|
+
const session = normalizeSession(res.data);
|
|
520
|
+
if (!session)
|
|
521
|
+
return { data: null, error: new UseBeckyError({ code: 'invalid_response', message: 'The server did not return a session.', status: 500 }) };
|
|
522
|
+
await this.setSession(session, event);
|
|
523
|
+
const out = { user: session.user, session };
|
|
524
|
+
if (res.data?.mfa_required || session.mfa_required)
|
|
525
|
+
out.mfaRequired = true;
|
|
526
|
+
return { data: out, error: null };
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Create an account. `session` is null when the project requires email confirmation.
|
|
530
|
+
* `captchaToken`: the token from the Turnstile / hCaptcha widget, when bot protection is on
|
|
531
|
+
* (Dashboard → Auth → Settings). Without it you get `error.code === 'captcha_required'`.
|
|
532
|
+
* `locale`: the language of the confirmation email, like `'de'` (default: the user's browser language).
|
|
533
|
+
*/
|
|
534
|
+
async signUp(credentials) {
|
|
535
|
+
await this.ready;
|
|
536
|
+
const res = await this.http.request('/auth/v1/signup', {
|
|
537
|
+
method: 'POST',
|
|
538
|
+
token: null,
|
|
539
|
+
body: {
|
|
540
|
+
email: credentials.email,
|
|
541
|
+
password: credentials.password,
|
|
542
|
+
data: credentials.data,
|
|
543
|
+
redirect_to: credentials.redirectTo ?? defaultRedirect(),
|
|
544
|
+
captcha_token: credentials.captchaToken,
|
|
545
|
+
...localeField(credentials.locale, 'signUp({ locale })'),
|
|
546
|
+
// The visitor's consent state, for a server-side tagging extension (sign_up). Undefined: not sent.
|
|
547
|
+
consent: await this.consentRef(),
|
|
548
|
+
},
|
|
549
|
+
});
|
|
550
|
+
if (res.error)
|
|
551
|
+
return { data: null, error: res.error };
|
|
552
|
+
const session = normalizeSession(res.data?.session);
|
|
553
|
+
if (session)
|
|
554
|
+
await this.setSession(session, 'SIGNED_IN');
|
|
555
|
+
return { data: { user: res.data?.user ?? session?.user ?? null, session }, error: null };
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Sign in with email + password. If `data.mfaRequired`, ask for a code and call `mfa.verify()`.
|
|
559
|
+
* Pass `captchaToken` when bot protection is on.
|
|
560
|
+
*/
|
|
561
|
+
async signIn(credentials) {
|
|
562
|
+
await this.ready;
|
|
563
|
+
const res = await this.http.request('/auth/v1/token', {
|
|
564
|
+
method: 'POST',
|
|
565
|
+
query: { grant_type: 'password' },
|
|
566
|
+
token: null,
|
|
567
|
+
body: { email: credentials.email, password: credentials.password, captcha_token: credentials.captchaToken },
|
|
568
|
+
});
|
|
569
|
+
return this.sessionResult(res, 'SIGNED_IN');
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Sign in with Google, GitHub or Apple. In a browser this redirects to the provider and
|
|
573
|
+
* back to `redirectTo` (default: the current page). Elsewhere it returns the URL to open.
|
|
574
|
+
*
|
|
575
|
+
* Uses PKCE: the server sends back a one-time `?code=` (never tokens in the URL) and this client swaps
|
|
576
|
+
* it for a session with a secret it kept in `storage` — automatically in a browser, or with
|
|
577
|
+
* `setSessionFromUrl(url)` in a React Native / Expo app. `flowType: 'implicit'` uses the older flow
|
|
578
|
+
* (tokens in the `#fragment`); it is also used when the runtime has no `crypto.getRandomValues`.
|
|
579
|
+
*/
|
|
580
|
+
async signInWith(provider, options = {}) {
|
|
581
|
+
const params = new URLSearchParams({ provider: String(provider), apikey: this.http.key });
|
|
582
|
+
const redirectTo = options.redirectTo ?? defaultRedirect();
|
|
583
|
+
if (redirectTo)
|
|
584
|
+
params.set('redirect_to', redirectTo);
|
|
585
|
+
// The visitor's consent state (server-side tagging) is not put in this address: anyone could craft such a link.
|
|
586
|
+
// It is sent with the code exchange below, which only this app can make (it holds the code verifier).
|
|
587
|
+
if (options.flowType !== 'implicit') {
|
|
588
|
+
const pkce = await createPkcePair();
|
|
589
|
+
if (pkce) {
|
|
590
|
+
try {
|
|
591
|
+
await this.storage.setItem(this.verifierKey, pkce.verifier);
|
|
592
|
+
await this.storage.removeItem(this.linkKey); // a sign-in, not a link
|
|
593
|
+
params.set('code_challenge', pkce.challenge);
|
|
594
|
+
params.set('code_challenge_method', 'S256');
|
|
595
|
+
}
|
|
596
|
+
catch { }
|
|
597
|
+
}
|
|
598
|
+
else if (!warnedNoPkce) {
|
|
599
|
+
warnedNoPkce = true;
|
|
600
|
+
try {
|
|
601
|
+
g.console?.warn?.('[usebecky] crypto.getRandomValues is not available, so social sign-in uses the older redirect flow (tokens in the URL). In React Native, install react-native-get-random-values and import it first in your entry file.');
|
|
602
|
+
}
|
|
603
|
+
catch { }
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
const url = `${this.http.url}/auth/v1/authorize?${params.toString()}`;
|
|
607
|
+
if (!options.skipBrowserRedirect && inBrowser() && typeof g.location?.assign === 'function')
|
|
608
|
+
g.location.assign(url);
|
|
609
|
+
return { data: { provider: String(provider), url }, error: null };
|
|
610
|
+
}
|
|
611
|
+
/**
|
|
612
|
+
* Sign in with an ID token from a native sign-in SDK: Sign in with Apple (iOS / macOS) or Google
|
|
613
|
+
* Sign-In / Credential Manager (Android, iOS). Pass the raw `nonce` if you used one (Apple: you gave
|
|
614
|
+
* Apple its SHA-256). The token's audience (your bundle ID or client ID) must be listed in
|
|
615
|
+
* Dashboard → Auth → Sign-in methods → "iOS bundle ID / Android client IDs (for native sign-in)".
|
|
616
|
+
*
|
|
617
|
+
* await baas.auth.signInWithIdToken({ provider: 'apple', token: identityToken, nonce: rawNonce })
|
|
618
|
+
*/
|
|
619
|
+
async signInWithIdToken(credentials) {
|
|
620
|
+
await this.ready;
|
|
621
|
+
const res = await this.http.request('/auth/v1/token', {
|
|
622
|
+
method: 'POST',
|
|
623
|
+
query: { grant_type: 'id_token' },
|
|
624
|
+
token: null,
|
|
625
|
+
// `consent`: only used when this creates the account (sign_up for a server-side tagging extension).
|
|
626
|
+
body: { provider: credentials.provider, id_token: credentials.token, nonce: credentials.nonce, consent: await this.consentRef() },
|
|
627
|
+
});
|
|
628
|
+
return this.sessionResult(res, 'SIGNED_IN');
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* Email a sign-in link (and a 6-digit code you can pass to `verifyCode`).
|
|
632
|
+
* Pass `createUser: true` to also let new people sign up this way, and `captchaToken` when bot
|
|
633
|
+
* protection is on. `locale`: the email's language, like `'de'` (default: the user's saved or browser language).
|
|
634
|
+
*/
|
|
635
|
+
async sendMagicLink(email, options = {}) {
|
|
636
|
+
const res = await this.http.request('/auth/v1/magiclink', {
|
|
637
|
+
method: 'POST',
|
|
638
|
+
token: null,
|
|
639
|
+
body: {
|
|
640
|
+
email,
|
|
641
|
+
redirect_to: options.redirectTo ?? defaultRedirect(),
|
|
642
|
+
create_user: options.createUser,
|
|
643
|
+
captcha_token: options.captchaToken,
|
|
644
|
+
...localeField(options.locale, 'sendMagicLink({ locale })'),
|
|
645
|
+
// Only matters when this creates the account (sign_up for a server-side tagging extension).
|
|
646
|
+
consent: options.createUser ? await this.consentRef() : undefined,
|
|
647
|
+
},
|
|
648
|
+
});
|
|
649
|
+
return res.error ? { data: null, error: res.error } : { data: {}, error: null };
|
|
650
|
+
}
|
|
651
|
+
/** Sign in with the 6-digit code from an email. */
|
|
652
|
+
async verifyCode(email, code, type = 'magiclink') {
|
|
653
|
+
await this.ready;
|
|
654
|
+
const res = await this.http.request('/auth/v1/verify', { method: 'POST', token: null, body: { email, token: String(code).trim(), type } });
|
|
655
|
+
return this.sessionResult(res, type === 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN');
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Email a password-reset link. After the redirect you get `PASSWORD_RECOVERY`; then call `updateUser({ password })`.
|
|
659
|
+
* Pass `captchaToken` when bot protection is on. `locale`: the email's language, like `'de'`.
|
|
660
|
+
*/
|
|
661
|
+
async resetPassword(email, options = {}) {
|
|
662
|
+
const res = await this.http.request('/auth/v1/recover', {
|
|
663
|
+
method: 'POST',
|
|
664
|
+
token: null,
|
|
665
|
+
body: { email, redirect_to: options.redirectTo ?? defaultRedirect(), captcha_token: options.captchaToken, ...localeField(options.locale, 'resetPassword({ locale })') },
|
|
666
|
+
});
|
|
667
|
+
return res.error ? { data: null, error: res.error } : { data: {}, error: null };
|
|
668
|
+
}
|
|
669
|
+
/** Resend the confirmation or magic-link email. `locale`: the email's language, like `'de'`. */
|
|
670
|
+
async resend(email, type = 'signup', options = {}) {
|
|
671
|
+
const res = await this.http.request('/auth/v1/resend', { method: 'POST', token: null, body: { email, type, ...localeField(options.locale, 'resend(…, { locale })') } });
|
|
672
|
+
return res.error ? { data: null, error: res.error } : { data: {}, error: null };
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Change the signed-in user's email, password or metadata (`data`). `locale`: the language of the
|
|
676
|
+
* email-change confirmation, like `'de'`. To remember a language for all later emails, save it in
|
|
677
|
+
* `data`: `updateUser({ data: { locale: 'de' } })`.
|
|
678
|
+
*/
|
|
679
|
+
async updateUser(attrs) {
|
|
680
|
+
const token = await this.getAccessToken();
|
|
681
|
+
if (!token)
|
|
682
|
+
return { data: null, error: notSignedIn() };
|
|
683
|
+
const { locale, ...rest } = attrs;
|
|
684
|
+
const res = await this.http.request('/auth/v1/user', { method: 'PUT', token, body: { ...rest, ...localeField(locale, 'updateUser({ locale })') } });
|
|
685
|
+
if (res.error || !res.data)
|
|
686
|
+
return { data: null, error: res.error ?? notSignedIn() };
|
|
687
|
+
if (this.session)
|
|
688
|
+
await this.setSession({ ...this.session, user: res.data }, 'USER_UPDATED');
|
|
689
|
+
return { data: { user: res.data }, error: null };
|
|
690
|
+
}
|
|
691
|
+
/** Sign out on this device (or `{ everywhere: true }` for all devices). */
|
|
692
|
+
async signOut(options = {}) {
|
|
693
|
+
await this.ready;
|
|
694
|
+
const token = this.session?.access_token;
|
|
695
|
+
let error = null;
|
|
696
|
+
if (token) {
|
|
697
|
+
const res = await this.http.request('/auth/v1/logout', { method: 'POST', query: { scope: options.everywhere ? 'global' : 'local' }, token, parse: 'none' });
|
|
698
|
+
// An expired/revoked session is already signed out on the server; that's fine.
|
|
699
|
+
if (res.error && res.error.status !== 401 && res.error.status !== 403 && res.error.status !== 404)
|
|
700
|
+
error = res.error;
|
|
701
|
+
}
|
|
702
|
+
this.clearTimer();
|
|
703
|
+
await this.setSession(null, 'SIGNED_OUT');
|
|
704
|
+
return { data: null, error };
|
|
705
|
+
}
|
|
706
|
+
/** The signed-in user, fresh from the server. `user` is null when signed out. */
|
|
707
|
+
async getUser() {
|
|
708
|
+
const token = await this.getAccessToken();
|
|
709
|
+
if (!token)
|
|
710
|
+
return { data: { user: null }, error: null };
|
|
711
|
+
const res = await this.http.request('/auth/v1/user', { token });
|
|
712
|
+
if (res.error)
|
|
713
|
+
return { data: null, error: res.error };
|
|
714
|
+
if (this.session && res.data && JSON.stringify(this.session.user) !== JSON.stringify(res.data)) {
|
|
715
|
+
this.session = { ...this.session, user: res.data };
|
|
716
|
+
await this.persist();
|
|
717
|
+
}
|
|
718
|
+
return { data: { user: res.data }, error: null };
|
|
719
|
+
}
|
|
720
|
+
/** Use tokens you got elsewhere (e.g. a deep link in a mobile app). */
|
|
721
|
+
async setSessionTokens(tokens) {
|
|
722
|
+
await this.ready;
|
|
723
|
+
const session = normalizeSession(tokens);
|
|
724
|
+
if (!session)
|
|
725
|
+
return { data: null, error: new UseBeckyError({ code: 'invalid_session', message: 'That is not a valid access token.', status: 400 }) };
|
|
726
|
+
this.session = session;
|
|
727
|
+
await this.fetchFullUser();
|
|
728
|
+
await this.setSession(this.session, 'SIGNED_IN');
|
|
729
|
+
return { data: { session: this.session }, error: null };
|
|
730
|
+
}
|
|
731
|
+
/**
|
|
732
|
+
* Finish a redirect sign-in from a URL you received yourself (React Native / Expo deep links).
|
|
733
|
+
* Handles both the PKCE `?code=` (social sign-in) and `#access_token=` (email links). In browsers this
|
|
734
|
+
* happens automatically.
|
|
735
|
+
*/
|
|
736
|
+
async setSessionFromUrl(url) {
|
|
737
|
+
await this.ready;
|
|
738
|
+
const query = new URLSearchParams(url.split('#')[0].split('?')[1] ?? '');
|
|
739
|
+
const code = query.get('code');
|
|
740
|
+
const queryError = redirectError(query);
|
|
741
|
+
if (queryError) {
|
|
742
|
+
await this.removeVerifier();
|
|
743
|
+
return { data: null, error: queryError };
|
|
744
|
+
}
|
|
745
|
+
if (code)
|
|
746
|
+
return this.exchangeCodeForSession(code);
|
|
747
|
+
const hash = url.includes('#') ? url.slice(url.indexOf('#') + 1) : url.includes('?') ? url.slice(url.indexOf('?') + 1) : '';
|
|
748
|
+
const result = this.sessionFromParams(new URLSearchParams(hash));
|
|
749
|
+
if (result.error || !result.session)
|
|
750
|
+
return { data: null, error: result.error ?? new UseBeckyError({ code: 'invalid_redirect', message: 'No session in that URL.', status: 400 }) };
|
|
751
|
+
this.session = result.session;
|
|
752
|
+
await this.fetchFullUser();
|
|
753
|
+
await this.setSession(this.session, result.type === 'recovery' ? 'PASSWORD_RECOVERY' : 'SIGNED_IN');
|
|
754
|
+
return { data: { session: this.session }, error: null };
|
|
755
|
+
}
|
|
756
|
+
/**
|
|
757
|
+
* Swap the one-time `code` from a social sign-in redirect (`redirectTo?code=...`) for a session, using
|
|
758
|
+
* the PKCE verifier that `signInWith()` kept. Usually you call `setSessionFromUrl(url)` instead, which
|
|
759
|
+
* calls this. Codes work once, for 5 minutes, and only in the app that started the sign-in.
|
|
760
|
+
*/
|
|
761
|
+
async exchangeCodeForSession(authCode) {
|
|
762
|
+
await this.ready;
|
|
763
|
+
const code = typeof authCode === 'string' ? authCode.trim() : '';
|
|
764
|
+
if (!code)
|
|
765
|
+
return { data: null, error: new UseBeckyError({ code: 'auth_code_required', message: 'Pass the "code" from the sign-in redirect.', status: 400 }) };
|
|
766
|
+
const verifier = await this.readVerifier();
|
|
767
|
+
if (!verifier) {
|
|
768
|
+
return {
|
|
769
|
+
data: null,
|
|
770
|
+
error: new UseBeckyError({
|
|
771
|
+
code: 'invalid_code_verifier',
|
|
772
|
+
message: 'This sign-in was not started in this app, or it was already finished.',
|
|
773
|
+
hint: 'Start the sign-in again with baas.auth.signInWith() in this app and use the same client (and storage) for setSessionFromUrl().',
|
|
774
|
+
status: 400,
|
|
775
|
+
}),
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
const res = await this.exchangeCode(code, verifier);
|
|
779
|
+
if (!res.session)
|
|
780
|
+
return { data: null, error: res.error ?? new UseBeckyError({ code: 'invalid_response', message: 'The server did not return a session.', status: 500 }) };
|
|
781
|
+
await this.setSession(res.session, 'SIGNED_IN');
|
|
782
|
+
return { data: { session: res.session }, error: null };
|
|
783
|
+
}
|
|
784
|
+
// ---- Passkeys -------------------------------------------------------------------------------
|
|
785
|
+
/**
|
|
786
|
+
* Sign in with a passkey: the browser shows the passkeys saved for this site, no email needed.
|
|
787
|
+
* `autofill: true` waits for the person to pick a passkey from the email field's autofill list (add
|
|
788
|
+
* `autocomplete="username webauthn"` to that input); cancel it with `signal`.
|
|
789
|
+
*/
|
|
790
|
+
async signInWithPasskey(options = {}) {
|
|
791
|
+
await this.ready;
|
|
792
|
+
const o = await this.http.request('/auth/v1/passkeys/authenticate/options', { method: 'POST', token: null, body: {} });
|
|
793
|
+
if (o.error || !o.data)
|
|
794
|
+
return { data: null, error: o.error ?? invalidResponse() };
|
|
795
|
+
let credential;
|
|
796
|
+
try {
|
|
797
|
+
credential = await getCredential(o.data.options, { custom: options.get, autofill: options.autofill, signal: options.signal });
|
|
798
|
+
}
|
|
799
|
+
catch (err) {
|
|
800
|
+
return { data: null, error: asError(err) };
|
|
801
|
+
}
|
|
802
|
+
const res = await this.http.request('/auth/v1/passkeys/authenticate', { method: 'POST', token: null, body: { challenge_id: o.data.challenge_id, credential } });
|
|
803
|
+
if (res.error?.code === 'passkey_not_found')
|
|
804
|
+
forgetUnknownPasskey(o.data.options.rpId, credential.id);
|
|
805
|
+
return this.sessionResult(res, 'SIGNED_IN');
|
|
806
|
+
}
|
|
807
|
+
async passkeyRegister(options = {}) {
|
|
808
|
+
const token = await this.getAccessToken();
|
|
809
|
+
if (!token)
|
|
810
|
+
return { data: null, error: notSignedIn() };
|
|
811
|
+
const o = await this.http.request('/auth/v1/passkeys/register/options', { method: 'POST', token, body: {} });
|
|
812
|
+
if (o.error || !o.data)
|
|
813
|
+
return { data: null, error: o.error ?? invalidResponse() };
|
|
814
|
+
let credential;
|
|
815
|
+
try {
|
|
816
|
+
credential = await createCredential(o.data.options, options.create);
|
|
817
|
+
}
|
|
818
|
+
catch (err) {
|
|
819
|
+
return { data: null, error: asError(err) };
|
|
820
|
+
}
|
|
821
|
+
const res = await this.http.request('/auth/v1/passkeys/register', { method: 'POST', token, body: { challenge_id: o.data.challenge_id, credential, friendly_name: options.friendlyName } });
|
|
822
|
+
if (res.error || !res.data)
|
|
823
|
+
return { data: null, error: res.error ?? invalidResponse() };
|
|
824
|
+
const session = normalizeSession(res.data.session);
|
|
825
|
+
if (session)
|
|
826
|
+
await this.setSession(session, 'USER_UPDATED');
|
|
827
|
+
return { data: { passkey: res.data.passkey }, error: null };
|
|
828
|
+
}
|
|
829
|
+
async passkeyList() {
|
|
830
|
+
const token = await this.getAccessToken();
|
|
831
|
+
if (!token)
|
|
832
|
+
return { data: null, error: notSignedIn() };
|
|
833
|
+
const res = await this.http.request('/auth/v1/passkeys', { token });
|
|
834
|
+
return res.error ? { data: null, error: res.error } : { data: { passkeys: res.data?.passkeys ?? [] }, error: null };
|
|
835
|
+
}
|
|
836
|
+
async passkeyRename(id, friendlyName) {
|
|
837
|
+
const token = await this.getAccessToken();
|
|
838
|
+
if (!token)
|
|
839
|
+
return { data: null, error: notSignedIn() };
|
|
840
|
+
const res = await this.http.request(`/auth/v1/passkeys/${encodeURIComponent(id)}`, { method: 'PATCH', token, body: { friendly_name: friendlyName } });
|
|
841
|
+
return res.error ? { data: null, error: res.error } : { data: { passkey: res.data }, error: null };
|
|
842
|
+
}
|
|
843
|
+
async passkeyRemove(id) {
|
|
844
|
+
const token = await this.getAccessToken();
|
|
845
|
+
if (!token)
|
|
846
|
+
return { data: null, error: notSignedIn() };
|
|
847
|
+
const res = await this.http.request(`/auth/v1/passkeys/${encodeURIComponent(id)}`, { method: 'DELETE', token });
|
|
848
|
+
return res.error ? { data: null, error: res.error } : { data: { id: res.data?.id ?? id }, error: null };
|
|
849
|
+
}
|
|
850
|
+
// ---- Phone (text-message codes) ---------------------------------------------------------------
|
|
851
|
+
/**
|
|
852
|
+
* Text a 6-digit sign-in code to a phone number (with country code, like `+49 170 1234567`), then call
|
|
853
|
+
* `verifyPhone(phone, code)`. New numbers get an account on verify unless `createUser: false`.
|
|
854
|
+
* Turn it on in Dashboard → Auth → Sign-in methods → Phone. Pass `captchaToken` when bot protection is on.
|
|
855
|
+
*/
|
|
856
|
+
async signInWithPhone(phone, options = {}) {
|
|
857
|
+
const res = await this.http.request('/auth/v1/phone/otp', { method: 'POST', token: null, body: { phone, create_user: options.createUser, captcha_token: options.captchaToken } });
|
|
858
|
+
return res.error ? { data: null, error: res.error } : { data: {}, error: null };
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Finish phone sign-in with the code from the text message. `type: 'phone_change'` finishes
|
|
862
|
+
* `updatePhone()` for the signed-in user instead.
|
|
863
|
+
*/
|
|
864
|
+
async verifyPhone(phone, code, options = {}) {
|
|
865
|
+
await this.ready;
|
|
866
|
+
if (options.type === 'phone_change') {
|
|
867
|
+
const token = await this.getAccessToken();
|
|
868
|
+
if (!token)
|
|
869
|
+
return { data: null, error: notSignedIn() };
|
|
870
|
+
const res = await this.http.request('/auth/v1/phone/change/verify', { method: 'POST', token, body: { phone, code: String(code).trim() } });
|
|
871
|
+
return this.sessionResult(res, 'USER_UPDATED');
|
|
872
|
+
}
|
|
873
|
+
// `consent`: only used when this creates the account (sign_up for a server-side tagging extension).
|
|
874
|
+
const res = await this.http.request('/auth/v1/phone/verify', { method: 'POST', token: null, body: { phone, code: String(code).trim(), consent: await this.consentRef() } });
|
|
875
|
+
return this.sessionResult(res, 'SIGNED_IN');
|
|
876
|
+
}
|
|
877
|
+
/** Change the signed-in user's phone number: texts a code to the new number. Then `verifyPhone(phone, code, { type: 'phone_change' })`. */
|
|
878
|
+
async updatePhone(phone, options = {}) {
|
|
879
|
+
const token = await this.getAccessToken();
|
|
880
|
+
if (!token)
|
|
881
|
+
return { data: null, error: notSignedIn() };
|
|
882
|
+
const res = await this.http.request('/auth/v1/phone/change', { method: 'POST', token, body: { phone, captcha_token: options.captchaToken } });
|
|
883
|
+
return res.error ? { data: null, error: res.error } : { data: {}, error: null };
|
|
884
|
+
}
|
|
885
|
+
// ---- Guests and linking -----------------------------------------------------------------------
|
|
886
|
+
/**
|
|
887
|
+
* Sign in as a guest: a real user (with an id your tables and access rules can use) but no email or password
|
|
888
|
+
* yet. Later, `linkEmail()`, `linkIdentity()` or `passkeys.register()` keep the same user and data.
|
|
889
|
+
* Turn guests on in Dashboard → Auth → Sign-in methods → Guests.
|
|
890
|
+
*/
|
|
891
|
+
async signInAnonymously(options = {}) {
|
|
892
|
+
await this.ready;
|
|
893
|
+
const res = await this.http.request('/auth/v1/anonymous', { method: 'POST', token: null, body: { data: options.data, captcha_token: options.captchaToken } });
|
|
894
|
+
return this.sessionResult(res, 'SIGNED_IN');
|
|
895
|
+
}
|
|
896
|
+
/** Give the signed-in user (usually a guest) an email and password. Same user id; a confirmation email is sent when the project asks for one. */
|
|
897
|
+
async linkEmail(credentials) {
|
|
898
|
+
const token = await this.getAccessToken();
|
|
899
|
+
if (!token)
|
|
900
|
+
return { data: null, error: notSignedIn() };
|
|
901
|
+
const res = await this.http.request('/auth/v1/link/email', { method: 'POST', token, body: { email: credentials.email, password: credentials.password, redirect_to: credentials.redirectTo ?? defaultRedirect() } });
|
|
902
|
+
return this.sessionResult(res, 'USER_UPDATED');
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Add a social account (Google, GitHub, Apple, ...) to the signed-in user, keeping the same user id. In a
|
|
906
|
+
* browser this redirects to the provider and back to `redirectTo`, where the session is picked up like after
|
|
907
|
+
* `signInWith()`. Elsewhere it returns the URL to open (finish with `setSessionFromUrl(url)`).
|
|
908
|
+
*/
|
|
909
|
+
async linkIdentity(provider, options = {}) {
|
|
910
|
+
const token = await this.getAccessToken();
|
|
911
|
+
if (!token)
|
|
912
|
+
return { data: null, error: notSignedIn() };
|
|
913
|
+
// Linking always uses PKCE: the server links only when this client (verifier) and this user (token) finish it.
|
|
914
|
+
const pkce = await createPkcePair();
|
|
915
|
+
if (!pkce) {
|
|
916
|
+
return {
|
|
917
|
+
data: null,
|
|
918
|
+
error: new UseBeckyError({ code: 'pkce_unavailable', message: "Linking accounts needs crypto.getRandomValues, which this runtime doesn't have.", hint: 'In React Native, install react-native-get-random-values and import it first in your entry file.', status: 0 }),
|
|
919
|
+
};
|
|
920
|
+
}
|
|
921
|
+
try {
|
|
922
|
+
await this.storage.setItem(this.verifierKey, pkce.verifier);
|
|
923
|
+
await this.storage.setItem(this.linkKey, '1');
|
|
924
|
+
}
|
|
925
|
+
catch { }
|
|
926
|
+
const res = await this.http.request('/auth/v1/link/authorize', {
|
|
927
|
+
method: 'POST',
|
|
928
|
+
token,
|
|
929
|
+
body: { provider, redirect_to: options.redirectTo ?? defaultRedirect(), code_challenge: pkce.challenge, code_challenge_method: 'S256' },
|
|
930
|
+
});
|
|
931
|
+
if (res.error || !res.data?.url) {
|
|
932
|
+
await this.removeVerifier();
|
|
933
|
+
return { data: null, error: res.error ?? invalidResponse() };
|
|
934
|
+
}
|
|
935
|
+
if (!options.skipBrowserRedirect && inBrowser() && typeof g.location?.assign === 'function')
|
|
936
|
+
g.location.assign(res.data.url);
|
|
937
|
+
return { data: { provider: String(provider), url: res.data.url }, error: null };
|
|
938
|
+
}
|
|
939
|
+
/** Link a native Sign in with Apple / Google ID token to the signed-in user (see `signInWithIdToken`). */
|
|
940
|
+
async linkIdToken(credentials) {
|
|
941
|
+
const token = await this.getAccessToken();
|
|
942
|
+
if (!token)
|
|
943
|
+
return { data: null, error: notSignedIn() };
|
|
944
|
+
const res = await this.http.request('/auth/v1/link/id_token', { method: 'POST', token, body: { provider: credentials.provider, id_token: credentials.token, nonce: credentials.nonce } });
|
|
945
|
+
return this.sessionResult(res, 'USER_UPDATED');
|
|
946
|
+
}
|
|
947
|
+
// ---- Enterprise single sign-on (SAML) --------------------------------------------------------
|
|
948
|
+
/**
|
|
949
|
+
* Sign in with a company account (Okta, Microsoft Entra ID, Google Workspace, ...). Pass the work email or its
|
|
950
|
+
* domain (`{ domain: 'acme.com' }`), or the connection's `providerId`. Redirects like `signInWith()` (PKCE);
|
|
951
|
+
* elsewhere returns the URL to open. Set up connections in Dashboard → Auth → Single sign-on (Business plan).
|
|
952
|
+
*/
|
|
953
|
+
async signInWithSSO(options) {
|
|
954
|
+
const pkce = await createPkcePair();
|
|
955
|
+
if (pkce) {
|
|
956
|
+
try {
|
|
957
|
+
await this.storage.setItem(this.verifierKey, pkce.verifier);
|
|
958
|
+
await this.storage.removeItem(this.linkKey);
|
|
959
|
+
}
|
|
960
|
+
catch { }
|
|
961
|
+
}
|
|
962
|
+
const res = await this.http.request('/auth/v1/sso', {
|
|
963
|
+
method: 'POST',
|
|
964
|
+
token: null,
|
|
965
|
+
body: {
|
|
966
|
+
domain: options.domain,
|
|
967
|
+
provider_id: options.providerId,
|
|
968
|
+
redirect_to: options.redirectTo ?? defaultRedirect(),
|
|
969
|
+
...(pkce ? { code_challenge: pkce.challenge, code_challenge_method: 'S256' } : {}),
|
|
970
|
+
},
|
|
971
|
+
});
|
|
972
|
+
if (res.error || !res.data?.url) {
|
|
973
|
+
await this.removeVerifier();
|
|
974
|
+
return { data: null, error: res.error ?? invalidResponse() };
|
|
975
|
+
}
|
|
976
|
+
if (!options.skipBrowserRedirect && inBrowser() && typeof g.location?.assign === 'function')
|
|
977
|
+
g.location.assign(res.data.url);
|
|
978
|
+
return { data: { url: res.data.url }, error: null };
|
|
979
|
+
}
|
|
980
|
+
/** Which sign-in methods the project has turned on (for building a login screen). */
|
|
981
|
+
async settings() {
|
|
982
|
+
const res = await this.http.request('/auth/v1/settings', { token: null });
|
|
983
|
+
return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
|
|
984
|
+
}
|
|
985
|
+
// ---- MFA -----------------------------------------------------------------------------------
|
|
986
|
+
async mfaEnroll(options = {}) {
|
|
987
|
+
const token = await this.getAccessToken();
|
|
988
|
+
if (!token)
|
|
989
|
+
return { data: null, error: notSignedIn() };
|
|
990
|
+
const res = await this.http.request('/auth/v1/factors', { method: 'POST', token, body: { factor_type: 'totp', friendly_name: options.friendlyName } });
|
|
991
|
+
if (res.error)
|
|
992
|
+
return { data: null, error: res.error };
|
|
993
|
+
const d = res.data ?? {};
|
|
994
|
+
return { data: { id: d.id, type: 'totp', secret: d.totp?.secret ?? d.secret, uri: d.totp?.uri ?? d.uri }, error: null };
|
|
995
|
+
}
|
|
996
|
+
async mfaVerify(factorId, code) {
|
|
997
|
+
const token = await this.getAccessToken();
|
|
998
|
+
if (!token)
|
|
999
|
+
return { data: null, error: notSignedIn() };
|
|
1000
|
+
const res = await this.http.request(`/auth/v1/factors/${encodeURIComponent(factorId)}/verify`, { method: 'POST', token, body: { code: String(code).trim() } });
|
|
1001
|
+
return this.sessionResult(res, 'MFA_CHALLENGE_VERIFIED');
|
|
1002
|
+
}
|
|
1003
|
+
async mfaUnenroll(factorId) {
|
|
1004
|
+
const token = await this.getAccessToken();
|
|
1005
|
+
if (!token)
|
|
1006
|
+
return { data: null, error: notSignedIn() };
|
|
1007
|
+
const res = await this.http.request(`/auth/v1/factors/${encodeURIComponent(factorId)}`, { method: 'DELETE', token });
|
|
1008
|
+
if (res.error)
|
|
1009
|
+
return { data: null, error: res.error };
|
|
1010
|
+
await this.getUser();
|
|
1011
|
+
return { data: { id: res.data?.id ?? factorId }, error: null };
|
|
1012
|
+
}
|
|
1013
|
+
async mfaListFactors() {
|
|
1014
|
+
const r = await this.getUser();
|
|
1015
|
+
if (r.error)
|
|
1016
|
+
return { data: null, error: r.error };
|
|
1017
|
+
const all = r.data.user?.factors ?? [];
|
|
1018
|
+
return { data: { all, totp: all.filter((f) => f.type === 'totp' && f.status === 'verified') }, error: null };
|
|
1019
|
+
}
|
|
1020
|
+
assuranceLevel() {
|
|
1021
|
+
if (!this.session)
|
|
1022
|
+
return { currentLevel: null, nextLevel: null };
|
|
1023
|
+
const current = decodeJwt(this.session.access_token)?.aal ?? 'aal1';
|
|
1024
|
+
const hasVerified = this.session.mfa_required === true || (this.session.user.factors ?? []).some((f) => f.status === 'verified');
|
|
1025
|
+
return { currentLevel: current, nextLevel: hasVerified ? 'aal2' : current };
|
|
1026
|
+
}
|
|
1027
|
+
/** Stop timers (for tests / server-side scripts). */
|
|
1028
|
+
dispose() {
|
|
1029
|
+
this.clearTimer();
|
|
1030
|
+
this.listeners.clear();
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
/** The error the server put in a redirect (`error`, `error_code`, `error_description`), or null. */
|
|
1034
|
+
function redirectError(params) {
|
|
1035
|
+
const err = params.get('error') || params.get('error_code');
|
|
1036
|
+
if (!err && !params.get('error_description'))
|
|
1037
|
+
return null;
|
|
1038
|
+
return new UseBeckyError({
|
|
1039
|
+
code: err || 'auth_redirect_error',
|
|
1040
|
+
message: params.get('error_description')?.replace(/\+/g, ' ') || 'Sign-in did not complete.',
|
|
1041
|
+
hint: 'Try signing in again. If it keeps failing, check the redirect URLs in Dashboard → Auth → Settings.',
|
|
1042
|
+
status: 400,
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
function defaultRedirect() {
|
|
1046
|
+
try {
|
|
1047
|
+
const loc = g.location;
|
|
1048
|
+
if (inBrowser() && loc?.href)
|
|
1049
|
+
return String(loc.href).split('#')[0];
|
|
1050
|
+
}
|
|
1051
|
+
catch { }
|
|
1052
|
+
return undefined;
|
|
1053
|
+
}
|
|
1054
|
+
function safeParse(s) {
|
|
1055
|
+
try {
|
|
1056
|
+
return JSON.parse(s);
|
|
1057
|
+
}
|
|
1058
|
+
catch {
|
|
1059
|
+
return null;
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
function safeCall(fn, event, session) {
|
|
1063
|
+
try {
|
|
1064
|
+
fn(event, session);
|
|
1065
|
+
}
|
|
1066
|
+
catch (err) {
|
|
1067
|
+
try {
|
|
1068
|
+
g.console?.error?.('[usebecky] Error in onAuthStateChange callback:', err);
|
|
1069
|
+
}
|
|
1070
|
+
catch { }
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
function invalidResponse() {
|
|
1074
|
+
return new UseBeckyError({ code: 'invalid_response', message: 'The server returned an unexpected response.', status: 500 });
|
|
1075
|
+
}
|
|
1076
|
+
function asError(err) {
|
|
1077
|
+
return err instanceof UseBeckyError ? err : new UseBeckyError({ code: 'passkey_failed', message: err?.message ?? String(err), status: 0 });
|
|
1078
|
+
}
|
|
1079
|
+
export function notSignedIn() {
|
|
1080
|
+
return new UseBeckyError({ code: 'not_signed_in', message: 'You need to be signed in to do that.', hint: 'Sign in first (for example with baas.auth.signIn), then try again.', status: 401 });
|
|
1081
|
+
}
|