@protobase/server 0.126.0 → 0.126.2
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/better-auth/auth-settings.d.ts +64 -0
- package/dist/better-auth/create-auth.d.ts +67 -2
- package/dist/better-auth/create-auth.js +10 -3
- package/dist/better-auth/names/modules/index.d.ts +9 -2
- package/dist/better-auth/names/modules/mail-senders.js +7 -2
- package/dist/better-auth/staff-checks.js +2 -0
- package/dist/better-auth/store/steps/index.js +3 -1
- package/dist/better-auth/store/steps/legacy-versions.js +4 -0
- package/dist/better-auth/store/steps/mail-senders/005-sender-sharing.js +24 -0
- package/dist/create-admin.js +10 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -1
- package/dist/package.js +1 -1
- package/dist/personal-mail/listed-mail-senders.d.ts +3 -1
- package/dist/personal-mail/listed-mail-senders.js +1 -0
- package/dist/personal-mail/mail-sender.d.ts +5 -3
- package/dist/personal-mail/mail-sender.js +22 -5
- package/dist/personal-mail/mail-senders-plugin.js +39 -3
- package/dist/personal-mail/personal-mailer.d.ts +8 -6
- package/dist/personal-mail/personal-mailer.js +25 -4
- package/dist/personal-mail/sender-address-error.d.ts +5 -4
- package/dist/personal-mail/sender-address-error.js +4 -3
- package/dist/personal-mail/sender-store.js +13 -6
- package/dist/personal-mail/shared-sender-store.d.ts +2 -0
- package/dist/personal-mail/shared-sender-store.js +39 -0
- package/dist/personal-mail/shared-senders.d.ts +11 -0
- package/dist/personal-mail/shared-senders.js +22 -0
- package/dist/relay/change-commands.js +34 -4
- package/dist/relay/client-events.d.ts +2 -2
- package/dist/relay/members-sql.js +30 -7
- package/dist/relay/realtime-channels.d.ts +25 -0
- package/dist/relay/realtime-channels.js +39 -0
- package/dist/relay/realtime-members-reads.js +16 -0
- package/dist/relay/realtime-members-schema.js +67 -0
- package/dist/relay/realtime-members-sql.js +120 -0
- package/dist/relay/relay-jobs.js +9 -1
- package/dist/relay/relay-models.js +27 -3
- package/dist/relay/relay-options.d.ts +16 -4
- package/dist/relay/relay-options.js +7 -2
- package/dist/relay/relay-runtime.js +3 -3
- package/dist/relay/relay-schema.d.ts +8 -5
- package/dist/relay/relay-schema.js +17 -5
- package/dist/relay/relay-switch.d.ts +1 -0
- package/dist/relay/relay-switch.js +12 -6
- package/dist/relay/ticket-route.js +2 -1
- package/dist/relay/typing-views.js +1 -1
- package/package.json +6 -6
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { argsOf, membersComment, membersSql, realtimeMembersTable, realtimeSchema, rowTrigger, truncateTrigger } from "./realtime-members-sql.js";
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
//#region src/relay/realtime-members-schema.ts
|
|
4
|
+
const storedArgs = (args) => Buffer.from(args.map((arg) => `${arg}\0`).join(""), "utf8").toString("hex");
|
|
5
|
+
/**
|
|
6
|
+
* Refuses channel tables that are partitions, or that inherit or are inherited from other than by partitioning: their
|
|
7
|
+
* rows are written through a table the triggers do not stand on. A partitioned channel table is kept (see `membersSql`).
|
|
8
|
+
*/
|
|
9
|
+
const refuseInherited = (tables) => {
|
|
10
|
+
if (tables.length === 0) return;
|
|
11
|
+
throw new Error(`realtime.members cannot keep the members of ${tables.join(", ")}: a partition or a table in an inheritance tree is not supported as a channel resource whose records list their members; use the partitioned table itself`);
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* The listed tables as the database has them: each one and its partitions as SQL names them, and whether
|
|
15
|
+
* it is refused (`refuseInherited`); and whether the members table exists.
|
|
16
|
+
*/
|
|
17
|
+
const listedTables = async (db, listed) => {
|
|
18
|
+
const { rows } = await sql`select name,
|
|
19
|
+
to_regclass(name)::text as rel, to_regclass(${realtimeMembersTable}) is not null as members,
|
|
20
|
+
exists (select from pg_class c where c.oid = to_regclass(name) and (c.relispartition or (c.relkind <> 'p' and exists (select from pg_inherits i where i.inhrelid = c.oid or i.inhparent = c.oid)))) as inherited,
|
|
21
|
+
array(select tree.relid::regclass::text from pg_partition_tree(to_regclass(name)) as tree where tree.relid <> to_regclass(name) order by tree.relid::regclass::text) as partitions
|
|
22
|
+
from unnest(${listed.map(({ table }) => table)}::text[]) with ordinality as listed(name, place) order by place`.execute(db);
|
|
23
|
+
refuseInherited(rows.filter((row) => row.inherited).map((row) => row.name));
|
|
24
|
+
return rows;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* Whether the triggers of this version stand on exactly the listed tables with their args, a truncate trigger on each
|
|
28
|
+
* of their partitions too, each firing on every write (enabled, not only for replicas), as must the clones of the row
|
|
29
|
+
* trigger Postgres keeps on the partitions, and the members table exists; the tables, as SQL names them, with any of
|
|
30
|
+
* them but clones; and the partitions of each listed table. A partition attached later lacks its truncate trigger, so
|
|
31
|
+
* startup asks for the migration that writes them all again.
|
|
32
|
+
*/
|
|
33
|
+
const standingTriggers = async (db, listed) => {
|
|
34
|
+
const tables = await listedTables(db, listed);
|
|
35
|
+
const { rows } = await sql`select t.tgname as name,
|
|
36
|
+
encode(t.tgargs, 'hex') as args, coalesce(obj_description(p.oid, 'pg_proc') = ${membersComment}, false) as current, t.tgenabled in ('O', 'A') as enabled,
|
|
37
|
+
t.tgparentid <> 0 as clone, t.tgrelid::regclass::text as "table"
|
|
38
|
+
from pg_trigger t join pg_proc p on p.oid = t.tgfoid join pg_namespace n on n.oid = p.pronamespace
|
|
39
|
+
where n.nspname = ${realtimeSchema} and p.proname = 'members_kept'`.execute(db);
|
|
40
|
+
const roots = rows.filter((row) => !row.clone);
|
|
41
|
+
const expected = listed.flatMap((table, i) => {
|
|
42
|
+
const { rel, partitions } = tables[i];
|
|
43
|
+
const args = storedArgs(argsOf(table));
|
|
44
|
+
return [`${rel}|${rowTrigger}|${args}`, ...[rel, ...partitions].map((on) => `${on}|${truncateTrigger}|${args}`)];
|
|
45
|
+
});
|
|
46
|
+
const found = roots.map((row) => `${row.table}|${row.name}|${row.args}`);
|
|
47
|
+
const exact = expected.length === found.length && expected.every((entry) => found.includes(entry)) && rows.every((row) => row.current && row.enabled);
|
|
48
|
+
const membersTable = listed.length === 0 || tables.every((row) => row.members && row.rel !== null);
|
|
49
|
+
return {
|
|
50
|
+
current: exact && membersTable,
|
|
51
|
+
standing: [...new Set(roots.map((row) => row.table))],
|
|
52
|
+
partitions: tables.map((row) => row.partitions)
|
|
53
|
+
};
|
|
54
|
+
};
|
|
55
|
+
/** The SQL that keeps `realtime.members` for the listed tables (`membersSql`); `undefined` when it is current. */
|
|
56
|
+
const realtimeMembersMigration = async (db, listed) => {
|
|
57
|
+
const { current, standing, partitions } = await standingTriggers(db, listed);
|
|
58
|
+
if (current) return;
|
|
59
|
+
return `${membersSql(listed, standing, partitions).join(";\n\n")};`;
|
|
60
|
+
};
|
|
61
|
+
/** Refuses to start while `realtime.members` would not follow the listed tables' members. */
|
|
62
|
+
const checkRealtimeMembers = async (db, listed, command) => {
|
|
63
|
+
if ((await standingTriggers(db, listed)).current) return;
|
|
64
|
+
throw new Error(`The realtime.members table, or the triggers that keep it on ${listed.map(({ table }) => table).join(", ")} and their partitions, is missing or out of date. Write it as a migration with \`${command}\`, apply it with the project's migrations, then start again.`);
|
|
65
|
+
};
|
|
66
|
+
//#endregion
|
|
67
|
+
export { checkRealtimeMembers, realtimeMembersMigration, refuseInherited };
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { tableSql } from "../changes/capture-sql.js";
|
|
2
|
+
//#region src/relay/realtime-members-sql.ts
|
|
3
|
+
/** The schema of the framework's realtime tables. */
|
|
4
|
+
const realtimeSchema = "realtime";
|
|
5
|
+
/** Who is in each channel whose record lists its members, one row for each person in each channel. */
|
|
6
|
+
const realtimeMembersTable = `${realtimeSchema}.members`;
|
|
7
|
+
const membersComment = `Protobase realtime members 3`;
|
|
8
|
+
const rowTrigger = "realtime_members";
|
|
9
|
+
const truncateTrigger = "realtime_members_truncated";
|
|
10
|
+
/** The table of a channel resource whose records list their members. */
|
|
11
|
+
const listedTable = ({ model, field }) => ({
|
|
12
|
+
resource: model.name,
|
|
13
|
+
table: tableSql(model),
|
|
14
|
+
key: model.fields[model.primaryKey[0]].column,
|
|
15
|
+
members: model.fields[field].column,
|
|
16
|
+
deleted: model.softDelete === void 0 ? "" : model.fields[model.softDelete].column
|
|
17
|
+
});
|
|
18
|
+
const literal = (text) => `'${text.replaceAll("'", "''")}'`;
|
|
19
|
+
/**
|
|
20
|
+
* The members table, keyed by channel so a notice's audience is read by its key, with an index by person for their
|
|
21
|
+
* tickets and co-members; `listed_members`, the user ids one state of a record lists, none once soft-deleted; and the
|
|
22
|
+
* trigger function. A truncate, of the table or of one of its partitions, writes the resource's members again from the
|
|
23
|
+
* table as it stands, so a truncated partition's siblings keep theirs. After each write that changes a record's key, members or soft
|
|
24
|
+
* delete, as it stands after every trigger before it, it writes the members of the record's old and new keys again
|
|
25
|
+
* from the table: row triggers that run after the write fire once the statement wrote every row, so a statement that
|
|
26
|
+
* swaps two records' keys leaves each key with the members its record lists.
|
|
27
|
+
*/
|
|
28
|
+
const baseSql = [
|
|
29
|
+
`create schema if not exists ${realtimeSchema}`,
|
|
30
|
+
`create table if not exists ${realtimeMembersTable} (
|
|
31
|
+
resource text not null,
|
|
32
|
+
channel_key text not null,
|
|
33
|
+
user_id text not null,
|
|
34
|
+
primary key (resource, channel_key, user_id)
|
|
35
|
+
)`,
|
|
36
|
+
`create index if not exists members_by_user on ${realtimeMembersTable} (user_id, resource)`,
|
|
37
|
+
`create or replace function ${realtimeSchema}.listed_members(entry jsonb, members_column text, deleted_column text) returns setof text
|
|
38
|
+
language sql immutable as $$
|
|
39
|
+
select distinct member from jsonb_array_elements_text(
|
|
40
|
+
case when (deleted_column = '' or entry ->> deleted_column is null) and jsonb_typeof(entry -> members_column) = 'array' then entry -> members_column else '[]'::jsonb end
|
|
41
|
+
) as member where member is not null
|
|
42
|
+
$$`,
|
|
43
|
+
`create or replace function ${realtimeSchema}.members_kept() returns trigger
|
|
44
|
+
language plpgsql as $$
|
|
45
|
+
declare
|
|
46
|
+
channel_resource text := tg_argv[0];
|
|
47
|
+
key_column text := tg_argv[1];
|
|
48
|
+
members_column text := tg_argv[2];
|
|
49
|
+
deleted_column text := tg_argv[3];
|
|
50
|
+
old_entry jsonb;
|
|
51
|
+
new_entry jsonb;
|
|
52
|
+
keys text[];
|
|
53
|
+
key_type text;
|
|
54
|
+
-- The table the trigger stands on: the partitioned one for a partition's clone or truncate trigger.
|
|
55
|
+
source regclass := coalesce(pg_partition_root(tg_relid), tg_relid);
|
|
56
|
+
begin
|
|
57
|
+
if tg_op = 'TRUNCATE' then
|
|
58
|
+
delete from ${realtimeMembersTable} m where m.resource = channel_resource;
|
|
59
|
+
execute format('insert into ${realtimeMembersTable} (resource, channel_key, user_id)
|
|
60
|
+
select $1, to_jsonb(t) ->> $2, member from %s t cross join lateral ${realtimeSchema}.listed_members(to_jsonb(t), $3, $4) as member
|
|
61
|
+
on conflict do nothing', source)
|
|
62
|
+
using channel_resource, key_column, members_column, deleted_column;
|
|
63
|
+
return null;
|
|
64
|
+
end if;
|
|
65
|
+
if tg_op <> 'INSERT' then old_entry := to_jsonb(old); end if;
|
|
66
|
+
if tg_op <> 'DELETE' then new_entry := to_jsonb(new); end if;
|
|
67
|
+
if tg_op = 'UPDATE' and old_entry -> key_column is not distinct from new_entry -> key_column
|
|
68
|
+
and old_entry -> members_column is not distinct from new_entry -> members_column
|
|
69
|
+
and (deleted_column = '' or old_entry -> deleted_column is not distinct from new_entry -> deleted_column) then
|
|
70
|
+
return null;
|
|
71
|
+
end if;
|
|
72
|
+
keys := array(select distinct k from unnest(array[old_entry ->> key_column, new_entry ->> key_column]) as k where k is not null);
|
|
73
|
+
delete from ${realtimeMembersTable} m where m.resource = channel_resource and m.channel_key = any(keys);
|
|
74
|
+
select format_type(a.atttypid, a.atttypmod) into key_type from pg_attribute a where a.attrelid = source and a.attname = key_column;
|
|
75
|
+
execute format('insert into ${realtimeMembersTable} (resource, channel_key, user_id)
|
|
76
|
+
select $1, to_jsonb(t) ->> $2, member from %s t cross join lateral ${realtimeSchema}.listed_members(to_jsonb(t), $3, $4) as member
|
|
77
|
+
where t.%I = any($5::%s[]) on conflict do nothing', source, key_column, key_type)
|
|
78
|
+
using channel_resource, key_column, members_column, deleted_column, keys;
|
|
79
|
+
return null;
|
|
80
|
+
end
|
|
81
|
+
$$`,
|
|
82
|
+
`comment on function ${realtimeSchema}.members_kept() is '${membersComment}'`
|
|
83
|
+
];
|
|
84
|
+
/** The args of a listed table's row trigger, as `members_kept` reads them. */
|
|
85
|
+
const argsOf = ({ resource, key, members, deleted }) => [
|
|
86
|
+
resource,
|
|
87
|
+
key,
|
|
88
|
+
members,
|
|
89
|
+
deleted
|
|
90
|
+
];
|
|
91
|
+
/** A truncate trigger's SQL on a channel table or one of its partitions, as SQL names it. */
|
|
92
|
+
const truncateSql = (listed, on) => `create trigger ${truncateTrigger} after truncate on ${on} for each statement execute function ${realtimeSchema}.members_kept(${argsOf(listed).map(literal).join(", ")})`;
|
|
93
|
+
const listedTableSql = (listed, partitions) => {
|
|
94
|
+
const { resource, table, key, members, deleted } = listed;
|
|
95
|
+
return [
|
|
96
|
+
`create trigger ${rowTrigger} after insert or delete or update on ${table} for each row execute function ${realtimeSchema}.members_kept(${argsOf(listed).map(literal).join(", ")})`,
|
|
97
|
+
truncateSql(listed, table),
|
|
98
|
+
...partitions.map((partition) => truncateSql(listed, partition)),
|
|
99
|
+
`delete from ${realtimeMembersTable} where resource = ${literal(resource)}`,
|
|
100
|
+
`insert into ${realtimeMembersTable} (resource, channel_key, user_id)
|
|
101
|
+
select ${literal(resource)}, to_jsonb(t) ->> ${literal(key)}, member from ${table} t
|
|
102
|
+
cross join lateral ${realtimeSchema}.listed_members(to_jsonb(t), ${literal(members)}, ${literal(deleted)}) as member
|
|
103
|
+
on conflict do nothing`
|
|
104
|
+
];
|
|
105
|
+
};
|
|
106
|
+
/**
|
|
107
|
+
* The SQL that keeps `realtime.members` for the listed tables: the table and its functions, the triggers of every
|
|
108
|
+
* table that has them dropped (`standing`, as SQL names each), each listed table's written, a truncate trigger on each
|
|
109
|
+
* of its partitions (`partitions`, by listed table, as SQL names each) included, its rows written again
|
|
110
|
+
* from the table, and the rows of resources no longer listed deleted. Writes made while the triggers are off, such as
|
|
111
|
+
* with `session_replication_role = replica`, are not kept until the next migration that writes it.
|
|
112
|
+
*/
|
|
113
|
+
const membersSql = (listed, standing, partitions) => [
|
|
114
|
+
...baseSql,
|
|
115
|
+
...standing.flatMap((table) => [`drop trigger if exists ${rowTrigger} on ${table}`, `drop trigger if exists ${truncateTrigger} on ${table}`]),
|
|
116
|
+
...listed.flatMap((table, i) => listedTableSql(table, partitions[i] ?? [])),
|
|
117
|
+
`delete from ${realtimeMembersTable} where resource <> all(array[${listed.map(({ resource }) => literal(resource)).join(", ")}]::text[])`
|
|
118
|
+
];
|
|
119
|
+
//#endregion
|
|
120
|
+
export { argsOf, listedTable, membersComment, membersSql, realtimeMembersTable, realtimeSchema, rowTrigger, truncateTrigger };
|
package/dist/relay/relay-jobs.js
CHANGED
|
@@ -68,5 +68,13 @@ const relayJobs = ({ client, sessionEnd, report }) => {
|
|
|
68
68
|
})
|
|
69
69
|
};
|
|
70
70
|
};
|
|
71
|
+
/**
|
|
72
|
+
* The relay's jobs while the app can use the relay but does not: `relay.close-sessions`, which the delete of sign-in
|
|
73
|
+
* sessions queues all the same, completes at once, as no socket is open on the relay.
|
|
74
|
+
*/
|
|
75
|
+
const idleRelayJobs = () => [defineJob({
|
|
76
|
+
name: closeSessionsJob,
|
|
77
|
+
run: async () => {}
|
|
78
|
+
})];
|
|
71
79
|
//#endregion
|
|
72
|
-
export { relayJobs };
|
|
80
|
+
export { idleRelayJobs, relayJobs };
|
|
@@ -2,9 +2,12 @@ import { capturedBy } from "../changes/capture-sql.js";
|
|
|
2
2
|
import { presenceModel } from "./presence-model.js";
|
|
3
3
|
import { relatedTarget } from "@protobase/schema/internal";
|
|
4
4
|
//#region src/relay/relay-models.ts
|
|
5
|
+
/** Whether a channel has members, from a members resource or a field of its own, rather than being open. */
|
|
6
|
+
const hasMembers = (channel) => Boolean(channel?.members ?? channel?.listed);
|
|
5
7
|
/**
|
|
6
8
|
* The options against the models, or an error naming what does not fit: a channel resource needs a key of one field, and
|
|
7
|
-
* its members resource a captured table, such as one with `.live()`, a relation field to it and a user field
|
|
9
|
+
* its members resource a captured table, such as one with `.live()`, a relation field to it and a user field; one whose
|
|
10
|
+
* members are a field of its own is captured itself, and that field is JSON.
|
|
8
11
|
*/
|
|
9
12
|
const relayModels = (options, models) => {
|
|
10
13
|
const byName = new Map(models.map((model) => [model.name, model]));
|
|
@@ -16,7 +19,9 @@ const relayModels = (options, models) => {
|
|
|
16
19
|
const model = byName.get(name);
|
|
17
20
|
if (!model) throw new Error(`${at}: the app has no resource "${name}"`);
|
|
18
21
|
if (model.primaryKey.length !== 1) throw new Error(`${at}: a channel resource needs a key of one field, as a channel is named <resource>/<key>`);
|
|
19
|
-
const
|
|
22
|
+
const listed = channel.members && "field" in channel.members ? listedModel(channel.members.field, model, `${at}.members`) : void 0;
|
|
23
|
+
if (listed && !captured(model)) throw new Error(`${at}.members: the changes of "${name}" are not captured, so the relay would not hear who joins or leaves: declare .live() on it`);
|
|
24
|
+
const own = channel.members && !("field" in channel.members) ? membersModel(channel.members, name, byName, `${at}.members`) : void 0;
|
|
20
25
|
if (own && !captured(own.model)) throw new Error(`${at}.members: the changes of "${own.model.name}" are not captured, so the relay would not hear of them: declare .live() on it`);
|
|
21
26
|
if (own) members.set(own.model.name, [...members.get(own.model.name) ?? [], {
|
|
22
27
|
...own,
|
|
@@ -24,6 +29,7 @@ const relayModels = (options, models) => {
|
|
|
24
29
|
}]);
|
|
25
30
|
channels.set(name, {
|
|
26
31
|
...own && { members: own },
|
|
32
|
+
...listed && { listed },
|
|
27
33
|
...channel.mentions !== void 0 && { mentions: channel.mentions }
|
|
28
34
|
});
|
|
29
35
|
}
|
|
@@ -53,6 +59,24 @@ const relayModels = (options, models) => {
|
|
|
53
59
|
...options.presence && { presence: presenceModel(options.presence, byName, captured) }
|
|
54
60
|
};
|
|
55
61
|
};
|
|
62
|
+
/**
|
|
63
|
+
* Why a field cannot list a channel record's members, or undefined when it can: it is a JSON field of user ids whose
|
|
64
|
+
* every change reaches the relay, so neither sensitive, which capture leaves out of the change, nor ignored by history.
|
|
65
|
+
*/
|
|
66
|
+
const listedFieldProblem = (model, field) => {
|
|
67
|
+
const definition = model.fields[field];
|
|
68
|
+
if (definition?.type !== "json") return `"${field}" of "${model.name}" is no JSON field of user ids`;
|
|
69
|
+
if (definition.sensitive) return `"${field}" of "${model.name}" is sensitive, so its changes never reach the relay`;
|
|
70
|
+
if (model.historyIgnore?.includes(field)) return `"${field}" of "${model.name}" is ignored by its history, so its changes never reach the relay`;
|
|
71
|
+
};
|
|
72
|
+
const listedModel = (field, model, at) => {
|
|
73
|
+
const problem = listedFieldProblem(model, field);
|
|
74
|
+
if (problem) throw new Error(`${at}.field: ${problem}`);
|
|
75
|
+
return {
|
|
76
|
+
model,
|
|
77
|
+
field
|
|
78
|
+
};
|
|
79
|
+
};
|
|
56
80
|
const membersModel = (members, channel, byName, at) => {
|
|
57
81
|
const model = byName.get(members.resource);
|
|
58
82
|
if (!model) throw new Error(`${at}.resource: the app has no resource "${members.resource}"`);
|
|
@@ -66,4 +90,4 @@ const membersModel = (members, channel, byName, at) => {
|
|
|
66
90
|
};
|
|
67
91
|
};
|
|
68
92
|
//#endregion
|
|
69
|
-
export { relayModels };
|
|
93
|
+
export { hasMembers, listedFieldProblem, relayModels };
|
|
@@ -8,13 +8,22 @@ export type RelayMembers = {
|
|
|
8
8
|
/** Its field holding the person's user id, such as `user_id`. */
|
|
9
9
|
user: string;
|
|
10
10
|
};
|
|
11
|
+
/**
|
|
12
|
+
* Where a channel resource's membership comes from: a JSON field of user ids on the channel record itself, as a
|
|
13
|
+
* conversation page's `members`. Who is in each channel is kept in `realtime.members`, which `protobase migration`
|
|
14
|
+
* writes with the triggers that keep it, so tickets and notices read it by index.
|
|
15
|
+
*/
|
|
16
|
+
export type RelayListedMembers = {
|
|
17
|
+
/** The channel resource's JSON field listing its members' user ids, such as `members`. */
|
|
18
|
+
field: string;
|
|
19
|
+
};
|
|
11
20
|
/** A resource whose records are channels on the relay, `<resource>/<key>`. */
|
|
12
21
|
export type RelayChannelOptions = {
|
|
13
22
|
/**
|
|
14
23
|
* Who is in each channel. Without it the channel is open: whoever may read the record gets it in a ticket when they
|
|
15
24
|
* ask for it, a visitor of the anonymous role too.
|
|
16
25
|
*/
|
|
17
|
-
members?: RelayMembers;
|
|
26
|
+
members?: RelayMembers | RelayListedMembers;
|
|
18
27
|
/** A field of the records noticed on the channel that lists the user ids a record mentions, such as a message's `mentions`. */
|
|
19
28
|
mentions?: string;
|
|
20
29
|
/**
|
|
@@ -63,13 +72,16 @@ export type RealtimeRelayOptions = {
|
|
|
63
72
|
apiKey?: string;
|
|
64
73
|
/** One of the app's ticket keys on the relay, which signs the connect tickets. */
|
|
65
74
|
ticketKey?: string;
|
|
66
|
-
/**
|
|
67
|
-
|
|
75
|
+
/**
|
|
76
|
+
* The channel resources by name. Defaults to one for each resource whose conversation page has `members`, with that
|
|
77
|
+
* field as its members (`defaultRelayChannels`).
|
|
78
|
+
*/
|
|
79
|
+
channels?: Record<string, RelayChannelOptions>;
|
|
68
80
|
/** Turns on presence: the relay reports who is online, away or offline, and the app keeps it in this resource. */
|
|
69
81
|
presence?: RelayPresence;
|
|
70
82
|
};
|
|
71
83
|
/** `realtime.relay` with its address, id and keys, the presence key included, from the config or the environment. */
|
|
72
|
-
export type RealtimeRelaySettings = Omit<RealtimeRelayOptions, 'presence'> & Required<Pick<RealtimeRelayOptions, 'url' | 'app' | 'apiKey' | 'ticketKey'>> & {
|
|
84
|
+
export type RealtimeRelaySettings = Omit<RealtimeRelayOptions, 'presence'> & Required<Pick<RealtimeRelayOptions, 'url' | 'app' | 'apiKey' | 'ticketKey' | 'channels'>> & {
|
|
73
85
|
presence?: RelayPresence & {
|
|
74
86
|
key: string;
|
|
75
87
|
};
|
|
@@ -38,6 +38,12 @@ const checkEvents = (where, events) => {
|
|
|
38
38
|
if (!Number.isInteger(burst) || burst < 1) throw new Error(`${where}.${name}.burst must be a positive whole number`);
|
|
39
39
|
}
|
|
40
40
|
};
|
|
41
|
+
const membersShape = (members) => {
|
|
42
|
+
if (members === void 0) return true;
|
|
43
|
+
if (typeof members !== "object" || members === null) return false;
|
|
44
|
+
if ("field" in members) return nonEmpty(members.field) && Object.keys(members).length === 1;
|
|
45
|
+
return nonEmpty(members.resource) && nonEmpty(members.channel) && nonEmpty(members.user);
|
|
46
|
+
};
|
|
41
47
|
/** The options, or an error naming what is wrong with their shape; `relayModels` checks them against the resources. */
|
|
42
48
|
const checkRelayOptions = (options) => {
|
|
43
49
|
if (!nonEmpty(options?.url) || !/^https?:\/\//.test(options.url)) throw new Error(`realtime.relay.url or ${realtimeVariables.url} must start with https:// or http://, not ${JSON.stringify(options?.url)}`);
|
|
@@ -48,8 +54,7 @@ const checkRelayOptions = (options) => {
|
|
|
48
54
|
}
|
|
49
55
|
if (typeof options.channels !== "object" || options.channels === null || Object.keys(options.channels).length === 0) throw new Error("realtime.relay.channels must name at least one channel resource");
|
|
50
56
|
for (const [name, channel] of Object.entries(options.channels)) {
|
|
51
|
-
|
|
52
|
-
if (members !== void 0 && !(nonEmpty(members.resource) && nonEmpty(members.channel) && nonEmpty(members.user))) throw new Error(`realtime.relay.channels.${name}.members must be { resource, channel, user }`);
|
|
57
|
+
if (!membersShape(channel?.members)) throw new Error(`realtime.relay.channels.${name}.members must be { resource, channel, user } or { field }`);
|
|
53
58
|
if (channel?.mentions !== void 0 && !nonEmpty(channel.mentions)) throw new Error(`realtime.relay.channels.${name}.mentions must name a field`);
|
|
54
59
|
if (channel?.events !== void 0) checkEvents(`realtime.relay.channels.${name}.events`, channel.events);
|
|
55
60
|
}
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import { runningJobs } from "../jobs/current.js";
|
|
2
2
|
import { dispatchJobName } from "../changes/capture-sql.js";
|
|
3
3
|
import { anonymousSession } from "../anonymous.js";
|
|
4
|
+
import { relayModels } from "./relay-models.js";
|
|
5
|
+
import { relayClient } from "./relay-commands.js";
|
|
6
|
+
import { relayJobs } from "./relay-jobs.js";
|
|
4
7
|
import { readableKeys } from "../channels/records-readable.js";
|
|
5
8
|
import { presenceCommands, presencePeople } from "./presence-commands.js";
|
|
6
9
|
import { audienceChannels, changeCommands, openChannels } from "./change-commands.js";
|
|
7
10
|
import { channelMembers, coMembers } from "./members-sql.js";
|
|
8
11
|
import { presenceRoutes } from "./presence-route.js";
|
|
9
12
|
import { presenceWriter } from "./presence-sql.js";
|
|
10
|
-
import { relayClient } from "./relay-commands.js";
|
|
11
|
-
import { relayJobs } from "./relay-jobs.js";
|
|
12
|
-
import { relayModels } from "./relay-models.js";
|
|
13
13
|
import { publicChannels } from "./public-channels.js";
|
|
14
14
|
import { sessionEnd } from "./session-end.js";
|
|
15
15
|
import { ticketRoutes } from "./ticket-route.js";
|
|
@@ -1,11 +1,14 @@
|
|
|
1
|
+
import { RealtimeRelaySettings } from "./relay-options.js";
|
|
1
2
|
import { AdminAuth } from "../better-auth/create-auth.js";
|
|
3
|
+
import { ResourceModel } from "@protobase/schema";
|
|
2
4
|
import { Db } from "@protobase/query";
|
|
3
5
|
//#region src/relay/relay-schema.d.ts
|
|
4
6
|
/**
|
|
5
|
-
* The SQL the relay needs of the app's database: the trigger that closes a
|
|
6
|
-
*
|
|
7
|
+
* The SQL the relay needs of the app's database, for its channels (`appRelayChannels`): the trigger that closes a
|
|
8
|
+
* deleted session's sockets, and `realtime.members` with the triggers that keep it from the channel records that list
|
|
9
|
+
* their members; `undefined` when it is current. `authWritten`: the same migration writes the auth store's steps before it.
|
|
7
10
|
*/
|
|
8
|
-
export declare const relayMigration: (db: Db, auth: AdminAuth | undefined, authWritten: boolean) => Promise<string | undefined>;
|
|
9
|
-
/** Refuses to start while the relay's trigger
|
|
10
|
-
export declare const checkRelaySchema: (db: Db, auth: AdminAuth | undefined) => Promise<void>;
|
|
11
|
+
export declare const relayMigration: (db: Db, auth: AdminAuth | undefined, authWritten: boolean, channels: RealtimeRelaySettings["channels"], models: readonly ResourceModel[]) => Promise<string | undefined>;
|
|
12
|
+
/** Refuses to start while the relay's trigger, or `realtime.members` and its triggers, are missing or out of date. */
|
|
13
|
+
export declare const checkRelaySchema: (db: Db, auth: AdminAuth | undefined, channels: RealtimeRelaySettings["channels"], models: readonly ResourceModel[]) => Promise<void>;
|
|
11
14
|
//#endregion
|
|
@@ -1,16 +1,28 @@
|
|
|
1
|
+
import { migrationCommand } from "../changes/capture-schema.js";
|
|
2
|
+
import { relayModels } from "./relay-models.js";
|
|
1
3
|
import { checkRelaySessions, relaySessionsMigration } from "./sessions-sql.js";
|
|
4
|
+
import { listedTable } from "./realtime-members-sql.js";
|
|
2
5
|
import { sessionsTable } from "./session-end.js";
|
|
6
|
+
import { checkRealtimeMembers, realtimeMembersMigration } from "./realtime-members-schema.js";
|
|
3
7
|
//#region src/relay/relay-schema.ts
|
|
4
8
|
const needsAuth = (auth) => {
|
|
5
9
|
if (!auth) throw new Error("relay needs the app's own sign-in (auth), whose sessions its tickets name and end");
|
|
6
10
|
return auth;
|
|
7
11
|
};
|
|
12
|
+
const listedTables = (channels, models) => [...relayModels({ channels }, models).channels.values()].flatMap((channel) => channel.listed ? [listedTable(channel.listed)] : []);
|
|
8
13
|
/**
|
|
9
|
-
* The SQL the relay needs of the app's database: the trigger that closes a
|
|
10
|
-
*
|
|
14
|
+
* The SQL the relay needs of the app's database, for its channels (`appRelayChannels`): the trigger that closes a
|
|
15
|
+
* deleted session's sockets, and `realtime.members` with the triggers that keep it from the channel records that list
|
|
16
|
+
* their members; `undefined` when it is current. `authWritten`: the same migration writes the auth store's steps before it.
|
|
11
17
|
*/
|
|
12
|
-
const relayMigration = (db, auth, authWritten
|
|
13
|
-
|
|
14
|
-
|
|
18
|
+
const relayMigration = async (db, auth, authWritten, channels, models) => {
|
|
19
|
+
const parts = [await relaySessionsMigration(db, sessionsTable(needsAuth(auth)), authWritten), await realtimeMembersMigration(db, listedTables(channels, models))].filter((part) => part !== void 0);
|
|
20
|
+
return parts.length > 0 ? parts.join("\n\n") : void 0;
|
|
21
|
+
};
|
|
22
|
+
/** Refuses to start while the relay's trigger, or `realtime.members` and its triggers, are missing or out of date. */
|
|
23
|
+
const checkRelaySchema = async (db, auth, channels, models) => {
|
|
24
|
+
await checkRelaySessions(db, sessionsTable(needsAuth(auth)));
|
|
25
|
+
await checkRealtimeMembers(db, listedTables(channels, models), migrationCommand);
|
|
26
|
+
};
|
|
15
27
|
//#endregion
|
|
16
28
|
export { checkRelaySchema, relayMigration };
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { appRelayChannels } from "./realtime-channels.js";
|
|
1
2
|
import { relaySettings } from "./relay-options.js";
|
|
2
3
|
//#region src/relay/relay-switch.ts
|
|
3
4
|
/** The variable with which a platform that runs the relay moves an app to it. */
|
|
@@ -11,14 +12,19 @@ const readRelaySwitch = (env) => {
|
|
|
11
12
|
};
|
|
12
13
|
/**
|
|
13
14
|
* The app's relay settings, or undefined without a relay: a config's `realtime.relay` turns it on whatever the switch
|
|
14
|
-
* says,
|
|
15
|
-
*
|
|
15
|
+
* says, and the switch turns it on without one; either way the channels are `appRelayChannels`', and the address and
|
|
16
|
+
* keys default to the platform's variables (`relaySettings`). The switch on for an app with no channels to derive
|
|
17
|
+
* stops the server.
|
|
16
18
|
*/
|
|
17
|
-
const appRelaySettings = (declared, env) => {
|
|
19
|
+
const appRelaySettings = (declared, env, app) => {
|
|
18
20
|
const on = readRelaySwitch(env);
|
|
19
|
-
if (declared) return
|
|
20
|
-
|
|
21
|
-
throw new Error(`${realtimeSwitchVariable} is true, but the
|
|
21
|
+
if (!declared && !on) return;
|
|
22
|
+
const channels = appRelayChannels(declared, app);
|
|
23
|
+
if (!channels) throw new Error(`${realtimeSwitchVariable} is true, but the app has no realtime.relay, and no live conversation resource whose page has members, with sign-in, to derive the relay's channels from`);
|
|
24
|
+
return relaySettings({
|
|
25
|
+
...declared,
|
|
26
|
+
channels
|
|
27
|
+
}, env);
|
|
22
28
|
};
|
|
23
29
|
//#endregion
|
|
24
30
|
export { appRelaySettings, readRelaySwitch, realtimeSwitchVariable };
|
|
@@ -3,6 +3,7 @@ import { channelRecord } from "../channels/channel-name.js";
|
|
|
3
3
|
import { recordReadable } from "../channels/record-readable.js";
|
|
4
4
|
import { anonymousSession } from "../anonymous.js";
|
|
5
5
|
import { jsonBody, jsonOnly } from "../notifications/history-request.js";
|
|
6
|
+
import { hasMembers } from "./relay-models.js";
|
|
6
7
|
import { peopleChannel } from "./presence-commands.js";
|
|
7
8
|
import { memberships } from "./members-sql.js";
|
|
8
9
|
import { signTicket } from "./ticket.js";
|
|
@@ -41,7 +42,7 @@ const ticketRoutes = ({ deps, options, models, jobs, sessionEnd }) => {
|
|
|
41
42
|
const resource = slash < 0 ? "" : name.slice(0, slash);
|
|
42
43
|
const refuse = () => notFound(`There is no channel ${name}`);
|
|
43
44
|
const channel = models.channels.get(resource);
|
|
44
|
-
if (!channel || channel
|
|
45
|
+
if (!channel || hasMembers(channel)) throw refuse();
|
|
45
46
|
const record = channelRecord(deps.registry, resource, name.slice(slash + 1));
|
|
46
47
|
if (record === void 0 || record === "too-long" || record.name !== name) throw refuse();
|
|
47
48
|
if (!await recordReadable(deps, anonymousSession(), record)) throw refuse();
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
const typingViewErrors = (views, channels) => views.flatMap((view) => {
|
|
7
7
|
const page = view.record;
|
|
8
8
|
if (!channels || !page || !("conversation" in page) || !page.conversation.typing) return [];
|
|
9
|
-
return channels.has(view.resource) ? [] : [`View "${view.resource}": record.conversation.typing goes through the record's relay channel, so "${view.resource}" needs to be in realtime.relay.channels`];
|
|
9
|
+
return channels.has(view.resource) ? [] : [`View "${view.resource}": record.conversation.typing goes through the record's relay channel, so "${view.resource}" needs to be in realtime.relay.channels, or its conversation page needs members`];
|
|
10
10
|
});
|
|
11
11
|
//#endregion
|
|
12
12
|
export { typingViewErrors };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@protobase/server",
|
|
3
|
-
"version": "0.126.
|
|
3
|
+
"version": "0.126.2",
|
|
4
4
|
"description": "The Protobase REST API as a Hono app, with Better Auth sign-in.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -44,11 +44,11 @@
|
|
|
44
44
|
"@better-auth/sso": "^1.7.12",
|
|
45
45
|
"@livekit/protocol": "1.53.1",
|
|
46
46
|
"@modelcontextprotocol/server": "^2.3.1",
|
|
47
|
-
"@protobase/layout": "0.126.
|
|
48
|
-
"@protobase/query": "0.126.
|
|
49
|
-
"@protobase/schema": "0.126.
|
|
50
|
-
"@protobase/workflow-plugins": "0.126.
|
|
51
|
-
"@protobase/workflows": "0.126.
|
|
47
|
+
"@protobase/layout": "0.126.2",
|
|
48
|
+
"@protobase/query": "0.126.2",
|
|
49
|
+
"@protobase/schema": "0.126.2",
|
|
50
|
+
"@protobase/workflow-plugins": "0.126.2",
|
|
51
|
+
"@protobase/workflows": "0.126.2",
|
|
52
52
|
"@react-email/render": "^2.1.0",
|
|
53
53
|
"@react-pdf/primitives": "^4.4.0",
|
|
54
54
|
"@react-pdf/renderer": "^4.9.0",
|