@protobase/server 0.4.1 → 0.6.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 (47) hide show
  1. package/dist/admin-options.d.ts +35 -0
  2. package/dist/aggregate-service.js +1 -1
  3. package/dist/assistant/assistant-settings.d.ts +4 -7
  4. package/dist/assistant/built-in-assistant.js +21 -5
  5. package/dist/assistant/chat-completions.d.ts +7 -1
  6. package/dist/assistant/conversations.d.ts +1 -1
  7. package/dist/assistant/records.d.ts +23 -0
  8. package/dist/assistant/records.js +53 -0
  9. package/dist/assistant/tools.d.ts +3 -0
  10. package/dist/assistant/turn.d.ts +4 -2
  11. package/dist/assistant/turn.js +3 -1
  12. package/dist/assistant/widget.d.ts +15 -0
  13. package/dist/assistant/widget.js +32 -0
  14. package/dist/batch/reorder.js +3 -3
  15. package/dist/better-auth/auth-schema.d.ts +14 -0
  16. package/dist/better-auth/auth-schema.js +35 -0
  17. package/dist/better-auth/create-auth.d.ts +41 -6
  18. package/dist/better-auth/create-auth.js +29 -8
  19. package/dist/better-auth/platform-sign-in.d.ts +30 -0
  20. package/dist/better-auth/platform-sign-in.js +88 -0
  21. package/dist/better-auth/policy-plugin.js +10 -5
  22. package/dist/better-auth/policy-store.js +5 -0
  23. package/dist/better-auth/sign-in-enforcement.js +11 -3
  24. package/dist/better-auth/sign-in-policy.d.ts +8 -1
  25. package/dist/better-auth/sign-in-policy.js +21 -7
  26. package/dist/better-auth/staff-plugin.js +1 -1
  27. package/dist/better-auth/status-route.js +10 -4
  28. package/dist/better-auth/users.d.ts +8 -1
  29. package/dist/better-auth/users.js +16 -1
  30. package/dist/create-admin.d.ts +2 -1
  31. package/dist/create-admin.js +15 -8
  32. package/dist/deps.d.ts +6 -0
  33. package/dist/index.d.ts +15 -9
  34. package/dist/index.js +5 -1
  35. package/dist/list-service.js +4 -4
  36. package/dist/project-config.d.ts +28 -0
  37. package/dist/project-config.js +111 -0
  38. package/dist/read-service.js +3 -3
  39. package/dist/registry.d.ts +2 -0
  40. package/dist/routes/record.js +2 -2
  41. package/dist/row-permissions.js +2 -2
  42. package/dist/scan-guard.d.ts +4 -0
  43. package/dist/types.d.ts +1 -32
  44. package/dist/write-pipeline.js +2 -2
  45. package/dist/write-shared.js +2 -2
  46. package/dist/write-update.js +2 -2
  47. package/package.json +4 -4
