@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.
Files changed (47) hide show
  1. package/dist/better-auth/auth-settings.d.ts +64 -0
  2. package/dist/better-auth/create-auth.d.ts +67 -2
  3. package/dist/better-auth/create-auth.js +10 -3
  4. package/dist/better-auth/names/modules/index.d.ts +9 -2
  5. package/dist/better-auth/names/modules/mail-senders.js +7 -2
  6. package/dist/better-auth/staff-checks.js +2 -0
  7. package/dist/better-auth/store/steps/index.js +3 -1
  8. package/dist/better-auth/store/steps/legacy-versions.js +4 -0
  9. package/dist/better-auth/store/steps/mail-senders/005-sender-sharing.js +24 -0
  10. package/dist/create-admin.js +10 -2
  11. package/dist/index.d.ts +3 -2
  12. package/dist/index.js +2 -1
  13. package/dist/package.js +1 -1
  14. package/dist/personal-mail/listed-mail-senders.d.ts +3 -1
  15. package/dist/personal-mail/listed-mail-senders.js +1 -0
  16. package/dist/personal-mail/mail-sender.d.ts +5 -3
  17. package/dist/personal-mail/mail-sender.js +22 -5
  18. package/dist/personal-mail/mail-senders-plugin.js +39 -3
  19. package/dist/personal-mail/personal-mailer.d.ts +8 -6
  20. package/dist/personal-mail/personal-mailer.js +25 -4
  21. package/dist/personal-mail/sender-address-error.d.ts +5 -4
  22. package/dist/personal-mail/sender-address-error.js +4 -3
  23. package/dist/personal-mail/sender-store.js +13 -6
  24. package/dist/personal-mail/shared-sender-store.d.ts +2 -0
  25. package/dist/personal-mail/shared-sender-store.js +39 -0
  26. package/dist/personal-mail/shared-senders.d.ts +11 -0
  27. package/dist/personal-mail/shared-senders.js +22 -0
  28. package/dist/relay/change-commands.js +34 -4
  29. package/dist/relay/client-events.d.ts +2 -2
  30. package/dist/relay/members-sql.js +30 -7
  31. package/dist/relay/realtime-channels.d.ts +25 -0
  32. package/dist/relay/realtime-channels.js +39 -0
  33. package/dist/relay/realtime-members-reads.js +16 -0
  34. package/dist/relay/realtime-members-schema.js +67 -0
  35. package/dist/relay/realtime-members-sql.js +120 -0
  36. package/dist/relay/relay-jobs.js +9 -1
  37. package/dist/relay/relay-models.js +27 -3
  38. package/dist/relay/relay-options.d.ts +16 -4
  39. package/dist/relay/relay-options.js +7 -2
  40. package/dist/relay/relay-runtime.js +3 -3
  41. package/dist/relay/relay-schema.d.ts +8 -5
  42. package/dist/relay/relay-schema.js +17 -5
  43. package/dist/relay/relay-switch.d.ts +1 -0
  44. package/dist/relay/relay-switch.js +12 -6
  45. package/dist/relay/ticket-route.js +2 -1
  46. package/dist/relay/typing-views.js +1 -1
  47. package/package.json +6 -6
@@ -1,6 +1,7 @@
1
1
  import { senderAddressInput } from "./sender-address-input.js";
2
2
  import { isRemoved } from "./sender-address-state.js";
3
3
  import { stateIn } from "./mail-sender.js";
4
+ import { listedShared, usableShared } from "./shared-senders.js";
4
5
  import { linkedMailbox } from "./personal-mailer.js";
5
6
  import { headersLocale } from "../locale/request-locale.js";
6
7
  import { storeSqlOf } from "../better-auth/store/store-sql.js";
@@ -18,7 +19,9 @@ const mailSenderPaths = {
18
19
  update: "/account/mail-senders/update",
19
20
  remove: "/account/mail-senders/remove",
20
21
  refresh: "/account/mail-senders/refresh",
21
- verify: "/account/mail-senders/verify"
22
+ verify: "/account/mail-senders/verify",
23
+ share: "/account/mail-senders/share",
24
+ unshare: "/account/mail-senders/unshare"
22
25
  };
23
26
  /** The longest signature, in characters: a closing and a few lines of contact details. */
24
27
  const maxSignatureLength = 2e3;
@@ -38,6 +41,10 @@ const noMailbox = {
38
41
  code: "MAILBOX_NOT_FOUND",
39
42
  message: "Connect a mailbox first."
40
43
  };
44
+ const notVerified = {
45
+ code: "MAIL_SENDER_NOT_VERIFIED",
46
+ message: "Only a verified address can be shared: prove it is yours first."
47
+ };
41
48
  const unlinkPath = "/unlink-account";
42
49
  const signatureField = z$1.string().max(maxSignatureLength).transform((value) => value.trim() ? value : null);
43
50
  const nameField = z$1.string().max(100).regex(/^[^\r\n]*$/).transform((value) => value.trim() || null);
