@protobase/client 0.46.2 → 0.46.4

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.
@@ -0,0 +1,17 @@
1
+ //#region src/account-profile.d.ts
2
+ /**
3
+ * A browser or app signed in to the account: its session token (to sign it out), whether it is this one, its user agent
4
+ * and IP address when known, when it signed in, was last active and expires, and the staff member's address for a
5
+ * staff session.
6
+ */
7
+ export type DeviceSession = {
8
+ token: string;
9
+ current: boolean;
10
+ userAgent?: string;
11
+ ipAddress?: string;
12
+ createdAt: string;
13
+ updatedAt: string;
14
+ expiresAt: string;
15
+ staff?: string;
16
+ };
17
+ //#endregion
@@ -0,0 +1,83 @@
1
+ import { authError } from "./auth-error.js";
2
+ //#region src/account-profile.ts
3
+ const isoDate = (value) => new Date(value).toISOString();
4
+ /** The signed-in person's name, address, password and signed-in devices. Each call rejects with `AuthError`. */
5
+ const accountProfile = (client) => ({
6
+ updateName: async (name) => {
7
+ const { error } = await client.updateUser({ name });
8
+ if (error) throw authError(error, "Could not change your name");
9
+ },
10
+ /** Changes the password, which the account must have; `signOutOthers` signs out every other device, this one stays signed in. */
11
+ changePassword: async (current, next, signOutOthers) => {
12
+ const { error } = await client.changePassword({
13
+ currentPassword: current,
14
+ newPassword: next,
15
+ revokeOtherSessions: signOutOthers
16
+ });
17
+ if (error) throw authError(error, "Could not change your password");
18
+ },
19
+ /**
20
+ * Gives an account without a password, such as one that signs in with emailed codes or GitHub, its first one; every
21
+ * device stays signed in. One that has a password already is refused (`PASSWORD_ALREADY_SET`).
22
+ */
23
+ setPassword: async (next) => {
24
+ const { error } = await client.$fetch("/account/set-password", {
25
+ method: "POST",
26
+ body: { newPassword: next }
27
+ });
28
+ if (error) throw authError(error, "Could not set your password");
29
+ },
30
+ /**
31
+ * Mails a code to `newEmail` that moves the account to it, when the server has mail (`status().changeEmail`). The answer
32
+ * is the same when another account has the address, which then gets no code.
33
+ */
34
+ requestEmailChange: async (newEmail) => {
35
+ const { error } = await client.$fetch("/email-otp/request-email-change", {
36
+ method: "POST",
37
+ body: { newEmail }
38
+ });
39
+ if (error) throw authError(error, "Could not send the code");
40
+ },
41
+ /** Moves the account to `newEmail` with the code mailed there; this device stays signed in, with the new address. */
42
+ changeEmail: async (newEmail, code) => {
43
+ const { error } = await client.$fetch("/email-otp/change-email", {
44
+ method: "POST",
45
+ body: {
46
+ newEmail,
47
+ otp: code
48
+ }
49
+ });
50
+ if (error) throw authError(error, "Could not change your address");
51
+ },
52
+ /** The devices signed in now, with this one marked `current`. */
53
+ sessions: async () => {
54
+ const [list, own] = await Promise.all([client.listSessions(), client.getSession()]);
55
+ if (list.error || !list.data) throw authError(list.error, "Could not read your devices");
56
+ const currentToken = own.data?.session.token;
57
+ return list.data.map((session) => {
58
+ const staff = session.impersonatedBy;
59
+ return {
60
+ token: session.token,
61
+ current: session.token === currentToken,
62
+ ...session.userAgent && { userAgent: session.userAgent },
63
+ ...session.ipAddress && { ipAddress: session.ipAddress },
64
+ createdAt: isoDate(session.createdAt),
65
+ updatedAt: isoDate(session.updatedAt),
66
+ expiresAt: isoDate(session.expiresAt),
67
+ ...staff && { staff }
68
+ };
69
+ });
70
+ },
71
+ /** Signs out one device, by its session token from `sessions`. */
72
+ revokeSession: async (token) => {
73
+ const { error } = await client.revokeSession({ token });
74
+ if (error) throw authError(error, "Could not sign out the device");
75
+ },
76
+ /** Signs out every device but this one. */
77
+ revokeOtherSessions: async () => {
78
+ const { error } = await client.revokeOtherSessions();
79
+ if (error) throw authError(error, "Could not sign out your other devices");
80
+ }
81
+ });
82
+ //#endregion
83
+ export { accountProfile };
@@ -31,7 +31,8 @@ export type SamlSignIn = {
31
31
  };