@@ -0,0 +1,88 @@
1
+ import { decodeJwt } from "jose";
2
+ //#region src/better-auth/platform-sign-in.ts
3
+ const signInIssuerVariable = "PROTOBASE_SIGN_IN_ISSUER";
4
+ const signInClientIdVariable = "PROTOBASE_SIGN_IN_CLIENT_ID";
5
+ const signInClientSecretVariable = "PROTOBASE_SIGN_IN_CLIENT_SECRET";
6
+ const signInProviderVariable = "PROTOBASE_SIGN_IN_PROVIDER";
7
+ const signInNameVariable = "PROTOBASE_SIGN_IN_NAME";
8
+ /**
9
+ * The provider the platform passes in `PROTOBASE_SIGN_IN_ISSUER`, `PROTOBASE_SIGN_IN_CLIENT_ID` and
10
+ * `PROTOBASE_SIGN_IN_CLIENT_SECRET` (with `PROTOBASE_SIGN_IN_PROVIDER` and `PROTOBASE_SIGN_IN_NAME` optional);
11
+ * `undefined` when none of the three is set. Some but not all of them stops the server at startup.
12
+ */
13
+ const readPlatformSignIn = (env) => {
14
+ const required = [
15
+ signInIssuerVariable,
16
+ signInClientIdVariable,
17
+ signInClientSecretVariable
18
+ ];
19
+ const [issuer, clientId, clientSecret] = required.map((name) => env[name]?.trim() || void 0);
20
+ if (!issuer && !clientId && !clientSecret) return void 0;
21
+ if (!issuer || !clientId || !clientSecret) throw new Error(`${required.join(", ")} go together: set all three for the platform sign-in provider, or none`);
22
+ const provider = env[signInProviderVariable]?.trim();
23
+ const name = env[signInNameVariable]?.trim();
24
+ return {
25
+ issuer,
26
+ clientId,
27
+ clientSecret,
28
+ ...provider && { provider },
29
+ ...name && { name }
30
+ };
31
+ };
32
+ const providerId = /^[a-z][a-z0-9-]*$/;
33
+ /** The provider with its defaults filled in; an issuer that is not a URL or a malformed id is an error. */
34
+ const resolvePlatformSignIn = (signIn) => {
35
+ if (!URL.canParse(signIn.issuer)) throw new Error(`The platform sign-in provider's issuer must be a URL, not "${signIn.issuer}"`);
36
+ const provider = signIn.provider ?? "oidc";
37
+ if (!providerId.test(provider)) throw new Error(`Invalid sign-in provider id "${provider}": use lowercase letters, digits or "-"`);
38
+ return {
39
+ ...signIn,
40
+ provider,
41
+ name: signIn.name ?? (provider === "github" ? "GitHub" : "SSO"),
42
+ scopes: signIn.scopes ?? []
43
+ };
44
+ };
45
+ /** The platform provider, unless the app configures a provider of its own with the same id, which then wins. */
46
+ const platformSignInFor = (signIn, socialProviders) => signIn && !socialProviders.includes(signIn.provider) ? signIn : void 0;
47
+ /**
48
+ * The person as an ID token Better Auth already verified (the provider's keys, this client and the nonce) says, once
49
+ * its issuer is the configured one; `null` without an ID token, so nothing comes from an unverified source.
50
+ */
51
+ const idTokenUser = (idToken, issuer) => {
52
+ if (!idToken) return null;
53
+ const claims = decodeJwt(idToken);
54
+ if (claims.iss !== issuer || typeof claims.sub !== "string" || !claims.sub || typeof claims.email !== "string") return null;
55
+ return {
56
+ id: claims.sub,
57
+ sub: claims.sub,
58
+ email: claims.email,
59
+ emailVerified: claims.email_verified === true,
60
+ name: typeof claims.name === "string" && claims.name ? claims.name : claims.email.split("@")[0],
61
+ ...typeof claims.picture === "string" && { image: claims.picture }
62
+ };
63
+ };
64
+ /**
65
+ * The provider for Better Auth's generic OAuth plugin: discovery, PKCE, the client secret in a Basic header, an ID
66
+ * token that must verify against the provider's keys, and no sign-up. A provider whose settings cannot be read at
67
+ * startup is left out until the next start.
68
+ */
69
+ const platformSignInProvider = (signIn) => ({
70
+ providerId: signIn.provider,
71
+ name: signIn.name,
72
+ clientId: signIn.clientId,
73
+ clientSecret: signIn.clientSecret,
74
+ discoveryUrl: `${signIn.issuer.replace(/\/$/, "")}/.well-known/openid-configuration`,
75
+ scopes: [
76
+ "openid",
77
+ "email",
78
+ "profile",
79
+ ...signIn.scopes
80
+ ],
81
+ pkce: true,
82
+ requireIdTokenVerification: true,
83
+ authentication: "basic",
84
+ disableSignUp: true,
85
+ getUserInfo: async (tokens) => idTokenUser(tokens.idToken, signIn.issuer)
86
+ });
87
+ //#endregion
88
+ export { idTokenUser, platformSignInFor, platformSignInProvider, readPlatformSignIn, resolvePlatformSignIn, signInClientIdVariable, signInClientSecretVariable, signInIssuerVariable, signInNameVariable, signInProviderVariable };
@@ -36,8 +36,9 @@ const refuse = (status, refusal) => new APIError(status, refusal);
36
36
  * applies it to Better Auth's own endpoints. A method the policy turns off answers `403 SIGN_IN_METHOD_FORBIDDEN`;
37
37
  * someone without what it requires gets a session, so they can set it up, but no API token (`403 SIGN_IN_SETUP_REQUIRED`).
38
38
  */
