@koolbase/core 12.43.0 → 12.45.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.
@@ -170,6 +170,45 @@ export interface KoolbaseAuditPage {
170
170
  limit: number;
171
171
  offset: number;
172
172
  }
173
+ /** One person in the app, as an app admin sees them. */
174
+ export interface KoolbaseMember {
175
+ id: string;
176
+ email: string;
177
+ fullName?: string;
178
+ avatarUrl?: string;
179
+ /** `invited` has not signed in yet. */
180
+ status: 'active' | 'invited' | 'disabled';
181
+ /** An app admin: only the project owner can disable them or change their roles. */
182
+ isAdmin: boolean;
183
+ /** The claims the project marked as ones app admins can give. Others are never sent. */
184
+ roles: Record<string, unknown>;
185
+ /** Pass back to `admin.setRoles` as `expectedVersion`. */
186
+ version: number;
187
+ joinedAt: string;
188
+ lastSeenAt?: string;
189
+ }
190
+ /** A page of members, with the total across all pages. */
191
+ export interface KoolbaseMemberPage {
192
+ members: KoolbaseMember[];
193
+ total: number;
194
+ }
195
+ /** A role an app admin may give, with how many people hold it. */
196
+ export interface KoolbaseAssignableRole {
197
+ key: string;
198
+ valueType: string;
199
+ /** The only values allowed, when the project limited them; empty otherwise. */
200
+ allowedValues: string[];
201
+ description?: string;
202
+ holders: number;
203
+ /** For each value, how many people hold it. */
204
+ values: Record<string, number>;
205
+ }
206
+ /** What `admin.setRoles` leaves: the roles now, and the version to pass next time. */
207
+ export interface KoolbaseMemberRoles {
208
+ id: string;
209
+ roles: Record<string, unknown>;
210
+ version: number;
211
+ }
173
212
  export interface ResendVerificationResult {
174
213
  alreadyVerified: boolean;
175
214
  /** When the link in the email stops working. Null when nothing was sent. */
@@ -181,6 +220,13 @@ export interface KoolbaseAuthStorage {
181
220
  saveSession(session: KoolbaseSession): Promise<void>;
182
221
  readSession(): Promise<KoolbaseSession | null>;
183
222
  clear(): Promise<void>;
223
+ /**
224
+ * Remember me: where the next sign-in's session lives, told before it is
225
+ * saved. `true`: as long as the storage keeps anything; `false`: until the
226
+ * tab or browser closes. Optional -- a storage without it (a keychain, the
227
+ * memory one, an app's own) keeps every session as it always has.
228
+ */
229
+ setRemember?(remember: boolean): Promise<void>;
184
230
  }
185
231
  /**
186
232
  * Result of KoolbaseAuth.restoreSession(). Apps should branch on this:
@@ -225,6 +271,13 @@ export interface RegisterParams {
225
271
  export interface LoginParams {
226
272
  email: string;
227
273
  password: string;
274
+ /**
275
+ * Whether this sign-in outlasts the browser (Remember me). Omitted: it
276
+ * does, as always. `false`: the session is kept for this tab only, and
277
+ * ends when it closes -- where the storage can tell the two apart (the
278
+ * browser's, in @koolbase/js; a keychain always keeps it).
279
+ */
280
+ remember?: boolean;
228
281
  }
