@koolbase/react-native 9.2.0 → 10.0.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.
Files changed (69) hide show
  1. package/CHANGELOG.md +1342 -0
  2. package/README.md +403 -568
  3. package/dist/{auth-storage.d.ts → cjs/auth-storage.d.ts} +1 -1
  4. package/dist/cjs/index.d.ts +19 -0
  5. package/dist/cjs/index.js +125 -0
  6. package/dist/cjs/package.json +3 -0
  7. package/dist/cjs/platform.d.ts +2 -0
  8. package/dist/cjs/platform.js +43 -0
  9. package/dist/esm/auth-storage.d.ts +26 -0
  10. package/dist/esm/auth-storage.js +100 -0
  11. package/dist/esm/index.d.ts +19 -0
  12. package/dist/esm/index.js +106 -0
  13. package/dist/esm/package.json +3 -0
  14. package/dist/esm/platform.d.ts +2 -0
  15. package/dist/esm/platform.js +37 -0
  16. package/package.json +30 -30
  17. package/dist/analytics.d.ts +0 -24
  18. package/dist/analytics.js +0 -114
  19. package/dist/apple-auth.d.ts +0 -22
  20. package/dist/apple-auth.js +0 -74
  21. package/dist/auth-errors.d.ts +0 -117
  22. package/dist/auth-errors.js +0 -250
  23. package/dist/auth.d.ts +0 -213
  24. package/dist/auth.js +0 -810
  25. package/dist/cache-store.d.ts +0 -50
  26. package/dist/cache-store.js +0 -197
  27. package/dist/code-push.d.ts +0 -59
  28. package/dist/code-push.js +0 -255
  29. package/dist/conflict.d.ts +0 -80
  30. package/dist/conflict.js +0 -84
  31. package/dist/database-errors.d.ts +0 -101
  32. package/dist/database-errors.js +0 -200
  33. package/dist/database.d.ts +0 -298
  34. package/dist/database.js +0 -852
  35. package/dist/device-id.d.ts +0 -1
  36. package/dist/device-id.js +0 -60
  37. package/dist/device-metadata.d.ts +0 -36
  38. package/dist/device-metadata.js +0 -102
  39. package/dist/errors.d.ts +0 -64
  40. package/dist/errors.js +0 -85
  41. package/dist/flags.d.ts +0 -15
  42. package/dist/flags.js +0 -76
  43. package/dist/function-errors.d.ts +0 -51
  44. package/dist/function-errors.js +0 -103
  45. package/dist/functions.d.ts +0 -15
  46. package/dist/functions.js +0 -83
  47. package/dist/index.d.ts +0 -49
  48. package/dist/index.js +0 -204
  49. package/dist/logic-engine.d.ts +0 -17
  50. package/dist/logic-engine.js +0 -193
  51. package/dist/messaging.d.ts +0 -13
  52. package/dist/messaging.js +0 -36
  53. package/dist/offline-state.d.ts +0 -97
  54. package/dist/offline-state.js +0 -200
  55. package/dist/pending-write.d.ts +0 -47
  56. package/dist/pending-write.js +0 -22
  57. package/dist/realtime.d.ts +0 -44
  58. package/dist/realtime.js +0 -195
  59. package/dist/record.d.ts +0 -2
  60. package/dist/record.js +0 -23
  61. package/dist/storage-errors.d.ts +0 -163
  62. package/dist/storage-errors.js +0 -253
  63. package/dist/storage.d.ts +0 -198
  64. package/dist/storage.js +0 -451
  65. package/dist/sync-engine.d.ts +0 -30
  66. package/dist/sync-engine.js +0 -290
  67. package/dist/types.d.ts +0 -487
  68. package/dist/types.js +0 -40
  69. /package/dist/{auth-storage.js → cjs/auth-storage.js} +0 -0