32
32
  /**
33
33
  * `needsAdmin` while no user exists yet; `signInMethods` the ways to sign in the server's policy leaves on;
34
- * `passwordReset` when the server can email reset links; `signUp` when anyone can make their own account (see
34
+ * `passwordReset` when the server can email reset links; `changeEmail` when it can email the code that confirms a new
35
+ * address (see `account.requestEmailChange`); `signUp` when anyone can make their own account (see
35
36
  * `sendSignUpCode`); `socialProviders` the ids of the sign-in providers, for example
36
37
  * `github`; `platformSignIn` the one of them the platform adds; `samlProviders` the app's SAML identity providers; `staffSignIn` the operator provider's name when its staff
37
38
  * can sign in as people; `organizations` when the app has them; `anonymous` when visitors may browse what the project's
@@ -43,6 +44,7 @@ export type SetupStatus = {
43
44
  needsAdmin: boolean;
44
45
  signInMethods: SignInMethod[];
45
46
  passwordReset: boolean;
47
+ changeEmail?: boolean;
46
48
  signUp?: boolean;
47
49
  socialProviders: string[];
48
50
  platformSignIn?: PlatformSignIn;
package/dist/auth.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { DeviceSession } from "./account-profile.js";
1
2
  import { SignInPolicy, SignInPolicyState } from "./sign-in-policy.js";
2
3
  import { AccountSignIn, AuthenticatorSetup, ConnectedApp, Passkey } from "./account-security.js";
3
4
  import { ConnectingClient } from "./connect.js";
@@ -23,7 +24,7 @@ export type AuthSessionOptions = {
23
24
  export declare const tokenExpiry: (token: string) => number;
24
25
  /**
25
26
  * The browser side of Better Auth: sign in with a password, an emailed code or a passkey (with a second step for an
26
- * account with two-factor authentication), the account's passkeys and two-factor authentication (`account`), the
27
+ * account with two-factor authentication), the account's name, password, devices, passkeys and two-factor authentication (`account`), the
27
28
  * sign-in policy for admins (`signInPolicy`), the people who can sign in for admins (`users`), staff of the operator
28
29
  * signing in as people (`staff`), organizations (`organizations`), the role the session acts with (`roles`), allowing an outside app such as an MCP client (`connect`), and a short-lived
29
30
  * JWT held in memory only (never in storage), fetched with the session cookie and refreshed before it expires.
@@ -50,6 +51,14 @@ export declare const createAuthSession: (options?: AuthSessionOptions) => {
50
51
  /** Sets a new password with the token from a reset link; the link works once. */
51
52
  resetPassword: (token: string, newPassword: string) => Promise<void>;
