@protobase/server 0.129.0 → 0.130.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/query-runner/grants-sql.js +32 -0
- package/dist/assistant/query-runner/query-input.js +33 -0
- package/dist/assistant/query-runner/query-module.js +44 -0
- package/dist/assistant/query-runner/query-runner.d.ts +8 -11
- package/dist/assistant/query-runner/query-runner.js +15 -57
- package/dist/assistant/query-runner/read-query.js +54 -0
- package/dist/assistant/query-runner/runner-sql.js +4 -20
- package/dist/assistant/query-runner/steps/001-role.js +19 -0
- package/dist/auth-store.d.ts +2 -2
- package/dist/auth-store.js +3 -3
- package/dist/better-auth/auth-schema.d.ts +13 -4
- package/dist/better-auth/auth-schema.js +40 -32
- package/dist/better-auth/auth-settings.d.ts +59 -11
- package/dist/better-auth/auth-settings.js +57 -13
- package/dist/better-auth/auth-tables.d.ts +6 -3
- package/dist/better-auth/auth-tables.js +12 -7
- package/dist/better-auth/authenticator.js +10 -2
- package/dist/better-auth/create-auth.d.ts +62 -7
- package/dist/better-auth/create-auth.js +55 -14
- package/dist/better-auth/device-sign-in-check.js +13 -0
- package/dist/better-auth/names/declaration.d.ts +18 -5
- package/dist/better-auth/names/declaration.js +3 -1
- package/dist/better-auth/names/modules/auth.js +9 -0
- package/dist/better-auth/names/modules/index.d.ts +34 -4
- package/dist/better-auth/names/modules/organizations.js +10 -3
- package/dist/better-auth/names/modules/personal-access-tokens.js +6 -3
- package/dist/better-auth/names/modules-on.js +25 -2
- package/dist/better-auth/names/resolve-names.d.ts +9 -1
- package/dist/better-auth/names/resolve-names.js +15 -9
- package/dist/better-auth/organizations/accept-invitation.js +5 -4
- package/dist/better-auth/organizations/add-every-user.js +3 -2
- package/dist/better-auth/organizations/host-scope.d.ts +10 -0
- package/dist/better-auth/organizations/host-scope.js +15 -0
- package/dist/better-auth/organizations/host.d.ts +12 -6
- package/dist/better-auth/organizations/host.js +99 -61
- package/dist/better-auth/organizations/kept-organizations.d.ts +21 -0
- package/dist/better-auth/organizations/kept-organizations.js +62 -0
- package/dist/better-auth/organizations/member-endpoints.js +4 -3
- package/dist/better-auth/organizations/options.d.ts +15 -0
- package/dist/better-auth/organizations/options.js +19 -1
- package/dist/better-auth/organizations/people-endpoint.js +3 -2
- package/dist/better-auth/organizations/pinned-membership.js +81 -0
- package/dist/better-auth/organizations/pinned-sessions.js +46 -0
- package/dist/better-auth/organizations/session-organization.js +3 -2
- package/dist/better-auth/organizations/store.js +14 -9
- package/dist/better-auth/personal-access-tokens/pinned-tokens.js +23 -0
- package/dist/better-auth/personal-access-tokens/token-plugin.js +75 -54
- package/dist/better-auth/personal-access-tokens/token-sessions.js +6 -3
- package/dist/better-auth/personal-access-tokens/token-store.js +15 -11
- package/dist/better-auth/store/adoption.js +25 -10
- package/dist/better-auth/store/drift.js +5 -4
- package/dist/better-auth/store/legacy-record.d.ts +10 -0
- package/dist/better-auth/store/legacy-record.js +56 -0
- package/dist/better-auth/store/migration-sql.js +31 -26
- package/dist/better-auth/store/offline/baseline-store.d.ts +35 -0
- package/dist/better-auth/store/offline/baseline-store.js +65 -0
- package/dist/better-auth/store/offline/module-switches.d.ts +27 -0
- package/dist/better-auth/store/offline/module-switches.js +94 -0
- package/dist/better-auth/store/offline/name-changes.d.ts +4 -1
- package/dist/better-auth/store/offline/name-changes.js +5 -2
- package/dist/better-auth/store/offline/offline-steps.d.ts +21 -6
- package/dist/better-auth/store/offline/offline-steps.js +30 -20
- package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
- package/dist/better-auth/store/offline/retired-watch.js +36 -0
- package/dist/better-auth/store/offline/settings-names.d.ts +3 -2
- package/dist/better-auth/store/offline/settings-names.js +10 -3
- package/dist/better-auth/store/offline/store-model.d.ts +9 -1
- package/dist/better-auth/store/offline/store-model.js +22 -5
- package/dist/better-auth/store/resources-outside.js +1 -1
- package/dist/better-auth/store/step-record.d.ts +13 -0
- package/dist/better-auth/store/step-record.js +59 -0
- package/dist/better-auth/store/steps/index.js +6 -1
- package/dist/better-auth/store/steps/legacy-versions.d.ts +7 -0
- package/dist/better-auth/store/steps/legacy-versions.js +4 -0
- package/dist/better-auth/store/steps/organizations/003-default-organization.js +113 -0
- package/dist/better-auth/store/steps/render.d.ts +3 -0
- package/dist/better-auth/store/steps/render.js +48 -25
- package/dist/better-auth/store/steps/step-lint.d.ts +14 -0
- package/dist/better-auth/store/steps/step-lint.js +31 -10
- package/dist/better-auth/store/steps/step.d.ts +18 -0
- package/dist/better-auth/store/steps/step.js +13 -4
- package/dist/better-auth/store/store-db.d.ts +6 -0
- package/dist/better-auth/store/store-db.js +11 -5
- package/dist/better-auth/store/store-names.d.ts +4 -0
- package/dist/better-auth/token-standing.js +12 -7
- package/dist/better-auth/users.d.ts +7 -2
- package/dist/better-auth/users.js +25 -3
- package/dist/built-in-resources.js +1 -1
- package/dist/calls/calls-module.js +42 -0
- package/dist/calls/calls-sql.js +4 -30
- package/dist/changes/capture-names.d.ts +3 -1
- package/dist/changes/capture-names.js +5 -2
- package/dist/changes/capture-schema-sql.d.ts +10 -0
- package/dist/changes/capture-schema-sql.js +21 -0
- package/dist/changes/capture-schema.d.ts +0 -18
- package/dist/changes/capture-schema.js +1 -74
- package/dist/changes/capture-sql.js +30 -24
- package/dist/changes/changes-input.js +36 -0
- package/dist/changes/changes-module.js +44 -0
- package/dist/changes/read-capture.js +67 -0
- package/dist/changes/steps/001-outbox.js +23 -0
- package/dist/channels/sends-module.js +37 -0
- package/dist/channels/sends-schema-sql.js +5 -5
- package/dist/comments/comments-module.js +30 -0
- package/dist/comments/comments-sql.js +1 -22
- package/dist/computed/buckets-sql.d.ts +5 -1
- package/dist/computed/buckets-sql.js +39 -46
- package/dist/computed/{buckets-schema.d.ts → buckets-targets.d.ts} +2 -3
- package/dist/computed/buckets-targets.js +50 -0
- package/dist/computed/computed-input.js +65 -0
- package/dist/computed/computed-module.js +102 -0
- package/dist/computed/formula-sql.js +14 -1
- package/dist/computed/read-computed.js +100 -0
- package/dist/computed/rollup-sql.js +13 -10
- package/dist/config-exports.d.ts +2 -2
- package/dist/create-admin.js +21 -5
- package/dist/derived/derived-module.js +89 -0
- package/dist/derived/derived-sql.js +1 -47
- package/dist/functions/define-function.d.ts +10 -4
- package/dist/functions/routes.js +5 -3
- package/dist/functions/supabase-routes.js +7 -5
- package/dist/history/history-module.js +34 -0
- package/dist/index.d.ts +19 -28
- package/dist/index.js +11 -21
- package/dist/internal.d.ts +27 -10
- package/dist/internal.js +22 -7
- package/dist/jobs/functions-sql.js +7 -11
- package/dist/jobs/job-data.js +36 -0
- package/dist/jobs/job-types.d.ts +6 -3
- package/dist/jobs/jobs-module.d.ts +5 -0
- package/dist/jobs/jobs-module.js +84 -0
- package/dist/jobs/run-job.d.ts +1 -1
- package/dist/jobs/run-job.js +7 -5
- package/dist/jobs/runtime.d.ts +9 -4
- package/dist/jobs/runtime.js +11 -6
- package/dist/jobs/schema.d.ts +0 -11
- package/dist/jobs/schema.js +1 -59
- package/dist/jobs/steps/001-pg-boss-45.js +483 -0
- package/dist/live/notices-module.js +30 -0
- package/dist/live/notices-sql.js +2 -1
- package/dist/mail/feedback/feedback-schema.js +3 -30
- package/dist/mail/feedback/mail-feedback-module.js +37 -0
- package/dist/mail/unsubscribe/unsubscribe-schema.js +3 -21
- package/dist/mail/unsubscribe/unsubscribes-module.js +31 -0
- package/dist/migration-record/check-record.d.ts +9 -7
- package/dist/migration-record/check-record.js +12 -11
- package/dist/migration-record/module-needs.js +30 -0
- package/dist/migration-record/read-record.js +27 -15
- package/dist/migration-record/record-model.d.ts +7 -2
- package/dist/migration-record/record-model.js +14 -6
- package/dist/migration-record/startup-decision.js +18 -7
- package/dist/migration-sql/additive-statements.d.ts +4 -0
- package/dist/migration-sql/additive-statements.js +105 -0
- package/dist/notifications/devices-module.js +61 -0
- package/dist/notifications/history-module.js +50 -0
- package/dist/notifications/notifications-targets.js +23 -0
- package/dist/notifications/read-table.js +16 -0
- package/dist/notifications/schema-sql.js +1 -22
- package/dist/notifications/schema.js +1 -101
- package/dist/notifications/table-names.js +40 -0
- package/dist/organization-scope/app-scope.js +38 -0
- package/dist/organization-scope/auth-request-organization.js +71 -0
- package/dist/organization-scope/organization-tables.js +20 -0
- package/dist/organization-scope/sign-in-organization.js +21 -0
- package/dist/package.js +1 -1
- package/dist/personal-mail/shared-sender-store.js +4 -2
- package/dist/realtime/relay/realtime-relay-module.js +37 -0
- package/dist/relation-found.js +6 -0
- package/dist/relay/read-relay.js +85 -0
- package/dist/relay/realtime-members-sql.js +51 -28
- package/dist/relay/relay-module.js +53 -0
- package/dist/relay/relay-targets.js +28 -0
- package/dist/relay/session-end.js +1 -3
- package/dist/relay/sessions-sql.js +4 -27
- package/dist/rest/table-routes.js +9 -2
- package/dist/schema-modules/feature-schemas-sql.d.ts +40 -0
- package/dist/schema-modules/feature-schemas-sql.js +51 -0
- package/dist/schema-modules/module-difference.d.ts +31 -0
- package/dist/schema-modules/module-difference.js +98 -0
- package/dist/schema-modules/modules-sql.js +13 -0
- package/dist/schema-modules/modules.d.ts +37 -0
- package/dist/schema-modules/modules.js +56 -0
- package/dist/schema-modules/needed-modules.d.ts +41 -0
- package/dist/schema-modules/needed-modules.js +61 -0
- package/dist/schema-modules/resource-difference.js +83 -0
- package/dist/schema-modules/schema-module.d.ts +112 -0
- package/dist/schema-modules/schema-module.js +8 -0
- package/dist/status/status-module.js +63 -0
- package/dist/status/status-targets.js +21 -0
- package/dist/types.d.ts +6 -1
- package/dist/user-tables/reloading-admin.d.ts +1 -0
- package/dist/user-tables/reloading-admin.js +1 -0
- package/dist/user-tables/schema-sql.js +1 -14
- package/dist/user-tables/schema.js +4 -27
- package/dist/user-tables/user-tables-module.js +38 -0
- package/dist/webhooks/table/delivery-log-module.js +36 -0
- package/dist/webhooks/table/owner-roles.js +3 -2
- package/dist/webhooks/table/schema-sql.js +27 -26
- package/dist/webhooks/table/webhooks-schema-module.js +63 -0
- package/dist/webhooks/table/webhooks-targets.js +26 -0
- package/dist/webhooks/webhooks.js +1 -1
- package/dist/workflows/custom-steps/custom-steps-module.js +51 -0
- package/dist/workflows/custom-steps/custom-steps-sql.js +10 -7
- package/dist/workflows/custom-steps/runners-sql.js +10 -7
- package/dist/workflows/read-catalogue.js +23 -0
- package/dist/workflows/schema-sql.js +12 -9
- package/dist/workflows/status-sql.js +12 -6
- package/dist/workflows/storage/storage-module.js +39 -0
- package/dist/workflows/storage/storage-sql.js +8 -5
- package/dist/workflows/workflows-schema-module.js +49 -0
- package/dist/workflows/workflows-tables-sql.js +32 -0
- package/dist/workflows/workflows-targets.js +16 -0
- package/package.json +6 -6
- package/dist/assistant/query-runner/runner-plan.js +0 -30
- package/dist/better-auth/store/migrations-table.js +0 -27
- package/dist/better-auth/store/modules-off.js +0 -17
- package/dist/calls/calls-sql.d.ts +0 -11
- package/dist/changes/capture-plan.js +0 -79
- package/dist/channels/sends-schema.d.ts +0 -7
- package/dist/channels/sends-schema.js +0 -18
- package/dist/comments/comments-sql.d.ts +0 -14
- package/dist/computed/buckets-plan.d.ts +0 -2
- package/dist/computed/buckets-plan.js +0 -88
- package/dist/computed/buckets-schema.js +0 -39
- package/dist/computed/computed-plan.js +0 -81
- package/dist/computed/computed-schema.d.ts +0 -16
- package/dist/computed/computed-schema.js +0 -63
- package/dist/derived/derived-sql.d.ts +0 -12
- package/dist/mail/feedback/feedback-schema.d.ts +0 -7
- package/dist/mail/unsubscribe/unsubscribe-schema.d.ts +0 -10
- package/dist/notifications/schema.d.ts +0 -14
- package/dist/realtime/relay/relay-schema.d.ts +0 -7
- package/dist/realtime/relay/relay-schema.js +0 -20
- package/dist/relay/realtime-members-schema.js +0 -67
- package/dist/relay/relay-schema.d.ts +0 -14
- package/dist/relay/relay-schema.js +0 -28
- package/dist/status/schema.d.ts +0 -12
- package/dist/status/schema.js +0 -33
- package/dist/user-tables/schema.d.ts +0 -11
- package/dist/webhooks/table/schema.d.ts +0 -16
- package/dist/webhooks/table/schema.js +0 -56
- package/dist/workflows/schema.d.ts +0 -13
- package/dist/workflows/schema.js +0 -88
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { queryRoleSql } from "./runner-sql.js";
|
|
2
|
+
//#region src/assistant/query-runner/grants-sql.ts
|
|
3
|
+
const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
4
|
+
const literal = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
5
|
+
/** A table as `to_regclass` takes it: the search path decides when it names no schema. */
|
|
6
|
+
const regclassText = ({ schema, name }) => schema ? `${quoted(schema)}.${quoted(name)}` : quoted(name);
|
|
7
|
+
const overTable = (table, declarations, body) => [
|
|
8
|
+
"do $$",
|
|
9
|
+
"declare",
|
|
10
|
+
` query_role text := ${queryRoleSql};`,
|
|
11
|
+
` found regclass := to_regclass(${literal(regclassText(table))});`,
|
|
12
|
+
...declarations,
|
|
13
|
+
"begin",
|
|
14
|
+
" if found is null then return; end if;",
|
|
15
|
+
...body,
|
|
16
|
+
"end $$;"
|
|
17
|
+
].join("\n");
|
|
18
|
+
/** Gives the query role select on `table` and usage on its schema; nothing while the table does not exist. */
|
|
19
|
+
const grantsSql = (table) => overTable(table, [], [" execute format('grant usage on schema %s to %I', (select relnamespace::regnamespace from pg_class where oid = found), query_role);", " execute format('grant select on table %s to %I', found, query_role);"]);
|
|
20
|
+
const held = (acl, privilege) => `exists (select from aclexplode(${acl}) a where a.grantee = (select oid from pg_roles where rolname = query_role) and a.privilege_type = '${privilege}')`;
|
|
21
|
+
/**
|
|
22
|
+
* Takes select on `table` back from the query role, and usage on its schema once the role reads no other table there;
|
|
23
|
+
* usage it does not hold itself is left alone, such as on a schema only its owner may grant on.
|
|
24
|
+
*/
|
|
25
|
+
const revokeSql = (table) => overTable(table, [" found_schema regnamespace;"], [
|
|
26
|
+
" select relnamespace into found_schema from pg_class where oid = found;",
|
|
27
|
+
" execute format('revoke select on table %s from %I', found, query_role);",
|
|
28
|
+
` if exists (select from pg_class c where c.relnamespace = found_schema and ${held("c.relacl", "SELECT")}) or not ${held("(select nspacl from pg_namespace where oid = found_schema)", "USAGE")} then return; end if;`,
|
|
29
|
+
" execute format('revoke usage on schema %s from %I', found_schema, query_role);"
|
|
30
|
+
]);
|
|
31
|
+
//#endregion
|
|
32
|
+
export { grantsSql, regclassText, revokeSql };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { storeAuthTables } from "../../better-auth/auth-tables.js";
|
|
2
|
+
//#region src/assistant/query-runner/query-input.ts
|
|
3
|
+
const same = (a, b) => a.name === b.name && (a.schema ?? "public") === (b.schema ?? "public");
|
|
4
|
+
/**
|
|
5
|
+
* What the query module takes from the app: each resource's table the role reads, by resource, but a table of the auth
|
|
6
|
+
* store `store` names or of one of its guarded schemas, and a table an earlier resource has already, so taking one
|
|
7
|
+
* resource's grants back never takes another's.
|
|
8
|
+
*/
|
|
9
|
+
const queryInput = (models, store) => {
|
|
10
|
+
const guarded = store ? storeAuthTables(store) : {
|
|
11
|
+
tables: [],
|
|
12
|
+
schemas: []
|
|
13
|
+
};
|
|
14
|
+
const grants = {};
|
|
15
|
+
for (const model of models) {
|
|
16
|
+
const table = {
|
|
17
|
+
...model.table.schema !== void 0 && { schema: model.table.schema },
|
|
18
|
+
name: model.table.name
|
|
19
|
+
};
|
|
20
|
+
if (table.schema !== void 0 && guarded.schemas.includes(table.schema)) continue;
|
|
21
|
+
if (guarded.tables.some((auth) => same(auth, table)) || Object.values(grants).some((given) => same(given.table, table))) continue;
|
|
22
|
+
grants[model.name] = {
|
|
23
|
+
table,
|
|
24
|
+
input: table
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
names: {},
|
|
29
|
+
resources: { grants }
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
//#endregion
|
|
33
|
+
export { queryInput };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { runnerSql } from "./runner-sql.js";
|
|
2
|
+
import { grantsSql, revokeSql } from "./grants-sql.js";
|
|
3
|
+
import { readQuery } from "./read-query.js";
|
|
4
|
+
import { roleStep } from "./steps/001-role.js";
|
|
5
|
+
//#region src/assistant/query-runner/query-module.ts
|
|
6
|
+
/**
|
|
7
|
+
* The query role's select on one resource's table and usage on its schema. Taken back once the resource is gone,
|
|
8
|
+
* leaving usage on the schema while the role reads another table there.
|
|
9
|
+
*/
|
|
10
|
+
const grants = {
|
|
11
|
+
name: "grants",
|
|
12
|
+
title: "The grants of the query role",
|
|
13
|
+
version: 1,
|
|
14
|
+
compatibleFrom: 1,
|
|
15
|
+
sql: (_names, input) => grantsSql(input),
|
|
16
|
+
drop: (_names, table) => revokeSql(table),
|
|
17
|
+
keptWhileOthers: false
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* The role the built-in assistant's read-only queries run as, `<database>_query`, which reads only the resources'
|
|
21
|
+
* tables (`queryInput`), and `query.run_read_only`, the runner every query goes through as that role.
|
|
22
|
+
*/
|
|
23
|
+
const queryModule = {
|
|
24
|
+
label: "the query role of the assistant's read-only queries",
|
|
25
|
+
title: "The role the assistant's read-only queries run as, which reads only the resources' tables",
|
|
26
|
+
steps: [{
|
|
27
|
+
step: 1,
|
|
28
|
+
name: "role",
|
|
29
|
+
title: "The query role",
|
|
30
|
+
additive: true,
|
|
31
|
+
sql: roleStep
|
|
32
|
+
}],
|
|
33
|
+
replaceables: [{
|
|
34
|
+
name: "runner",
|
|
35
|
+
title: "The runner the queries go through, query.run_read_only()",
|
|
36
|
+
version: 1,
|
|
37
|
+
compatibleFrom: 1,
|
|
38
|
+
sql: runnerSql
|
|
39
|
+
}],
|
|
40
|
+
resourceReplaceables: [grants],
|
|
41
|
+
read: readQuery(grants)
|
|
42
|
+
};
|
|
43
|
+
//#endregion
|
|
44
|
+
export { queryModule };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { ResourceModel } from "@protobase/schema";
|
|
2
1
|
import { Db } from "@protobase/query";
|
|
3
2
|
//#region src/assistant/query-runner/query-runner.d.ts
|
|
4
3
|
/** A table as config names it: the search path decides when it names no schema. */
|
|
@@ -12,15 +11,13 @@ export type GuardedTables = {
|
|
|
12
11
|
schemas: readonly string[];
|
|
13
12
|
};
|
|
14
13
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
14
|
+
* Refuses to go on while the runner of the assistant's read-only queries, which the record of migrations says is there,
|
|
15
|
+
* does not run as a role weaker than the app's: it is no security definer, or runs as the app's role itself or one it
|
|
16
|
+
* is a member of, a superuser, a login role, or one that can read an auth table, or while that role may call a
|
|
17
|
+
* security-definer function that runs as a role able to read one. A migration cannot promise these: they are the live
|
|
18
|
+
* database's, such as a grant made by hand. It checks the owner's privileges, not its name, so a database cloned under
|
|
19
|
+
* another name still passes. A resource added since the last migration is not checked: Postgres refuses to read its
|
|
20
|
+
* table until then.
|
|
17
21
|
*/
|
|
18
|
-
export declare const
|
|
19
|
-
/**
|
|
20
|
-
* Refuses to go on while the runner of the assistant's read-only queries is missing or out of date, or runs as a role
|
|
21
|
-
* that is not weaker than the app's: the app's role itself or one it is a member of, a superuser, a login role, or one
|
|
22
|
-
* that can read an auth table, or while the role may call a security-definer function that runs as a role able to
|
|
23
|
-
* read one. It checks the owner's privileges, not its name, so a database cloned under another name still passes. A resource added since the last migration is not checked: Postgres refuses to read its table until then.
|
|
24
|
-
*/
|
|
25
|
-
export declare const checkQueryRunner: (db: Db, authTables: GuardedTables) => Promise<void>;
|
|
22
|
+
export declare const checkQueryRoleSafety: (db: Db, authTables: GuardedTables) => Promise<void>;
|
|
26
23
|
//#endregion
|
|
@@ -1,57 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { queryRoleSql, queryRunnerSignature, queryRunnerSql, runnerBody } from "./runner-sql.js";
|
|
4
|
-
import { plannedGrants } from "./runner-plan.js";
|
|
1
|
+
import { queryRunnerSignature } from "./runner-sql.js";
|
|
2
|
+
import { regclassText } from "./grants-sql.js";
|
|
5
3
|
import { sql } from "kysely";
|
|
6
4
|
//#region src/assistant/query-runner/query-runner.ts
|
|
7
|
-
const quoted = (name) => `"${name.replaceAll("\"", "\"\"")}"`;
|
|
8
|
-
const regclassText = ({ schema, name }) => schema ? `${quoted(schema)}.${quoted(name)}` : quoted(name);
|
|
9
|
-
const roleSql = sql.raw(queryRoleSql);
|
|
10
5
|
const rowsOf = async (db, query) => (await query.execute(db)).rows;
|
|
11
6
|
const guardedRelations = ({ tables, schemas }) => sql`select c.oid, c.relnamespace from pg_class c join pg_namespace n on n.oid = c.relnamespace
|
|
12
7
|
where c.oid in (select to_regclass(t.name) from unnest(${tables.map(regclassText)}::text[]) as t(name)) or n.nspname = any(${[...schemas]}::text[])`;
|
|
13
|
-
const
|
|
14
|
-
join pg_class c on c.oid = to_regclass(t.name) join pg_namespace n on n.oid = c.relnamespace order by t.n`);
|
|
15
|
-
const readRunner = async (db) => {
|
|
16
|
-
const [runner] = await rowsOf(db, sql`select p.prosrc as source, p.prosecdef as definer, pg_get_userbyid(p.proowner) as owner,
|
|
17
|
-
(p.proacl is null or exists (select from aclexplode(p.proacl) a where a.grantee = 0 and a.privilege_type = 'EXECUTE')) as executable
|
|
18
|
-
from pg_proc p where p.oid = to_regprocedure(${queryRunnerSignature})`);
|
|
19
|
-
return runner;
|
|
20
|
-
};
|
|
21
|
-
/** What the database holds of the query role and its runner, and the tables the role should read and must not. Only reads the catalogue. */
|
|
22
|
-
const readQueryRunner = async (db, models, authTables) => {
|
|
23
|
-
const [role] = await rowsOf(db, sql`select ${roleSql} as name, exists (select from pg_roles where rolname = ${roleSql}) as exists`);
|
|
24
|
-
const tables = await rowsOf(db, sql`select n.nspname as schema, c.relname as name from pg_class c join pg_namespace n on n.oid = c.relnamespace, aclexplode(c.relacl) a
|
|
25
|
-
where a.grantee = (select oid from pg_roles where rolname = ${roleSql}) and a.privilege_type = 'SELECT' order by 1, 2`);
|
|
26
|
-
const schemas = await rowsOf(db, sql`select n.nspname as schema from pg_namespace n, aclexplode(n.nspacl) a
|
|
27
|
-
where a.grantee = (select oid from pg_roles where rolname = ${roleSql}) and a.privilege_type = 'USAGE' order by 1`);
|
|
28
|
-
return {
|
|
29
|
-
role,
|
|
30
|
-
runner: await readRunner(db),
|
|
31
|
-
resources: await resolved(db, models.map((model) => model.table)),
|
|
32
|
-
authTables: await resolved(db, authTables.tables),
|
|
33
|
-
guardedSchemas: [...authTables.schemas],
|
|
34
|
-
granted: {
|
|
35
|
-
tables,
|
|
36
|
-
schemas: schemas.map((found) => found.schema)
|
|
37
|
-
}
|
|
38
|
-
};
|
|
39
|
-
};
|
|
40
|
-
/**
|
|
41
|
-
* The SQL that makes the role the assistant's read-only queries run as, and its runner, and grants it exactly the
|
|
42
|
-
* resources' tables, never an auth table; `undefined` when the database is current.
|
|
43
|
-
*/
|
|
44
|
-
const queryRunnerMigration = async (db, models, authTables) => {
|
|
45
|
-
const { role, runner, resources, authTables: auth, guardedSchemas, granted } = await readQueryRunner(db, models, authTables);
|
|
46
|
-
const plan = plannedGrants({
|
|
47
|
-
resources,
|
|
48
|
-
authTables: auth,
|
|
49
|
-
guardedSchemas,
|
|
50
|
-
granted
|
|
51
|
-
});
|
|
52
|
-
return role.exists && runner?.source === runnerBody && runner.definer && runner.owner === role.name && !runner.executable && plan.grants.length === 0 && plan.revokes.length === 0 ? void 0 : queryRunnerSql(plan);
|
|
53
|
-
};
|
|
54
|
-
const refusal = (state) => /* @__PURE__ */ new Error(`The query role of the assistant's read-only queries ${state}. Write it as a migration with \`${migrationCommand}\`, run with the built-in assistant's key set (${modelVariables.apiKey} or options.assistant.apiKey), apply it with the project's migrations, then start again.`);
|
|
8
|
+
const refusal = (state) => /* @__PURE__ */ new Error(`The query role of the assistant's read-only queries ${state}. Take back by hand what it was given, then start again.`);
|
|
55
9
|
const leakingFunctions = (db, authTables) => rowsOf(db, sql`with runner as (select proowner as role from pg_proc where oid = to_regprocedure(${queryRunnerSignature}))
|
|
56
10
|
select format('%I.%I(%s)', n.nspname, p.proname, pg_get_function_identity_arguments(p.oid)) as name
|
|
57
11
|
from pg_proc p join pg_namespace n on n.oid = p.pronamespace, runner
|
|
@@ -61,18 +15,22 @@ const leakingFunctions = (db, authTables) => rowsOf(db, sql`with runner as (sele
|
|
|
61
15
|
where has_schema_privilege(p.proowner, c.relnamespace, 'USAGE') and has_any_column_privilege(p.proowner, c.oid, 'SELECT'))
|
|
62
16
|
order by 1`);
|
|
63
17
|
/**
|
|
64
|
-
* Refuses to go on while the runner of the assistant's read-only queries
|
|
65
|
-
*
|
|
66
|
-
* that can read an auth table, or while
|
|
67
|
-
*
|
|
18
|
+
* Refuses to go on while the runner of the assistant's read-only queries, which the record of migrations says is there,
|
|
19
|
+
* does not run as a role weaker than the app's: it is no security definer, or runs as the app's role itself or one it
|
|
20
|
+
* is a member of, a superuser, a login role, or one that can read an auth table, or while that role may call a
|
|
21
|
+
* security-definer function that runs as a role able to read one. A migration cannot promise these: they are the live
|
|
22
|
+
* database's, such as a grant made by hand. It checks the owner's privileges, not its name, so a database cloned under
|
|
23
|
+
* another name still passes. A resource added since the last migration is not checked: Postgres refuses to read its
|
|
24
|
+
* table until then.
|
|
68
25
|
*/
|
|
69
|
-
const
|
|
70
|
-
const [runner] = await rowsOf(db, sql`select p.
|
|
26
|
+
const checkQueryRoleSafety = async (db, authTables) => {
|
|
27
|
+
const [runner] = await rowsOf(db, sql`select p.prosecdef as definer,
|
|
71
28
|
(o.rolsuper or o.rolcanlogin or pg_has_role(p.proowner, current_user, 'MEMBER')) as strong,
|
|
72
29
|
exists (select from (${guardedRelations(authTables)}) c
|
|
73
30
|
where has_schema_privilege(p.proowner, c.relnamespace, 'USAGE') and has_any_column_privilege(p.proowner, c.oid, 'SELECT')) as reads_auth
|
|
74
31
|
from pg_proc p join pg_roles o on o.oid = p.proowner where p.oid = to_regprocedure(${queryRunnerSignature})`);
|
|
75
|
-
if (!runner
|
|
32
|
+
if (!runner) return;
|
|
33
|
+
if (!runner.definer) throw refusal(`is not what ${queryRunnerSignature} runs as: it is no security definer`);
|
|
76
34
|
if (runner.strong) throw refusal("is not weaker than the app's database role");
|
|
77
35
|
if (runner.reads_auth) throw refusal("can read the auth schema");
|
|
78
36
|
const leaking = await leakingFunctions(db, authTables);
|
|
@@ -80,4 +38,4 @@ const checkQueryRunner = async (db, authTables) => {
|
|
|
80
38
|
throw new Error(`The query role of the assistant's read-only queries can read the auth schema through the security-definer functions ${leaking.map((found) => found.name).join(", ")}. Revoke execute on them from PUBLIC, or move them to a schema without a resource, then start again.`);
|
|
81
39
|
};
|
|
82
40
|
//#endregion
|
|
83
|
-
export {
|
|
41
|
+
export { checkQueryRoleSafety };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { queryRoleSql, queryRunnerSchema, queryRunnerSignature, runnerBody } from "./runner-sql.js";
|
|
2
|
+
import { resourceEntry } from "../../schema-modules/resource-difference.js";
|
|
3
|
+
import { regclassText } from "./grants-sql.js";
|
|
4
|
+
import { sql } from "kysely";
|
|
5
|
+
//#region src/assistant/query-runner/read-query.ts
|
|
6
|
+
const roleSql = sql.raw(queryRoleSql);
|
|
7
|
+
const rowsOf = async (db, query) => (await query.execute(db)).rows;
|
|
8
|
+
const same = (a, b) => a.schema === b.schema && a.name === b.name;
|
|
9
|
+
/**
|
|
10
|
+
* The query module as the database has it for `input`: step 1 once the role and the runner's schema are there, the
|
|
11
|
+
* runner at version 1 when it is this version's, run as the role and not executable by PUBLIC, each resource whose
|
|
12
|
+
* table the role reads, at no digest when it lacks usage on the table's schema, so its grants are written again; and
|
|
13
|
+
* each table the role reads that no resource has, by its name, so they are taken back. Nothing without the role.
|
|
14
|
+
*/
|
|
15
|
+
const readQuery = (grants) => async (db, input) => {
|
|
16
|
+
const [role] = await rowsOf(db, sql`select ${roleSql} as name, exists (select from pg_roles where rolname = ${roleSql}) as exists, to_regnamespace(${queryRunnerSchema}) is not null as schema`);
|
|
17
|
+
if (!role.exists) return;
|
|
18
|
+
const [runner] = await rowsOf(db, sql`select p.prosrc as source, p.prosecdef as definer, pg_get_userbyid(p.proowner) as owner,
|
|
19
|
+
(p.proacl is null or exists (select from aclexplode(p.proacl) a where a.grantee = 0 and a.privilege_type = 'EXECUTE')) as executable
|
|
20
|
+
from pg_proc p where p.oid = to_regprocedure(${queryRunnerSignature})`);
|
|
21
|
+
const granted = await rowsOf(db, sql`select n.nspname as schema, c.relname as name from pg_class c join pg_namespace n on n.oid = c.relnamespace, aclexplode(c.relacl) a
|
|
22
|
+
where a.grantee = (select oid from pg_roles where rolname = ${roleSql}) and a.privilege_type = 'SELECT' order by 1, 2`);
|
|
23
|
+
const usage = (await rowsOf(db, sql`select n.nspname as schema from pg_namespace n, aclexplode(n.nspacl) a
|
|
24
|
+
where a.grantee = (select oid from pg_roles where rolname = ${roleSql}) and a.privilege_type = 'USAGE'`)).map((found) => found.schema);
|
|
25
|
+
const given = Object.entries(input.resources[grants.name] ?? {});
|
|
26
|
+
const resolved = await rowsOf(db, sql`select n.nspname as schema, c.relname as name from unnest(${given.map(([, one]) => regclassText(one.table))}::text[]) with ordinality as t(name, place)
|
|
27
|
+
left join pg_class c on c.oid = to_regclass(t.name) left join pg_namespace n on n.oid = c.relnamespace order by t.place`);
|
|
28
|
+
const entries = {};
|
|
29
|
+
given.forEach(([key, one], i) => {
|
|
30
|
+
const table = resolved[i];
|
|
31
|
+
if (table.schema === null || table.name === null || !granted.some((found) => same(found, table))) return;
|
|
32
|
+
const entry = resourceEntry(grants, input.names, one);
|
|
33
|
+
entries[key] = usage.includes(table.schema) ? entry : {
|
|
34
|
+
...entry,
|
|
35
|
+
digest: ""
|
|
36
|
+
};
|
|
37
|
+
});
|
|
38
|
+
for (const found of granted) {
|
|
39
|
+
if (resolved.some((table) => table.schema !== null && same(found, table))) continue;
|
|
40
|
+
entries[`${found.schema}.${found.name}`] = {
|
|
41
|
+
version: grants.version,
|
|
42
|
+
digest: "",
|
|
43
|
+
table: found
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
const current = runner?.source === runnerBody && runner.definer && runner.owner === role.name && !runner.executable;
|
|
47
|
+
return {
|
|
48
|
+
lastStep: role.schema ? 1 : 0,
|
|
49
|
+
replaceables: current ? { runner: 1 } : {},
|
|
50
|
+
...Object.keys(entries).length > 0 && { resources: { [grants.name]: entries } }
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
//#endregion
|
|
54
|
+
export { readQuery };
|
|
@@ -30,27 +30,11 @@ begin
|
|
|
30
30
|
close rows;
|
|
31
31
|
end
|
|
32
32
|
`;
|
|
33
|
-
const literal = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
34
|
-
const grantSql = ({ grants, revokes }) => [...grants.map((grant) => grant.on === "schema" ? ` execute format('grant usage on schema %I to %I', ${literal(grant.schema)}, query_role);` : ` execute format('grant select on table %I.%I to %I', ${literal(grant.schema)}, ${literal(grant.name)}, query_role);`), ...revokes.map((revoke) => revoke.on === "schema" ? ` execute format('revoke usage on schema %I from %I', ${literal(revoke.schema)}, query_role);` : ` execute format('revoke select on table %I.%I from %I', ${literal(revoke.schema)}, ${literal(revoke.name)}, query_role);`)];
|
|
35
33
|
/**
|
|
36
|
-
* The
|
|
37
|
-
*
|
|
38
|
-
* to hand it the function, and so may execute the runner; PUBLIC may not. The role bypasses row-level security only
|
|
39
|
-
* when the migrating role may give it that: a superuser, or a role with BYPASSRLS on Postgres 16 or later.
|
|
34
|
+
* The runner, made again and handed to the query role, which it runs every statement as; the migrating role, a member
|
|
35
|
+
* of the role, may execute it, PUBLIC may not.
|
|
40
36
|
*/
|
|
41
|
-
const
|
|
42
|
-
`create schema if not exists ${queryRunnerSchema};`,
|
|
43
|
-
[
|
|
44
|
-
"do $$",
|
|
45
|
-
"declare",
|
|
46
|
-
` query_role text := ${queryRoleSql};`,
|
|
47
|
-
"begin",
|
|
48
|
-
" if not exists (select from pg_roles where rolname = query_role) then execute format('create role %I nologin', query_role); end if;",
|
|
49
|
-
" execute format('grant %I to current_user', query_role);",
|
|
50
|
-
" if (select rolsuper or (rolbypassrls and current_setting('server_version_num')::int >= 160000) from pg_roles where rolname = current_user) then execute format('alter role %I bypassrls', query_role); end if;",
|
|
51
|
-
...grantSql(plan),
|
|
52
|
-
"end $$;"
|
|
53
|
-
].join("\n"),
|
|
37
|
+
const runnerSql = () => [
|
|
54
38
|
`create or replace function ${queryRunnerFunction}(statement text, row_limit integer) returns setof json language plpgsql security definer as $f$${runnerBody}$f$;`,
|
|
55
39
|
[
|
|
56
40
|
"do $$",
|
|
@@ -65,4 +49,4 @@ const queryRunnerSql = (plan) => [
|
|
|
65
49
|
`revoke execute on function ${queryRunnerSignature} from public;`
|
|
66
50
|
].join("\n\n");
|
|
67
51
|
//#endregion
|
|
68
|
-
export { queryRoleSql, queryRunnerFunction, queryRunnerSchema, queryRunnerSignature,
|
|
52
|
+
export { queryRoleSql, queryRunnerFunction, queryRunnerSchema, queryRunnerSignature, runnerBody, runnerSql };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { queryRoleSql, queryRunnerSchema } from "../runner-sql.js";
|
|
2
|
+
//#region src/assistant/query-runner/steps/001-role.ts
|
|
3
|
+
/**
|
|
4
|
+
* The runner's schema and the role the read-only queries run as. The migrating role becomes a member of the role,
|
|
5
|
+
* which Postgres 16 needs to hand it the runner. The role bypasses row-level security only when the migrating role may
|
|
6
|
+
* give it that: a superuser, or a role with BYPASSRLS on Postgres 16 or later.
|
|
7
|
+
*/
|
|
8
|
+
const roleStep = () => `create schema if not exists ${queryRunnerSchema};
|
|
9
|
+
|
|
10
|
+
do $$
|
|
11
|
+
declare
|
|
12
|
+
query_role text := ${queryRoleSql};
|
|
13
|
+
begin
|
|
14
|
+
if not exists (select from pg_roles where rolname = query_role) then execute format('create role %I nologin', query_role); end if;
|
|
15
|
+
execute format('grant %I to current_user', query_role);
|
|
16
|
+
if (select rolsuper or (rolbypassrls and current_setting('server_version_num')::int >= 160000) from pg_roles where rolname = current_user) then execute format('alter role %I bypassrls', query_role); end if;
|
|
17
|
+
end $$;`;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { roleStep };
|
package/dist/auth-store.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
//#region src/auth-store.d.ts
|
|
2
2
|
/** The store's tables besides the user table, under their built-in names. */
|
|
3
3
|
export declare const storeTableNames: string[];
|
|
4
|
-
/** The
|
|
5
|
-
export declare const
|
|
4
|
+
/** The records of the store's steps, `auth_steps`, and of the versions a store recorded before it, under their built-in names. */
|
|
5
|
+
export declare const storeRecordNames: string[];
|
|
6
6
|
//#endregion
|
package/dist/auth-store.js
CHANGED
|
@@ -3,7 +3,7 @@ import { storeTableNamesOf } from "./better-auth/store/table-names.js";
|
|
|
3
3
|
//#region src/auth-store.ts
|
|
4
4
|
/** The store's tables besides the user table, under their built-in names. */
|
|
5
5
|
const storeTableNames = storeTableNamesOf(resolveNames({ schema: void 0 }));
|
|
6
|
-
/** The
|
|
7
|
-
const
|
|
6
|
+
/** The records of the store's steps, `auth_steps`, and of the versions a store recorded before it, under their built-in names. */
|
|
7
|
+
const storeRecordNames = [resolveNames({ schema: void 0 }).table("auth_steps").name, resolveNames({ schema: void 0 }).table("auth_migrations").name];
|
|
8
8
|
//#endregion
|
|
9
|
-
export {
|
|
9
|
+
export { storeRecordNames, storeTableNames };
|
|
@@ -1,10 +1,19 @@
|
|
|
1
1
|
import { AdminAuth } from "./create-auth.js";
|
|
2
|
+
import { KeptModule } from "./store/offline/store-model.js";
|
|
3
|
+
import "../internal.js";
|
|
2
4
|
//#region src/better-auth/auth-schema.d.ts
|
|
3
5
|
/**
|
|
4
|
-
* The SQL that brings the admin store to this version of Protobase: the
|
|
5
|
-
* followed by its row in `
|
|
6
|
-
*
|
|
7
|
-
*
|
|
6
|
+
* The SQL that brings the admin store to this version of Protobase: the parts of the modules that are on it has not
|
|
7
|
+
* applied, each followed by its row in `auth_steps`; for a store without that table, the table first. A store that
|
|
8
|
+
* recorded versions of the former chain in `auth_migrations` gets its parts recorded from them; one an earlier
|
|
9
|
+
* Protobase made without any record is adopted: the versions it matches are recorded as applied (`planAdoption`), the
|
|
10
|
+
* others' steps follow. `undefined` when the store is current. The SQL never drops anything.
|
|
8
11
|
*/
|
|
9
12
|
export declare const authSchemaMigration: (auth: AdminAuth) => Promise<string | undefined>;
|
|
13
|
+
/**
|
|
14
|
+
* The modules the config turns off whose steps the store has, each at its last step, which a project's first snapshot
|
|
15
|
+
* keeps: the store has their tables. Read from `auth_steps`, or from `auth_migrations`, or for a store with neither,
|
|
16
|
+
* from the versions its adoption finds it has.
|
|
17
|
+
*/
|
|
18
|
+
export declare const keptStoreModules: (auth: AdminAuth) => Promise<KeptModule[]>;
|
|
10
19
|
//#endregion
|
|
@@ -1,49 +1,57 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { allModules } from "./names/modules-on.js";
|
|
2
2
|
import { storeNames } from "./store/store-names.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
import { plainStoreDb } from "./store/store-db.js";
|
|
4
|
+
import { appliedSteps, hadOf } from "./store/step-record.js";
|
|
5
|
+
import { keptModule } from "./store/offline/store-model.js";
|
|
6
|
+
import { recordedSteps } from "./store/offline/baseline-store.js";
|
|
7
|
+
import { stepRecordSql, stepsSql } from "./store/migration-sql.js";
|
|
6
8
|
import { renderSteps } from "./store/steps/render.js";
|
|
7
|
-
import {
|
|
9
|
+
import { appliedVersions, stepRecordMigration, stepsOfVersions } from "./store/legacy-record.js";
|
|
10
|
+
import { migrationNames, organizationsInput } from "./store/steps/step.js";
|
|
8
11
|
import { adoptionSql, planAdoption, storeHasTables } from "./store/adoption.js";
|
|
9
|
-
import { hadByVersion, refuseModulesOff } from "./store/modules-off.js";
|
|
10
12
|
//#region src/better-auth/auth-schema.ts
|
|
11
|
-
const
|
|
12
|
-
const
|
|
13
|
-
|
|
14
|
-
};
|
|
15
|
-
/**
|
|
16
|
-
* The steps whose versions `applied` lacks, each version followed by its row in `auth_migrations`; written only with
|
|
17
|
-
* every module on (`refuseModulesOff`, `hadByVersion`).
|
|
18
|
-
*/
|
|
19
|
-
const pendingSql = (names, applied) => {
|
|
20
|
-
const rendered = renderSteps(migrationNames(names), names.names.modules, hadByVersion(applied));
|
|
21
|
-
const versions = legacyVersions.map(({ version }) => version).filter((version) => !applied.includes(version));
|
|
22
|
-
return rendered.length === 0 ? void 0 : stepsSql(names, rendered, versions);
|
|
13
|
+
const pendingSql = (auth, names, had) => {
|
|
14
|
+
const rendered = renderSteps(migrationNames(names), names.names.modules, had, organizationsInput(auth.organizations?.options));
|
|
15
|
+
return rendered.length === 0 ? [] : [stepsSql(names, rendered)];
|
|
23
16
|
};
|
|
24
17
|
/**
|
|
25
|
-
* The SQL that brings the admin store to this version of Protobase: the
|
|
26
|
-
* followed by its row in `
|
|
27
|
-
*
|
|
28
|
-
*
|
|
18
|
+
* The SQL that brings the admin store to this version of Protobase: the parts of the modules that are on it has not
|
|
19
|
+
* applied, each followed by its row in `auth_steps`; for a store without that table, the table first. A store that
|
|
20
|
+
* recorded versions of the former chain in `auth_migrations` gets its parts recorded from them; one an earlier
|
|
21
|
+
* Protobase made without any record is adopted: the versions it matches are recorded as applied (`planAdoption`), the
|
|
22
|
+
* others' steps follow. `undefined` when the store is current. The SQL never drops anything.
|
|
29
23
|
*/
|
|
30
24
|
const authSchemaMigration = async (auth) => {
|
|
31
25
|
const names = storeNames(auth);
|
|
32
|
-
refuseModulesOff(names);
|
|
33
26
|
const db = plainStoreDb(auth);
|
|
34
|
-
const applied = await
|
|
35
|
-
if (applied !== void 0)
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
if (!await storeHasTables(db, names)) return [
|
|
27
|
+
const applied = await appliedSteps(db, names);
|
|
28
|
+
if (applied !== void 0) return pendingSql(auth, names, hadOf(applied))[0];
|
|
29
|
+
const record = stepRecordSql(names);
|
|
30
|
+
const versions = await appliedVersions(db, names);
|
|
31
|
+
if (versions !== void 0) return [stepRecordMigration(names), ...pendingSql(auth, names, hadOf(stepsOfVersions(versions)))].join("\n\n");
|
|
32
|
+
if (!await storeHasTables(db, names)) return [record, ...pendingSql(auth, names, hadOf([]))].join("\n\n");
|
|
40
33
|
const { adopted, pending } = await planAdoption(db, names);
|
|
41
|
-
const rest = pending.length === 0 ? [] :
|
|
34
|
+
const rest = pending.length === 0 ? [] : pendingSql(auth, names, hadOf(stepsOfVersions(adopted.map(({ migration }) => migration.version))));
|
|
42
35
|
return [
|
|
43
|
-
|
|
36
|
+
record,
|
|
44
37
|
adoptionSql(names, adopted),
|
|
45
38
|
...rest
|
|
46
39
|
].join("\n\n");
|
|
47
40
|
};
|
|
41
|
+
const adoptedVersions = async (db, names) => await storeHasTables(db, names) ? (await planAdoption(db, names)).adopted.map(({ migration }) => migration.version) : [];
|
|
42
|
+
/**
|
|
43
|
+
* The modules the config turns off whose steps the store has, each at its last step, which a project's first snapshot
|
|
44
|
+
* keeps: the store has their tables. Read from `auth_steps`, or from `auth_migrations`, or for a store with neither,
|
|
45
|
+
* from the versions its adoption finds it has.
|
|
46
|
+
*/
|
|
47
|
+
const keptStoreModules = async (auth) => {
|
|
48
|
+
const names = storeNames(auth);
|
|
49
|
+
const db = plainStoreDb(auth);
|
|
50
|
+
const steps = await appliedSteps(db, names);
|
|
51
|
+
const versions = steps === void 0 ? await appliedVersions(db, names) ?? await adoptedVersions(db, names) : void 0;
|
|
52
|
+
const applied = steps ?? stepsOfVersions(versions ?? []);
|
|
53
|
+
const recorded = recordedSteps(applied);
|
|
54
|
+
return allModules.filter((module) => !names.names.modules.includes(module) && recorded[module] !== void 0).map((module) => keptModule(names, module, recorded[module]));
|
|
55
|
+
};
|
|
48
56
|
//#endregion
|
|
49
|
-
export { authSchemaMigration };
|
|
57
|
+
export { authSchemaMigration, keptStoreModules };
|
|
@@ -24,18 +24,24 @@ import { SignInPolicy } from "./sign-in-policy.js";
|
|
|
24
24
|
import { McpAuthOptions } from "./mcp/mcp-plugins.js";
|
|
25
25
|
import { OAuthApiResource } from "./oauth-api.js";
|
|
26
26
|
import { PersonalAccessTokensOptions } from "./personal-access-tokens/options.js";
|
|
27
|
-
import { OrganizationsOptions, ResolvedOrganizations } from "./organizations/options.js";
|
|
28
27
|
import { JobDefinition } from "../jobs/job-types.js";
|
|
29
|
-
import { Session } from "../types.js";
|
|
28
|
+
import { Session, TenantValue } from "../types.js";
|
|
29
|
+
import { OrganizationsOptions, ResolvedOrganizations } from "./organizations/options.js";
|
|
30
|
+
import { PinRead } from "./organizations/kept-organizations.js";
|
|
30
31
|
import { SignUpField } from "./sign-up/sign-up-fields.js";
|
|
31
32
|
import { CreateAuthOptions, UserCreatedHook } from "./create-auth.js";
|
|
32
33
|
import "../index.js";
|
|
33
|
-
import { Db } from "@protobase/query";
|
|
34
|
+
import { Db, ScopedDb } from "@protobase/query";
|
|
34
35
|
import { OrganizationOptions } from "better-auth/plugins/organization";
|
|
35
36
|
//#region src/better-auth/auth-settings.d.ts
|
|
36
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* What every hook of the project's own gets as its last argument: the app's database, kept to the organization the
|
|
39
|
+
* hook is about on the tables whose rows belong to one (`ScopedDb`), such as the new organization in
|
|
40
|
+
* `onOrganizationCreated`; a hook about no organization, such as `onUserCreated`, sees none of their rows, and while
|
|
41
|
+
* organizations are off after being on, the pinned organization's.
|
|
42
|
+
*/
|
|
37
43
|
export type HookContext = {
|
|
38
|
-
db:
|
|
44
|
+
db: ScopedDb;
|
|
39
45
|
};
|
|
40
46
|
type OrganizationHooks = NonNullable<OrganizationOptions['organizationHooks']>;
|
|
41
47
|
/**
|
|
@@ -68,7 +74,7 @@ export type AuthHooks = {
|
|
|
68
74
|
* `auth` in `protobase.config.ts`: the sign-in settings as data. The store is the app's own database, in `schema`;
|
|
69
75
|
* the hooks and a mailer of the project's own are found in auth/hooks.ts and auth/mailer.ts.
|
|
70
76
|
*/
|
|
71
|
-
export type AuthSettings = Omit<CreateAuthOptions, 'database' | 'secret' | 'generateUserId' | 'onUserCreated' | 'mailer' | 'organizations' | 'mcp' | 'workflowConnections' | 'senderVerifiers'> & {
|
|
77
|
+
export type AuthSettings = Omit<CreateAuthOptions, 'database' | 'secret' | 'generateUserId' | 'onUserCreated' | 'mailer' | 'organizations' | 'organizationsOff' | 'mcp' | 'workflowConnections' | 'senderVerifiers'> & {
|
|
72
78
|
/** Signs cookies and encrypts the JWT private keys, such as `PROTOBASE_SECRET`. Generate with `openssl rand -base64 32`. */
|
|
73
79
|
secret?: string;
|
|
74
80
|
/** The schema of the auth store in the app's database; default `auth`. */
|
|
@@ -77,22 +83,34 @@ export type AuthSettings = Omit<CreateAuthOptions, 'database' | 'secret' | 'gene
|
|
|
77
83
|
generateUserId?: 'uuid';
|
|
78
84
|
/** `false` turns mail off whatever the environment says; default SMTP from `PROTOBASE_SMTP_URL` and `PROTOBASE_MAIL_FROM`. */
|
|
79
85
|
mailer?: false;
|
|
80
|
-
/**
|
|
81
|
-
|
|
86
|
+
/**
|
|
87
|
+
* Organizations (see `OrganizationsOptions`): `enabled` turns them on; their hooks are in the hooks module. Turning them
|
|
88
|
+
* off sets `enabled: false` and keeps `default`, whose organization then stands in for every one.
|
|
89
|
+
*/
|
|
90
|
+
organizations?: Omit<OrganizationsOptions, 'generateId' | 'onCreated' | 'beforeDelete' | 'hooks'> & {
|
|
91
|
+
enabled: boolean;
|
|
92
|
+
};
|
|
82
93
|
/** Turns on the OAuth provider for MCP clients: `true`, or the endpoint's `path` and the `connectPage`. */
|
|
83
94
|
mcp?: true | Omit<McpAuthOptions, 'fetchClientMetadata'>;
|
|
84
95
|
};
|
|
85
96
|
export type AppAuthInput = {
|
|
86
|
-
/**
|
|
97
|
+
/**
|
|
98
|
+
* The app's database: sign-in queries run through it, its plugins included, kept with organizations on to the
|
|
99
|
+
* organization the request works in (`signInOrganization`); each hook gets it kept to the organization it is about.
|
|
100
|
+
*/
|
|
87
101
|
db: Db;
|
|
88
102
|
hooks?: AuthHooks;
|
|
89
103
|
/** A mailer of the project's own, in place of the default. */
|
|
90
104
|
mailer?: Mailer;
|
|
91
105
|
/** The connections the app's workflow plugins declare, which people connect accounts through. */
|
|
92
106
|
workflowConnections?: CreateAuthOptions['workflowConnections'];
|
|
107
|
+
/** `authenticate.tenant`, which pins the default organization while organizations are off after being on. */
|
|
108
|
+
tenant?: TenantValue;
|
|
109
|
+
/** The organization pinned while organizations are off after being on (`pinnedOrganization`), which hooks about none work in. */
|
|
110
|
+
pinned?: PinRead;
|
|
93
111
|
};
|
|
94
112
|
/** createAuth's options for the `auth` settings, the store in the app's own database. */
|
|
95
|
-
export declare const appAuthOptions: (settings: AuthSettings, { db, hooks, mailer, workflowConnections }: AppAuthInput) => CreateAuthOptions;
|
|
113
|
+
export declare const appAuthOptions: (settings: AuthSettings, { db, hooks, mailer, workflowConnections, tenant, pinned }: AppAuthInput) => CreateAuthOptions;
|
|
96
114
|
/** The app's Better Auth from its `auth` settings, built at serve time with only the plugins they turn on. */
|
|
97
115
|
export declare const buildAppAuth: (settings: AuthSettings, input: AppAuthInput) => Promise<import("better-auth").Auth<{
|
|
98
116
|
user: {
|
|
@@ -6229,6 +6247,26 @@ export declare const buildAppAuth: (settings: AuthSettings, input: AppAuthInput)
|
|
|
6229
6247
|
handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
|
|
6230
6248
|
}[];
|
|
6231
6249
|
};
|
|
6250
|
+
} | {
|
|
6251
|
+
id: "protobase-pinned-membership";
|
|
6252
|
+
schema: {
|
|
6253
|
+
member: {
|
|
6254
|
+
modelName: string;
|
|
6255
|
+
fields: {
|
|
6256
|
+
organizationId: import("better-auth").DBFieldAttribute;
|
|
6257
|
+
userId: import("better-auth").DBFieldAttribute;
|
|
6258
|
+
role: import("better-auth").DBFieldAttribute;
|
|
6259
|
+
createdAt: import("better-auth").DBFieldAttribute;
|
|
6260
|
+
appRoles: import("better-auth").DBFieldAttribute;
|
|
6261
|
+
};
|
|
6262
|
+
};
|
|
6263
|
+
};
|
|
6264
|
+
hooks: {
|
|
6265
|
+
before: {
|
|
6266
|
+
matcher: (context: import("better-auth").HookEndpointContext) => boolean;
|
|
6267
|
+
handler: import("better-call").Middleware<import("better-call").MiddlewareOptions, (inputContext: import("better-call").MiddlewareInputContext<import("better-call").MiddlewareOptions>) => Promise<void>>;
|
|
6268
|
+
}[];
|
|
6269
|
+
};
|
|
6232
6270
|
} | {
|
|
6233
6271
|
id: "protobase-personal-access-tokens";
|
|
6234
6272
|
schema: Record<"personalAccessToken", {
|
|
@@ -12235,7 +12273,15 @@ export declare const buildAppAuth: (settings: AuthSettings, input: AppAuthInput)
|
|
|
12235
12273
|
databaseHooks: {
|
|
12236
12274
|
user: {
|
|
12237
12275
|
create: {
|
|
12238
|
-
after?: ((user:
|
|
12276
|
+
after?: ((user: {
|
|
12277
|
+
id: string;
|
|
12278
|
+
createdAt: Date;
|
|
12279
|
+
updatedAt: Date;
|
|
12280
|
+
email: string;
|
|
12281
|
+
emailVerified: boolean;
|
|
12282
|
+
name: string;
|
|
12283
|
+
image?: string | null | undefined;
|
|
12284
|
+
} & Record<string, unknown>, context: import("better-auth").GenericEndpointContext | null) => Promise<void>) | undefined;
|
|
12239
12285
|
before: (user: {
|
|
12240
12286
|
id: string;
|
|
12241
12287
|
createdAt: Date;
|
|
@@ -12464,6 +12510,8 @@ export declare const buildAppAuth: (settings: AuthSettings, input: AppAuthInput)
|
|
|
12464
12510
|
roles: string[];
|
|
12465
12511
|
roleDefinitions: RoleDefinitions;
|
|
12466
12512
|
organizations: ResolvedOrganizations | undefined;
|
|
12513
|
+
pinnedOrganization: PinRead;
|
|
12514
|
+
keptTables: string[];
|
|
12467
12515
|
defaultRole: string | undefined;
|
|
12468
12516
|
generatesUserIds: boolean;
|
|
12469
12517
|
mail: boolean;
|