@@ -82,8 +89,13 @@ const ownRow = (rows, id) => {
82
89
  * verification by each verifier; `POST /account/mail-senders/verify { id }` starts every verifier on one of the
83
90
  * person's addresses on a connection they can send through, and answers that address's `verifications`; and
84
91
  * `POST /mail-sender-verifications/report` settles one from outside (`reportEndpoint`). Without, neither path exists.
92
+ *
93
+ * `POST /account/mail-senders/share { id }` shares one of the person's addresses with the app's other senders, refused
94
+ * with a 409 `MAIL_SENDER_NOT_VERIFIED` unless it is `verified`; `POST /account/mail-senders/unshare { id }` makes it
95
+ * theirs alone again. The list answers, as `shared`, the verified addresses others shared with the person that are in
96
+ * reach (`sharedWith`), each by id, address and display name alone.
85
97
  */
86
- const mailSendersPlugin = (providers, names, mailOf, inUse, verifications) => ({
98
+ const mailSendersPlugin = (providers, names, mailOf, inUse, verifications, sharedWith) => ({
87
99
  id: "protobase-mail-senders",
88
100
  schema: names.tables(mailSenderModel),
89
101
  hooks: { before: [{
@@ -102,9 +114,10 @@ const mailSendersPlugin = (providers, names, mailOf, inUse, verifications) => ({
102
114
  use: [sessionMiddleware]
103
115
  }, async (ctx) => {
104
116
  const { userId, book } = await bookOf(ctx, providers, verifications);
105
- const latest = verifications ? await verifications.latestOf(userId) : void 0;
117
+ const [latest, shared] = await Promise.all([verifications ? verifications.latestOf(userId) : void 0, sharedWith ? sharedWith(userId) : []]);
106
118
  return ctx.json({
107
119
  ...listedMailSenders(book, latest),
120
+ shared: usableShared(shared, providers).map(listedShared),
108
121
  verifiers: Boolean(verifications)
109
122
  });
110
123
  }),
@@ -176,6 +189,29 @@ const mailSendersPlugin = (providers, names, mailOf, inUse, verifications) => ({
176
189
  const connections = await mailOf(ctx.context.session.user.id).refresh();
177
190
  return ctx.json({ connections });
178
191
  }),
192
+ shareMailSender: createAuthEndpoint(mailSenderPaths.share, {
193
+ method: "POST",
194
+ use: [sessionMiddleware],
195
+ body: z$1.object({ id: idField })
196
+ }, async (ctx) => {
197
+ const { userId, store, book } = await bookOf(ctx, providers, verifications);
198
+ const row = ownRow(book.rows, ctx.body.id);
199
+ if (stateIn(book, row) !== "verified") throw new APIError("CONFLICT", notVerified);
200
+ const shared = await store.share(userId, row.id, /* @__PURE__ */ new Date());
201
+ if (!shared) throw new APIError("NOT_FOUND", notFound);
202
+ return ctx.json({ sender: listedSender(book, shared) });
203
+ }),
204
+ unshareMailSender: createAuthEndpoint(mailSenderPaths.unshare, {
205
+ method: "POST",
206
+ use: [sessionMiddleware],
207
+ body: z$1.object({ id: idField })
208
+ }, async (ctx) => {
209
+ const { userId, store, book } = await bookOf(ctx, providers, verifications);
210
+ ownRow(book.rows, ctx.body.id);
211
+ const row = await store.share(userId, ctx.body.id, null);
212
+ if (!row) throw new APIError("NOT_FOUND", notFound);
213
+ return ctx.json({ sender: listedSender(book, row) });
214
+ }),
179
215
  ...verifications && {
180
216
  verifyMailSender: createAuthEndpoint(mailSenderPaths.verify, {
181
217
  method: "POST",
@@ -15,16 +15,18 @@ export type PersonalMailMessage = MailMessage & {
15
15
  export type PersonalMail = {
16
16
  /**
17
17
  * Sends `message` through the mailbox connection of the From address it names, from that address, with its display
18
- * name: the record decides both, so they cannot disagree. Rejects, sending nothing, with a 404 problem for an id
19
- * that is not one of the person's, and with a `SenderAddressError` for an address the provider says the mailbox
20
- * cannot send as (`failed`), one still `pending`, or one on no connection they can send through (`detached`). An
21
- * address no listing read yet is listed first, when its provider can. Resolves to the `Message-ID` the recipient
18
+ * name: the record decides both, so they cannot disagree. An address someone else shared with the person goes out
19
+ * through its owner's connection, only while it is shared, verified and its owner in reach. Rejects, sending nothing,
20
+ * with a 404 problem for an id that is neither one of the person's nor shared with them, and with a
21
+ * `SenderAddressError` for an address the provider says the mailbox cannot send as (`failed`), one still `pending`,
22
+ * one on no connection they can send through (`detached`), or a shared one whose owner must connect their mailbox
23
+ * again (`owner_unlinked`). An address no listing read yet is listed first, when its provider can. Resolves to the `Message-ID` the recipient
22
24
  * sees when the mail provider can tell it (see `SentMail`).
23
25
  */
24
26
  send: (message: PersonalMailMessage) => Promise<SentMail>;
25
- /** The sender a From address stands for, with its record's id and own signature, or refuses as `chooseSender` does. */
27
+ /** The sender a From address stands for, the person's own or one shared with them, with its record's id and own signature, or refuses as `chooseSender` does. */
26
28
  sender: (address?: string) => Promise<MailSender>;
27
- /** Every sender the person may choose, as a send dialog lists them, each with its state. */
29
+ /** Every sender the person may choose, as a send dialog lists them, each with its state, those shared with them last. */
28
30
  senders: () => Promise<MailSender[]>;
29
31
  /** Lists the send-as addresses of each of the person's connections whose provider can, each on its own (`listConnections`). */
30
32
  refresh: () => Promise<ConnectionListing[]>;
@@ -4,6 +4,7 @@ import { hasListing, isRemoved, senderRowState } from "./sender-address-state.js
4
4
  import { chooseSender, usableSenders } from "./mail-sender.js";
5
5
  import { mailboxConnections } from "./mailbox-connections.js";
6
6
  import { listConnection, listConnections } from "./sender-listing.js";
7
+ import { sharedConnection, sharedState, usableShared } from "./shared-senders.js";
7
8
  //#region src/personal-mail/personal-mailer.ts
8
9
  /**
9
10
  * The mail provider of `linked`, the accounts linked to a person, of the app's `providers` in their order, with the
@@ -26,7 +27,8 @@ const refuseOwnFrom = (message) => {
26
27
  };
27
28
  /**
28
29
  * Mail from `userId`'s own mailbox: each message goes out through one of the connections they linked, with an access
29
- * token refreshed when it expired, from a From address record of theirs. Rejects with a `PersonalMailError` and sends
30
+ * token refreshed when it expired, from a From address record of theirs, or through its owner's connection from one
31
+ * shared with them. Rejects with a `PersonalMailError` and sends
30
32
  * nothing when the mailbox it goes through is not linked (`not_linked`) or the provider no longer honours the link (`link_expired`).
31
33
  */
32
34
  const personalMailer = (accounts, providers, senders, userId, now = () => /* @__PURE__ */ new Date()) => {
@@ -52,7 +54,7 @@ const personalMailer = (accounts, providers, senders, userId, now = () => /* @__
52
54
  };
53
55
  };
54
56
  const sendThrough = async ({ account, provider }, message, row) => {
55
- const accessToken = await accounts.accessToken(userId, account, provider.id);
57
+ const accessToken = await accounts.accessToken(row?.userId ?? userId, account, provider.id);
56
58
  return provider.send(message, accessToken, row && {
57
59
  address: row.address,
58
60
  ...row.name && { name: row.name }
@@ -68,6 +70,24 @@ const personalMailer = (accounts, providers, senders, userId, now = () => /* @__
68
70
  if ((await listConnection(lister, connection)).status !== "listed") return row;
69
71
  return (await senders.ofUser(userId)).find((candidate) => candidate.id === row.id) ?? row;
70
72
  };
73
+ const sendShared = async (id, message) => {
74
+ const [row] = senders.sharedWith ? await senders.sharedWith(userId, id) : [];
75
+ if (!row) throw new SenderAddressNotFoundError();
76
+ const state = sharedState(row, providers);
77
+ const connection = sharedConnection(row, providers);
78
+ if (state === "detached") throw new SenderAddressError("sender_address_owner_unlinked");
79
+ if (state !== "verified" || !connection) throw new SenderAddressNotFoundError();
80
+ try {
81
+ return await sendThrough(connection, message, row);
82
+ } catch (error) {
83
+ if (error instanceof PersonalMailError && error.code === "link_expired") throw new SenderAddressError("sender_address_owner_unlinked");
84
+ throw error;
85
+ }
86
+ };
87
+ const withShared = async (book) => senders.sharedWith ? {
88
+ ...book,
89
+ shared: usableShared(await senders.sharedWith(userId), providers)
90
+ } : book;
71
91
  return {
72
92
  send: async ({ sender_address_id, ...message }) => {
73
93
  refuseOwnFrom(message);
@@ -75,6 +95,7 @@ const personalMailer = (accounts, providers, senders, userId, now = () => /* @__
75
95
  if (sender_address_id === null) return sendAsMailbox(book, message);
76
96
  const row = sender_address_id === void 0 ? book.rows.find((candidate) => candidate.isDefault && !isRemoved(candidate)) : book.rows.find((candidate) => candidate.id === sender_address_id);
77
97
  if (!row && sender_address_id === void 0) return sendAsMailbox(book, message);
98
+ if (!row && sender_address_id !== void 0) return sendShared(sender_address_id, message);
78
99
  if (!row || isRemoved(row)) throw new SenderAddressNotFoundError();
79
100
  const connection = book.connections.find(({ account }) => account.id === row.connectionId);
80
101
  if (!connection) throw new SenderAddressError("sender_address_detached");
@@ -83,8 +104,8 @@ const personalMailer = (accounts, providers, senders, userId, now = () => /* @__
83
104
  if (state === "pending") throw new SenderAddressError("sender_address_pending");
84
105
  return sendThrough(connection, message, row);
85
106
  },
86
- sender: async (address) => chooseSender(await bookOf(), address),
87
- senders: async () => usableSenders(await bookOf()),
107
+ sender: async (address) => chooseSender(await withShared(await bookOf()), address),
108
+ senders: async () => usableSenders(await withShared(await bookOf())),
88
109
  refresh: async () => listConnections(lister, (await bookOf()).connections)
89
110
  };
90
111
  };
@@ -3,17 +3,18 @@ import { HttpProblem } from "../problem.js";
3
3
  /**
4
4
  * Why a message names a From address it cannot go out from, sending nothing: `failed`, the mailbox's provider says it
5
5
  * cannot send as it; `pending`, its owner has not confirmed it with the provider yet; `detached`, it is on no mailbox
6
- * connection its owner can send through; `ambiguous`, an address or the mailbox's own stands for more than one of them.
6
+ * connection its owner can send through; `ambiguous`, an address or the mailbox's own stands for more than one of them;
7
+ * `owner_unlinked`, an address someone else shared goes out through a mailbox of theirs that they must connect again.
7
8
  */
8
- export type SenderAddressErrorCode = 'sender_address_failed' | 'sender_address_pending' | 'sender_address_detached' | 'sender_address_ambiguous';
9
+ export type SenderAddressErrorCode = 'sender_address_failed' | 'sender_address_pending' | 'sender_address_detached' | 'sender_address_ambiguous' | 'sender_address_owner_unlinked';
9
10
  /** Thrown when a send names a From address it cannot go out from; it answers as a 409 problem whose `code` says why. */
10
11
  export declare class SenderAddressError extends HttpProblem {
11
12
  readonly code: SenderAddressErrorCode;
12
13
  constructor(code: SenderAddressErrorCode);
13
14
  }
14
15
  /**
15
- * Thrown when a send names a From address id that is not one of the sender's: unknown, removed or someone else's, in
16
- * the same words, so the answer does not tell which. It answers as a 404 problem.
16
+ * Thrown when a send names a From address id that is not one of the sender's: unknown, removed, or someone else's and
17
+ * not shared with them, or no longer verified, in the same words, so the answer does not tell which. It answers as a 404 problem.
17
18
  */
18
19
  export declare class SenderAddressNotFoundError extends HttpProblem {
19
20
  constructor();
@@ -4,7 +4,8 @@ const details = {
4
4
  sender_address_failed: "Your mailbox cannot send as this address: set it up with your mail provider, or choose another",
5
5
  sender_address_pending: "This address still waits for you to confirm it with your mail provider",
6
6
  sender_address_detached: "This address is on no mailbox you have connected: add it again under Account → Mailbox",
7
- sender_address_ambiguous: "This address is on more than one of your mailboxes: choose the From address by its id"
7
+ sender_address_ambiguous: "This address is on more than one of your mailboxes: choose the From address by its id",
8
+ sender_address_owner_unlinked: "This address belongs to someone else, who must connect their mailbox again before mail goes out from it"
8
9
  };
9
10
  /** Thrown when a send names a From address it cannot go out from; it answers as a 409 problem whose `code` says why. */
10
11
  var SenderAddressError = class extends HttpProblem {
@@ -15,8 +16,8 @@ var SenderAddressError = class extends HttpProblem {
15
16
  }
16
17
  };
17
18
  /**
18
- * Thrown when a send names a From address id that is not one of the sender's: unknown, removed or someone else's, in
19
- * the same words, so the answer does not tell which. It answers as a 404 problem.
19
+ * Thrown when a send names a From address id that is not one of the sender's: unknown, removed, or someone else's and
20
+ * not shared with them, or no longer verified, in the same words, so the answer does not tell which. It answers as a 404 problem.
20
21
  */
21
22
  var SenderAddressNotFoundError = class extends HttpProblem {
22
23
  constructor() {
@@ -14,7 +14,7 @@ const columns = (store) => {
14
14
  sql`${c.connection_id} as "connectionId"`,
15
15
  sql`${c.address} as address`,
16
16
  sql`${c.name} as name`,
17
- sql`${c.shared} as shared`,
17
+ sql`${c.shared_at} as "sharedAt"`,
18
18
  sql`${c.signature} as signature`,
19
19
  sql`${c.is_default} as "isDefault"`,
20
20
  sql`${c.created_at} as "createdAt"`,
@@ -41,8 +41,8 @@ const sqlSenderStore = (store) => ({
41
41
  type: async (sender, at) => {
42
42
  const s = await store();
43
43
  const { table, c, selected } = columns(s);
44
- const { rows } = await sql`insert into ${table} (id, ${c.user_id}, ${c.connection_id}, ${c.address}, ${c.name}, ${c.shared}, ${c.signature}, ${c.is_default}, ${c.created_at}, ${c.typed_at})
45
- values (${s.newId}, ${sender.userId}, ${sender.connectionId}, ${sender.address}, ${sender.name}, false, ${sender.signature}, false, ${at}, ${at})
44
+ const { rows } = await sql`insert into ${table} (id, ${c.user_id}, ${c.connection_id}, ${c.address}, ${c.name}, ${c.signature}, ${c.is_default}, ${c.created_at}, ${c.typed_at})
45
+ values (${s.newId}, ${sender.userId}, ${sender.connectionId}, ${sender.address}, ${sender.name}, ${sender.signature}, false, ${at}, ${at})
46
46
  on conflict (${c.connection_id}, ${c.address_key}) do update set ${c.typed_at} = greatest(excluded.${c.typed_at}, ${table}.${c.removed_at} + interval '1 millisecond'), ${c.name} = excluded.${c.name}, ${c.signature} = excluded.${c.signature}
47
47
  returning ${selected}`.execute(s.db);
48
48
  return rows[0];
@@ -54,8 +54,8 @@ returning ${selected}`.execute(s.db);
54
54
  const states = listed.map(({ provider_state }) => provider_state ?? null);
55
55
  await sql`with listed (address, state) as (select * from unnest(${addresses}::text[], ${states}::text[])),
56
56
  upserted as (
57
- insert into ${table} (id, ${c.user_id}, ${c.connection_id}, ${c.address}, ${c.shared}, ${c.is_default}, ${c.created_at}, ${c.listed_at}, ${c.provider_state}, ${c.provider_state_read_at})
58
- select ${s.newId}, ${userId}, ${connectionId}, listed.address, false, false, ${readAt}, ${readAt}, listed.state, ${readAt} from listed
57
+ insert into ${table} (id, ${c.user_id}, ${c.connection_id}, ${c.address}, ${c.is_default}, ${c.created_at}, ${c.listed_at}, ${c.provider_state}, ${c.provider_state_read_at})
58
+ select ${s.newId}, ${userId}, ${connectionId}, listed.address, false, ${readAt}, ${readAt}, listed.state, ${readAt} from listed
59
59
  on conflict (${c.connection_id}, ${c.address_key}) do update set ${c.listed_at} = excluded.${c.listed_at}, ${c.provider_state} = excluded.${c.provider_state}, ${c.provider_state_read_at} = excluded.${c.provider_state_read_at}
60
60
  where ${table}.${c.provider_state_read_at} is null or ${table}.${c.provider_state_read_at} <= excluded.${c.provider_state_read_at}
61
61
  returning id
@@ -84,7 +84,14 @@ where ${c.connection_id} = ${connectionId} and ${c.user_id} = ${userId} and ${c.
84
84
  remove: async (userId, id, at) => {
85
85
  const s = await store();
86
86
  const { table, c } = columns(s);
87
- await sql`update ${table} set ${c.removed_at} = ${at}, ${c.is_default} = false where id = ${id} and ${c.user_id} = ${userId}`.execute(s.db);
87
+ await sql`update ${table} set ${c.removed_at} = ${at}, ${c.is_default} = false, ${c.shared_at} = null where id = ${id} and ${c.user_id} = ${userId}`.execute(s.db);
88
+ },
89
+ share: async (userId, id, at) => {
90
+ const s = await store();
91
+ const { table, c, selected } = columns(s);
92
+ const sharedAt = at === null ? sql`null` : sql`coalesce(${c.shared_at}, ${at})`;
93
+ const { rows } = await sql`update ${table} set ${c.shared_at} = ${sharedAt} where id = ${id} and ${c.user_id} = ${userId} returning ${selected}`.execute(s.db);
94
+ return rows[0];
88
95
  }
89
96
  });
90
97
  //#endregion
@@ -0,0 +1,2 @@
1
+ import "../better-auth/store/store-sql.js";
2
+ import "./sender-store.js";
@@ -0,0 +1,39 @@
1
+ import { sql } from "kysely";
2
+ //#region src/personal-mail/shared-sender-store.ts
3
+ /**
4
+ * The shared addresses in SQL, on the auth store: one query, which the shared addresses' partial index on their owner
5
+ * serves, joined with the owner's account and, with `organizations`, filtered to owners in an organization of the
6
+ * person's. Its rows carry no state: `sharedState` derives it, as for the owner's own addresses.
7
+ */
8
+ const sharedSenderReader = (store, { organizations, verifiers }) => async (userId, id) => {
9
+ const s = await store();
10
+ const sender = s.table("mail_sender");
11
+ const c = sender.columns;
12
+ const account = s.table("account");
13
+ const a = account.columns;
14
+ const verification = s.table("mail_sender_verification");
15
+ const v = verification.columns;
16
+ const member = organizations ? s.table("member") : void 0;
17
+ const proved = verifiers.length === 0 ? sql`null::timestamptz` : sql`(select max(${v.settled_at}) from ${verification} where ${v.sender_id} = ${sender}.id and ${v.verifier} = any(${[...verifiers]}::text[]) and ${v.state} = 'verified' and ${v.valid_until} > now())`;
18
+ const inReach = member ? sql`and ${sender}.${c.user_id} in (select theirs.${member.columns.user_id} from ${member} as mine join ${member} as theirs on theirs.${member.columns.organization_id} = mine.${member.columns.organization_id} where mine.${member.columns.user_id} = ${userId})` : sql``;
19
+ const named = id === void 0 ? sql`` : sql`and ${sender}.id = ${id}`;
20
+ const { rows } = await sql`select ${sender}.id, ${sender}.${c.user_id} as "userId", ${sender}.${c.connection_id} as "connectionId", ${sender}.${c.address} as address,
21
+ ${sender}.${c.name} as name, ${sender}.${c.shared_at} as "sharedAt", ${sender}.${c.signature} as signature, false as "isDefault", ${sender}.${c.created_at} as "createdAt",
22
+ ${sender}.${c.typed_at} as "typedAt", ${sender}.${c.listed_at} as "listedAt", ${sender}.${c.provider_state} as "providerState",
23
+ ${sender}.${c.provider_state_read_at} as "providerStateReadAt", ${sender}.${c.removed_at} as "removedAt",
24
+ case when ${account}.id is null then null else json_build_object('id', ${account}.id, 'providerId', ${account}.${a.provider_id}, 'scope', ${account}.${a.scope}, 'createdAt', ${account}.${a.created_at}) end as account,
25
+ ${proved} as "provedAt"
26
+ from ${sender}
27
+ left join ${account} on ${account}.id = ${sender}.${c.connection_id} and ${account}.${a.user_id} = ${sender}.${c.user_id}
28
+ where ${sender}.${c.shared_at} is not null and ${sender}.${c.user_id} <> ${userId} ${named} ${inReach}
29
+ order by ${sender}.${c.created_at}, ${sender}.${c.address_key}, ${sender}.id`.execute(s.db);
30
+ return rows.map((row) => ({
31
+ ...row,
32
+ account: row.account && {
33
+ ...row.account,
34
+ createdAt: new Date(row.account.createdAt)
35
+ }
36
+ }));
37
+ };
38
+ //#endregion
39
+ export { sharedSenderReader };
@@ -0,0 +1,11 @@
1
+ import "./sender-address-state.js";
2
+ import "./mailbox-connections.js";
3
+ import "./shared-sender-store.js";
4
+ //#region src/personal-mail/shared-senders.d.ts
5
+ /** An address someone else shared, as the person sees it: never its owner, nor the mailbox it goes out through. */
6
+ export type SharedSender = {
7
+ id: string;
8
+ address: string;
9
+ name?: string;
10
+ };
11
+ //#endregion
@@ -0,0 +1,22 @@
1
+ import { storedScopes } from "./linked-accounts.js";
2
+ import { senderRowState } from "./sender-address-state.js";
3
+ import { mailboxConnections } from "./mailbox-connections.js";
4
+ //#region src/personal-mail/shared-senders.ts
5
+ /** The connection a shared address goes out through: its owner's account, while that still holds a provider's send scopes. */
6
+ const sharedConnection = ({ account }, providers) => account ? mailboxConnections([{
7
+ id: account.id,
8
+ providerId: account.providerId,
9
+ scopes: storedScopes(account.scope),
10
+ createdAt: account.createdAt
11
+ }], providers)[0] : void 0;
12
+ /** The state of a shared address, derived as for its owner (`senderRowState`): only a `verified` one goes out. */
13
+ const sharedState = (row, providers) => senderRowState(row, sharedConnection(row, providers) !== void 0, row.provedAt ?? void 0);
14
+ /** The shared addresses the person may send from: those still verified. */
15
+ const usableShared = (rows, providers) => rows.filter((row) => sharedState(row, providers) === "verified");
16
+ const listedShared = ({ id, address, name }) => ({
17
+ id,
18
+ address,
19
+ ...name && { name }
20
+ });
21
+ //#endregion
22
+ export { listedShared, sharedConnection, sharedState, usableShared };
@@ -1,3 +1,4 @@
1
+ import { hasMembers } from "./relay-models.js";
1
2
  import { peopleChannel } from "./presence-commands.js";
2
3
  //#region src/relay/change-commands.ts
3
4
  /** The event every notice of a change is published as. */
@@ -11,9 +12,9 @@ const channelsOf = (models, resource, record) => (models.placements.get(resource
11
12
  /** The channels a change is noticed on: where the record was and where it is, each once. */
12
13
  const noticedChannels = (models, change) => [.../* @__PURE__ */ new Set([...channelsOf(models, change.resource, change.before), ...channelsOf(models, change.resource, change.after)])];
13
14
  /** The channels with members whose people a batch's notices go to, which `channelMembers` reads. */
14
- const audienceChannels = (models, changes) => [...new Set(changes.flatMap((change) => noticedChannels(models, change)))].filter((channel) => models.channels.get(channel.slice(0, channel.indexOf("/")))?.members);
15
+ const audienceChannels = (models, changes) => [...new Set(changes.flatMap((change) => noticedChannels(models, change)))].filter((channel) => hasMembers(models.channels.get(channel.slice(0, channel.indexOf("/")))));
15
16
  /** The open channels, without members, that a batch's notices go to everyone joined to, whose records `publicChannels` reads. */
16
- const openChannels = (models, changes) => [...new Set(changes.flatMap((change) => noticedChannels(models, change)))].filter((channel) => !models.channels.get(channel.slice(0, channel.indexOf("/")))?.members);
17
+ const openChannels = (models, changes) => [...new Set(changes.flatMap((change) => noticedChannels(models, change)))].filter((channel) => !hasMembers(models.channels.get(channel.slice(0, channel.indexOf("/")))));
17
18
  const membership = (members, record) => {
18
19
  if (!record || !present(record[members.field]) || !present(record[members.user])) return;
19
20
  if (members.model.softDelete !== void 0 && present(record[members.model.softDelete])) return;
@@ -37,6 +38,35 @@ const membersCommands = (models, change) => (models.members.get(change.resource)
37
38
  users: [before.user]
38
39
  }] : []];
39
40
  });
41
+ const listedIn = (listed, record) => {
42
+ if (!record) return;
43
+ const value = record[listed.field];
44
+ const deleted = listed.model.softDelete !== void 0 && present(record[listed.model.softDelete]);
45
+ const users = Array.isArray(value) && !deleted ? value.filter(present).map(String) : [];
46
+ return {
47
+ channel: channelName(listed.model.name, record[listed.model.primaryKey[0]]),
48
+ users: new Set(users)
49
+ };
50
+ };
51
+ const missing = (from, other) => [...from ?? []].filter((user) => !other?.has(user));
52
+ const listedCommands = (models, change) => {
53
+ const listed = models.channels.get(change.resource)?.listed;
54
+ if (!listed) return [];
55
+ const before = change.operation === "create" || change.operation === "undelete" ? void 0 : listedIn(listed, change.before);
56
+ const after = change.operation === "delete" ? void 0 : listedIn(listed, change.after);
57
+ const moved = before && after && before.channel !== after.channel;
58
+ const added = after ? missing(after.users, moved ? void 0 : before?.users) : [];
59
+ const removed = before ? missing(before.users, moved ? void 0 : after?.users) : [];
60
+ return [...added.length > 0 ? [{
61
+ kind: "add",
62
+ channel: after.channel,
63
+ users: added
64
+ }] : [], ...removed.length > 0 ? [{
65
+ kind: "remove",
66
+ channel: before.channel,
67
+ users: removed
68
+ }] : []];
69
+ };
40
70
  const mentionsOf = (record, field) => {
41
71
  if (field === void 0 || !record) return;
42
72
  const value = record[field];
@@ -47,7 +77,7 @@ const notice = (models, change, channel, members, moved) => {
47
77
  const options = models.channels.get(channel.slice(0, channel.indexOf("/")));
48
78
  const mentions = mentionsOf(change.after ?? change.before, options.mentions);
49
79
  const extra = moved.filter((command) => command.channel === channel).flatMap((command) => command.users);
50
- const users = options.members ? [.../* @__PURE__ */ new Set([...members.get(channel) ?? [], ...extra])] : void 0;
80
+ const users = hasMembers(options) ? [.../* @__PURE__ */ new Set([...members.get(channel) ?? [], ...extra])] : void 0;
51
81
  return {
52
82
  kind: "publish",
53
83
  id: `${change.sequence}:${channel}`,
@@ -80,7 +110,7 @@ const reaches = (command, open) => command.users === void 0 ? open.has(command.c
80
110
  * it before hear nothing once it is not. A notice of a channel with no one to reach is left out.
81
111
  */
82
112
  const changeCommands = (models, changes, members, open) => changes.flatMap((change) => {
83
- const moved = membersCommands(models, change);
113
+ const moved = [...membersCommands(models, change), ...listedCommands(models, change)];
84
114
  const notices = noticedChannels(models, change).map((channel) => notice(models, change, channel, members, moved)).filter((command) => reaches(command, open));
85
115
  return [
86
116
  ...moved.filter((command) => command.kind === "add").flatMap((add) => [add, joinedCommand(change.sequence, add)]),
@@ -1,4 +1,4 @@
1
- import { RealtimeRelayOptions } from "./relay-options.js";
1
+ import { RelayChannelOptions } from "./relay-options.js";
2
2
  import { ViewModel } from "@protobase/schema";
3
3
  //#region src/relay/client-events.d.ts
4
4
  /** The resources whose conversation page has `typing`, so their channels carry the typing event. */
@@ -8,7 +8,7 @@ export declare const typingResources: (views: readonly ViewModel[]) => Set<strin
8
8
  * conversation page types unless the resource declares a `typing` of its own, in the relay's field names. Undefined
9
9
  * when no channel has an event, so clients send nothing.
10
10
  */
11
- export declare const relayClientEvents: (channels: RealtimeRelayOptions["channels"], typing: ReadonlySet<string>) => {
11
+ export declare const relayClientEvents: (channels: Record<string, RelayChannelOptions>, typing: ReadonlySet<string>) => {
12
12
  channels: {
13
13
  [k: string]: {
14
14
  readonly events: {
@@ -1,5 +1,6 @@
1
1
  import { quoteIdent, tableSql } from "../changes/capture-sql.js";
2
2
  import { channelName } from "./change-commands.js";
3
+ import { listedAudience, listedCoMembers, listedMemberships, listedResources } from "./realtime-members-reads.js";
3
4
  import { sql } from "kysely";
4
5
  //#region src/relay/members-sql.ts
5
6
  const column = (members, field) => sql.raw(quoteIdent(members.model.fields[field].column));
@@ -8,8 +9,9 @@ const live = (members) => {
8
9
  return field === void 0 ? sql`true` : sql`${column(members, field)} is null`;
9
10
  };
10
11
  /**
11
- * The members of the named channels as the members tables hold them now, one query for each channel resource with
12
- * members, in the caller's transaction: what the dispatch's notices go to. Its relation column needs an index.
12
+ * The members of the named channels as the members tables and `realtime.members` hold them now, one query for each
13
+ * channel resource with a members resource and one for those whose records list their members, in the caller's
14
+ * transaction: what the dispatch's notices go to. A members resource's relation column needs an index.
13
15
  */
14
16
  const channelMembers = async (db, models, channels) => {
15
17
  const found = /* @__PURE__ */ new Map();
@@ -18,6 +20,17 @@ const channelMembers = async (db, models, channels) => {
18
20
  const resource = channel.slice(0, channel.indexOf("/"));
19
21
  byResource.set(resource, [...byResource.get(resource) ?? [], channel]);
20
22
  }
23
+ const listed = [...byResource].filter(([resource]) => models.channels.get(resource)?.listed);
24
+ if (listed.length > 0) {
25
+ const { rows } = await listedAudience(listed.map(([resource, named]) => ({
26
+ resource,
27
+ keys: named.map((channel) => channel.slice(resource.length + 1))
28
+ }))).execute(db);
29
+ for (const row of rows) {
30
+ const channel = channelName(row.resource, row.channel);
31
+ found.set(channel, [...found.get(channel) ?? [], row.user]);
32
+ }
33
+ }
21
34
  for (const [resource, named] of byResource) {
22
35
  const members = models.channels.get(resource)?.members;
23
36
  if (!members) continue;
@@ -31,9 +44,17 @@ const channelMembers = async (db, models, channels) => {
31
44
  }
32
45
  return found;
33
46
  };
34
- /** The channels with members that the person is in, one query for each channel resource with members; its user column needs an index. */
47
+ /**
48
+ * The channels with members that the person is in: one query for each channel resource with a members resource, whose
49
+ * user column needs an index, and one of `realtime.members` for those whose records list their members.
50
+ */
35
51
  const memberships = async (db, models, user) => {
36
52
  const channels = [];
53
+ const listed = listedResources(models);
54
+ if (listed.length > 0) {
55
+ const { rows } = await listedMemberships(listed, user).execute(db);
56
+ channels.push(...rows.map((row) => channelName(row.resource, row.channel)));
57
+ }
37
58
  for (const [resource, { members }] of models.channels) {
38
59
  if (!members) continue;
39
60
  const { rows } = await sql`select distinct ${column(members, members.field)} as channel
@@ -49,15 +70,17 @@ const liveAs = (alias, members) => {
49
70
  };
50
71
  /**
51
72
  * By person, everyone who shares a channel with members with them, themselves included, in one query over every
52
- * members table, in the caller's transaction: who hears of their presence. Its user and relation columns need indexes.
73
+ * members table and `realtime.members`, in the caller's transaction: who hears of their presence. Its user and
74
+ * relation columns need indexes.
53
75
  */
54
76
  const coMembers = async (db, models, people) => {
55
77
  const found = /* @__PURE__ */ new Map();
56
78
  const tables = [...models.channels.values()].flatMap(({ members }) => members ? [members] : []);
57
- if (people.length === 0 || tables.length === 0) return found;
58
- const pairs = tables.map((members) => sql`select ${aliased("a", members, members.user)}::text as person, ${aliased("b", members, members.user)}::text as other
79
+ const listed = listedResources(models);
80
+ if (people.length === 0 || tables.length === 0 && listed.length === 0) return found;
81
+ const pairs = [...listed.length > 0 ? [listedCoMembers(listed, people)] : [], ...tables.map((members) => sql`select ${aliased("a", members, members.user)}::text as person, ${aliased("b", members, members.user)}::text as other
59
82
  from ${sql.raw(tableSql(members.model))} a join ${sql.raw(tableSql(members.model))} b on ${aliased("b", members, members.field)} = ${aliased("a", members, members.field)}
60
- where ${aliased("a", members, members.user)} = any(${people}) and ${liveAs("a", members)} and ${liveAs("b", members)}`);
83
+ where ${aliased("a", members, members.user)} = any(${people}) and ${liveAs("a", members)} and ${liveAs("b", members)}`)];
61
84
  const { rows } = await sql`${sql.join(pairs, sql` union `)}`.execute(db);
62
85
  for (const row of rows) found.set(row.person, [...found.get(row.person) ?? [], row.other]);
63
86
  return found;
@@ -0,0 +1,25 @@
1
+ import { RealtimeRelayOptions, RelayChannelOptions } from "./relay-options.js";
2
+ import { ResourceModel, ViewModel } from "@protobase/schema";
3
+ //#region src/relay/realtime-channels.d.ts
4
+ /** What the relay's channels are derived from: the app's views and resources, and whether it has its own sign-in. */
5
+ export type RelayApp = {
6
+ views: readonly ViewModel[];
7
+ models: readonly ResourceModel[];
8
+ signIn: boolean;
9
+ };
10
+ /**
11
+ * The relay's channels an app gets without declaring them: one for each resource whose conversation page has
12
+ * `members`, a JSON field of user ids on the record, with that field as its members, when its changes are captured,
13
+ * such as with `.live()`, so the relay hears who joins and leaves, its key is one field and the field's changes are
14
+ * captured (`listedFieldProblem`). A page without `members` gives none, as a channel without members would be open.
15
+ * Views of one resource that list members in different fields stop it: the channel takes one.
16
+ */
17
+ export declare const defaultRelayChannels: ({ views, models }: Pick<RelayApp, "views" | "models">) => Record<string, RelayChannelOptions>;
18
+ /**
19
+ * The channels of the relay the app uses or can be moved to: `realtime.relay`'s, else the defaults. Undefined when the
20
+ * app cannot use the relay: no `realtime.relay`, and no sign-in, whose sessions tickets name, or no default channel.
21
+ * It decides whether `protobase migration` writes the relay's part, the build's manifest entry, and what the
22
+ * platform's switch turns on.
23
+ */
24
+ export declare const appRelayChannels: (declared: RealtimeRelayOptions | undefined, app: RelayApp) => Record<string, RelayChannelOptions> | undefined;
25
+ //#endregion
@@ -0,0 +1,39 @@
1
+ import { capturedBy } from "../changes/capture-sql.js";
2
+ import { listedFieldProblem } from "./relay-models.js";
3
+ //#region src/relay/realtime-channels.ts
4
+ /**
5
+ * The relay's channels an app gets without declaring them: one for each resource whose conversation page has
6
+ * `members`, a JSON field of user ids on the record, with that field as its members, when its changes are captured,
7
+ * such as with `.live()`, so the relay hears who joins and leaves, its key is one field and the field's changes are
8
+ * captured (`listedFieldProblem`). A page without `members` gives none, as a channel without members would be open.
9
+ * Views of one resource that list members in different fields stop it: the channel takes one.
10
+ */
11
+ const defaultRelayChannels = ({ views, models }) => {
12
+ const captured = capturedBy(models);
13
+ const byName = new Map(models.map((model) => [model.name, model]));
14
+ const fields = /* @__PURE__ */ new Map();
15
+ for (const view of views) {
16
+ const page = view.record;
17
+ if (!page || !("conversation" in page) || page.conversation.members === void 0) continue;
18
+ const model = byName.get(view.resource);
19
+ if (!model || !captured(model) || model.primaryKey.length !== 1 || listedFieldProblem(model, page.conversation.members)) continue;
20
+ const other = fields.get(view.resource);
21
+ if (other !== void 0 && other !== page.conversation.members) throw new Error(`Views of "${view.resource}": their conversation pages list members in "${other}" and "${page.conversation.members}", but the relay's channel on "${view.resource}" takes one members field`);
22
+ fields.set(view.resource, page.conversation.members);
23
+ }
24
+ return Object.fromEntries([...fields].map(([resource, field]) => [resource, { members: { field } }]));
25
+ };
26
+ /**
27
+ * The channels of the relay the app uses or can be moved to: `realtime.relay`'s, else the defaults. Undefined when the
28
+ * app cannot use the relay: no `realtime.relay`, and no sign-in, whose sessions tickets name, or no default channel.
29
+ * It decides whether `protobase migration` writes the relay's part, the build's manifest entry, and what the
30
+ * platform's switch turns on.
31
+ */
32
+ const appRelayChannels = (declared, app) => {
33
+ if (declared) return declared.channels ?? defaultRelayChannels(app);
34
+ if (!app.signIn) return;
35
+ const derived = defaultRelayChannels(app);
36
+ return Object.keys(derived).length > 0 ? derived : void 0;
37
+ };
38
+ //#endregion
39
+ export { appRelayChannels, defaultRelayChannels };
@@ -0,0 +1,16 @@
1
+ import { realtimeMembersTable } from "./realtime-members-sql.js";
2
+ import { sql } from "kysely";
3
+ //#region src/relay/realtime-members-reads.ts
4
+ const members = sql.raw(realtimeMembersTable);
5
+ /** The channel resources whose records list their members, which `realtime.members` holds. */
6
+ const listedResources = (models) => [...models.channels].flatMap(([resource, channel]) => channel.listed ? [resource] : []);
7
+ /** Who is in the named channels of each resource, by the table's key. */
8
+ const listedAudience = (named) => sql`${sql.join(named.map(({ resource, keys }) => sql`select resource, channel_key as channel, user_id as "user" from ${members} where resource = ${resource} and channel_key = any(${keys}::text[])`), sql` union all `)}`;
9
+ /** The channels of these resources the person is in, by the index by person. */
10
+ const listedMemberships = (resources, user) => sql`select resource, channel_key as channel from ${members} where user_id = ${user} and resource = any(${resources}::text[])`;
11
+ /** Each of these people with everyone who shares a channel of these resources with them, themselves included. */
12
+ const listedCoMembers = (resources, people) => sql`select a.user_id as person, b.user_id as other from ${members} a
13
+ join ${members} b on b.resource = a.resource and b.channel_key = a.channel_key
14
+ where a.user_id = any(${people}::text[]) and a.resource = any(${resources}::text[])`;
15
+ //#endregion
16
+ export { listedAudience, listedCoMembers, listedMemberships, listedResources };