52
53
  account: {
54
+ updateName: (name: string) => Promise<void>;
55
+ changePassword: (current: string, next: string, signOutOthers: boolean) => Promise<void>;
56
+ setPassword: (next: string) => Promise<void>;
57
+ requestEmailChange: (newEmail: string) => Promise<void>;
58
+ changeEmail: (newEmail: string, code: string) => Promise<void>;
59
+ sessions: () => Promise<DeviceSession[]>;
60
+ revokeSession: (token: string) => Promise<void>;
61
+ revokeOtherSessions: () => Promise<void>;
53
62
  signInMethods: () => Promise<AccountSignIn>;
54
63
  passkeys: () => Promise<Passkey[]>;
55
64
  addPasskey: (name?: string) => Promise<void>;
package/dist/auth.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { AuthError, authError } from "./auth-error.js";
2
+ import { accountProfile } from "./account-profile.js";
2
3
  import { accountSecurity } from "./account-security.js";
3
4
  import { connectClient } from "./connect.js";
4
5
  import { betterAuthClient } from "./better-auth-client.js";
@@ -20,7 +21,7 @@ const tokenExpiry = (token) => {
20
21
  };
21
22
  /**
22
23
  * The browser side of Better Auth: sign in with a password, an emailed code or a passkey (with a second step for an
23
- * account with two-factor authentication), the account's passkeys and two-factor authentication (`account`), the
24
+ * account with two-factor authentication), the account's name, password, devices, passkeys and two-factor authentication (`account`), the
24
25
  * sign-in policy for admins (`signInPolicy`), the people who can sign in for admins (`users`), staff of the operator
25
26
  * signing in as people (`staff`), organizations (`organizations`), the role the session acts with (`roles`), allowing an outside app such as an MCP client (`connect`), and a short-lived
26
27
  * JWT held in memory only (never in storage), fetched with the session cookie and refreshed before it expires.
@@ -76,6 +77,7 @@ const createAuthSession = (options = {}) => {
76
77
  needsAdmin: Boolean(body.needsAdmin),
77
78
  signInMethods: body.signInMethods ?? ["password"],
78
79
  passwordReset: Boolean(body.passwordReset),
80
+ ...body.changeEmail && { changeEmail: true },
79
81
  ...body.signUp && { signUp: true },
80
82
  socialProviders: body.socialProviders ?? [],
81
83
  ...body.platformSignIn && { platformSignIn: body.platformSignIn },
@@ -150,7 +152,10 @@ const createAuthSession = (options = {}) => {
150
152
  });
151
153
  if (error) throw authError(error, "Could not set the password");
152
154
  },
153
- account: accountSecurity(client),
155
+ account: {
156
+ ...accountSecurity(client),
157
+ ...accountProfile(client)
158
+ },
154
159
  connect: connectClient(client),
155
160
  organizations: organizationsClient(client, () => token({ refresh: true })),
156
161
  roles: rolesClient(client, () => token({ refresh: true })),
package/dist/index.d.ts CHANGED
@@ -10,6 +10,7 @@ import { ApiError, PreconditionFailedError, ProblemDetails, ProblemError, isApiE
10
10
  import { fileUrl } from "./file-urls.js";
11
11
  import { routedClient } from "./routed-client.js";
12
12
  import { SourceMeta, sourceMeta } from "./source-meta.js";
13
+ import { DeviceSession } from "./account-profile.js";
13
14
  import { SignInPolicy, SignInPolicyClient, SignInPolicyState, SignInRule, StaffAccessRule } from "./sign-in-policy.js";
14
15
  import { AccountSecurity, AccountSignIn, AuthenticatorSetup, ConnectedApp, Passkey, RequiredSetup } from "./account-security.js";
15
16
  import { ConnectClient, ConnectingClient } from "./connect.js";
@@ -23,4 +24,4 @@ import { AuthSession, AuthSessionOptions, createAuthSession, tokenExpiry } from
23
24
  import { createStaticSession } from "./static-session.js";
24
25
  import { AssistantClient, AssistantClientOptions, AssistantConnection, createAssistantClient } from "./assistant.js";
25
26
  import { RuntimeClient, RuntimeClientOptions, RuntimeLastUpdate, RuntimePolicy, RuntimeStatus, RuntimeUpdateStage, createRuntimeClient } from "./runtime.js";
26
- export { type AccountSecurity, type AccountSignIn, type ActiveRole, type Aggregate, type AggregateGroup, type AggregateParams, type AggregateSplitTotal, ApiError, type AppUser, type AssistantClient, type AssistantClientOptions, type AssistantConnection, AuthError, type AuthSession, type AuthSessionOptions, type AuthUser, type AuthenticatorSetup, type BatchOp, type BatchRef, type BatchResult, type Client, type ClientOptions, type CommentPage, type CommentPerson, type ConnectClient, type ConnectedApp, type ConnectingClient, type CurrentOrganization, type DevicesClient, type Facet, type FilterInput, type FormChallenge, type FormProof, type Histogram, type HistogramBucket, type HistoryChange, type HistoryPage, type InboxNotification, type InboxPage, type InvitationPreview, type InvitationSent, type InvokeOptions, type ListPage, type ListParams, type LiveChange, type LiveHandlers, type MapBounds, type MapBucket, type MapLayerModel, type MapParams, type MapResult, type MentionableUser, type Meta, type MetaResult, type NotificationHistoryClient, type Organization, type OrganizationInvitation, type OrganizationMember, type OrganizationRole, type OrganizationsClient, type OrganizationsFound, type Passkey, type PlatformSignIn, type PluginRef, PreconditionFailedError, type ProblemDetails, type ProblemError, type PublicForm, type RecordComment, type RecordOf, type RecordPermissions, type RecordPhotos, type RegisteredDevice, type RelatedLabels, type RequiredSetup, type ResourcePermissions, type ResourceRef, type RoleLabel, type RoleOption, type RolesClient, type RuntimeClient, type RuntimeClientOptions, type RuntimeLastUpdate, type RuntimePolicy, type RuntimeStatus, type RuntimeUpdateStage, type SamlSignIn, type Series, type SeriesParams, type SeriesPoint, type SetupStatus, type SignInMethod, type SignInPolicy, type SignInPolicyClient, type SignInPolicyState, type SignInResult, type SignInRule, type SourceMeta, type SourceRef, type StaffAccessRule, type StaffSignIn, type StaffSignInClient, type Stored, type StoredFile, type StoredFileVariant, type TwoFactorMethod, type UploadOptions, type UploadProgress, type UploadResult, type UserInvitation, type UserInvitationSent, type UsersClient, type UsersFound, type WebDeviceRegistration, createAssistantClient, createAuthSession, createClient, createRuntimeClient, createStaticSession, fileUrl, filterText, isApiError, listWire, routedClient, sourceMeta, tokenExpiry };
27
+ export { type AccountSecurity, type AccountSignIn, type ActiveRole, type Aggregate, type AggregateGroup, type AggregateParams, type AggregateSplitTotal, ApiError, type AppUser, type AssistantClient, type AssistantClientOptions, type AssistantConnection, AuthError, type AuthSession, type AuthSessionOptions, type AuthUser, type AuthenticatorSetup, type BatchOp, type BatchRef, type BatchResult, type Client, type ClientOptions, type CommentPage, type CommentPerson, type ConnectClient, type ConnectedApp, type ConnectingClient, type CurrentOrganization, type DeviceSession, type DevicesClient, type Facet, type FilterInput, type FormChallenge, type FormProof, type Histogram, type HistogramBucket, type HistoryChange, type HistoryPage, type InboxNotification, type InboxPage, type InvitationPreview, type InvitationSent, type InvokeOptions, type ListPage, type ListParams, type LiveChange, type LiveHandlers, type MapBounds, type MapBucket, type MapLayerModel, type MapParams, type MapResult, type MentionableUser, type Meta, type MetaResult, type NotificationHistoryClient, type Organization, type OrganizationInvitation, type OrganizationMember, type OrganizationRole, type OrganizationsClient, type OrganizationsFound, type Passkey, type PlatformSignIn, type PluginRef, PreconditionFailedError, type ProblemDetails, type ProblemError, type PublicForm, type RecordComment, type RecordOf, type RecordPermissions, type RecordPhotos, type RegisteredDevice, type RelatedLabels, type RequiredSetup, type ResourcePermissions, type ResourceRef, type RoleLabel, type RoleOption, type RolesClient, type RuntimeClient, type RuntimeClientOptions, type RuntimeLastUpdate, type RuntimePolicy, type RuntimeStatus, type RuntimeUpdateStage, type SamlSignIn, type Series, type SeriesParams, type SeriesPoint, type SetupStatus, type SignInMethod, type SignInPolicy, type SignInPolicyClient, type SignInPolicyState, type SignInResult, type SignInRule, type SourceMeta, type SourceRef, type StaffAccessRule, type StaffSignIn, type StaffSignInClient, type Stored, type StoredFile, type StoredFileVariant, type TwoFactorMethod, type UploadOptions, type UploadProgress, type UploadResult, type UserInvitation, type UserInvitationSent, type UsersClient, type UsersFound, type WebDeviceRegistration, createAssistantClient, createAuthSession, createClient, createRuntimeClient, createStaticSession, fileUrl, filterText, isApiError, listWire, routedClient, sourceMeta, tokenExpiry };
@@ -3,8 +3,9 @@ import { AuthSession } from "./auth.js";
3
3
  //#region src/static-session.d.ts
4
4
  /**
5
5
  * A session that is already signed in with a token you hold, for stories and scripts (`protobase token <email>`).
6
- * It never refreshes, so use a token that outlives the run. Its account has nothing to set up, and it cannot change
7
- * passkeys, two-factor authentication, the sign-in policy, organizations or its role, and is never a staff session.
6
+ * It never refreshes, so use a token that outlives the run. Its account has nothing to set up and no devices, and it
7
+ * cannot change its name, password, passkeys, two-factor authentication, the sign-in policy, organizations or its role,
8
+ * and is never a staff session.
8
9
  */
9
10
  export declare const createStaticSession: (token: string, user?: AuthUser) => AuthSession;
10
11
  //#endregion
@@ -5,8 +5,9 @@ const unsupported = (what) => async () => {
5
5
  };
6
6
  /**
7
7
  * A session that is already signed in with a token you hold, for stories and scripts (`protobase token <email>`).
8
- * It never refreshes, so use a token that outlives the run. Its account has nothing to set up, and it cannot change
9
- * passkeys, two-factor authentication, the sign-in policy, organizations or its role, and is never a staff session.
8
+ * It never refreshes, so use a token that outlives the run. Its account has nothing to set up and no devices, and it
9
+ * cannot change its name, password, passkeys, two-factor authentication, the sign-in policy, organizations or its role,
10
+ * and is never a staff session.
10
11
  */
11
12
  const createStaticSession = (token, user = {
12
13
  id: "token",
@@ -74,7 +75,15 @@ const createStaticSession = (token, user = {
74
75
  linkedProviders: async () => [],
75
76
  linkProvider: unsupported("link a sign-in provider"),
76
77
  connectedApps: async () => [],
77
- disconnectApp: unsupported("disconnect an app")
78
+ disconnectApp: unsupported("disconnect an app"),
79
+ updateName: unsupported("change its name"),
80
+ changePassword: unsupported("change its password"),
81
+ setPassword: unsupported("set its password"),
82
+ requestEmailChange: unsupported("change its address"),
83
+ changeEmail: unsupported("change its address"),
84
+ sessions: async () => [],
85
+ revokeSession: unsupported("sign out a device"),
86
+ revokeOtherSessions: unsupported("sign out other devices")
78
87
  },
79
88
  connect: {
80
89
  client: unsupported("allow an app"),
package/dist/types.d.ts CHANGED
@@ -261,6 +261,7 @@ export type Meta = {
261
261
  resources: ResourceModel[];
262
262
  views: ViewModel[];
263
263
  pages?: PageModel[];
264
+ account?: PageModel;
264
265
  permissions?: Record<string, ResourcePermissions>;
265
266
  userMenu?: UserMenuModel;
266
267
  signIn?: SignInViewModel[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/client",
3
- "version": "0.46.2",
3
+ "version": "0.46.4",
4
4
  "description": "Typed fetch client for the Protobase REST API.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -30,8 +30,8 @@
30
30
  },
31
31
  "dependencies": {
32
32
  "@better-auth/passkey": "^1.7.12",
33
- "@protobase/layout": "0.46.2",
34
- "@protobase/schema": "0.46.2",
33
+ "@protobase/layout": "0.46.4",
34
+ "@protobase/schema": "0.46.4",
35
35
  "@simplewebauthn/browser": "^13.3.0",
36
36
  "better-auth": "^1.7.12"
37
37
  }