@protobase/server 0.129.1 → 0.130.1
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.d.ts +1 -1
- 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/archive-revival.d.ts +11 -0
- package/dist/better-auth/store/offline/archive-revival.js +25 -0
- package/dist/better-auth/store/offline/baseline-store.d.ts +11 -7
- package/dist/better-auth/store/offline/baseline-store.js +15 -12
- package/dist/better-auth/store/offline/contract-gate.d.ts +18 -0
- package/dist/better-auth/store/offline/contract-gate.js +35 -0
- package/dist/better-auth/store/offline/module-archive.d.ts +41 -0
- package/dist/better-auth/store/offline/module-archive.js +95 -0
- package/dist/better-auth/store/offline/module-delete.d.ts +22 -0
- package/dist/better-auth/store/offline/module-delete.js +99 -0
- package/dist/better-auth/store/offline/module-switches.d.ts +32 -0
- package/dist/better-auth/store/offline/module-switches.js +113 -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 -7
- package/dist/better-auth/store/offline/offline-steps.js +29 -20
- package/dist/better-auth/store/offline/retired-watch.d.ts +5 -0
- package/dist/better-auth/store/offline/retired-watch.js +43 -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 +27 -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 +7 -1
- 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/store/store-sql.d.ts +1 -1
- 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 +30 -10
- package/dist/internal.js +26 -8
- 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
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { parseAppRoles } from "./app-roles.js";
|
|
2
|
+
import { acrossOrganizations, inOrganization } from "../../organization-scope/sign-in-organization.js";
|
|
2
3
|
import { sql } from "kysely";
|
|
3
4
|
//#region src/better-auth/organizations/store.ts
|
|
4
5
|
/** Better Auth's `findMany` returns 100 rows unless told otherwise; these lists are read whole. */
|
|
@@ -14,8 +15,9 @@ const organizationRoleOf = (member) => {
|
|
|
14
15
|
};
|
|
15
16
|
/** A member who is an owner, in SQL: `owner` is one of the names in their role, as `organizationRoleOf` reads it. */
|
|
16
17
|
const isOwner = (role) => sql`'owner' = any(regexp_split_to_array(regexp_replace(${role}, '^\\s+|\\s+$', '', 'g'), '\\s*,\\s*'))`;
|
|
18
|
+
/** Someone's membership of the organization named, read in that organization. */
|
|
17
19
|
const findMember = async (adapter, where) => {
|
|
18
|
-
const row = await adapter.findOne({
|
|
20
|
+
const row = await inOrganization(where.organizationId, () => adapter.findOne({
|
|
19
21
|
model: "member",
|
|
20
22
|
where: [{
|
|
21
23
|
field: "organizationId",
|
|
@@ -24,27 +26,29 @@ const findMember = async (adapter, where) => {
|
|
|
24
26
|
field: "userId",
|
|
25
27
|
value: where.userId
|
|
26
28
|
}]
|
|
27
|
-
});
|
|
29
|
+
}));
|
|
28
30
|
return row ? memberOf(row) : void 0;
|
|
29
31
|
};
|
|
32
|
+
/** A membership by its id, whatever its organization: the caller's right to it is checked in its organization next. */
|
|
30
33
|
const findMemberById = async (adapter, id) => {
|
|
31
|
-
const row = await adapter.findOne({
|
|
34
|
+
const row = await acrossOrganizations("a member is found by its id, before the caller's right is checked in its organization", () => adapter.findOne({
|
|
32
35
|
model: "member",
|
|
33
36
|
where: [{
|
|
34
37
|
field: "id",
|
|
35
38
|
value: id
|
|
36
39
|
}]
|
|
37
|
-
});
|
|
40
|
+
}));
|
|
38
41
|
return row ? memberOf(row) : void 0;
|
|
39
42
|
};
|
|
40
|
-
|
|
43
|
+
/** Every organization someone is a member of. */
|
|
44
|
+
const membershipsOf = async (adapter, userId) => (await acrossOrganizations("a user lists their own memberships, one in each organization", () => adapter.findMany({
|
|
41
45
|
model: "member",
|
|
42
46
|
where: [{
|
|
43
47
|
field: "userId",
|
|
44
48
|
value: userId
|
|
45
49
|
}],
|
|
46
50
|
limit: everyRow
|
|
47
|
-
})).map(memberOf);
|
|
51
|
+
}))).map(memberOf);
|
|
48
52
|
const findOrganization = (adapter, id) => adapter.findOne({
|
|
49
53
|
model: "organization",
|
|
50
54
|
where: [{
|
|
@@ -52,13 +56,14 @@ const findOrganization = (adapter, id) => adapter.findOne({
|
|
|
52
56
|
value: id
|
|
53
57
|
}]
|
|
54
58
|
});
|
|
55
|
-
|
|
59
|
+
/** Sets a member's app roles, in the member's organization. */
|
|
60
|
+
const setAppRoles = (adapter, member, appRoles) => inOrganization(member.organizationId, () => adapter.update({
|
|
56
61
|
model: "member",
|
|
57
62
|
where: [{
|
|
58
63
|
field: "id",
|
|
59
|
-
value:
|
|
64
|
+
value: member.id
|
|
60
65
|
}],
|
|
61
66
|
update: { appRoles: [...appRoles] }
|
|
62
|
-
});
|
|
67
|
+
}));
|
|
63
68
|
//#endregion
|
|
64
69
|
export { everyRow, findMember, findMemberById, findOrganization, isOwner, membershipsOf, organizationRoleOf, setAppRoles };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
//#region src/better-auth/personal-access-tokens/pinned-tokens.ts
|
|
3
|
+
/** Stores a token made in the pinned organization `organizationId`, as `storeToken` stores one. */
|
|
4
|
+
const storePinnedToken = async (store, kept, data) => {
|
|
5
|
+
const token = kept.table("personal_access_token");
|
|
6
|
+
const c = token.columns;
|
|
7
|
+
const [row] = (await sql`insert into ${token} (id, ${c.user_id}, ${c.name}, ${c.token_hash}, ${c.role}, ${c.organization_id}, ${c.created_at}, ${c.expires_at})
|
|
8
|
+
values (${store.newId}, ${data.userId}, ${data.name}, ${data.tokenHash}, ${data.role}, ${data.organizationId}, ${data.createdAt}, ${data.expiresAt ?? null})
|
|
9
|
+
returning id::text as id`.execute(store.db)).rows;
|
|
10
|
+
return {
|
|
11
|
+
...data,
|
|
12
|
+
id: row.id,
|
|
13
|
+
lastUsedAt: null
|
|
14
|
+
};
|
|
15
|
+
};
|
|
16
|
+
/** The organization the token `id` was made in, `null` for one made in none, such as one made before tokens kept theirs while organizations were off. */
|
|
17
|
+
const tokenOrganization = async (store, kept, id) => {
|
|
18
|
+
const token = kept.table("personal_access_token");
|
|
19
|
+
const [row] = (await sql`select ${token.columns.organization_id}::text as organization_id from ${token} where id = ${id}`.execute(store.db)).rows;
|
|
20
|
+
return row?.organization_id ?? null;
|
|
21
|
+
};
|
|
22
|
+
//#endregion
|
|
23
|
+
export { storePinnedToken, tokenOrganization };
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { everyRow } from "../organizations/store.js";
|
|
2
2
|
import { sessionRoles } from "../roles/session-role.js";
|
|
3
|
+
import { storeSqlOf } from "../store/store-sql.js";
|
|
3
4
|
import { newToken, tokenHash } from "./token-format.js";
|
|
5
|
+
import { storePinnedToken } from "./pinned-tokens.js";
|
|
4
6
|
import { deleteToken, listedToken, personalAccessTokenModel, storeToken, tokensOf } from "./token-store.js";
|
|
5
7
|
import * as z$1 from "zod";
|
|
6
8
|
import { APIError, createAuthEndpoint, sessionMiddleware } from "better-auth/api";
|
|
@@ -18,6 +20,10 @@ const noRole = {
|
|
|
18
20
|
code: "NO_ROLE",
|
|
19
21
|
message: "You have no role in this app here, so a token could do nothing."
|
|
20
22
|
};
|
|
23
|
+
const noOrganization = {
|
|
24
|
+
code: "NO_ORGANIZATION",
|
|
25
|
+
message: "Choose the organization the token works in first."
|
|
26
|
+
};
|
|
21
27
|
const idsIn = (values) => [{
|
|
22
28
|
field: "id",
|
|
23
29
|
value: values,
|
|
@@ -40,63 +46,78 @@ const labelsFor = async (adapter, definitions, rows) => {
|
|
|
40
46
|
* The signed-in person's personal access tokens, which act as them from a script:
|
|
41
47
|
* `GET /account/personal-access-tokens` lists them, newest first, without the tokens themselves;
|
|
42
48
|
* `POST /account/personal-access-tokens/create { name, expiresInDays? }` makes one with the role and organization the
|
|
43
|
-
* session works with, and answers the token, once, beside the listed entry;
|
|
49
|
+
* session works with, and answers the token, once, beside the listed entry; with `organizations`, a session without an
|
|
50
|
+
* active organization makes none, as every token works in one; with `pinned`, while organizations are off after being
|
|
51
|
+
* on, every token is made in the organization `pin` reads, in its column as `kept` names it, which the account page
|
|
52
|
+
* does not name;
|
|
44
53
|
* `POST /account/personal-access-tokens/revoke { id }` deletes one, so it stops at its next request; one that is gone
|
|
45
54
|
* already is no error. Each acts on the session's own person only. The store keeps each token's SHA-256 hash alone.
|
|
46
55
|
*/
|
|
47
|
-
const personalAccessTokensPlugin = ({ options, definitions, names }) =>
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
56
|
+
const personalAccessTokensPlugin = ({ options, definitions, names, organizations, pinned }) => {
|
|
57
|
+
const shown = (row) => organizations ? row : {
|
|
58
|
+
...row,
|
|
59
|
+
organizationId: null
|
|
60
|
+
};
|
|
61
|
+
return {
|
|
62
|
+
id: "protobase-personal-access-tokens",
|
|
63
|
+
schema: names.tables(personalAccessTokenModel),
|
|
64
|
+
endpoints: {
|
|
65
|
+
listPersonalAccessTokens: createAuthEndpoint(personalAccessTokenPaths.list, {
|
|
66
|
+
method: "GET",
|
|
67
|
+
use: [sessionMiddleware]
|
|
68
|
+
}, async (ctx) => {
|
|
69
|
+
const rows = (await tokensOf(ctx.context.adapter, ctx.context.session.user.id)).map(shown);
|
|
70
|
+
const labels = await labelsFor(ctx.context.adapter, definitions, rows);
|
|
71
|
+
return ctx.json({ tokens: rows.map((row) => listedToken(row, labels)) });
|
|
72
|
+
}),
|
|
73
|
+
createPersonalAccessToken: createAuthEndpoint(personalAccessTokenPaths.create, {
|
|
74
|
+
method: "POST",
|
|
75
|
+
use: [sessionMiddleware],
|
|
76
|
+
body: z$1.object({
|
|
77
|
+
name: z$1.string().trim().min(1).max(100),
|
|
78
|
+
expiresInDays: z$1.number().int().min(1).max(maxTokenDays).optional()
|
|
79
|
+
})
|
|
80
|
+
}, async (ctx) => {
|
|
81
|
+
const { user, session } = ctx.context.session;
|
|
82
|
+
if (organizations && !session.activeOrganizationId) throw new APIError("FORBIDDEN", noOrganization);
|
|
83
|
+
const context = ctx.context;
|
|
84
|
+
const { active } = await sessionRoles(context, {
|
|
85
|
+
user,
|
|
86
|
+
session
|
|
87
|
+
});
|
|
88
|
+
if (!active) throw new APIError("FORBIDDEN", noRole);
|
|
89
|
+
const token = newToken(options.prefix);
|
|
90
|
+
const now = /* @__PURE__ */ new Date();
|
|
91
|
+
const data = {
|
|
92
|
+
userId: user.id,
|
|
93
|
+
name: ctx.body.name,
|
|
94
|
+
tokenHash: await tokenHash(token),
|
|
95
|
+
role: active,
|
|
96
|
+
organizationId: session.activeOrganizationId ?? null,
|
|
97
|
+
createdAt: now,
|
|
98
|
+
expiresAt: ctx.body.expiresInDays === void 0 ? null : new Date(now.getTime() + ctx.body.expiresInDays * dayMs)
|
|
99
|
+
};
|
|
100
|
+
const pin = await pinned?.pin();
|
|
101
|
+
const row = pin ? await storePinnedToken(storeSqlOf(ctx.context), pinned.kept, {
|
|
102
|
+
...data,
|
|
103
|
+
organizationId: pin.id
|
|
104
|
+
}) : await storeToken(ctx.context.adapter, data);
|
|
105
|
+
const labels = await labelsFor(ctx.context.adapter, definitions, [shown(row)]);
|
|
106
|
+
return ctx.json({
|
|
107
|
+
token,
|
|
108
|
+
personalAccessToken: listedToken(shown(row), labels)
|
|
109
|
+
});
|
|
110
|
+
}),
|
|
111
|
+
revokePersonalAccessToken: createAuthEndpoint(personalAccessTokenPaths.revoke, {
|
|
112
|
+
method: "POST",
|
|
113
|
+
use: [sessionMiddleware],
|
|
114
|
+
body: z$1.object({ id: z$1.string().min(1) })
|
|
115
|
+
}, async (ctx) => {
|
|
116
|
+
await deleteToken(ctx.context.adapter, ctx.context.session.user.id, ctx.body.id);
|
|
117
|
+
return ctx.json({ revoked: true });
|
|
65
118
|
})
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const { active } = await sessionRoles(context, {
|
|
70
|
-
user,
|
|
71
|
-
session
|
|
72
|
-
});
|
|
73
|
-
if (!active) throw new APIError("FORBIDDEN", noRole);
|
|
74
|
-
const token = newToken(options.prefix);
|
|
75
|
-
const now = /* @__PURE__ */ new Date();
|
|
76
|
-
const row = await storeToken(ctx.context.adapter, {
|
|
77
|
-
userId: user.id,
|
|
78
|
-
name: ctx.body.name,
|
|
79
|
-
tokenHash: await tokenHash(token),
|
|
80
|
-
role: active,
|
|
81
|
-
organizationId: session.activeOrganizationId ?? null,
|
|
82
|
-
createdAt: now,
|
|
83
|
-
expiresAt: ctx.body.expiresInDays === void 0 ? null : new Date(now.getTime() + ctx.body.expiresInDays * dayMs)
|
|
84
|
-
});
|
|
85
|
-
const labels = await labelsFor(ctx.context.adapter, definitions, [row]);
|
|
86
|
-
return ctx.json({
|
|
87
|
-
token,
|
|
88
|
-
personalAccessToken: listedToken(row, labels)
|
|
89
|
-
});
|
|
90
|
-
}),
|
|
91
|
-
revokePersonalAccessToken: createAuthEndpoint(personalAccessTokenPaths.revoke, {
|
|
92
|
-
method: "POST",
|
|
93
|
-
use: [sessionMiddleware],
|
|
94
|
-
body: z$1.object({ id: z$1.string().min(1) })
|
|
95
|
-
}, async (ctx) => {
|
|
96
|
-
await deleteToken(ctx.context.adapter, ctx.context.session.user.id, ctx.body.id);
|
|
97
|
-
return ctx.json({ revoked: true });
|
|
98
|
-
})
|
|
99
|
-
}
|
|
100
|
-
});
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
};
|
|
101
122
|
//#endregion
|
|
102
123
|
export { maxTokenDays, personalAccessTokenPaths, personalAccessTokensPlugin };
|
|
@@ -17,19 +17,22 @@ const refused = () => unauthorized("The personal access token is invalid, expire
|
|
|
17
17
|
* as a token's does (`checkUserStanding`): exist, not be banned, and still hold the token's role where it works, in its
|
|
18
18
|
* organization with organizations on. The session has that one role and organization, as a token of the session that
|
|
19
19
|
* made it would, and no `signIn`, so what only the person's own sign-in may do is refused. Use is noted at most once a
|
|
20
|
-
* minute (`noteUse`).
|
|
20
|
+
* minute (`noteUse`). While organizations are off after being on, a token works only when made in the pinned
|
|
21
|
+
* organization, and its user is still a member there; any other is refused as an unknown one is.
|
|
21
22
|
*/
|
|
22
|
-
const personalAccessTokenSessions = ({ prefix, context, organizations, tenant }) => async (token, now = /* @__PURE__ */ new Date()) => {
|
|
23
|
+
const personalAccessTokenSessions = ({ prefix, context, organizations, pinned, tenant }) => async (token, now = /* @__PURE__ */ new Date()) => {
|
|
23
24
|
if (!isWellFormed(token, prefix)) throw refused();
|
|
24
25
|
const store = await context();
|
|
25
26
|
const row = await findTokenByHash(store.adapter, await tokenHash(token));
|
|
26
27
|
if (!row || row.expiresAt && new Date(row.expiresAt) <= now) throw refused();
|
|
28
|
+
const pin = organizations ? void 0 : (await pinned?.pin())?.id;
|
|
29
|
+
if (pin !== void 0 && await pinned.organizationOf(store, row.id) !== pin) throw refused();
|
|
27
30
|
const organizationId = organizations ? row.organizationId ?? void 0 : void 0;
|
|
28
31
|
const organizationRole = await checkUserStanding(store, {
|
|
29
32
|
userId: row.userId,
|
|
30
33
|
roles: [row.role],
|
|
31
34
|
...organizationId && { organizationId }
|
|
32
|
-
}, organizations, now);
|
|
35
|
+
}, organizations, now, pin);
|
|
33
36
|
await noteUse(store.adapter, row, now);
|
|
34
37
|
const roles = [row.role].filter((role) => role !== noGlobalRole);
|
|
35
38
|
const tenantValue = tenant === void 0 ? organizationId : typeof tenant === "function" ? await tenant() : tenant;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { acrossOrganizations, inOrganization } from "../../organization-scope/sign-in-organization.js";
|
|
1
2
|
import { everyRow } from "../organizations/store.js";
|
|
2
3
|
//#region src/better-auth/personal-access-tokens/token-store.ts
|
|
3
4
|
/** Better Auth's model for personal access tokens: one row per token, holding its hash and never the token. */
|
|
@@ -13,15 +14,17 @@ const listedToken = (row, labels) => ({
|
|
|
13
14
|
...row.expiresAt && { expiresAt: iso(row.expiresAt) },
|
|
14
15
|
...row.lastUsedAt && { lastUsedAt: iso(row.lastUsedAt) }
|
|
15
16
|
});
|
|
16
|
-
const
|
|
17
|
+
const organizationOf = (row) => row.organizationId ?? void 0;
|
|
18
|
+
/** The token of a hash, whatever its organization. */
|
|
19
|
+
const findTokenByHash = (adapter, tokenHash) => acrossOrganizations("a token is looked up by its hash, a key unique across the app, before its organization is known", () => adapter.findOne({
|
|
17
20
|
model: personalAccessTokenModel,
|
|
18
21
|
where: [{
|
|
19
22
|
field: "tokenHash",
|
|
20
23
|
value: tokenHash
|
|
21
24
|
}]
|
|
22
|
-
});
|
|
23
|
-
/** The user's tokens, newest first. */
|
|
24
|
-
const tokensOf = (adapter, userId) => adapter.findMany({
|
|
25
|
+
}));
|
|
26
|
+
/** The user's tokens, newest first, from every organization. */
|
|
27
|
+
const tokensOf = (adapter, userId) => acrossOrganizations("a user lists their own tokens, each made in an organization of theirs", () => adapter.findMany({
|
|
25
28
|
model: personalAccessTokenModel,
|
|
26
29
|
where: [{
|
|
27
30
|
field: "userId",
|
|
@@ -32,13 +35,14 @@ const tokensOf = (adapter, userId) => adapter.findMany({
|
|
|
32
35
|
direction: "desc"
|
|
33
36
|
},
|
|
34
37
|
limit: everyRow
|
|
35
|
-
});
|
|
36
|
-
|
|
38
|
+
}));
|
|
39
|
+
/** Stores a token, in the organization it works in. */
|
|
40
|
+
const storeToken = (adapter, data) => inOrganization(organizationOf(data), () => adapter.create({
|
|
37
41
|
model: personalAccessTokenModel,
|
|
38
42
|
data
|
|
39
|
-
});
|
|
43
|
+
}));
|
|
40
44
|
/** Deletes the user's token `id`; one that is not theirs, or gone already, is left as it is. */
|
|
41
|
-
const deleteToken = (adapter, userId, id) => adapter.deleteMany({
|
|
45
|
+
const deleteToken = (adapter, userId, id) => acrossOrganizations("a user deletes one of their own tokens, made in any organization of theirs", () => adapter.deleteMany({
|
|
42
46
|
model: personalAccessTokenModel,
|
|
43
47
|
where: [{
|
|
44
48
|
field: "id",
|
|
@@ -47,20 +51,20 @@ const deleteToken = (adapter, userId, id) => adapter.deleteMany({
|
|
|
47
51
|
field: "userId",
|
|
48
52
|
value: userId
|
|
49
53
|
}]
|
|
50
|
-
});
|
|
54
|
+
}));
|
|
51
55
|
/** How stale `lastUsedAt` may get: a script's many requests update it once a minute, not on each one. */
|
|
52
56
|
const lastUsedPrecisionMs = 6e4;
|
|
53
57
|
/** Notes that the token was used `now`, unless it was within the last minute. */
|
|
54
58
|
const noteUse = async (adapter, row, now) => {
|
|
55
59
|
if (row.lastUsedAt && now.getTime() - new Date(row.lastUsedAt).getTime() < 6e4) return;
|
|
56
|
-
await adapter.update({
|
|
60
|
+
await inOrganization(organizationOf(row), () => adapter.update({
|
|
57
61
|
model: personalAccessTokenModel,
|
|
58
62
|
where: [{
|
|
59
63
|
field: "id",
|
|
60
64
|
value: row.id
|
|
61
65
|
}],
|
|
62
66
|
update: { lastUsedAt: now }
|
|
63
|
-
});
|
|
67
|
+
}));
|
|
64
68
|
};
|
|
65
69
|
//#endregion
|
|
66
70
|
export { deleteToken, findTokenByHash, lastUsedPrecisionMs, listedToken, noteUse, personalAccessTokenModel, storeToken, tokensOf };
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import { allModules } from "../names/modules-on.js";
|
|
1
2
|
import { resolveNames } from "../names/resolve-names.js";
|
|
2
3
|
import { ddl } from "./ddl.js";
|
|
3
|
-
import { recordMigrations } from "./migrations-table.js";
|
|
4
|
-
import { legacyVersions } from "./steps/legacy-versions.js";
|
|
5
|
-
import { statementsSql } from "./migration-sql.js";
|
|
6
4
|
import { moduleSteps } from "./steps/index.js";
|
|
5
|
+
import { recordSteps } from "./step-record.js";
|
|
6
|
+
import { statementsSql } from "./migration-sql.js";
|
|
7
|
+
import { legacyVersions } from "./steps/legacy-versions.js";
|
|
7
8
|
import { renderSteps } from "./steps/render.js";
|
|
9
|
+
import { stepsOfVersions } from "./legacy-record.js";
|
|
8
10
|
import { migrationNames } from "./steps/step.js";
|
|
9
11
|
import { sql } from "kysely";
|
|
10
12
|
//#region src/better-auth/store/adoption.ts
|
|
@@ -12,9 +14,17 @@ const key = ({ table, column }) => `${table}.${column}`;
|
|
|
12
14
|
const columnsIn = async (db, schema) => (await sql`select table_name as "table", column_name as "column", udt_name as "type" from information_schema.columns
|
|
13
15
|
where table_schema = ${schema === void 0 ? sql`current_schema()` : schema} order by table_name, ordinal_position`.execute(db)).rows;
|
|
14
16
|
const scratchSchema = "protobase_auth_adoption";
|
|
17
|
+
const scratchOrganizations = {
|
|
18
|
+
default: {
|
|
19
|
+
id: "00000000-0000-0000-0000-000000000000",
|
|
20
|
+
name: "scratch",
|
|
21
|
+
slug: "scratch"
|
|
22
|
+
},
|
|
23
|
+
existingUsersRole: "scratch"
|
|
24
|
+
};
|
|
15
25
|
/**
|
|
16
|
-
* For each version, the columns its steps make: every step of every module
|
|
17
|
-
* that is rolled back.
|
|
26
|
+
* For each version, the columns its steps make: every step of every module, as the former chain made them with every
|
|
27
|
+
* module on, runs in a scratch schema, in a transaction that is rolled back.
|
|
18
28
|
*/
|
|
19
29
|
const madeColumns = async (db, names) => {
|
|
20
30
|
const tx = await db.startTransaction().execute();
|
|
@@ -22,7 +32,8 @@ const madeColumns = async (db, names) => {
|
|
|
22
32
|
await sql`create schema ${sql.id(scratchSchema)}`.execute(tx);
|
|
23
33
|
const scratch = resolveNames({
|
|
24
34
|
...names.names.input,
|
|
25
|
-
schema: scratchSchema
|
|
35
|
+
schema: scratchSchema,
|
|
36
|
+
modules: allModules
|
|
26
37
|
});
|
|
27
38
|
const made = new Map(legacyVersions.map(({ version }) => [version, []]));
|
|
28
39
|
let before = [];
|
|
@@ -30,7 +41,7 @@ const madeColumns = async (db, names) => {
|
|
|
30
41
|
...names,
|
|
31
42
|
schema: scratchSchema,
|
|
32
43
|
names: scratch
|
|
33
|
-
}), scratch.modules, () => false)) {
|
|
44
|
+
}), scratch.modules, () => false, scratchOrganizations)) {
|
|
34
45
|
for (const statement of part.statements) await statement.execute(tx);
|
|
35
46
|
const after = await columnsIn(tx, scratchSchema);
|
|
36
47
|
made.get(part.version).push(...after.filter((column) => !before.some((earlier) => key(earlier) === key(column))));
|
|
@@ -43,7 +54,11 @@ const madeColumns = async (db, names) => {
|
|
|
43
54
|
/** Whether the store has any table of the steps besides the user table, which may be another system's. */
|
|
44
55
|
const storeHasTables = async (db, names) => {
|
|
45
56
|
const tables = new Set((await columnsIn(db, names.schema)).map((column) => column.table));
|
|
46
|
-
|
|
57
|
+
const every = resolveNames({
|
|
58
|
+
...names.names.input,
|
|
59
|
+
modules: allModules
|
|
60
|
+
});
|
|
61
|
+
return Object.values(moduleSteps).some((steps) => steps.some((step) => step.tables.some((table) => tables.has(every.tables[table].name))));
|
|
47
62
|
};
|
|
48
63
|
/** Which versions the store matches and which it still needs; a version it matches only partly is an error. */
|
|
49
64
|
const planAdoption = async (db, names) => {
|
|
@@ -70,7 +85,7 @@ const planAdoption = async (db, names) => {
|
|
|
70
85
|
return adoption;
|
|
71
86
|
};
|
|
72
87
|
/**
|
|
73
|
-
* The SQL that records the adopted
|
|
88
|
+
* The SQL that records the steps of the adopted versions as applied, once it finds every column they make with its type; it
|
|
74
89
|
* stops the migration, naming what it lacks, on a database that differs from the one it was written from.
|
|
75
90
|
*/
|
|
76
91
|
const adoptionSql = (names, adopted) => {
|
|
@@ -91,7 +106,7 @@ begin
|
|
|
91
106
|
end if;
|
|
92
107
|
end
|
|
93
108
|
$adopt$`;
|
|
94
|
-
return `-- The auth store an earlier Protobase made, without a record of its migrations, adopted: ${adopted.map(({ migration }) => `${migration.version} ${migration.name}`).join(", ")}\n-- recorded as applied, once every table and column they make is there.\n${statementsSql([check,
|
|
109
|
+
return `-- The auth store an earlier Protobase made, without a record of its migrations, adopted: ${adopted.map(({ migration }) => `${migration.version} ${migration.name}`).join(", ")}\n-- recorded as applied, once every table and column they make is there.\n${statementsSql([check, recordSteps(names, stepsOfVersions(adopted.map(({ migration }) => migration.version)))])}`;
|
|
95
110
|
};
|
|
96
111
|
//#endregion
|
|
97
112
|
export { adoptionSql, planAdoption, storeHasTables };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { plainStoreDb } from "./store-db.js";
|
|
2
1
|
import { storeNames } from "./store-names.js";
|
|
2
|
+
import { plainStoreDb } from "./store-db.js";
|
|
3
3
|
import { sql } from "kysely";
|
|
4
4
|
import { getSchema } from "better-auth/db";
|
|
5
5
|
import { getMigrations } from "better-auth/db/migration";
|
|
@@ -31,10 +31,11 @@ const authSchemaDrift = async (auth) => {
|
|
|
31
31
|
} : auth.options;
|
|
32
32
|
const { toBeCreated, toBeAdded, toBeAddedIndexes, schemaProblems } = await getMigrations(options, { throwOnUnsafe: false });
|
|
33
33
|
const view = auth.users.keyTable ? auth.names.table("user").name : void 0;
|
|
34
|
+
const compared = ({ table }) => table !== view && !auth.keptTables.includes(table);
|
|
34
35
|
const tables = [
|
|
35
|
-
...toBeCreated.filter(
|
|
36
|
-
...toBeAdded.filter(
|
|
37
|
-
...toBeAddedIndexes.filter(
|
|
36
|
+
...toBeCreated.filter(compared).map(({ table }) => `lacks the table ${table}`),
|
|
37
|
+
...toBeAdded.filter(compared).flatMap(({ table, fields }) => Object.keys(fields).map((field) => `lacks the column ${table}.${field}`)),
|
|
38
|
+
...toBeAddedIndexes.filter(compared).map(({ name }) => `lacks the index ${name}`),
|
|
38
39
|
...schemaProblems
|
|
39
40
|
];
|
|
40
41
|
return view ? [...tables, ...await userViewDrift(auth)] : tables;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import "../names/resolve-names.js";
|
|
2
|
+
import { StoreNames } from "./store-names.js";
|
|
3
|
+
import { AppliedStep } from "./step-record.js";
|
|
4
|
+
import { Kysely } from "kysely";
|
|
5
|
+
//#region src/better-auth/store/legacy-record.d.ts
|
|
6
|
+
/** The parts the store applied, from the versions it recorded: every part of each version. */
|
|
7
|
+
export declare const stepsOfVersions: (versions: readonly number[]) => AppliedStep[];
|
|
8
|
+
/** The record of the store's steps, made when it is missing and filled from `auth_migrations`, for a store that recorded versions. */
|
|
9
|
+
export declare const stepRecordMigration: (names: StoreNames) => string;
|
|
10
|
+
//#endregion
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { allModules } from "../names/modules-on.js";
|
|
2
|
+
import { ddl } from "./ddl.js";
|
|
3
|
+
import { moduleSteps } from "./steps/index.js";
|
|
4
|
+
import { stepRecordTable } from "./step-record.js";
|
|
5
|
+
import { guardedBlock, stepRecordSql } from "./migration-sql.js";
|
|
6
|
+
import { latestStoreVersion } from "./steps/legacy-versions.js";
|
|
7
|
+
import { partVersion } from "./steps/render.js";
|
|
8
|
+
import { sql } from "kysely";
|
|
9
|
+
//#region src/better-auth/store/legacy-record.ts
|
|
10
|
+
/** The table, in the store's schema, as the store's names resolve `auth_migrations`. */
|
|
11
|
+
const legacyRecordTable = ({ names }) => names.table("auth_migrations");
|
|
12
|
+
/** Every part of every step with the version of the former chain that made it, as that chain made them, every module on. */
|
|
13
|
+
const legacyParts = () => allModules.flatMap((module) => moduleSteps[module].flatMap((step) => [module, ...allModules.filter((target) => step.adds?.[target])].map((target) => ({
|
|
14
|
+
module,
|
|
15
|
+
step: step.step,
|
|
16
|
+
target,
|
|
17
|
+
version: partVersion(module, step, target)
|
|
18
|
+
}))));
|
|
19
|
+
/** The parts the store applied, from the versions it recorded: every part of each version. */
|
|
20
|
+
const stepsOfVersions = (versions) => {
|
|
21
|
+
const newer = versions.filter((version) => version > latestStoreVersion);
|
|
22
|
+
if (newer.length > 0) throw new Error(`The auth store records version ${newer.join(", ")} in auth_migrations, which this version of Protobase does not ship; upgrade Protobase`);
|
|
23
|
+
return legacyParts().filter((part) => versions.includes(part.version)).map(({ module, step, target }) => ({
|
|
24
|
+
module,
|
|
25
|
+
step,
|
|
26
|
+
target
|
|
27
|
+
}));
|
|
28
|
+
};
|
|
29
|
+
/** The versions the store recorded, in order; `undefined` when it has no `auth_migrations`. */
|
|
30
|
+
const appliedVersions = async (db, names) => {
|
|
31
|
+
const table = legacyRecordTable(names);
|
|
32
|
+
const [found] = (await sql`select to_regclass(${String(table)}) is not null as found`.execute(db)).rows;
|
|
33
|
+
if (!found?.found) return;
|
|
34
|
+
const { version } = table.columns;
|
|
35
|
+
return (await sql`select ${version} as version from ${table} order by ${version}`.execute(db)).rows.map((row) => row.version);
|
|
36
|
+
};
|
|
37
|
+
/**
|
|
38
|
+
* The statement that fills `auth_steps` from `auth_migrations`, once that table is there: every part of each version
|
|
39
|
+
* it records, at the time it recorded it. A part recorded already is left as it is.
|
|
40
|
+
*/
|
|
41
|
+
const fillFromLegacySql = (names) => {
|
|
42
|
+
const legacy = legacyRecordTable(names);
|
|
43
|
+
const steps = stepRecordTable(names);
|
|
44
|
+
const { module, step, target, applied_at } = steps.columns;
|
|
45
|
+
const parts = legacyParts().map((part) => ddl`(${sql.lit(part.module)}, ${sql.lit(part.step)}, ${sql.lit(part.target)}, ${sql.lit(part.version)})`);
|
|
46
|
+
const fill = ddl`insert into ${steps} (${module}, ${step}, ${target}, ${applied_at})
|
|
47
|
+
select part.module, part.step, part.target, legacy.${legacy.columns.applied_at}
|
|
48
|
+
from (values ${sql.join(parts, sql`, `)}) as part (module, step, target, version)
|
|
49
|
+
join ${legacy} legacy on legacy.${legacy.columns.version} = part.version
|
|
50
|
+
on conflict do nothing`;
|
|
51
|
+
return `-- The steps the store recorded by version in ${legacy.name}, recorded by step.\n${guardedBlock(ddl`to_regclass(${sql.lit(String(legacy))}) is not null`, [fill])}`;
|
|
52
|
+
};
|
|
53
|
+
/** The record of the store's steps, made when it is missing and filled from `auth_migrations`, for a store that recorded versions. */
|
|
54
|
+
const stepRecordMigration = (names) => [stepRecordSql(names), fillFromLegacySql(names)].join("\n\n");
|
|
55
|
+
//#endregion
|
|
56
|
+
export { appliedVersions, fillFromLegacySql, legacyParts, legacyRecordTable, stepRecordMigration, stepsOfVersions };
|
|
@@ -1,43 +1,48 @@
|
|
|
1
1
|
import { ddl, ddlText } from "./ddl.js";
|
|
2
|
-
import {
|
|
3
|
-
import { legacyVersions } from "./steps/legacy-versions.js";
|
|
4
|
-
import { sql } from "kysely";
|
|
2
|
+
import { createStepRecord, partOf, recordSteps, stepRecorded } from "./step-record.js";
|
|
5
3
|
//#region src/better-auth/store/migration-sql.ts
|
|
6
4
|
/** The statements as SQL text. */
|
|
7
5
|
const statementsSql = (statements) => statements.map((statement) => `${ddlText(statement)};`).join("\n\n");
|
|
8
6
|
const comment = ({ module, step, on }) => `-- ${module} ${step.step} ${step.name}${on === void 0 ? "" : `, on the tables of ${on}`}: ${step.title}.`;
|
|
9
|
-
const partStatements = (names,
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
7
|
+
const partStatements = (names, part) => [...part.statements, recordSteps(names, [partOf(part)])];
|
|
8
|
+
/**
|
|
9
|
+
* The rendered steps, each under a comment naming it, each followed by the row that records it in `auth_steps`, as
|
|
10
|
+
* one transaction: what a part leaves for after it commits runs in it, before that row.
|
|
11
|
+
*/
|
|
12
|
+
const stepsSql = (names, rendered) => rendered.map((part) => `${comment(part)}\n${statementsSql([
|
|
13
|
+
...part.statements,
|
|
14
|
+
...part.after(false),
|
|
15
|
+
recordSteps(names, [partOf(part)])
|
|
16
|
+
])}`).join("\n\n");
|
|
14
17
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
18
|
+
* What the rendered steps leave for once the migration's transaction commits, as a migration's `.after.sql` runs it:
|
|
19
|
+
* outside a transaction, each statement under a comment naming its part; `undefined` when they leave nothing.
|
|
17
20
|
*/
|
|
18
|
-
const
|
|
19
|
-
const
|
|
21
|
+
const afterStepsSql = (rendered) => {
|
|
22
|
+
const parts = rendered.flatMap((part) => {
|
|
23
|
+
const statements = part.after(true);
|
|
24
|
+
return statements.length === 0 ? [] : [`${comment(part)}\n${statementsSql(statements)}`];
|
|
25
|
+
});
|
|
26
|
+
return parts.length === 0 ? void 0 : `${parts.join("\n\n")}\n`;
|
|
27
|
+
};
|
|
28
|
+
const blockQuote = "$step$";
|
|
20
29
|
const statementQuote = "$statement$";
|
|
21
|
-
|
|
30
|
+
/** The statements as one block that runs them only while `when` holds, each executed as text. */
|
|
31
|
+
const guardedBlock = (when, statements) => {
|
|
22
32
|
const texts = statements.map(ddlText);
|
|
23
33
|
const quoted = texts.find((text) => text.includes(blockQuote) || text.includes(statementQuote));
|
|
24
34
|
if (quoted) throw new Error(`A step's statement holds ${blockQuote} or ${statementQuote}, which guard it: ${quoted}`);
|
|
25
|
-
|
|
26
|
-
const recorded = ddlText(ddl`select from ${table} where ${table.columns.version} = ${sql.lit(version)}`);
|
|
27
|
-
return `do ${blockQuote} begin\nif not exists (${recorded}) then\n${texts.map((text) => `execute ${statementQuote}${text}${statementQuote};`).join("\n")}\nend if;\nend ${blockQuote};`;
|
|
35
|
+
return `do ${blockQuote} begin\nif ${ddlText(when)} then\n${texts.map((text) => `execute ${statementQuote}${text}${statementQuote};`).join("\n")}\nend if;\nend ${blockQuote};`;
|
|
28
36
|
};
|
|
29
37
|
/**
|
|
30
|
-
* The rendered steps as `stepsSql` writes them, each part run only while `
|
|
31
|
-
*
|
|
32
|
-
*/
|
|
33
|
-
const guardedStepsSql = (names, rendered, versions) => rendered.map((part, i) => `${comment(part)}\n${unlessRecorded(names, part.version, partStatements(names, rendered, versions, i))}`).join("\n\n");
|
|
34
|
-
/**
|
|
35
|
-
* The migrations table, for a store that has none yet, in the store's schema, made when it is missing. With
|
|
36
|
-
* `ifMissing`, the table too is made only when missing, for a database a host made it in already.
|
|
38
|
+
* The rendered steps as `stepsSql` writes them, each part run only while `auth_steps` lacks it, so a database that has
|
|
39
|
+
* it already, such as one `protobase-serve migrate-release` brought to a release, skips it.
|
|
37
40
|
*/
|
|
38
|
-
const
|
|
41
|
+
const guardedStepsSql = (names, rendered) => rendered.map((part) => `${comment(part)}\n${guardedBlock(ddl`not ${stepRecorded(names, part)}`, partStatements(names, part))}`).join("\n\n");
|
|
42
|
+
/** The record of the store's steps, for a store that has none yet, in the store's schema, made when it is missing. */
|
|
43
|
+
const stepRecordSql = (names) => {
|
|
39
44
|
const schema = names.schema === void 0 ? [] : [ddl`create schema if not exists ${names.schema}`];
|
|
40
|
-
return `-- The record of the auth store's
|
|
45
|
+
return `-- The record of the auth store's steps.\n${statementsSql([...schema, createStepRecord(names)])}`;
|
|
41
46
|
};
|
|
42
47
|
//#endregion
|
|
43
|
-
export {
|
|
48
|
+
export { afterStepsSql, guardedBlock, guardedStepsSql, statementsSql, stepRecordSql, stepsSql };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ModuleId } from "../../names/modules/index.js";
|
|
2
|
+
import { StoreNames } from "../store-names.js";
|
|
3
|
+
//#region src/better-auth/store/offline/archive-revival.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* The statements that give back to each column `module` left in use on the tables of `existing` the foreign key to its
|
|
6
|
+
* table, once that table is made again, where the column has none: not checked against the rows there, whose values
|
|
7
|
+
* may name a row the archive holds, such as a token's organization, which then no longer works. As SQL text after a
|
|
8
|
+
* comment; `undefined` when it leaves none.
|
|
9
|
+
*/
|
|
10
|
+
export declare const restoredKeysSql: (names: StoreNames, module: ModuleId, existing: readonly ModuleId[]) => string | undefined;
|
|
11
|
+
//#endregion
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { generatedName } from "../../names/identifier-length.js";
|
|
2
|
+
import { ddl } from "../ddl.js";
|
|
3
|
+
import { statementsSql } from "../migration-sql.js";
|
|
4
|
+
import { stillWrittenColumns } from "./module-switches.js";
|
|
5
|
+
import { sql } from "kysely";
|
|
6
|
+
//#region src/better-auth/store/offline/archive-revival.ts
|
|
7
|
+
/**
|
|
8
|
+
* The statements that give back to each column `module` left in use on the tables of `existing` the foreign key to its
|
|
9
|
+
* table, once that table is made again, where the column has none: not checked against the rows there, whose values
|
|
10
|
+
* may name a row the archive holds, such as a token's organization, which then no longer works. As SQL text after a
|
|
11
|
+
* comment; `undefined` when it leaves none.
|
|
12
|
+
*/
|
|
13
|
+
const restoredKeysSql = (names, module, existing) => {
|
|
14
|
+
const statements = stillWrittenColumns(names, module, existing).map(({ table, column, references }) => ddl`do $restore$
|
|
15
|
+
begin
|
|
16
|
+
if not exists (select from pg_constraint where conrelid = ${sql.lit(String(table))}::regclass and contype = 'f' and confrelid = ${sql.lit(String(references))}::regclass) then
|
|
17
|
+
alter table ${table} add constraint ${sql.id(generatedName(`${table.name}_${column.name}_fkey`))} foreign key (${column}) references ${references} (id) on delete cascade not valid;
|
|
18
|
+
end if;
|
|
19
|
+
end
|
|
20
|
+
$restore$`);
|
|
21
|
+
if (statements.length === 0) return;
|
|
22
|
+
return `-- ${module} on: the columns it left in use while off point at its tables again where an archive took their foreign key; a value the archive holds no longer names a row.\n${statementsSql(statements)}`;
|
|
23
|
+
};
|
|
24
|
+
//#endregion
|
|
25
|
+
export { restoredKeysSql };
|