package/dist/auth.js DELETED
@@ -1,810 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KoolbaseAuth = void 0;
4
- const types_1 = require("./types");
5
- const auth_errors_1 = require("./auth-errors");
6
- const auth_storage_1 = require("./auth-storage");
7
- const device_metadata_1 = require("./device-metadata");
8
- class KoolbaseAuth {
9
- constructor(config) {
10
- this.session = null;
11
- this.ongoingRefresh = null;
12
- this.listeners = new Set();
13
- this.config = config;
14
- this.metadata = new device_metadata_1.DeviceMetadata(config.appVersion);
15
- this.fetchFn = config.fetch ?? ((url, init) => fetch(url, init));
16
- this.timeoutMs = config.authTimeout ?? 10000;
17
- if (config.authStorage) {
18
- this.storage = config.authStorage;
19
- }
20
- else if ((0, auth_storage_1.isKeychainAvailable)()) {
21
- this.storage = new auth_storage_1.SecureAuthStorage();
22
- }
23
- else {
24
- this.storage = null;
25
- // eslint-disable-next-line no-console
26
- console.warn('[Koolbase] No persistent auth storage available. Sessions will not ' +
27
- 'survive app restarts. Install react-native-keychain for the ' +
28
- 'default secure backend, or provide KoolbaseConfig.authStorage ' +
29
- 'with your own implementation.');
30
- }
31
- }
32
- // ─── Auth state listener ────────────────────────────────────────────────
33
- /**
34
- * Subscribe to authentication state changes. The listener fires:
35
- * - Immediately on subscribe, with the current user (or null).
36
- * - On every successful login, register, refresh, session restoration.
37
- * - On logout / explicit setSession(null).
38
- * - On linkPhone success (user object updated with phone fields).
39
- *
40
- * Returns an unsubscribe function. Call it when the consumer no longer
41
- * needs updates (e.g. in a React useEffect cleanup).
42
- *
43
- * Listener errors are swallowed so a buggy listener can't break auth
44
- * state propagation to other listeners.
45
- *
46
- * @example
47
- * const unsubscribe = auth.onAuthStateChange((user) => {
48
- * setCurrentUser(user);
49
- * });
50
- * // later:
51
- * unsubscribe();
52
- */
53
- onAuthStateChange(listener) {
54
- this.listeners.add(listener);
55
- // Fire immediately with current state — matches RN ecosystem
56
- // convention (Firebase Auth, Supabase Auth) so consumers don't
57
- // need to separately read currentUser on mount.
58
- try {
59
- listener(this.session?.user ?? null);
60
- }
61
- catch {
62
- // swallow
63
- }
64
- return () => {
65
- this.listeners.delete(listener);
66
- };
67
- }
68
- fireAuthStateChange() {
69
- const user = this.session?.user ?? null;
70
- for (const listener of this.listeners) {
71
- try {
72
- listener(user);
73
- }
74
- catch {
75
- // swallow — one broken listener doesn't break others
76
- }
77
- }
78
- }
79
- // ─── Headers ────────────────────────────────────────────────────────────
80
- /**
81
- * Compose the full header set for an outbound request: base headers,
82
- * device metadata, and optionally the Authorization bearer token.
83
- * Async because device metadata's first build may read from keychain.
84
- */
85
- async prepareHeaders(includeAuth) {
86
- const deviceHeaders = await this.metadata.build();
87
- return {
88
- 'Content-Type': 'application/json',
89
- 'x-api-key': this.config.publicKey,
90
- ...deviceHeaders,
91
- ...(includeAuth && this.session
92
- ? { Authorization: `Bearer ${this.session.accessToken}` }
93
- : {}),
94
- };
95
- }
96
- // ─── Request plumbing ───────────────────────────────────────────────────
97
- /**
98
- * Low-level request helper used by every endpoint. Wires together:
99
- * - The injected fetch implementation (config.fetch or global fetch)
100
- * - Device metadata + x-api-key + auth header in one place
101
- * - AbortController-based timeout (config.authTimeout, default 10s)
102
- *
103
- * On timeout, fetch rejects with an AbortError; callers see this as a
104
- * non-KoolbaseAuthError exception, which restoreSession() treats as
105
- * Offline (preserving optimistic state).
106
- */
107
- async authRequest(path, options = {}) {
108
- const headers = await this.prepareHeaders(options.includeAuth ?? false);
109
- const controller = new AbortController();
110
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
111
- try {
112
- return await this.fetchFn(`${this.config.baseUrl}${path}`, {
113
- method: options.method ?? 'GET',
114
- headers,
115
- body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
116
- signal: controller.signal,
117
- });
118
- }
119
- finally {
120
- clearTimeout(timer);
121
- }
122
- }
123
- /**
124
- * Authenticated request wrapper. Refreshes the access token if it's
125
- * stale (within 1-min buffer of expiry) before issuing the call, then
126
- * delegates to {@link authRequest} with includeAuth=true.
127
- */
128
- async authedRequest(path, options = {}) {
129
- await this._ensureValidToken();
130
- return this.authRequest(path, { ...options, includeAuth: true });
131
- }
132
- // ─── Internal session lifecycle ─────────────────────────────────────────
133
- async setSessionInternal(session) {
134
- this.session = session;
135
- if (this.storage) {
136
- try {
137
- await this.storage.saveSession(session);
138
- }
139
- catch (err) {
140
- // eslint-disable-next-line no-console
141
- console.warn('[Koolbase] Failed to persist session; staying signed in for this ' +
142
- 'session only:', err);
143
- }
144
- }
145
- this.fireAuthStateChange();
146
- }
147
- /**
148
- * Discards the stored session without contacting the server.
149
- *
150
- * For when the session is already known to be unusable — the server rejected
151
- * the token, or a build was pointed at a different project and the persisted
152
- * session belongs to the old one. Unlike `logout()` there is no server call:
153
- * the token has already been refused, and asking for it to be revoked would
154
- * only add a round trip that cannot succeed.
155
- *
156
- * Safe in any state, including with no session at all. The SDK calls this
157
- * itself when a request is rejected as unauthenticated, so most apps will not
158
- * need to.
159
- */
160
- async clearStoredSession() {
161
- await this.clearSessionInternal();
162
- }
163
- async clearSessionInternal() {
164
- this.session = null;
165
- if (this.storage) {
166
- try {
167
- await this.storage.clear();
168
- }
169
- catch {
170
- // best effort
171
- }
172
- }
173
- this.fireAuthStateChange();
174
- }
175
- // ─── Session restoration ────────────────────────────────────────────────
176
- async restoreSession() {
177
- if (!this.storage)
178
- return types_1.RestoreResult.NoSession;
179
- const persisted = await this.storage.readSession();
180
- if (!persisted)
181
- return types_1.RestoreResult.NoSession;
182
- // Optimistic restore — populate state and fire listener before any
183
- // network call. App can render authenticated UI immediately.
184
- this.session = persisted;
185
- this.fireAuthStateChange();
186
- const expiresAt = persisted.expiresAt
187
- ? new Date(persisted.expiresAt).getTime()
188
- : 0;
189
- const oneMinuteMs = 60 * 1000;
190
- if (expiresAt > Date.now() + oneMinuteMs) {
191
- return types_1.RestoreResult.Restored;
192
- }
193
- try {
194
- await this.refresh(persisted.refreshToken);
195
- return types_1.RestoreResult.Restored;
196
- }
197
- catch (e) {
198
- if (e instanceof auth_errors_1.SessionExpiredError ||
199
- e instanceof auth_errors_1.TokenRevokedError ||
200
- e instanceof auth_errors_1.InvalidCredentialsError) {
201
- await this.clearSessionInternal();
202
- return types_1.RestoreResult.Expired;
203
- }
204
- return types_1.RestoreResult.Offline;
205
- }
206
- }
207
- // ─── Public auth API ────────────────────────────────────────────────────
208
- async register(params) {
209
- if (params.password.length < 8)
210
- throw new auth_errors_1.WeakPasswordError();
211
- const res = await this.authRequest('/v1/sdk/auth/register', {
212
- method: 'POST',
213
- body: params,
214
- });
215
- const session = await this.parseSessionResponse(res, false);
216
- await this.setSessionInternal(session);
217
- return session.user;
218
- }
219
- async login(params) {
220
- const res = await this.authRequest('/v1/sdk/auth/login', {
221
- method: 'POST',
222
- body: params,
223
- });
224
- const session = await this.parseSessionResponse(res, false);
225
- await this.setSessionInternal(session);
226
- return session;
227
- }
228
- /**
229
- * Sign in with Apple using a credential obtained from a native Apple
230
- * Sign-In SDK.
231
- *
232
- * The SDK is library-agnostic — use any native Apple Sign-In package
233
- * (`@invertase/react-native-apple-authentication`, etc.) and pass the
234
- * resulting `identityToken`, optional `nonce`, and optional `fullName`.
235
- *
236
- * `fullName` is meaningful only on first sign-in — Apple omits name
237
- * data on subsequent sign-ins. The server persists at link time and
238
- * ignores on subsequent sign-ins.
239
- *
240
- * On success the session is persisted via the configured storage and
241
- * `onAuthStateChange` fires with the resolved user.
242
- *
243
- * @throws AppleSignInNotConfiguredError when Apple is not enabled in
244
- * the dashboard OAuth config for this environment (400).
245
- * @throws InvalidAppleTokenError when the token signature, audience,
246
- * expiry, replay, or nonce check failed server-side (401).
247
- * @throws UserDisabledError when the account flag is set to disabled (403).
248
- * @throws AppleEmailRequiredError when Apple did not return email for
249
- * a new-account sign-in (400).
250
- * @throws OAuthEmailConflictError when email matches existing user
251
- * but auto-link rule blocked (409).
252
- */
253
- async signInWithApple(params) {
254
- const body = {
255
- identity_token: params.identityToken,
256
- };
257
- if (params.nonce && params.nonce.length > 0) {
258
- body.nonce = params.nonce;
259
- }
260
- if (params.fullName) {
261
- const nameJson = {};
262
- if (params.fullName.givenName)
263
- nameJson.given_name = params.fullName.givenName;
264
- if (params.fullName.familyName)
265
- nameJson.family_name = params.fullName.familyName;
266
- if (Object.keys(nameJson).length > 0) {
267
- body.full_name = nameJson;
268
- }
269
- }
270
- const res = await this.authRequest('/v1/sdk/auth/oauth/apple', {
271
- method: 'POST',
272
- body,
273
- });
274
- const session = await this.parseAppleSessionResponse(res);
275
- await this.setSessionInternal(session);
276
- return session;
277
- }
278
- /**
279
- * Sign in with Google using an idToken from a native Google Sign-In SDK.
280
- *
281
- * The SDK is library-agnostic — use any native Google Sign-In package
282
- * (`@react-native-google-signin/google-signin`, etc.) and pass the
283
- * resulting `idToken`. Google embeds the user's name and email in the
284
- * idToken itself, so this method does not take a `fullName` parameter
285
- * (unlike `signInWithApple`).
286
- *
287
- * On success the session is persisted via the configured storage and
288
- * `onAuthStateChange` fires with the resolved user.
289
- *
290
- * @throws GoogleSignInNotConfiguredError when Google is not enabled
291
- * in the OAuth config for this environment (400).
292
- * @throws InvalidGoogleTokenError when the token signature, audience,
293
- * expiry, replay, or nonce check failed server-side (401).
294
- * @throws UserDisabledError when the account flag is set to disabled (403).
295
- * @throws GoogleEmailRequiredError when Google did not return email
296
- * for a new-account sign-in (400).
297
- * @throws OAuthEmailConflictError when email matches existing user
298
- * but auto-link rule blocked (409).
299
- */
300
- async signInWithGoogle(params) {
301
- const body = {
302
- identity_token: params.idToken,
303
- };
304
- if (params.nonce && params.nonce.length > 0) {
305
- body.nonce = params.nonce;
306
- }
307
- const res = await this.authRequest('/v1/sdk/auth/oauth/google', {
308
- method: 'POST',
309
- body,
310
- });
311
- const session = await this.parseGoogleSessionResponse(res);
312
- await this.setSessionInternal(session);
313
- return session;
314
- }
315
- /**
316
- * Parses a /v1/sdk/auth/oauth/google response. Code-first: the server
317
- * emits unified OAuth codes (oauth_not_configured, invalid_oauth_token,
318
- * oauth_email_required, oauth_email_conflict) for both providers; the
319
- * provider distinction is made here so Google codes map to Google-specific
320
- * errors. Status + message logic is retained as a fallback for older servers.
321
- */
322
- async parseGoogleSessionResponse(res) {
323
- if (res.status === 200) {
324
- const data = await res.json();
325
- return {
326
- accessToken: data.access_token,
327
- refreshToken: data.refresh_token,
328
- expiresAt: data.expires_at,
329
- user: this.mapUser(data.user),
330
- };
331
- }
332
- let body = {};
333
- try {
334
- body = await res.json();
335
- }
336
- catch {
337
- // best-effort error message extraction
338
- }
339
- const code = body?.code ?? '';
340
- const errorMessage = body?.error ?? '';
341
- // ─── code-first ───
342
- switch (code) {
343
- case 'oauth_not_configured':
344
- throw new auth_errors_1.GoogleSignInNotConfiguredError();
345
- case 'invalid_oauth_token':
346
- throw new auth_errors_1.InvalidGoogleTokenError();
347
- case 'account_disabled':
348
- throw new auth_errors_1.UserDisabledError();
349
- case 'oauth_email_required':
350
- throw new auth_errors_1.GoogleEmailRequiredError();
351
- case 'oauth_email_conflict':
352
- throw new auth_errors_1.OAuthEmailConflictError();
353
- case 'rate_limit':
354
- throw new auth_errors_1.RateLimitError(errorMessage || undefined);
355
- }
356
- // ─── status + message fallback (pre-code servers) ───
357
- if (res.status === 400) {
358
- if (errorMessage.includes('not configured')) {
359
- throw new auth_errors_1.GoogleSignInNotConfiguredError();
360
- }
361
- if (errorMessage.includes('did not return email')) {
362
- throw new auth_errors_1.GoogleEmailRequiredError();
363
- }
364
- throw new auth_errors_1.KoolbaseAuthError(`google sign-in failed: ${errorMessage}`, 'google_signin_failed');
365
- }
366
- if (res.status === 401)
367
- throw new auth_errors_1.InvalidGoogleTokenError();
368
- if (res.status === 403)
369
- throw new auth_errors_1.UserDisabledError();
370
- if (res.status === 409)
371
- throw new auth_errors_1.OAuthEmailConflictError();
372
- if (res.status === 429)
373
- throw new auth_errors_1.RateLimitError(errorMessage);
374
- throw new auth_errors_1.KoolbaseAuthError(`google sign-in failed: ${res.status} ${errorMessage}`, `google_signin_http_${res.status}`);
375
- }
376
- /**
377
- * Parses a /v1/sdk/auth/oauth/apple response. Code-first; the provider
378
- * distinction is made here so the server's unified OAuth codes map to
379
- * Apple-specific errors. Status + message logic is retained as a fallback
380
- * for older servers.
381
- */
382
- async parseAppleSessionResponse(res) {
383
- if (res.status === 200) {
384
- const data = await res.json();
385
- return {
386
- accessToken: data.access_token,
387
- refreshToken: data.refresh_token,
388
- expiresAt: data.expires_at,
389
- user: this.mapUser(data.user),
390
- };
391
- }
392
- let body = {};
393
- try {
394
- body = await res.json();
395
- }
396
- catch {
397
- // best-effort error message extraction
398
- }
399
- const code = body?.code ?? '';
400
- const errorMessage = body?.error ?? '';
401
- // ─── code-first ───
402
- switch (code) {
403
- case 'oauth_not_configured':
404
- throw new auth_errors_1.AppleSignInNotConfiguredError();
405
- case 'invalid_oauth_token':
406
- throw new auth_errors_1.InvalidAppleTokenError();
407
- case 'account_disabled':
408
- throw new auth_errors_1.UserDisabledError();
409
- case 'oauth_email_required':
410
- throw new auth_errors_1.AppleEmailRequiredError();
411
- case 'oauth_email_conflict':
412
- throw new auth_errors_1.OAuthEmailConflictError();
413
- case 'rate_limit':
414
- throw new auth_errors_1.RateLimitError(errorMessage || undefined);
415
- }
416
- // ─── status + message fallback (pre-code servers) ───
417
- if (res.status === 400) {
418
- if (errorMessage.includes('not configured')) {
419
- throw new auth_errors_1.AppleSignInNotConfiguredError();
420
- }
421
- if (errorMessage.includes('did not return email')) {
422
- throw new auth_errors_1.AppleEmailRequiredError();
423
- }
424
- throw new auth_errors_1.KoolbaseAuthError(`apple sign-in failed: ${errorMessage}`, 'apple_signin_failed');
425
- }
426
- if (res.status === 401)
427
- throw new auth_errors_1.InvalidAppleTokenError();
428
- if (res.status === 403)
429
- throw new auth_errors_1.UserDisabledError();
430
- if (res.status === 409)
431
- throw new auth_errors_1.OAuthEmailConflictError();
432
- if (res.status === 429)
433
- throw new auth_errors_1.RateLimitError(errorMessage);
434
- throw new auth_errors_1.KoolbaseAuthError(`apple sign-in failed: ${res.status} ${errorMessage}`, `apple_signin_http_${res.status}`);
435
- }
436
- async refresh(refreshToken) {
437
- if (this.ongoingRefresh) {
438
- return this.ongoingRefresh;
439
- }
440
- const promise = this._doRefresh(refreshToken);
441
- this.ongoingRefresh = promise;
442
- promise
443
- .catch(() => {
444
- // swallow; original promise still rejects to awaiters
445
- })
446
- .finally(() => {
447
- if (this.ongoingRefresh === promise) {
448
- this.ongoingRefresh = null;
449
- }
450
- });
451
- return promise;
452
- }
453
- async _doRefresh(refreshToken) {
454
- const token = refreshToken ?? this.session?.refreshToken;
455
- if (!token) {
456
- throw new auth_errors_1.SessionExpiredError();
457
- }
458
- const res = await this.authRequest('/v1/sdk/auth/refresh', {
459
- method: 'POST',
460
- body: { refresh_token: token },
461
- });
462
- const session = await this.parseSessionResponse(res, true);
463
- await this.setSessionInternal(session);
464
- return session;
465
- }
466
- async logout() {
467
- let serverSucceeded = true;
468
- try {
469
- if (this.session) {
470
- // Best-effort: don't auto-refresh during logout. If the token's
471
- // already expired, we still want to clear local state — server
472
- // will reap expired sessions itself.
473
- const res = await this.authRequest('/v1/sdk/auth/logout', {
474
- method: 'POST',
475
- includeAuth: true,
476
- });
477
- if (!res.ok)
478
- serverSucceeded = false;
479
- }
480
- }
481
- catch {
482
- serverSucceeded = false;
483
- }
484
- finally {
485
- await this.clearSessionInternal();
486
- }
487
- return serverSucceeded;
488
- }
489
- async forgotPassword(email) {
490
- const res = await this.authRequest('/v1/sdk/auth/password-reset', {
491
- method: 'POST',
492
- body: { email },
493
- });
494
- await this.checkResponse(res);
495
- }
496
- async resetPassword(token, password) {
497
- const res = await this.authRequest('/v1/sdk/auth/password-reset/confirm', {
498
- method: 'POST',
499
- body: { token, password },
500
- });
501
- await this.checkResponse(res);
502
- }
503
- async unlock(token) {
504
- const res = await this.authRequest('/v1/sdk/auth/unlock', {
505
- method: 'POST',
506
- body: { token },
507
- });
508
- await this.checkResponse(res);
509
- }
510
- get currentUser() {
511
- return this.session?.user ?? null;
512
- }
513
- get accessToken() {
514
- return this.session?.accessToken ?? null;
515
- }
516
- /**
517
- * Currently-valid access token for data-plane requests, refreshing
518
- * (via refresh()) if the cached one is near expiry. Returns null when no
519
- * session exists or refresh fails — callers then go api-key-only and the
520
- * server treats it as having no end-user identity. The db/storage/functions
521
- * clients pull from this per request so identity follows the live session.
522
- */
523
- async validAccessToken() {
524
- if (!this.session)
525
- return null;
526
- try {
527
- return await this._ensureValidToken();
528
- }
529
- catch {
530
- return null;
531
- }
532
- }
533
- async setSession(session) {
534
- if (session) {
535
- await this.setSessionInternal(session);
536
- }
537
- else {
538
- await this.clearSessionInternal();
539
- }
540
- }
541
- // ─── OAuth (DEPRECATED — see v1.10.0) ───────────────────────────────────
542
- /**
543
- * @deprecated v1.9.0: Server endpoint /v1/sdk/auth/oauth not yet
544
- * shipped. This method previously routed to /v1/auth/oauth (dashboard
545
- * developer OAuth) which never created project-scoped end-user
546
- * sessions. Properly implemented in v1.10.0 with provider-specific
547
- * server endpoints under /v1/sdk/auth/oauth/{apple,google,github}.
548
- * Use email/password sign-in for now.
549
- *
550
- * @throws Always throws KoolbaseAuthError('not_implemented').
551
- */
552
- async oauthLogin(_params) {
553
- throw new auth_errors_1.KoolbaseAuthError('OAuth sign-in is not yet implemented for the Koolbase SDK. ' +
554
- 'Planned for v1.10.0 (server-side endpoints under ' +
555
- '/v1/sdk/auth/oauth/{provider}). Use email/password authentication ' +
556
- 'in the meantime.', 'not_implemented');
557
- }
558
- // ─── Phone OTP ──────────────────────────────────────────────────────────
559
- async sendOtp(params) {
560
- this.validatePhone(params.phoneNumber);
561
- const res = await this.authRequest('/v1/sdk/auth/phone/send-otp', {
562
- method: 'POST',
563
- body: { phone_number: params.phoneNumber },
564
- });
565
- const data = await this.parsePhoneResponse(res);
566
- return { expiresAt: data.expires_at };
567
- }
568
- async verifyOtp(params) {
569
- this.validatePhone(params.phoneNumber);
570
- const res = await this.authRequest('/v1/sdk/auth/phone/verify-otp', {
571
- method: 'POST',
572
- body: {
573
- phone_number: params.phoneNumber,
574
- code: params.code,
575
- },
576
- });
577
- const data = await this.parsePhoneResponse(res);
578
- const session = {
579
- accessToken: data.access_token,
580
- refreshToken: data.refresh_token,
581
- expiresAt: data.expires_at,
582
- user: this.mapUser(data.user),
583
- };
584
- await this.setSessionInternal(session);
585
- return { session, isNewUser: data.is_new_user ?? false };
586
- }
587
- async linkPhone(params) {
588
- if (!this.session) {
589
- throw new auth_errors_1.KoolbaseAuthError('Must be signed in to link a phone number', 'unauthenticated');
590
- }
591
- this.validatePhone(params.phoneNumber);
592
- const res = await this.authedRequest('/v1/sdk/auth/phone/link', {
593
- method: 'POST',
594
- body: {
595
- phone_number: params.phoneNumber,
596
- code: params.code,
597
- },
598
- });
599
- const body = await this.parsePhoneResponse(res);
600
- // Update local session: prefer the canonical user from the server
601
- // response if present; otherwise merge the linked phone into the
602
- // existing in-memory user. Either way, setSessionInternal fires the
603
- // auth state listener so consumers can react to the phone link.
604
- if (this.session) {
605
- const updatedUser = body.user
606
- ? this.mapUser(body.user)
607
- : {
608
- ...this.session.user,
609
- phoneNumber: params.phoneNumber,
610
- phoneVerified: true,
611
- };
612
- await this.setSessionInternal({
613
- ...this.session,
614
- user: updatedUser,
615
- });
616
- }
617
- }
618
- // ─── Cleanup ────────────────────────────────────────────────────────────
619
- /**
620
- * Release resources held by this auth client. Clears the in-memory
621
- * listener set. Does not invalidate sessions or clear storage — call
622
- * {@link logout} for that.
623
- */
624
- dispose() {
625
- this.listeners.clear();
626
- }
627
- // ─── Helpers ────────────────────────────────────────────────────────────
628
- validatePhone(phoneNumber) {
629
- if (!/^\+[1-9]\d{6,14}$/.test(phoneNumber)) {
630
- throw new auth_errors_1.InvalidPhoneNumberError();
631
- }
632
- }
633
- async _ensureValidToken() {
634
- if (this.session && this.session.expiresAt) {
635
- const expiresAt = new Date(this.session.expiresAt).getTime();
636
- if (Date.now() < expiresAt - 60 * 1000) {
637
- return this.session.accessToken;
638
- }
639
- }
640
- if (!this.session) {
641
- throw new auth_errors_1.SessionExpiredError();
642
- }
643
- try {
644
- const session = await this.refresh();
645
- return session.accessToken;
646
- }
647
- catch (e) {
648
- if (e instanceof auth_errors_1.KoolbaseAuthError)
649
- throw e;
650
- throw new auth_errors_1.SessionExpiredError();
651
- }
652
- }
653
- mapUser(raw) {
654
- return {
655
- id: raw.id,
656
- email: raw.email ?? '',
657
- phoneNumber: raw.phone_number,
658
- phoneVerified: raw.phone_verified ?? false,
659
- fullName: raw.full_name,
660
- avatarUrl: raw.avatar_url,
661
- verified: raw.verified ?? false,
662
- createdAt: raw.created_at,
663
- };
664
- }
665
- /**
666
- * Parse a session-returning response (login, register, refresh).
667
- * Non-2xx is delegated to throwTypedError, which is code-first
668
- * (reads body.code) with a status/message fallback. isRefresh only
669
- * affects how a bare 401 (no code, older server) is interpreted.
670
- */
671
- async parseSessionResponse(res, isRefresh) {
672
- if (!res.ok)
673
- await this.throwTypedError(res, isRefresh); // never returns
674
- const data = await res.json();
675
- return {
676
- accessToken: data.access_token,
677
- refreshToken: data.refresh_token,
678
- expiresAt: data.expires_at,
679
- user: this.mapUser(data.user),
680
- };
681
- }
682
- async checkResponse(res) {
683
- if (res.ok)
684
- return;
685
- await this.throwTypedError(res);
686
- }
687
- /**
688
- * Map a non-2xx credential/session response to a typed error.
689
- *
690
- * Code-first: the server now emits a stable `code` on every error
691
- * (contract conformance), so we switch on body.code. The status +
692
- * message logic is retained as a fallback for older servers or any
693
- * response that arrives without a code. isRefresh only changes how a
694
- * bare 401 is interpreted in the fallback path.
695
- */
696
- async throwTypedError(res, isRefresh = false) {
697
- let body = {};
698
- try {
699
- body = await res.json();
700
- }
701
- catch {
702
- // ignore
703
- }
704
- const code = body.code ?? '';
705
- const msg = body.error ?? '';
706
- // ─── code-first ───
707
- switch (code) {
708
- case 'invalid_credentials':
709
- throw new auth_errors_1.InvalidCredentialsError();
710
- case 'email_in_use':
711
- throw new auth_errors_1.EmailAlreadyInUseError();
712
- case 'account_disabled':
713
- throw new auth_errors_1.UserDisabledError();
714
- case 'account_locked':
715
- throw new auth_errors_1.AccountLockedError();
716
- case 'invalid_refresh_token':
717
- // Refresh token rejected — the session is unrecoverable; re-login.
718
- throw new auth_errors_1.SessionExpiredError();
719
- case 'token_revoked':
720
- throw new auth_errors_1.TokenRevokedError();
721
- case 'invalid_unlock_token':
722
- throw new auth_errors_1.UnlockTokenInvalidError();
723
- case 'rate_limit':
724
- throw new auth_errors_1.RateLimitError(msg || undefined);
725
- }
726
- // ─── status fallback (pre-code servers) ───
727
- if (res.status === 409)
728
- throw new auth_errors_1.EmailAlreadyInUseError();
729
- if (res.status === 401) {
730
- throw isRefresh ? new auth_errors_1.SessionExpiredError() : new auth_errors_1.InvalidCredentialsError();
731
- }
732
- if (res.status === 403)
733
- throw new auth_errors_1.UserDisabledError();
734
- if (res.status === 429) {
735
- if (msg.includes('account temporarily locked')) {
736
- throw new auth_errors_1.AccountLockedError();
737
- }
738
- throw new auth_errors_1.RateLimitError(msg || undefined);
739
- }
740
- // ─── legacy message fallback ───
741
- if (msg.includes('invalid or expired unlock token')) {
742
- throw new auth_errors_1.UnlockTokenInvalidError();
743
- }
744
- if (msg.includes('session revoked') ||
745
- msg.includes('token revoked') ||
746
- msg.includes('session has been revoked')) {
747
- throw new auth_errors_1.TokenRevokedError();
748
- }
749
- throw new auth_errors_1.KoolbaseAuthError(msg || `Request failed: ${res.status}`, code || `http_${res.status}`);
750
- }
751
- /**
752
- * Parse a phone-auth response. Code-first, with a phone-specific twist:
753
- * the server emits the generic `rate_limit` code for the phone endpoints
754
- * (they share the default 429), but phone has a dedicated server-side
755
- * rate-limiter, so we surface OtpRateLimitError rather than RateLimitError.
756
- * Status + message logic is retained as a fallback for older servers.
757
- */
758
- async parsePhoneResponse(res) {
759
- let body = {};
760
- try {
761
- body = await res.json();
762
- }
763
- catch {
764
- // ignore
765
- }
766
- if (res.ok)
767
- return body;
768
- const code = body.code ?? '';
769
- const msg = body.error ?? '';
770
- // ─── code-first ───
771
- switch (code) {
772
- case 'invalid_phone':
773
- throw new auth_errors_1.InvalidPhoneNumberError();
774
- case 'otp_expired':
775
- throw new auth_errors_1.OtpExpiredError();
776
- case 'otp_invalid':
777
- throw new auth_errors_1.OtpInvalidError();
778
- case 'otp_max_attempts':
779
- throw new auth_errors_1.OtpMaxAttemptsError();
780
- case 'phone_in_use':
781
- throw new auth_errors_1.PhoneAlreadyLinkedError();
782
- case 'sms_not_configured':
783
- throw new auth_errors_1.SmsConfigMissingError();
784
- case 'rate_limit':
785
- throw new auth_errors_1.OtpRateLimitError();
786
- }
787
- // ─── status fallback (pre-code servers) ───
788
- if (res.status === 429)
789
- throw new auth_errors_1.OtpRateLimitError();
790
- if (res.status === 409)
791
- throw new auth_errors_1.PhoneAlreadyLinkedError();
792
- // ─── legacy message fallback ───
793
- if (msg.includes('E.164'))
794
- throw new auth_errors_1.InvalidPhoneNumberError();
795
- if (msg.includes('OTP has expired'))
796
- throw new auth_errors_1.OtpExpiredError();
797
- if (msg.includes('too many incorrect attempts')) {
798
- throw new auth_errors_1.OtpMaxAttemptsError();
799
- }
800
- if (msg.includes('invalid OTP') ||
801
- msg.includes('invalid or expired OTP')) {
802
- throw new auth_errors_1.OtpInvalidError();
803
- }
804
- if (msg.includes('SMS provider not configured')) {
805
- throw new auth_errors_1.SmsConfigMissingError();
806
- }
807
- throw new auth_errors_1.KoolbaseAuthError(msg || 'An unexpected error occurred', code || undefined);
808
- }
809
- }
810
- exports.KoolbaseAuth = KoolbaseAuth;