229
282
  export interface SendOtpParams {
230
283
  phoneNumber: string;
@@ -232,6 +285,13 @@ export interface SendOtpParams {
232
285
  export interface VerifyOtpParams {
233
286
  phoneNumber: string;
234
287
  code: string;
288
+ /**
289
+ * Whether this sign-in outlasts the browser (Remember me). Omitted: it
290
+ * does, as always. `false`: the session is kept for this tab only, and
291
+ * ends when it closes -- where the storage can tell the two apart (the
292
+ * browser's, in @koolbase/js; a keychain always keeps it).
293
+ */
294
+ remember?: boolean;
235
295
  }
236
296
  export interface LinkPhoneParams {
237
297
  phoneNumber: string;
@@ -609,6 +669,13 @@ export interface AppleFullName {
609
669
  export interface SignInWithAppleParams {
610
670
  identityToken: string;
611
671
  nonce?: string;
672
+ /**
673
+ * Whether this sign-in outlasts the browser (Remember me). Omitted: it
674
+ * does, as always. `false`: the session is kept for this tab only, and
675
+ * ends when it closes -- where the storage can tell the two apart (the
676
+ * browser's, in @koolbase/js; a keychain always keeps it).
677
+ */
678
+ remember?: boolean;
612
679
  fullName?: AppleFullName;
613
680
  /** The credential's authorization code: the server exchanges it for the
614
681
  * token it revokes when the account is deleted, as Apple asks. */
@@ -627,6 +694,13 @@ export interface SignInWithAppleParams {
627
694
  export interface SignInWithGoogleParams {
628
695
  idToken: string;
629
696
  nonce?: string;
697
+ /**
698
+ * Whether this sign-in outlasts the browser (Remember me). Omitted: it
699
+ * does, as always. `false`: the session is kept for this tab only, and
700
+ * ends when it closes -- where the storage can tell the two apart (the
701
+ * browser's, in @koolbase/js; a keychain always keeps it).
702
+ */
703
+ remember?: boolean;
630
704
  }
631
705
  export type BatchOp = {
632
706
  type: 'insert';
@@ -0,0 +1,55 @@
1
+ import type { KoolbaseAssignableRole, KoolbaseMember, KoolbaseMemberPage, KoolbaseMemberRoles } from './types.js';
2
+ type AdminRequest = (path: string, options?: {
3
+ method?: string;
4
+ body?: unknown;
5
+ }) => Promise<any>;
6
+ /**
7
+ * Managing the app's people from inside the app, for its own admins.
8
+ *
9
+ * Only a signed-in person whose `app_admin` claim is true may use these; the
10
+ * project owner gives that claim in the dashboard. Everyone else gets
11
+ * `NotAppAdminError`. The server checks on every request, so taking the claim
12
+ * away takes effect at once.
13
+ *
14
+ * When the admin has two-step sign-in on, disabling, enabling and changing
15
+ * roles need it confirmed in the last ten minutes: catch
16
+ * `RecentMfaRequiredError`, call `stepUpMfa`, and try again.
17
+ *
18
+ * Reached through `Koolbase.auth.admin`; not built by apps.
19
+ */
20
+ export declare class KoolbaseAppAdmin {
21
+ private readonly request;
22
+ constructor(request: AdminRequest);
23
+ /** The app's people, newest first. `query` matches email or name. */
24
+ members(options?: {
25
+ query?: string;
26
+ limit?: number;
27
+ offset?: number;
28
+ }): Promise<KoolbaseMemberPage>;
29
+ /** The roles admins may give, for a role picker. */
30
+ roles(): Promise<KoolbaseAssignableRole[]>;
31
+ /**
32
+ * Invite someone by email. They get an email to set up their account, and
33
+ * `roles` are given at once. Throws `MemberExistsError` when the email
34
+ * already has an account.
35
+ */
36
+ invite(params: {
37
+ email: string;
38
+ fullName?: string;
39
+ roles?: Record<string, unknown>;
40
+ }): Promise<KoolbaseMember>;
41
+ /** Stop someone signing in, and sign them out everywhere. */
42
+ disable(userId: string): Promise<void>;
43
+ /** Let a disabled person sign in again. */
44
+ enable(userId: string): Promise<void>;
45
+ /**
46
+ * Change someone's roles. Only the keys given change; `null` removes a
47
+ * role. Pass the member's `version` as `expectedVersion`: when someone else
48
+ * changed them since, this throws `ClaimsVersionConflictError` carrying the
49
+ * new version, and nothing is changed.
50
+ */
51
+ setRoles(userId: string, roles: Record<string, unknown>, options: {
52
+ expectedVersion: number;
53
+ }): Promise<KoolbaseMemberRoles>;
54
+ }
55
+ export {};
@@ -0,0 +1,103 @@
1
+ function mapMember(r) {
2
+ return {
3
+ id: String(r.id),
4
+ email: String(r.email ?? ''),
5
+ fullName: r.full_name ?? undefined,
6
+ avatarUrl: r.avatar_url ?? undefined,
7
+ status: r.status ?? 'active',
8
+ isAdmin: Boolean(r.is_admin),
9
+ roles: r.roles ?? {},
10
+ version: Number(r.version ?? 0),
11
+ joinedAt: String(r.joined_at),
12
+ lastSeenAt: r.last_seen_at ?? undefined,
13
+ };
14
+ }
15
+ /**
16
+ * Managing the app's people from inside the app, for its own admins.
17
+ *
18
+ * Only a signed-in person whose `app_admin` claim is true may use these; the
19
+ * project owner gives that claim in the dashboard. Everyone else gets
20
+ * `NotAppAdminError`. The server checks on every request, so taking the claim
21
+ * away takes effect at once.
22
+ *
23
+ * When the admin has two-step sign-in on, disabling, enabling and changing
24
+ * roles need it confirmed in the last ten minutes: catch
25
+ * `RecentMfaRequiredError`, call `stepUpMfa`, and try again.
26
+ *
27
+ * Reached through `Koolbase.auth.admin`; not built by apps.
28
+ */
29
+ export class KoolbaseAppAdmin {
30
+ constructor(request) {
31
+ this.request = request;
32
+ }
33
+ /** The app's people, newest first. `query` matches email or name. */
34
+ async members(options) {
35
+ const params = new URLSearchParams();
36
+ if (options?.query)
37
+ params.set('q', options.query);
38
+ if (options?.limit !== undefined)
39
+ params.set('limit', String(options.limit));
40
+ if (options?.offset !== undefined)
41
+ params.set('offset', String(options.offset));
42
+ const qs = params.toString();
43
+ const body = await this.request(`/v1/sdk/admin/members${qs ? `?${qs}` : ''}`);
44
+ return {
45
+ members: (body.members ?? []).map(mapMember),
46
+ total: Number(body.total ?? 0),
47
+ };
48
+ }
49
+ /** The roles admins may give, for a role picker. */
50
+ async roles() {
51
+ const body = await this.request('/v1/sdk/admin/roles');
52
+ return (body.roles ?? []).map((r) => ({
53
+ key: String(r.key),
54
+ valueType: String(r.value_type ?? 'string'),
55
+ allowedValues: (r.allowed_values ?? []).map(String),
56
+ description: r.description ?? undefined,
57
+ holders: Number(r.holders ?? 0),
58
+ values: r.values ?? {},
59
+ }));
60
+ }
61
+ /**
62
+ * Invite someone by email. They get an email to set up their account, and
63
+ * `roles` are given at once. Throws `MemberExistsError` when the email
64
+ * already has an account.
65
+ */
66
+ async invite(params) {
67
+ const body = await this.request('/v1/sdk/admin/members/invite', {
68
+ method: 'POST',
69
+ body: {
70
+ email: params.email,
71
+ ...(params.fullName !== undefined ? { full_name: params.fullName } : {}),
72
+ ...(params.roles && Object.keys(params.roles).length ? { roles: params.roles } : {}),
73
+ },
74
+ });
75
+ return mapMember(body);
76
+ }
77
+ /** Stop someone signing in, and sign them out everywhere. */
78
+ async disable(userId) {
79
+ await this.request(`/v1/sdk/admin/members/${encodeURIComponent(userId)}/disable`, {
80
+ method: 'POST',
81
+ });
82
+ }
83
+ /** Let a disabled person sign in again. */
84
+ async enable(userId) {
85
+ await this.request(`/v1/sdk/admin/members/${encodeURIComponent(userId)}/enable`, {
86
+ method: 'POST',
87
+ });
88
+ }
89
+ /**
90
+ * Change someone's roles. Only the keys given change; `null` removes a
91
+ * role. Pass the member's `version` as `expectedVersion`: when someone else
92
+ * changed them since, this throws `ClaimsVersionConflictError` carrying the
93
+ * new version, and nothing is changed.
94
+ */
95
+ async setRoles(userId, roles, options) {
96
+ const body = await this.request(`/v1/sdk/admin/members/${encodeURIComponent(userId)}/roles`, { method: 'PUT', body: { roles, expected_version: options.expectedVersion } });
97
+ return {
98
+ id: String(body.id),
99
+ roles: body.roles ?? {},
100
+ version: Number(body.version ?? 0),
101
+ };
102
+ }
103
+ }
@@ -299,3 +299,35 @@ export declare class MfaEnrollmentNotFoundError extends KoolbaseAuthError {
299
299
  export declare class MfaNotEnabledError extends KoolbaseAuthError {
300
300
  constructor();
301
301
  }
302
+ /** The signed-in person is not an app admin. The project owner gives the `app_admin` claim in the dashboard. */
303
+ export declare class NotAppAdminError extends KoolbaseAuthError {
304
+ constructor();
305
+ }
306
+ /** An admin tried to disable themselves or change their own roles. */
307
+ export declare class AppAdminSelfError extends KoolbaseAuthError {
308
+ constructor();
309
+ }
310
+ /** The person is an app admin too; only the project owner can change them. */
311
+ export declare class AppAdminTargetIsAdminError extends KoolbaseAuthError {
312
+ constructor();
313
+ }
314
+ /** The project has not let app admins give this role. */
315
+ export declare class RoleNotAssignableError extends KoolbaseAuthError {
316
+ constructor(message?: string);
317
+ }
318
+ /** The role exists, but not with this value. */
319
+ export declare class RoleValueNotAllowedError extends KoolbaseAuthError {
320
+ constructor(message?: string);
321
+ }
322
+ /** The invited email already has an account in this app. */
323
+ export declare class MemberExistsError extends KoolbaseAuthError {
324
+ constructor();
325
+ }
326
+ /**
327
+ * The person's roles changed since they were read; nothing was changed. Read
328
+ * them again, or retry with `currentVersion`.
329
+ */
330
+ export declare class ClaimsVersionConflictError extends KoolbaseAuthError {
331
+ readonly currentVersion: number | null;
332
+ constructor(currentVersion: number | null);
333
+ }
@@ -502,3 +502,64 @@ export class MfaNotEnabledError extends KoolbaseAuthError {
502
502
  Object.setPrototypeOf(this, MfaNotEnabledError.prototype);
503
503
  }
504
504
  }
505
+ // ─── In-app admin ──────────────────────────────────────────────────────────
506
+ /** The signed-in person is not an app admin. The project owner gives the `app_admin` claim in the dashboard. */
507
+ export class NotAppAdminError extends KoolbaseAuthError {
508
+ constructor() {
509
+ super('Only app admins can do this', 'app_admin_required');
510
+ this.name = 'NotAppAdminError';
511
+ Object.setPrototypeOf(this, NotAppAdminError.prototype);
512
+ }
513
+ }
514
+ /** An admin tried to disable themselves or change their own roles. */
515
+ export class AppAdminSelfError extends KoolbaseAuthError {
516
+ constructor() {
517
+ super('You cannot change your own account here', 'app_admin_self');
518
+ this.name = 'AppAdminSelfError';
519
+ Object.setPrototypeOf(this, AppAdminSelfError.prototype);
520
+ }
521
+ }
522
+ /** The person is an app admin too; only the project owner can change them. */
523
+ export class AppAdminTargetIsAdminError extends KoolbaseAuthError {
524
+ constructor() {
525
+ super('Another app admin can only be changed by the project owner', 'app_admin_target_is_admin');
526
+ this.name = 'AppAdminTargetIsAdminError';
527
+ Object.setPrototypeOf(this, AppAdminTargetIsAdminError.prototype);
528
+ }
529
+ }
530
+ /** The project has not let app admins give this role. */
531
+ export class RoleNotAssignableError extends KoolbaseAuthError {
532
+ constructor(message) {
533
+ super(message ?? 'App admins cannot give this role', 'role_not_assignable');
534
+ this.name = 'RoleNotAssignableError';
535
+ Object.setPrototypeOf(this, RoleNotAssignableError.prototype);
536
+ }
537
+ }
538
+ /** The role exists, but not with this value. */
539
+ export class RoleValueNotAllowedError extends KoolbaseAuthError {
540
+ constructor(message) {
541
+ super(message ?? 'That value is not allowed for this role', 'role_value_not_allowed');
542
+ this.name = 'RoleValueNotAllowedError';
543
+ Object.setPrototypeOf(this, RoleValueNotAllowedError.prototype);
544
+ }
545
+ }
546
+ /** The invited email already has an account in this app. */
547
+ export class MemberExistsError extends KoolbaseAuthError {
548
+ constructor() {
549
+ super('Someone with this email is already in the app', 'member_exists');
550
+ this.name = 'MemberExistsError';
551
+ Object.setPrototypeOf(this, MemberExistsError.prototype);
552
+ }
553
+ }
554
+ /**
555
+ * The person's roles changed since they were read; nothing was changed. Read
556
+ * them again, or retry with `currentVersion`.
557
+ */
558
+ export class ClaimsVersionConflictError extends KoolbaseAuthError {
559
+ constructor(currentVersion) {
560
+ super("This person's roles changed since you opened them", 'claims_version_conflict');
561
+ this.currentVersion = currentVersion;
562
+ this.name = 'ClaimsVersionConflictError';
563
+ Object.setPrototypeOf(this, ClaimsVersionConflictError.prototype);
564
+ }
565
+ }
@@ -1,4 +1,5 @@
1
1
  import { AuthStateListener, KoolbaseConfig, KoolbaseSession, KoolbaseUser, LinkPhoneParams, LoginParams, OtpSendResult, PhoneVerifyResult, RegisterParams, RestoreResult, KoolbaseAuditPage, KoolbaseSessionInfo, ResendVerificationResult, SendOtpParams, SignUpResult, SignInWithAppleParams, VerifyOtpParams } from './types.js';
2
+ import { KoolbaseAppAdmin } from './app-admin.js';
2
3
  import type { KoolbaseAvatarFile, SignInWithGoogleParams, SignOutReason } from './types.js';
3
4
  export declare class KoolbaseAuth {
4
5
  private config;
@@ -71,6 +72,19 @@ export declare class KoolbaseAuth {
71
72
  * the caller's own request would have failed first.
72
73
  */
73
74
  private updateUserAndPersist;
75
+ /**
76
+ * Remember me: the choice of the sign-in under way, held until its session
77
+ * is saved -- through a second step (MFA) too. Null: none under way.
78
+ */
79
+ private pendingRemember;
80
+ /** A sign-in starts: its Remember me, omitted meaning remembered. */
81
+ private beginSignIn;
82
+ /**
83
+ * A sign-in's session: told to the storage where it lives first (Remember
84
+ * me), then saved. A refresh or a profile change is not a sign-in and
85
+ * keeps the place the session already has.
86
+ */
87
+ private setSignedInSession;
74
88
  private setSessionInternal;
75
89
  /**
76
90
  * Discards the stored session without contacting the server.
@@ -327,6 +341,13 @@ export declare class KoolbaseAuth {
327
341
  }): Promise<KoolbaseAuditPage>;
328
342
  unlock(token: string): Promise<void>;
329
343
  get currentUser(): KoolbaseUser | null;
344
+ private _admin?;
345
+ /**
346
+ * Managing the app's people, for the app's own admins (the `app_admin`
347
+ * claim). See {@link KoolbaseAppAdmin}.
348
+ */
349
+ get admin(): KoolbaseAppAdmin;
350
+ private adminRequest;
330
351
  get accessToken(): string | null;
331
352
  /**
332
353
  * Currently-valid access token for data-plane requests, refreshing
@@ -378,6 +399,7 @@ export declare class KoolbaseAuth {
378
399
  signInWithEmailCode(params: {
379
400
  email: string;
380
401
  code: string;
402
+ remember?: boolean;
381
403
  }): Promise<KoolbaseSession>;
382
404
  private mfaRequired;
383
405
  /** Finishes sign-in with a code from the person's authenticator app. */
package/dist/esm/auth.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { KoolbaseInvalidPublicKeyError, previewErrorFor } from './errors';
2
2
  import { koolbaseFetch } from './network.js';
3
3
  import { RestoreResult, } from './types.js';
4
- import { AccountLockedError, EmailAlreadyInUseError, InvalidCredentialsError, InvalidPhoneNumberError, KoolbaseAuthError, OtpExpiredError, OtpInvalidError, OtpMaxAttemptsError, OtpRateLimitError, PhoneAlreadyLinkedError, IdentityNotFoundError, InsufficientScopeError, MalformedSessionResponseError, ProviderIdentityAlreadyLinkedError, AccountExistsError, ContactNotVerifiedError, CurrentPasswordIncorrectError, HideRequiresVerificationError, InsufficientAuthorityError, LastCredentialError, OAuthOnlyAccountError, SessionRequiredError, SignupsDisabledError, TokenAlreadyUsedError, TokenExpiredError, UnsupportedOAuthProviderError, RateLimitError, retryAfterOf, VerificationResendCooldownError, VerificationResendDailyCapError, SessionExpiredError, SmsConfigMissingError, TokenRevokedError, UnlockTokenInvalidError, UserDisabledError, WeakPasswordError, AppleEmailRequiredError, AppleSignInNotConfiguredError, InvalidAppleTokenError, OAuthEmailConflictError, GoogleEmailRequiredError, GoogleSignInNotConfiguredError, InvalidGoogleTokenError, EmailCodeDisabledError, MfaRequiredError, RecentAuthRequiredError, RecentMfaRequiredError, MfaAlreadyEnabledError, MfaEnrollmentNotFoundError, MfaNotEnabledError, } from './auth-errors.js';
4
+ import { AccountLockedError, EmailAlreadyInUseError, InvalidCredentialsError, InvalidPhoneNumberError, KoolbaseAuthError, OtpExpiredError, OtpInvalidError, OtpMaxAttemptsError, OtpRateLimitError, PhoneAlreadyLinkedError, IdentityNotFoundError, InsufficientScopeError, MalformedSessionResponseError, ProviderIdentityAlreadyLinkedError, AccountExistsError, ContactNotVerifiedError, CurrentPasswordIncorrectError, HideRequiresVerificationError, InsufficientAuthorityError, LastCredentialError, OAuthOnlyAccountError, SessionRequiredError, SignupsDisabledError, TokenAlreadyUsedError, TokenExpiredError, UnsupportedOAuthProviderError, RateLimitError, retryAfterOf, VerificationResendCooldownError, VerificationResendDailyCapError, SessionExpiredError, SmsConfigMissingError, TokenRevokedError, UnlockTokenInvalidError, UserDisabledError, WeakPasswordError, AppleEmailRequiredError, AppleSignInNotConfiguredError, InvalidAppleTokenError, OAuthEmailConflictError, GoogleEmailRequiredError, GoogleSignInNotConfiguredError, InvalidGoogleTokenError, EmailCodeDisabledError, MfaRequiredError, RecentAuthRequiredError, RecentMfaRequiredError, MfaAlreadyEnabledError, MfaEnrollmentNotFoundError, MfaNotEnabledError, NotAppAdminError, AppAdminSelfError, AppAdminTargetIsAdminError, RoleNotAssignableError, RoleValueNotAllowedError, MemberExistsError, ClaimsVersionConflictError, } from './auth-errors.js';
5
+ import { KoolbaseAppAdmin } from './app-admin.js';
5
6
  import { KoolbaseServiceUnavailableError } from './errors.js';
6
7
  import { getPlatform } from './platform.js';
7
8
  import { DeviceMetadata } from './device-metadata.js';
@@ -23,6 +24,11 @@ export class KoolbaseAuth {
23
24
  this.signOutReason = null;
24
25
  /** The last renewal failed for want of a connection, not because the server refused it (#96). */
25
26
  this.renewalUnavailable = false;
27
+ /**
28
+ * Remember me: the choice of the sign-in under way, held until its session
29
+ * is saved -- through a second step (MFA) too. Null: none under way.
30
+ */
31
+ this.pendingRemember = null;
26
32
  this.config = config;
27
33
  this.metadata = new DeviceMetadata(config.appVersion);
28
34
  this.fetchFn = config.fetch ?? ((url, init) => koolbaseFetch(url, init));
@@ -162,6 +168,29 @@ export class KoolbaseAuth {
162
168
  return;
163
169
  await this.setSessionInternal({ ...this.session, user });
164
170
  }
171
+ /** A sign-in starts: its Remember me, omitted meaning remembered. */
172
+ beginSignIn(remember) {
173
+ this.pendingRemember = remember ?? true;
174
+ }
175
+ /**
176
+ * A sign-in's session: told to the storage where it lives first (Remember
177
+ * me), then saved. A refresh or a profile change is not a sign-in and
178
+ * keeps the place the session already has.
179
+ */
180
+ async setSignedInSession(session) {
181
+ const remember = this.pendingRemember ?? true;
182
+ this.pendingRemember = null;
183
+ if (this.storage?.setRemember) {
184
+ try {
185
+ await this.storage.setRemember(remember);
186
+ }
187
+ catch (err) {
188
+ // eslint-disable-next-line no-console
189
+ console.warn('[Koolbase] Could not apply Remember me:', err);
190
+ }
191
+ }
192
+ await this.setSessionInternal(session);
193
+ }
165
194
  async setSessionInternal(session) {
166
195
  this.session = session;
167
196
  this.signOutReason = null;
@@ -345,16 +374,20 @@ export class KoolbaseAuth {
345
374
  };
346
375
  }
347
376
  const session = this.sessionFromBody(data);
348
- await this.setSessionInternal(session);
377
+ this.beginSignIn(undefined);
378
+ await this.setSignedInSession(session);
349
379
  return { status: 'authenticated', user: session.user, session };
350
380
  }
351
381
  async login(params) {
382
+ // Remember me is this device's, never the server's.
383
+ const { remember, ...body } = params;
384
+ this.beginSignIn(remember);
352
385
  const res = await this.authRequest('/v1/sdk/auth/login', {
353
386
  method: 'POST',
354
- body: params,
387
+ body,
355
388
  });
356
389
  const session = await this.parseSessionResponse(res, false);
357
- await this.setSessionInternal(session);
390
+ await this.setSignedInSession(session);
358
391
  return session;
359
392
  }
360
393
  /**
@@ -383,6 +416,7 @@ export class KoolbaseAuth {
383
416
  * but auto-link rule blocked (409).
384
417
  */
385
418
  async signInWithApple(params) {
419
+ this.beginSignIn(params.remember);
386
420
  const body = {
387
421
  identity_token: params.identityToken,
388
422
  };
@@ -412,7 +446,7 @@ export class KoolbaseAuth {
412
446
  body,
413
447
  });
414
448
  const session = await this.parseAppleSessionResponse(res);
415
- await this.setSessionInternal(session);
449
+ await this.setSignedInSession(session);
416
450
  return session;
417
451
  }
418
452
  /**
@@ -438,6 +472,7 @@ export class KoolbaseAuth {
438
472
  * but auto-link rule blocked (409).
439
473
  */
440
474
  async signInWithGoogle(params) {
475
+ this.beginSignIn(params.remember);
441
476
  const body = {
442
477
  identity_token: params.idToken,
443
478
  };
@@ -449,7 +484,7 @@ export class KoolbaseAuth {
449
484
  body,
450
485
  });
451
486
  const session = await this.parseGoogleSessionResponse(res);
452
- await this.setSessionInternal(session);
487
+ await this.setSignedInSession(session);
453
488
  return session;
454
489
  }
455
490
  /**
@@ -965,6 +1000,66 @@ export class KoolbaseAuth {
965
1000
  get currentUser() {
966
1001
  return this.session?.user ?? null;
967
1002
  }
1003
+ /**
1004
+ * Managing the app's people, for the app's own admins (the `app_admin`
1005
+ * claim). See {@link KoolbaseAppAdmin}.
1006
+ */
1007
+ get admin() {
1008
+ if (!this._admin) {
1009
+ this._admin = new KoolbaseAppAdmin((path, options) => this.adminRequest(path, options));
1010
+ }
1011
+ return this._admin;
1012
+ }
1013
+ async adminRequest(path, options = {}) {
1014
+ const res = await this.authedRequest(path, options);
1015
+ if (res.ok)
1016
+ return res.json().catch(() => ({}));
1017
+ let body = {};
1018
+ try {
1019
+ body = await res.json();
1020
+ }
1021
+ catch {
1022
+ // ignore
1023
+ }
1024
+ const code = body.code ?? '';
1025
+ const msg = body.error ?? '';
1026
+ // The admin routes' own codes first. Their plain failures (a member not
1027
+ // found, a conflict, a refusal) keep the server's words: the general
1028
+ // status fallback would call a 409 an email in use and a 403 a disabled
1029
+ // account, neither of which an admin route means.
1030
+ switch (code) {
1031
+ // Never sent by these routes; mapped so every parser here handles the
1032
+ // challenge the same way (mfa.test checks each switch).
1033
+ case 'mfa_required':
1034
+ throw this.mfaRequired(body);
1035
+ case 'app_admin_required':
1036
+ throw new NotAppAdminError();
1037
+ case 'app_admin_self':
1038
+ throw new AppAdminSelfError();
1039
+ case 'app_admin_target_is_admin':
1040
+ throw new AppAdminTargetIsAdminError();
1041
+ case 'role_not_assignable':
1042
+ throw new RoleNotAssignableError(msg || undefined);
1043
+ case 'role_value_not_allowed':
1044
+ throw new RoleValueNotAllowedError(msg || undefined);
1045
+ case 'member_exists':
1046
+ throw new MemberExistsError();
1047
+ case 'claims_version_conflict':
1048
+ throw new ClaimsVersionConflictError(typeof body.version === 'number' ? body.version : null);
1049
+ case 'not_found':
1050
+ case 'conflict':
1051
+ case 'permission_denied':
1052
+ case 'validation_error':
1053
+ throw new KoolbaseAuthError(msg || 'The request was refused.', code);
1054
+ }
1055
+ // The body is read; hand the general parser what it read.
1056
+ return this.throwTypedError({
1057
+ ok: false,
1058
+ status: res.status,
1059
+ headers: res.headers,
1060
+ json: async () => body,
1061
+ });
1062
+ }
968
1063
  get accessToken() {
969
1064
  return this.session?.accessToken ?? null;
970
1065
  }
@@ -1042,12 +1137,13 @@ export class KoolbaseAuth {
1042
1137
  * @throws EmailCodeDisabledError if the project has switched this off
1043
1138
  */
1044
1139
  async signInWithEmailCode(params) {
1140
+ this.beginSignIn(params.remember);
1045
1141
  const res = await this.authRequest('/v1/sdk/auth/email/code/verify', {
1046
1142
  method: 'POST',
1047
1143
  body: { email: params.email, code: params.code },
1048
1144
  });
1049
1145
  const session = await this.parseSessionResponse(res, false);
1050
- await this.setSessionInternal(session);
1146
+ await this.setSignedInSession(session);
1051
1147
  return session;
1052
1148
  }
1053
1149
  // ─── Two-step sign-in (MFA) ─────────────────────────────────────────────
@@ -1067,7 +1163,8 @@ export class KoolbaseAuth {
1067
1163
  body: { challenge_token: params.challengeToken, code: params.code },
1068
1164
  });
1069
1165
  const session = await this.parseSessionResponse(res, false);
1070
- await this.setSessionInternal(session);
1166
+ // The second step of the sign-in that asked for it: its Remember me.
1167
+ await this.setSignedInSession(session);
1071
1168
  return session;
1072
1169
  }
1073
1170
  /**
@@ -1093,7 +1190,7 @@ export class KoolbaseAuth {
1093
1190
  expiresAt: data.expires_at,
1094
1191
  user: this.mapUser(data.user),
1095
1192
  };
1096
- await this.setSessionInternal(session);
1193
+ await this.setSignedInSession(session);
1097
1194
  return { session, recoveryCodesRemaining: Number(data.recovery_codes_remaining ?? 0) };
1098
1195
  }
1099
1196
  /**
@@ -1158,6 +1255,7 @@ export class KoolbaseAuth {
1158
1255
  }
1159
1256
  async verifyOtp(params) {
1160
1257
  this.validatePhone(params.phoneNumber);
1258
+ this.beginSignIn(params.remember);
1161
1259
  const res = await this.authRequest('/v1/sdk/auth/phone/verify-otp', {
1162
1260
  method: 'POST',
1163
1261
  body: {
@@ -1172,7 +1270,7 @@ export class KoolbaseAuth {
1172
1270
  expiresAt: data.expires_at,
1173
1271
  user: this.mapUser(data.user),
1174
1272
  };
1175
- await this.setSessionInternal(session);
1273
+ await this.setSignedInSession(session);
1176
1274
  return { session, isNewUser: data.is_new_user ?? false };
1177
1275
  }
1178
1276
  async linkPhone(params) {
@@ -10,6 +10,7 @@ export * from './auth-errors.js';
10
10
  export * from './database-errors.js';
11
11
  export * from './storage-errors.js';
12
12
  export { KoolbaseAuth } from './auth.js';
13
+ export { KoolbaseAppAdmin } from './app-admin.js';
13
14
  export { KoolbaseDatabase } from './database.js';
14
15
  export { KoolbaseCollectionController, collectionQueryKey, initialCollectionState, } from './collection-controller.js';
15
16
  export type { CollectionQuery, CollectionState, CollectionStatus } from './collection-controller.js';
package/dist/esm/index.js CHANGED
@@ -15,6 +15,7 @@ export * from './auth-errors.js';
15
15
  export * from './database-errors.js';
16
16
  export * from './storage-errors.js';
17
17
  export { KoolbaseAuth } from './auth.js';
18
+ export { KoolbaseAppAdmin } from './app-admin.js';
18
19
  export { KoolbaseDatabase } from './database.js';
19
20
  export { KoolbaseCollectionController, collectionQueryKey, initialCollectionState, } from './collection-controller.js';
20
21
  export { KoolbaseRecordController, initialRecordState } from './record-controller.js';