39
- const signInPolicyPlugin = ({ mail, socialProviders, operator }) => {
39
+ const signInPolicyPlugin = ({ mail, socialProviders, operator, platformSignIn }) => {
40
40
  const currentPolicy = async (context) => effectiveSignInPolicy((await readSignInPolicy(context.adapter)).policy, { mail });
41
+ const providersUnder = (policy) => [...socialProviders, ...platformSignIn && policy.platformSignIn === "allowed" ? [platformSignIn.provider] : []];
41
42
  const policyAdmin = adminOnly("Only an admin can change how people sign in.");
42
43
  const policyAnswer = async (context) => {
43
44
  const stored = await readSignInPolicy(context.adapter);
@@ -47,6 +48,7 @@ const signInPolicyPlugin = ({ mail, socialProviders, operator }) => {
47
48
  effective: effectiveSignInPolicy(stored.policy, { mail }),
48
49
  mail,
49
50
  ...operator && { operator },
51
+ ...platformSignIn && { platformSignIn: platformSignIn.name },
50
52
  ...stored.savedAt && { savedAt: stored.savedAt },
51
53
  ...savedBy && { savedBy }
52
54
  };
@@ -72,9 +74,10 @@ const signInPolicyPlugin = ({ mail, socialProviders, operator }) => {
72
74
  message: "Choose one of the offered rules for every sign-in method."
73
75
  });
74
76
  const user = ctx.context.session.user;
77
+ const admin = await accountMethods(ctx.context, user, providersUnder(effectiveSignInPolicy(policy, { mail })));
75
78
  const problem = signInPolicyProblem(policy, {
76
79
  mail,
77
- admin: await accountMethods(ctx.context, user, socialProviders)
80
+ admin
78
81
  });
79
82
  if (problem) throw refuse("BAD_REQUEST", {
80
83
  code: "SIGN_IN_POLICY_REFUSED",
@@ -92,7 +95,7 @@ const signInPolicyPlugin = ({ mail, socialProviders, operator }) => {
92
95
  use: [sessionMiddleware]
93
96
  }, async (ctx) => {
94
97
  const policy = await currentPolicy(ctx.context);
95
- const { socialSignIn: _, ...account } = await accountMethods(ctx.context, ctx.context.session.user, socialProviders);
98
+ const { socialSignIn: _, ...account } = await accountMethods(ctx.context, ctx.context.session.user, providersUnder(policy));
96
99
  return ctx.json({
97
100
  policy,
98
101
  mail,
@@ -112,14 +115,16 @@ const signInPolicyPlugin = ({ mail, socialProviders, operator }) => {
112
115
  const policy = await currentPolicy(ctx.context);
113
116
  const refusal = policyRefusal(policy, {
114
117
  path,
115
- body: ctx.body
118
+ body: ctx.body,
119
+ params: ctx.params,
120
+ ...platformSignIn && { platformProvider: platformSignIn.provider }
116
121
  });
117
122
  if (refusal) throw refuse("FORBIDDEN", refusal);
118
123
  if (path === "/sign-in/email-otp") return vouchForCreatedAccount(ctx.context, ctx.body.email);
119
124
  if (!(path === "/token" && (policy.twoFactor === "required" || policy.passkey === "required") || path === "/passkey/delete-passkey" && policy.passkey === "required")) return;
120
125
  const session = await getSessionFromCtx(ctx);
121
126
  if (!session || isStaffSession(session.session)) return;
122
- const account = await accountMethods(ctx.context, session.user, socialProviders);
127
+ const account = await accountMethods(ctx.context, session.user, providersUnder(policy));
123
128
  if (path === "/token" && missingRequiredMethods(policy, account).length > 0) throw refuse("FORBIDDEN", setupRequired);
124
129
  if (path === "/passkey/delete-passkey" && account.passkeys <= 1) throw refuse("FORBIDDEN", lastPasskeyRequired);
125
130
  })
@@ -24,6 +24,11 @@ const signInPolicySchema = { [signInPolicyModel]: { fields: {
24
24
  required: true,
25
25
  defaultValue: "allowed"
26
26
  },
27
+ platformSignIn: {
28
+ type: "string",
29
+ required: true,
30
+ defaultValue: "allowed"
31
+ },
27
32
  createdAt: {
28
33
  type: "date",
29
34
  required: true
@@ -13,6 +13,8 @@ const passkeyPaths = [
13
13
  "/passkey/verify-registration"
14
14
  ];
15
15
  const staffSignInPath = "/staff/sign-in";
16
+ const providerPaths = ["/sign-in/social", "/link-social"];
17
+ const callbackPath = "/callback/:id";
16
18
  const accountPaths = [
17
19
  "/email-otp/send-verification-otp",
18
20
  "/passkey/delete-passkey",
@@ -26,23 +28,29 @@ const isPoliced = (path) => path !== void 0 && ([
26
28
  ...emailCodePaths,
27
29
  ...passkeyPaths,
28
30
  ...accountPaths,
31
+ ...providerPaths,
32
+ callbackPath,
29
33
  "/staff/sign-in"
30
34
  ].includes(path) || path.startsWith("/reset-password/"));
31
- const methodOf = (path, body) => {
35
+ const providerOf = ({ path, body, params }) => providerPaths.includes(path) ? body?.provider : path === callbackPath ? params?.id : void 0;
36
+ const methodOf = (request) => {
37
+ const { path, body } = request;
32
38
  if (passwordPaths.includes(path) || path.startsWith("/reset-password/")) return "password";
33
39
  if (emailCodePaths.includes(path)) return "emailCode";
34
40
  if (path === "/email-otp/send-verification-otp" && body?.type === "sign-in") return "emailCode";
35
41
  if (passkeyPaths.includes(path)) return "passkey";
36
42
  if (path === "/two-factor/enable") return "twoFactor";
37
43
  if (path === "/staff/sign-in") return "staffAccess";
44
+ if (request.platformProvider !== void 0 && providerOf(request) === request.platformProvider) return "platformSignIn";
38
45
  };
39
46
  /**
40
47
  * Why the policy refuses a request to Better Auth at `path`, or `undefined` when it lets it through: a method the
41
48
  * policy turns off, or turning off two-factor authentication while the policy requires it. Removing the last passkey
42
49
  * while passkeys are required depends on the account, so the plugin checks that itself.
43
50
  */
44
- const policyRefusal = (policy, { path, body }) => {
45
- const method = methodOf(path, body);
51
+ const policyRefusal = (policy, request) => {
52
+ const { path } = request;
53
+ const method = methodOf(request);
46
54
  if (method && policy[method] === "forbidden") return {
47
55
  code: "SIGN_IN_METHOD_FORBIDDEN",
48
56
  message: signInPolicyMethods[method].forbidden
@@ -7,7 +7,8 @@ export type StaffAccessRule = 'allowed' | 'notify' | 'forbidden';
7
7
  * The app's sign-in policy. `password`, `emailCode` and `passkey` are ways to sign in; `twoFactor` is the second step
8
8
  * after a password or an emailed code. Only a passkey and two-factor authentication can be required: they are set up
9
9
  * once per person, so "required" sends everyone without one to set it up. `staffAccess` is whether the operator's
10
- * staff may sign in as people, for support.
10
+ * staff may sign in as people, for support. `platformSignIn` is whether people may sign in through the provider the
11
+ * platform adds (see `PlatformSignIn`), which the app's developer did not choose.
11
12
  */
12
13
  export type SignInPolicy = {
13
14
  password: 'allowed' | 'forbidden';
@@ -15,6 +16,7 @@ export type SignInPolicy = {
15
16
  passkey: SignInRule;
16
17
  twoFactor: SignInRule;
17
18
  staffAccess: StaffAccessRule;
19
+ platformSignIn: 'allowed' | 'forbidden';
18
20
  };
19
21
  /** Each method with the rules it takes, its name, and what the server answers when the policy turns it off. */
20
22
  export declare const signInPolicyMethods: {
@@ -43,6 +45,11 @@ export declare const signInPolicyMethods: {
43
45
  readonly rules: readonly ["allowed", "notify", "forbidden"];
44
46
  readonly forbidden: "Staff sign-in is turned off for this app.";
45
47
  };
48
+ readonly platformSignIn: {
49
+ readonly label: "Sign-in through the platform";
50
+ readonly rules: readonly ["allowed", "forbidden"];
51
+ readonly forbidden: "Signing in through the platform is turned off for this app.";
52
+ };
46
53
  };
47
54
  /** Everything allowed and nothing required: the policy of an app whose admins never saved one. */
48
55
  export declare const defaultSignInPolicy: SignInPolicy;
@@ -37,6 +37,11 @@ const signInPolicyMethods = {
37
37
  "forbidden"
38
38
  ],
39
39
  forbidden: "Staff sign-in is turned off for this app."
40
+ },
41
+ platformSignIn: {
42
+ label: "Sign-in through the platform",
43
+ rules: ["allowed", "forbidden"],
44
+ forbidden: "Signing in through the platform is turned off for this app."
40
45
  }
41
46
  };
42
47
  /** Everything allowed and nothing required: the policy of an app whose admins never saved one. */
@@ -45,7 +50,8 @@ const defaultSignInPolicy = {
45
50
  emailCode: "allowed",
46
51
  passkey: "allowed",
47
52
  twoFactor: "allowed",
48
- staffAccess: "allowed"
53
+ staffAccess: "allowed",
54
+ platformSignIn: "allowed"
49
55
  };
50
56
  const methodNames = Object.keys(signInPolicyMethods);
51
57
  /** A policy from a request body or a stored row; `undefined` when a method is missing or has a rule it does not take. */
@@ -57,13 +63,21 @@ const parseSignInPolicy = (input) => {
57
63
  /**
58
64
  * The policy as it applies. Emailed codes need mail; without mail, password sign-in is on whatever the policy says, so
59
65
  * an app whose mail settings went missing does not lock out everyone who had only emailed codes left. Staff sign-in
60
- * that emails the person is off without mail, since nobody would be told.
66
+ * that emails the person is off without mail, since nobody would be told. Sign-in through the platform is off while
67
+ * passkeys or two-factor authentication are required: it skips the app's second step, and the provider's own cannot
68
+ * be checked.
61
69
  */
62
- const effectiveSignInPolicy = (policy, { mail }) => mail ? policy : {
63
- ...policy,
64
- password: "allowed",
65
- emailCode: "forbidden",
66
- ...policy.staffAccess === "notify" && { staffAccess: "forbidden" }
70
+ const effectiveSignInPolicy = (policy, { mail }) => {
71
+ const strict = policy.passkey === "required" || policy.twoFactor === "required";
72
+ return {
73
+ ...policy,
74
+ ...!mail && {
75
+ password: "allowed",
76
+ emailCode: "forbidden"
77
+ },
78
+ ...!mail && policy.staffAccess === "notify" && { staffAccess: "forbidden" },
79
+ ...strict && { platformSignIn: "forbidden" }
80
+ };
67
81
  };
68
82
  /** The required methods `account` has not set up yet, in the order a setup page asks for them. */
69
83
  const missingRequiredMethods = (policy, account) => [...policy.twoFactor === "required" && !account.twoFactor ? ["twoFactor"] : [], ...policy.passkey === "required" && account.passkeys === 0 ? ["passkey"] : []];
@@ -9,7 +9,7 @@ import { deleteSessionCookie } from "better-auth/cookies";
9
9
  * Staff of the operator sign in as a person of this app, for support (see `staffSignInEndpoints`). A staff session
10
10
  * shows who started it and why, can be stopped, and cannot change the person's sign-in or the sign-in policy. Every
11
11
  * staff sign-in is logged for the app's admins. The plugin is there without an operator provider too, so its table
12
- * exists from the first `auth:migrate`.
12
+ * exists from the first auth migration.
13
13
  */
14
14
  const staffSignInPlugin = ({ operator, mailer }) => ({
15
15
  id: "protobase-staff-sign-in",
@@ -7,24 +7,30 @@ import { Hono } from "hono";
7
7
  * `GET {authBase}/status`: `needsAdmin` while the admin store has no user, so a login page can say how to create one;
8
8
  * `signInMethods`, the ways to sign in the sign-in policy leaves on (`password`, `emailCode`, `passkey`), so it offers
9
9
  * only those; `passwordReset` when reset mail can be sent and passwords are on, so it offers "Forgot password?" only
10
- * then; the ids of the configured `socialProviders`, so it offers "Continue with GitHub" when `github` is one; and
11
- * `staffSignIn`, the operator provider's name, when staff can sign in as people.
10
+ * then; the ids of the `socialProviders` people can sign in with, so it offers "Continue with GitHub" when `github` is
11
+ * one; `platformSignIn`, the id and name of the platform's provider when it is one of them; and `staffSignIn`, the
12
+ * operator provider's name, when staff can sign in as people.
12
13
  */
13
14
  const statusRoute = (auth) => {
14
15
  const app = new Hono();
15
16
  app.get("/status", async (c) => {
16
- const policy = effectiveSignInPolicy((await readSignInPolicy((await auth.$context).adapter)).policy, { mail: auth.mail });
17
+ const context = await auth.$context;
18
+ const policy = effectiveSignInPolicy((await readSignInPolicy(context.adapter)).policy, { mail: auth.mail });
17
19
  const signInMethods = [
18
20
  ...policy.password === "allowed" ? ["password"] : [],
19
21
  ...policy.emailCode === "allowed" ? ["emailCode"] : [],
20
22
  ...policy.passkey !== "forbidden" ? ["passkey"] : []
21
23
  ];
22
24
  const staffSignIn = auth.operator && policy.staffAccess !== "forbidden" ? auth.operator : void 0;
25
+ const platform = auth.platformSignIn;
26
+ const platformSignIn = platform && policy.platformSignIn === "allowed" && context.socialProviders.some((provider) => provider.id === platform.provider) ? platform : void 0;
27
+ const socialProviders = [...auth.socialProviders, ...platformSignIn ? [platformSignIn.provider] : []];
23
28
  return c.json({
24
29
  needsAdmin: !await hasUsers(auth),
25
30
  signInMethods,
26
31
  passwordReset: auth.passwordReset && policy.password === "allowed",
27
- socialProviders: auth.socialProviders,
32
+ socialProviders,
33
+ ...platformSignIn && { platformSignIn },
28
34
  ...staffSignIn && { staffSignIn }
29
35
  });
30
36
  });
@@ -3,11 +3,17 @@ import { parseRoles } from "./parse-roles.js";
3
3
  //#region src/better-auth/users.d.ts
4
4
  /** The roles this auth instance allows, `admin` first. */
5
5
  export declare const roleChoices: (auth: AdminAuth) => string[];
6
+ /** An account at a sign-in provider, as Better Auth keys it: `{ providerId: 'github', accountId: '<GitHub user id>' }`. */
7
+ export type LinkedAccount = {
8
+ providerId: string;
9
+ accountId: string;
10
+ };
6
11
  export type NewUser = {
7
12
  email: string;
8
13
  password: string;
9
14
  name?: string;
10
15
  role?: string;
16
+ accounts?: LinkedAccount[];
11
17
  };
12
18
  export type StoredUser = {
13
19
  id: string;
@@ -21,7 +27,8 @@ export declare const hasUsers: (auth: AdminAuth) => Promise<boolean>;
21
27
  /**
22
28
  * Creates a user directly in the admin store. Host side only (no HTTP route creates accounts while the store is empty):
23
29
  * the first user is always an `admin`, later ones get `role` (default `user`). The address counts as verified, so the
24
- * user can also sign in with an emailed code.
30
+ * user can also sign in with an emailed code. `accounts` link the user to sign-in providers up front, so a provider
31
+ * signs them in by its own id whatever address it reports; one that signs in another user already is refused.
25
32
  */
26
33
  export declare const createUser: (auth: AdminAuth, input: NewUser) => Promise<{
27
34
  id: string;
@@ -10,22 +10,37 @@ const checkRoles = (auth, role) => {
10
10
  };
11
11
  /** Whether the admin store has any user yet. */
12
12
  const hasUsers = async (auth) => (await auth.$context).adapter.count({ model: "user" }).then((count) => count > 0);
13
+ const checkAccounts = async (auth, accounts) => {
14
+ const { internalAdapter } = await auth.$context;
15
+ for (const account of accounts) {
16
+ if (!account.providerId || !account.accountId || account.providerId === "credential") throw new Error(`Cannot link an account "${account.providerId}:${account.accountId}"`);
17
+ if (await internalAdapter.findAccountByKey(account)) throw new Error(`The ${account.providerId} account ${account.accountId} signs in another user already`);
18
+ }
19
+ };
13
20
  /**
14
21
  * Creates a user directly in the admin store. Host side only (no HTTP route creates accounts while the store is empty):
15
22
  * the first user is always an `admin`, later ones get `role` (default `user`). The address counts as verified, so the
16
- * user can also sign in with an emailed code.
23
+ * user can also sign in with an emailed code. `accounts` link the user to sign-in providers up front, so a provider
24
+ * signs them in by its own id whatever address it reports; one that signs in another user already is refused.
17
25
  */
18
26
  const createUser = async (auth, input) => {
19
27
  const first = !await hasUsers(auth);
20
28
  const requested = input.role ?? auth.defaultRole;
21
29
  if (!first && requested === void 0) throw new Error(`A role is required: choose one of ${auth.roles.join(", ")}`);
22
30
  const role = first ? "admin" : checkRoles(auth, requested).join(",");
31
+ const accounts = input.accounts ?? [];
32
+ await checkAccounts(auth, accounts);
23
33
  const { user } = await auth.api.createUser({ body: {
24
34
  email: input.email,
25
35
  password: input.password,
26
36
  name: input.name ?? input.email.split("@")[0],
27
37
  role
28
38
  } });
39
+ const { internalAdapter } = await auth.$context;
40
+ for (const account of accounts) await internalAdapter.linkAccount({
41
+ userId: user.id,
42
+ ...account
43
+ });
29
44
  return {
30
45
  id: user.id,
31
46
  email: user.email,
@@ -1,6 +1,7 @@
1
1
  import { AdminAuth } from "./better-auth/create-auth.js";
2
2
  import { ResourceSource } from "./resource-source.js";
3
- import { AdminEnv, AdminOptions, Authenticator, PageSource, ViewSource } from "./types.js";
3
+ import { AdminEnv, Authenticator, PageSource, ViewSource } from "./types.js";
4
+ import { AdminOptions } from "./admin-options.js";
4
5
  import { Hono } from "hono";
5
6
  import { UserMenuSource } from "@protobase/schema";
6
7
  import { Db } from "@protobase/query";
@@ -1,5 +1,6 @@
1
1
  import { assistantSettings } from "./assistant/assistant-settings.js";
2
2
  import { createErrorHandler } from "./error-handler.js";
3
+ import { assistantRecords } from "./assistant/records.js";
3
4
  import { builtInAssistant } from "./assistant/built-in-assistant.js";
4
5
  import { consoleAuditQueue } from "./audit/console-queue.js";
5
6
  import { authBasePath } from "./better-auth/create-auth.js";
@@ -84,14 +85,20 @@ const createAdmin = ({ resources, views = [], pages = [], userMenu, db, authenti
84
85
  app.route(authBasePath, statusRoute(auth));
85
86
  app.on(["GET", "POST"], `${authBasePath}/*`, (c) => auth.handler(c.req.raw));
86
87
  }
87
- if (assistant?.kind === "built-in") app.route(`${systemPath}/assistant`, builtInAssistant({
88
- model: assistant.model,
89
- chats: assistant.chats,
90
- db,
91
- meta,
92
- authenticate,
93
- report: options.onUnhandledError
94
- }));
88
+ if (assistant?.kind === "built-in") {
89
+ const tools = options.assistant ? options.assistant.tools : void 0;
90
+ const records = (session) => assistantRecords(deps, session);
91
+ app.route(`${systemPath}/assistant`, builtInAssistant({
92
+ model: assistant.model,
93
+ chats: assistant.chats,
94
+ db,
95
+ meta,
96
+ authenticate,
97
+ tools,
98
+ records,
99
+ report: options.onUnhandledError
100
+ }));
101
+ }
95
102
  app.route("/", batchRoute(deps, authenticate, meta));
96
103
  app.route(basePath, api);
97
104
  app.route(deps.systemPath || "/", system);
package/dist/deps.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ import "./types.js";
2
+ import "./registry.js";
3
+ import "./scan-guard.js";
4
+ import { PageModel } from "@protobase/layout";
5
+ import { ResolveOptions, ViewModel } from "@protobase/schema";
6
+ import { Db } from "@protobase/query";
package/dist/index.d.ts CHANGED
@@ -1,28 +1,34 @@
1
1
  import { SignInPolicy, SignInRule, StaffAccessRule, defaultSignInPolicy, signInPolicyMethods } from "./better-auth/sign-in-policy.js";
2
2
  import { StaffSignIn } from "./better-auth/staff-log.js";
3
3
  import { OperatorProvider, readOperatorSettings } from "./better-auth/operator-provider.js";
4
+ import { PlatformSignIn, readPlatformSignIn } from "./better-auth/platform-sign-in.js";
4
5
  import { AdminAuth, CreateAuthOptions, UserCreatedHook, createAuth, normalizeRoles } from "./better-auth/create-auth.js";
5
6
  import { ResourceSource, configExports } from "./resource-source.js";
6
- import { AssistantOptions, AssistantSettings, ModelSettings, assistantRoles, assistantSettings, assistantVariables, seesAssistant } from "./assistant/assistant-settings.js";
7
+ import { ChatMessage, ChatTextPart, Completion, CompletionOptions, ModelError, ModelSettings, ReasoningDetail, ReasoningEffort, ToolCall, ToolSpec, streamChatCompletion } from "./assistant/chat-completions.js";
8
+ import { Admin, AuditEvent, AuditQueue, Authenticator, PipelineHook, ScanGuardMode, Session, TenantValue, User, ViewSource, WriteEvent, WriteOperation } from "./types.js";
9
+ import { ConversationRecord, ConversationStore } from "./assistant/conversation-store.js";
10
+ import { Conversation, ConversationsOptions, conversationKey, createConversations } from "./assistant/conversations.js";
11
+ import { ApprovalAnswer, ApprovalRequest, requestApproval } from "./assistant/approval.js";
12
+ import { RecordKeyInput, ToolRecord, ToolRecords } from "./assistant/records.js";
13
+ import { AssistantTool, ToolContext, defineTool } from "./assistant/tools.js";
14
+ import { AssistantOptions, AssistantSettings, assistantRoles, assistantSettings, assistantVariables, seesAssistant } from "./assistant/assistant-settings.js";
7
15
  import { RuntimeOptions, runtimeUrl, runtimeVariable, seesRuntime } from "./runtime/runtime-settings.js";
8
- import { Admin, AdminOptions, AuditEvent, AuditQueue, Authenticator, PipelineHook, ScanGuardMode, Session, TenantValue, User, ViewSource, WriteEvent, WriteOperation } from "./types.js";
16
+ import { AdminOptions } from "./admin-options.js";
9
17
  import { CreateAdminInput, createAdmin } from "./create-admin.js";
18
+ import { ProjectConfig, defineConfig, mergeConfig } from "./project-config.js";
10
19
  import { consoleAuditQueue } from "./audit/console-queue.js";
11
20
  import { JwtOptions, jwtAuthenticator } from "./auth/jwt.js";
12
21
  import { HttpProblem, badRequest, forbidden, notFound, unauthorized } from "./problem.js";
13
22
  import { BetterAuthAuthenticatorOptions, betterAuthAuthenticator } from "./better-auth/authenticator.js";
14
23
  import { parseRoles } from "./better-auth/parse-roles.js";
15
- import { NewUser, StoredUser, createUser, deleteUser, hasUsers, listUsers, roleChoices, setUserBanned, setUserRole } from "./better-auth/users.js";
24
+ import { LinkedAccount, NewUser, StoredUser, createUser, deleteUser, hasUsers, listUsers, roleChoices, setUserBanned, setUserRole } from "./better-auth/users.js";
16
25
  import { IssueTokenOptions, issueToken, maxTokenTtlSeconds } from "./better-auth/tokens.js";
17
- import { ChatMessage, ChatTextPart, Completion, CompletionOptions, ModelError, ReasoningDetail, ReasoningEffort, ToolCall, ToolSpec, streamChatCompletion } from "./assistant/chat-completions.js";
18
- import { ConversationRecord, ConversationStore } from "./assistant/conversation-store.js";
19
- import { Conversation, ConversationsOptions, conversationKey, createConversations } from "./assistant/conversations.js";
26
+ import { authSchemaMigration, checkAuthSchema } from "./better-auth/auth-schema.js";
20
27
  import { AssistantBackend, assistantProtocolRoutes } from "./assistant/protocol-routes.js";
21
28
  import { fileConversationStore } from "./assistant/file-conversation-store.js";
22
29
  import { withCacheBreakpoints } from "./assistant/cache-breakpoints.js";
23
- import { ApprovalAnswer, ApprovalRequest, requestApproval } from "./assistant/approval.js";
24
- import { AssistantTool, ToolContext, defineTool } from "./assistant/tools.js";
25
30
  import { TurnOptions, runTurn } from "./assistant/turn.js";
31
+ import { WidgetOptions, maxWidgetPropsBytes, widget } from "./assistant/widget.js";
26
32
  import { QueryOptions, QueryResult, runReadOnlyQuery, runReadWriteQuery } from "./assistant/run-query.js";
27
33
  import { readOnlyQueryTool, readWriteQueryTool } from "./assistant/query-tools.js";
28
- export { type Admin, type AdminAuth, type AdminOptions, type ApprovalAnswer, type ApprovalRequest, type AssistantBackend, type AssistantOptions, type AssistantSettings, type AssistantTool, type AuditEvent, type AuditQueue, type Authenticator, type BetterAuthAuthenticatorOptions, type ChatMessage, type ChatTextPart, type Completion, type CompletionOptions, type Conversation, type ConversationRecord, type ConversationStore, type ConversationsOptions, type CreateAdminInput, type CreateAuthOptions, HttpProblem, type IssueTokenOptions, type JwtOptions, ModelError, type ModelSettings, type NewUser, type OperatorProvider, type PipelineHook, type QueryOptions, type QueryResult, type ReasoningDetail, type ReasoningEffort, type ResourceSource, type RuntimeOptions, type ScanGuardMode, type Session, type SignInPolicy, type SignInRule, type StaffAccessRule, type StaffSignIn, type StoredUser, type TenantValue, type ToolCall, type ToolContext, type ToolSpec, type TurnOptions, type User, type UserCreatedHook, type ViewSource, type WriteEvent, type WriteOperation, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, badRequest, betterAuthAuthenticator, configExports, consoleAuditQueue, conversationKey, createAdmin, createAuth, createConversations, createUser, defaultSignInPolicy, defineTool, deleteUser, fileConversationStore, forbidden, hasUsers, issueToken, jwtAuthenticator, listUsers, maxTokenTtlSeconds, normalizeRoles, notFound, parseRoles, readOnlyQueryTool, readOperatorSettings, readWriteQueryTool, requestApproval, roleChoices, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, seesAssistant, seesRuntime, setUserBanned, setUserRole, signInPolicyMethods, streamChatCompletion, unauthorized, withCacheBreakpoints };
34
+ export { type Admin, type AdminAuth, type AdminOptions, type ApprovalAnswer, type ApprovalRequest, type AssistantBackend, type AssistantOptions, type AssistantSettings, type AssistantTool, type AuditEvent, type AuditQueue, type Authenticator, type BetterAuthAuthenticatorOptions, type ChatMessage, type ChatTextPart, type Completion, type CompletionOptions, type Conversation, type ConversationRecord, type ConversationStore, type ConversationsOptions, type CreateAdminInput, type CreateAuthOptions, HttpProblem, type IssueTokenOptions, type JwtOptions, type LinkedAccount, ModelError, type ModelSettings, type NewUser, type OperatorProvider, type PipelineHook, type PlatformSignIn, type ProjectConfig, type QueryOptions, type QueryResult, type ReasoningDetail, type ReasoningEffort, type RecordKeyInput, type ResourceSource, type RuntimeOptions, type ScanGuardMode, type Session, type SignInPolicy, type SignInRule, type StaffAccessRule, type StaffSignIn, type StoredUser, type TenantValue, type ToolCall, type ToolContext, type ToolRecord, type ToolRecords, type ToolSpec, type TurnOptions, type User, type UserCreatedHook, type ViewSource, type WidgetOptions, type WriteEvent, type WriteOperation, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaMigration, badRequest, betterAuthAuthenticator, checkAuthSchema, configExports, consoleAuditQueue, conversationKey, createAdmin, createAuth, createConversations, createUser, defaultSignInPolicy, defineConfig, defineTool, deleteUser, fileConversationStore, forbidden, hasUsers, issueToken, jwtAuthenticator, listUsers, maxTokenTtlSeconds, maxWidgetPropsBytes, mergeConfig, normalizeRoles, notFound, parseRoles, readOnlyQueryTool, readOperatorSettings, readPlatformSignIn, readWriteQueryTool, requestApproval, roleChoices, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, seesAssistant, seesRuntime, setUserBanned, setUserRole, signInPolicyMethods, streamChatCompletion, unauthorized, widget, withCacheBreakpoints };
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ import { ModelError, streamChatCompletion } from "./assistant/chat-completions.j
12
12
  import { runTurn } from "./assistant/turn.js";
13
13
  import { consoleAuditQueue } from "./audit/console-queue.js";
14
14
  import { readOperatorSettings } from "./better-auth/operator-provider.js";
15
+ import { readPlatformSignIn } from "./better-auth/platform-sign-in.js";
15
16
  import { defaultSignInPolicy, signInPolicyMethods } from "./better-auth/sign-in-policy.js";
16
17
  import { parseRoles } from "./better-auth/parse-roles.js";
17
18
  import { createAuth, normalizeRoles } from "./better-auth/create-auth.js";
@@ -19,7 +20,10 @@ import { createUser, deleteUser, hasUsers, listUsers, roleChoices, setUserBanned
19
20
  import { runtimeUrl, runtimeVariable, seesRuntime } from "./runtime/runtime-settings.js";
20
21
  import { createAdmin } from "./create-admin.js";
21
22
  import { configExports } from "./resource-source.js";
23
+ import { defineConfig, mergeConfig } from "./project-config.js";
22
24
  import { jwtAuthenticator } from "./auth/jwt.js";
23
25
  import { betterAuthAuthenticator } from "./better-auth/authenticator.js";
24
26
  import { issueToken, maxTokenTtlSeconds } from "./better-auth/tokens.js";
25
- export { HttpProblem, ModelError, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, badRequest, betterAuthAuthenticator, configExports, consoleAuditQueue, conversationKey, createAdmin, createAuth, createConversations, createUser, defaultSignInPolicy, defineTool, deleteUser, fileConversationStore, forbidden, hasUsers, issueToken, jwtAuthenticator, listUsers, maxTokenTtlSeconds, normalizeRoles, notFound, parseRoles, readOnlyQueryTool, readOperatorSettings, readWriteQueryTool, requestApproval, roleChoices, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, seesAssistant, seesRuntime, setUserBanned, setUserRole, signInPolicyMethods, streamChatCompletion, unauthorized, withCacheBreakpoints };
27
+ import { authSchemaMigration, checkAuthSchema } from "./better-auth/auth-schema.js";
28
+ import { maxWidgetPropsBytes, widget } from "./assistant/widget.js";
29
+ export { HttpProblem, ModelError, assistantProtocolRoutes, assistantRoles, assistantSettings, assistantVariables, authSchemaMigration, badRequest, betterAuthAuthenticator, checkAuthSchema, configExports, consoleAuditQueue, conversationKey, createAdmin, createAuth, createConversations, createUser, defaultSignInPolicy, defineConfig, defineTool, deleteUser, fileConversationStore, forbidden, hasUsers, issueToken, jwtAuthenticator, listUsers, maxTokenTtlSeconds, maxWidgetPropsBytes, mergeConfig, normalizeRoles, notFound, parseRoles, readOnlyQueryTool, readOperatorSettings, readPlatformSignIn, readWriteQueryTool, requestApproval, roleChoices, runReadOnlyQuery, runReadWriteQuery, runTurn, runtimeUrl, runtimeVariable, seesAssistant, seesRuntime, setUserBanned, setUserRole, signInPolicyMethods, streamChatCompletion, unauthorized, widget, withCacheBreakpoints };
@@ -1,11 +1,11 @@
1
- import { checkedFilter, checkedSort } from "./filter-input.js";
2
- import { readScope, requestAccess, requireOperation } from "./request-access.js";
3
- import { readTransaction } from "./transactions.js";
4
1
  import { etagAlias } from "./sql-parts.js";
5
2
  import { etagOf } from "./etag.js";
6
3
  import { exposeRow, pickFields } from "./rows.js";
7
- import { deletedRows, listParams, pageSizeOf, parseParams, seekParams, selectedFields } from "./params.js";
4
+ import { checkedFilter, checkedSort } from "./filter-input.js";
5
+ import { readScope, requestAccess, requireOperation } from "./request-access.js";
8
6
  import { rowPermissions } from "./row-permissions.js";
7
+ import { readTransaction } from "./transactions.js";
8
+ import { deletedRows, listParams, pageSizeOf, parseParams, seekParams, selectedFields } from "./params.js";
9
9
  import { estimateCount, exactCount, listQuery, seekToPosition } from "@protobase/query";
10
10
  //#region src/list-service.ts
11
11
  /**
@@ -0,0 +1,28 @@
1
+ import { AdminAuth } from "./better-auth/create-auth.js";
2
+ import { Authenticator } from "./types.js";
3
+ import { AdminOptions } from "./admin-options.js";
4
+ import { Db } from "@protobase/query";
5
+ //#region src/project-config.d.ts
6
+ /** What `protobase.config.ts` may default-export. Everything is optional. */
7
+ export type ProjectConfig = {
8
+ /** Names the config in errors, such as two configs defining the same tool; an extension should set it. */
9
+ name?: string;
10
+ /** Configs this one extends: merged in order before it (see `mergeConfig`). */
11
+ extends?: ProjectConfig[];
12
+ /** The config module, e.g. `import * as config from './config'`; default: ./config/index.ts and ./config/*\/ui.ts. */
13
+ config?: Record<string, unknown>;
14
+ db?: Db;
15
+ authenticate?: Authenticator;
16
+ /** A Better Auth instance; createAdmin mounts its routes under /api/auth. */
17
+ auth?: AdminAuth;
18
+ options?: AdminOptions;
19
+ };
20
+ /** Typed identity, for `export default defineConfig({ extends: [...], config, auth, ... })` in `protobase.config.ts`. */
21
+ export declare const defineConfig: (config: ProjectConfig) => ProjectConfig;
22
+ /**
23
+ * One config from several, each after the ones it `extends`, the last being the app's own. Named things are all kept:
24
+ * resources, views and pages of the config modules, assistant tools; one name defined by two configs is an error naming
25
+ * both. Write hooks run in the same order. Every other value is the last config's that sets it, so the app's own wins.
26
+ */
27
+ export declare const mergeConfig: (...configs: ProjectConfig[]) => ProjectConfig;
28
+ //#endregion