@protobase/server 0.124.1 → 0.125.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/better-auth/auth-settings.d.ts +56 -70
  2. package/dist/better-auth/auth-settings.js +6 -1
  3. package/dist/better-auth/create-auth.d.ts +59 -69
  4. package/dist/better-auth/create-auth.js +15 -11
  5. package/dist/better-auth/names/modules/index.d.ts +83 -0
  6. package/dist/better-auth/names/modules/mail-senders.js +130 -69
  7. package/dist/better-auth/staff-checks.js +1 -1
  8. package/dist/better-auth/store/steps/index.js +3 -1
  9. package/dist/better-auth/store/steps/legacy-versions.js +4 -0
  10. package/dist/better-auth/store/steps/mail-senders/004-sender-verifications.js +41 -0
  11. package/dist/create-admin.js +3 -1
  12. package/dist/index.d.ts +5 -5
  13. package/dist/index.js +3 -4
  14. package/dist/locale/en.js +1 -5
  15. package/dist/locale/nl.js +1 -5
  16. package/dist/package.js +1 -1
  17. package/dist/personal-mail/listed-mail-senders.d.ts +16 -0
  18. package/dist/personal-mail/listed-mail-senders.js +18 -6
  19. package/dist/personal-mail/mail-sender.d.ts +1 -0
  20. package/dist/personal-mail/mail-sender.js +1 -1
  21. package/dist/personal-mail/mail-senders-plugin.js +44 -46
  22. package/dist/personal-mail/personal-mailer.js +7 -2
  23. package/dist/personal-mail/sender-address-state.js +8 -5
  24. package/dist/personal-mail/sender-store.d.ts +2 -1
  25. package/dist/personal-mail/verifiers/report-endpoint.js +40 -0
  26. package/dist/personal-mail/verifiers/sender-address-verifier.d.ts +62 -0
  27. package/dist/personal-mail/verifiers/sender-verifications.d.ts +6 -0
  28. package/dist/personal-mail/verifiers/sender-verifications.js +28 -0
  29. package/dist/personal-mail/verifiers/start-verification.d.ts +4 -0
  30. package/dist/personal-mail/verifiers/start-verification.js +34 -0
  31. package/dist/personal-mail/verifiers/verification-outcome.js +49 -0
  32. package/dist/personal-mail/verifiers/verification-secret.js +8 -0
  33. package/dist/personal-mail/verifiers/verification-store.d.ts +17 -0
  34. package/dist/personal-mail/verifiers/verification-store.js +130 -0
  35. package/dist/personal-mail/verifiers/verification-sweep.js +45 -0
  36. package/dist/personal-mail/verifiers/verifier-list.js +26 -0
  37. package/dist/personal-mail/verifiers/verify-tools.js +30 -0
  38. package/dist/relay/relay-options.d.ts +23 -6
  39. package/dist/relay/relay-options.js +25 -4
  40. package/dist/relay/relay-runtime.js +0 -2
  41. package/dist/webhooks/attempt.js +1 -1
  42. package/package.json +6 -6
  43. package/dist/personal-mail/alias-checks.d.ts +0 -14
  44. package/dist/personal-mail/alias-checks.js +0 -29
  45. package/dist/personal-mail/mail-check-service.js +0 -41
  46. package/dist/personal-mail/mail-check-settings.js +0 -18
  47. package/dist/personal-mail/mail-check-signing.d.ts +0 -10
  48. package/dist/personal-mail/mail-check-signing.js +0 -13
@@ -0,0 +1,130 @@
1
+ import { checkIntervalMs, maxPendingMs, maxValidMs, verificationExpired, verifyLeaseMs } from "./verification-outcome.js";
2
+ import { sql } from "kysely";
3
+ //#region src/personal-mail/verifiers/verification-store.ts
4
+ const interval = (ms) => sql.raw(`interval '${ms / 1e3} seconds'`);
5
+ const parts = (store) => {
6
+ const table = store.table("mail_sender_verification");
7
+ const v = table.columns;
8
+ const sender = store.table("mail_sender");
9
+ const selected = sql.join([
10
+ sql`${table}.id`,
11
+ sql`${table}.${v.sender_id} as "senderId"`,
12
+ sql`${table}.${v.verifier} as verifier`,
13
+ sql`${table}.${v.state} as state`,
14
+ sql`${table}.${v.created_at} as "createdAt"`,
15
+ sql`${table}.${v.expires_at} as "expiresAt"`,
16
+ sql`${table}.${v.settled_at} as "settledAt"`,
17
+ sql`${table}.${v.valid_until} as "validUntil"`,
18
+ sql`${table}.${v.error_code} as "errorCode"`,
19
+ sql`${table}.${v.error} as error`
20
+ ]);
21
+ return {
22
+ table,
23
+ v,
24
+ sender,
25
+ s: sender.columns,
26
+ selected
27
+ };
28
+ };
29
+ /**
30
+ * The verifications in SQL, on the auth store, each call one statement. Every settle is one update guarded by
31
+ * `state = 'pending' and expires_at > now()`, so a verification settles once, whichever of `verify`, the sweep and a
32
+ * report comes first, and none after it expired.
33
+ */
34
+ const verificationStore = (store) => ({
35
+ /** Fails, as expired, the pending verification of `senderId` by `verifier` whose time ran out, a `verify` that never returned included. */
36
+ expireOverdue: async (senderId, verifier) => {
37
+ const s = await store();
38
+ const { table, v } = parts(s);
39
+ await sql`update ${table} set ${v.state} = 'failed', ${v.settled_at} = now(), ${v.error_code} = ${verificationExpired}
40
+ where ${v.sender_id} = ${senderId} and ${v.verifier} = ${verifier} and ${v.state} = 'pending' and ${v.expires_at} <= now()`.execute(s.db);
41
+ },
42
+ /** Starts a verification of `senderId` by `verifier`, pending for the lease `verify` has: its id, or none while one is pending already. */
43
+ start: async (senderId, verifier, secretHash) => {
44
+ const s = await store();
45
+ const { table, v } = parts(s);
46
+ const { rows } = await sql`insert into ${table} (id, ${v.sender_id}, ${v.verifier}, ${v.state}, ${v.secret_hash}, ${v.created_at}, ${v.expires_at}, ${v.next_check_at})
47
+ values (${s.newId}, ${senderId}, ${verifier}, 'pending', ${secretHash}, now(), now() + ${interval(verifyLeaseMs)}, now() + ${interval(verifyLeaseMs)})
48
+ on conflict (${v.sender_id}, ${v.verifier}) where ${v.state} = 'pending' do nothing
49
+ returning id`.execute(s.db);
50
+ return rows[0]?.id;
51
+ },
52
+ /**
53
+ * Records `outcome` of the verification `key` names, if `verifier` started it and it is still pending in time:
54
+ * whether it did. The first pending outcome (`first`) sets when it expires, at most 24 hours after it started; a
55
+ * later one only when it is checked next, a minute on at the soonest and never after it expires. `valid_until` counts at most 28 days.
56
+ */
57
+ settle: async (key, verifier, outcome, first = false) => {
58
+ const s = await store();
59
+ const { table, v } = parts(s);
60
+ const set = (() => {
61
+ if (outcome.state === "verified") return sql`${v.state} = 'verified', ${v.settled_at} = now(), ${v.valid_until} = least(${outcome.valid_until}::timestamptz, now() + ${interval(maxValidMs)})`;
62
+ if (outcome.state === "failed") return sql`${v.state} = 'failed', ${v.settled_at} = now(), ${v.error_code} = ${outcome.error_code}, ${v.error} = ${outcome.error ?? null}`;
63
+ const interval_ = sql`now() + ${interval(checkIntervalMs)}`;
64
+ const nextCheck = outcome.check_after ? sql`greatest(${outcome.check_after}::timestamptz, ${interval_})` : interval_;
65
+ if (!first) return sql`${v.next_check_at} = least(${nextCheck}, ${v.expires_at})`;
66
+ const expires = sql`least(${outcome.expires_at}::timestamptz, ${v.created_at} + ${interval(maxPendingMs)})`;
67
+ return sql`${v.expires_at} = ${expires}, ${v.next_check_at} = least(${nextCheck}, ${expires})`;
68
+ })();
69
+ const match = "id" in key ? sql`id = ${key.id}` : sql`${v.secret_hash} = ${key.secretHash}`;
70
+ const { rows } = await sql`update ${table} set ${set}
71
+ where ${match} and ${v.verifier} = ${verifier} and ${v.state} = 'pending' and ${v.expires_at} > now()
72
+ returning id`.execute(s.db);
73
+ return rows.length === 1;
74
+ },
75
+ /** Fails, as expired, every pending verification whose time ran out, of any verifier. */
76
+ expireDue: async () => {
77
+ const s = await store();
78
+ const { table, v } = parts(s);
79
+ await sql`update ${table} set ${v.state} = 'failed', ${v.settled_at} = now(), ${v.error_code} = ${verificationExpired}
80
+ where ${v.state} = 'pending' and ${v.expires_at} <= now()`.execute(s.db);
81
+ },
82
+ /**
83
+ * Claims up to `limit` pending verifications of `verifiers` due for a check, moving their next check a minute on as
84
+ * it claims them: a sweep running beside this one skips them, as they are locked, and then finds them not due.
85
+ */
86
+ claimDue: async (verifiers, limit) => {
87
+ const s = await store();
88
+ const { table, v, sender, s: c } = parts(s);
89
+ const { rows } = await sql`with claimed as (
90
+ update ${table} set ${v.next_check_at} = now() + ${interval(checkIntervalMs)}
91
+ from ${sender}
92
+ where ${table}.id in (
93
+ select id from ${table}
94
+ where ${v.state} = 'pending' and ${v.next_check_at} <= now() and ${v.expires_at} > now() and ${v.verifier} = any(${[...verifiers]}::text[])
95
+ order by ${v.next_check_at} limit ${limit}
96
+ for update skip locked
97
+ ) and ${sender}.id = ${table}.${v.sender_id}
98
+ returning ${table}.id, ${table}.${v.verifier} as verifier, ${sender}.${c.address} as address, ${sender}.${c.name} as name
99
+ )
100
+ select * from claimed order by address, verifier`.execute(s.db);
101
+ return rows;
102
+ },
103
+ /** The latest verification of each of `userId`'s addresses by each of `verifiers`. */
104
+ latestOf: async (userId, verifiers) => {
105
+ if (verifiers.length === 0) return [];
106
+ const s = await store();
107
+ const { table, v, sender, s: c, selected } = parts(s);
108
+ const { rows } = await sql`select * from (
109
+ select distinct on (${table}.${v.sender_id}, ${table}.${v.verifier}) ${selected} from ${table}
110
+ join ${sender} on ${sender}.id = ${table}.${v.sender_id}
111
+ where ${sender}.${c.user_id} = ${userId} and ${table}.${v.verifier} = any(${[...verifiers]}::text[])
112
+ order by ${table}.${v.sender_id}, ${table}.${v.verifier}, ${table}.${v.created_at} desc
113
+ ) as latest order by "createdAt", verifier`.execute(s.db);
114
+ return rows;
115
+ },
116
+ /** The verified verifications by `verifiers` of `userId`'s addresses that still count. */
117
+ proofsOf: async (userId, verifiers) => {
118
+ if (verifiers.length === 0) return [];
119
+ const s = await store();
120
+ const { table, v, sender, s: c } = parts(s);
121
+ const { rows } = await sql`select ${table}.${v.sender_id} as "senderId", max(${table}.${v.settled_at}) as "settledAt" from ${table}
122
+ join ${sender} on ${sender}.id = ${table}.${v.sender_id}
123
+ where ${sender}.${c.user_id} = ${userId} and ${table}.${v.verifier} = any(${[...verifiers]}::text[]) and ${table}.${v.state} = 'verified' and ${table}.${v.valid_until} > now()
124
+ group by ${table}.${v.sender_id}
125
+ order by "settledAt"`.execute(s.db);
126
+ return rows;
127
+ }
128
+ });
129
+ //#endregion
130
+ export { verificationStore };
@@ -0,0 +1,45 @@
1
+ import { defineJob } from "../../jobs/define-job.js";
2
+ import { validOutcome } from "./verification-outcome.js";
3
+ //#region src/personal-mail/verifiers/verification-sweep.ts
4
+ /** How many due verifications the sweep claims at once. */
5
+ const batchSize = 100;
6
+ /**
7
+ * One pass of the sweep: fails every pending verification whose time ran out as `verification_expired`, then calls
8
+ * `check` on each one due, claimed a batch at a time so a sweep beside it checks each once, and records its outcome.
9
+ * A `check` that throws leaves its verification pending, to be checked again or expire; the throws are rethrown
10
+ * together once every due verification had its turn.
11
+ */
12
+ const sweepVerifications = async (verifiers, store) => {
13
+ await store.expireDue();
14
+ const checking = new Map(verifiers.flatMap((verifier) => verifier.check ? [[verifier.id, verifier.check]] : []));
15
+ if (checking.size === 0) return;
16
+ const errors = [];
17
+ for (;;) {
18
+ const claimed = await store.claimDue([...checking.keys()], batchSize);
19
+ for (const row of claimed) {
20
+ const input = {
21
+ verification_id: row.id,
22
+ address: row.address,
23
+ ...row.name && { name: row.name }
24
+ };
25
+ const outcome = await checking.get(row.verifier)(input).then((value) => ({ value }), (error) => void errors.push(error));
26
+ if (!outcome) continue;
27
+ await store.settle({ id: row.id }, row.verifier, validOutcome(outcome.value, /* @__PURE__ */ new Date(), false) ?? {
28
+ state: "failed",
29
+ error_code: "verifier_error"
30
+ });
31
+ }
32
+ if (claimed.length < batchSize) break;
33
+ }
34
+ if (errors.length > 0) throw new AggregateError(errors, `${errors.length} From address verification checks failed`);
35
+ };
36
+ /** The sweep, each minute, on the app's jobs. */
37
+ const verificationSweepJob = (verifiers, store) => defineJob({
38
+ name: "auth.mail-sender-verifications",
39
+ schedule: "* * * * *",
40
+ timeout: "5 minutes",
41
+ maxAttempts: 1,
42
+ run: async () => sweepVerifications(verifiers, store)
43
+ });
44
+ //#endregion
45
+ export { sweepVerifications, verificationSweepJob };
@@ -0,0 +1,26 @@
1
+ //#region src/personal-mail/verifiers/verifier-list.ts
2
+ const idPattern = /^[a-z][a-z0-9_.-]{0,63}$/;
3
+ /**
4
+ * The verifiers of one app, as its trusted code adds them with `add_verifier` while the app starts: each id once, in
5
+ * lowercase letters, digits, `_`, `.` and `-`, as verifications store it. Once `freeze` is called, as the app's auth is
6
+ * built, `add_verifier` refuses.
7
+ */
8
+ const senderVerifierList = () => {
9
+ const verifiers = [];
10
+ let frozen = false;
11
+ const add_verifier = (verifier) => {
12
+ if (frozen) throw new Error(`add_verifier: "${verifier.id}" comes after the app started; add verifiers while it starts`);
13
+ if (!idPattern.test(verifier.id)) throw new Error(`add_verifier: the id "${verifier.id}" must be lowercase letters, digits, "_", "." or "-", starting with a letter, at most 64 characters`);
14
+ if (verifiers.some(({ id }) => id === verifier.id)) throw new Error(`add_verifier: two verifiers have the id "${verifier.id}"`);
15
+ verifiers.push(verifier);
16
+ };
17
+ return {
18
+ add_verifier,
19
+ freeze: () => {
20
+ frozen = true;
21
+ return [...verifiers];
22
+ }
23
+ };
24
+ };
25
+ //#endregion
26
+ export { senderVerifierList };
@@ -0,0 +1,30 @@
1
+ import * as z$1 from "zod";
2
+ //#region src/personal-mail/verifiers/verify-tools.ts
3
+ const message = z$1.object({
4
+ to: z$1.email(),
5
+ subject: z$1.string().min(1).max(998),
6
+ text: z$1.string(),
7
+ html: z$1.string().optional()
8
+ });
9
+ /**
10
+ * The tools of one `verify` of the address record `senderId`: `send` goes through `mail`, its owner's mailbox, From that
11
+ * record, to one recipient, once. Only `to`, `subject`, `text` and `html` are read, so a From, a Sender, copies, header
12
+ * fields or attachments a verifier passes never reach the message.
13
+ */
14
+ const verifyTools = (mail, senderId) => {
15
+ let sent = false;
16
+ return { send: async (given) => {
17
+ if (sent) throw new Error("A verification sends one test message; verify called tools.send again");
18
+ const { to, subject, text, html } = message.parse(given);
19
+ sent = true;
20
+ await mail.send({
21
+ sender_address_id: senderId,
22
+ to,
23
+ subject,
24
+ text,
25
+ ...html !== void 0 && { html }
26
+ });
27
+ } };
28
+ };
29
+ //#endregion
30
+ export { verifyTools };
@@ -50,21 +50,38 @@ export type RelayPresence = {
50
50
  /** The bearer token the relay's presence reports carry, at least 32 characters. */
51
51
  key: string;
52
52
  };
53
- /** The realtime relay the app hands its connections to (`realtime.relay` in `protobase.config.ts`). */
53
+ /**
54
+ * The realtime relay the app hands its connections to (`realtime.relay` in `protobase.config.ts`). Its address, id
55
+ * and keys default to the variables of `relayVariables`, which a platform that runs the relay sets.
56
+ */
54
57
  export type RealtimeRelayOptions = {
55
58
  /** The relay's address, such as `https://relay.example.com`: its app commands, and its socket at `/socket`. */
56
- url: string;
59
+ url?: string;
57
60
  /** The app's id on the relay. */
58
- app: string;
61
+ app?: string;
59
62
  /** One of the app's API keys on the relay, which its commands carry. */
60
- apiKey: string;
63
+ apiKey?: string;
61
64
  /** One of the app's ticket keys on the relay, which signs the connect tickets. */
62
- ticketKey: string;
65
+ ticketKey?: string;
63
66
  /** The channel resources by name. */
64
67
  channels: Record<string, RelayChannelOptions>;
65
68
  /** Turns on presence: the relay reports who is online, away or offline, and the app keeps it in this resource. */
66
69
  presence?: RelayPresence;
67
70
  };
71
+ /** `realtime.relay` with its address, id and keys, from the config or the environment. */
72
+ export type RealtimeRelaySettings = RealtimeRelayOptions & Required<Pick<RealtimeRelayOptions, 'url' | 'app' | 'apiKey' | 'ticketKey'>>;
73
+ /** The variables a platform that runs the relay sets, which `realtime.relay`'s address, id and keys default to. */
74
+ export declare const relayVariables: {
75
+ readonly url: "PROTOBASE_RELAY_URL";
76
+ readonly app: "PROTOBASE_RELAY_APP";
77
+ readonly apiKey: "PROTOBASE_RELAY_API_KEY";
78
+ readonly ticketKey: "PROTOBASE_RELAY_TICKET_KEY";
79
+ };
68
80
  /** The options, or an error naming what is wrong with their shape; `relayModels` checks them against the resources. */
69
- export declare const checkRelayOptions: (options: RealtimeRelayOptions) => RealtimeRelayOptions;
81
+ export declare const checkRelayOptions: (options: RealtimeRelayOptions) => RealtimeRelaySettings;
82
+ /**
83
+ * `realtime.relay` with each of its address, id and keys the config leaves out taken from its variable in `env`, then
84
+ * checked: a value in the config wins, and one missing from both fails the check, naming the key and its variable.
85
+ */
86
+ export declare const relaySettings: (options: RealtimeRelayOptions, env: Record<string, string | undefined>) => RealtimeRelaySettings;
70
87
  //#endregion
@@ -1,4 +1,11 @@
1
1
  //#region src/relay/relay-options.ts
2
+ /** The variables a platform that runs the relay sets, which `realtime.relay`'s address, id and keys default to. */
3
+ const relayVariables = {
4
+ url: "PROTOBASE_RELAY_URL",
5
+ app: "PROTOBASE_RELAY_APP",
6
+ apiKey: "PROTOBASE_RELAY_API_KEY",
7
+ ticketKey: "PROTOBASE_RELAY_TICKET_KEY"
8
+ };
2
9
  const appPattern = /^[a-z0-9_-]{1,64}$/;
3
10
  const minKeyLength = 32;
4
11
  const maxEventBytes = 65536;
@@ -32,9 +39,12 @@ const checkEvents = (where, events) => {
32
39
  };
33
40
  /** The options, or an error naming what is wrong with their shape; `relayModels` checks them against the resources. */
34
41
  const checkRelayOptions = (options) => {
35
- if (!nonEmpty(options?.url) || !/^https?:\/\//.test(options.url)) throw new Error(`realtime.relay.url must start with https:// or http://, not ${JSON.stringify(options?.url)}`);
36
- if (typeof options.app !== "string" || !appPattern.test(options.app)) throw new Error(`realtime.relay.app must be 1 to 64 of a-z, 0-9, _ and -, as the relay names the app, not ${JSON.stringify(options.app)}`);
37
- for (const key of ["apiKey", "ticketKey"]) if (typeof options[key] !== "string" || options[key].length < minKeyLength) throw new Error(`realtime.relay.${key} must be a string of at least ${minKeyLength} characters, such as from an environment variable`);
42
+ if (!nonEmpty(options?.url) || !/^https?:\/\//.test(options.url)) throw new Error(`realtime.relay.url or ${relayVariables.url} must start with https:// or http://, not ${JSON.stringify(options?.url)}`);
43
+ if (typeof options.app !== "string" || !appPattern.test(options.app)) throw new Error(`realtime.relay.app or ${relayVariables.app} must be 1 to 64 of a-z, 0-9, _ and -, as the relay names the app, not ${JSON.stringify(options.app)}`);
44
+ for (const key of ["apiKey", "ticketKey"]) {
45
+ const value = options[key];
46
+ if (typeof value !== "string" || value.length < minKeyLength) throw new Error(`realtime.relay.${key} or ${relayVariables[key]} must be a string of at least ${minKeyLength} characters`);
47
+ }
38
48
  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");
39
49
  for (const [name, channel] of Object.entries(options.channels)) {
40
50
  const members = channel?.members;
@@ -49,5 +59,16 @@ const checkRelayOptions = (options) => {
49
59
  }
50
60
  return options;
51
61
  };
62
+ /**
63
+ * `realtime.relay` with each of its address, id and keys the config leaves out taken from its variable in `env`, then
64
+ * checked: a value in the config wins, and one missing from both fails the check, naming the key and its variable.
65
+ */
66
+ const relaySettings = (options, env) => checkRelayOptions({
67
+ ...options,
68
+ url: options.url || env[relayVariables.url],
69
+ app: options.app || env[relayVariables.app],
70
+ apiKey: options.apiKey || env[relayVariables.apiKey],
71
+ ticketKey: options.ticketKey || env[relayVariables.ticketKey]
72
+ });
52
73
  //#endregion
53
- export { checkRelayOptions, eventLimit };
74
+ export { checkRelayOptions, eventLimit, relaySettings, relayVariables };
@@ -11,7 +11,6 @@ import { relayClient } from "./relay-commands.js";
11
11
  import { relayJobs } from "./relay-jobs.js";
12
12
  import { relayModels } from "./relay-models.js";
13
13
  import { publicChannels } from "./public-channels.js";
14
- import { checkRelayOptions } from "./relay-options.js";
15
14
  import { sessionEnd } from "./session-end.js";
16
15
  import { ticketRoutes } from "./ticket-route.js";
17
16
  //#region src/relay/relay-runtime.ts
@@ -21,7 +20,6 @@ import { ticketRoutes } from "./ticket-route.js";
21
20
  * own sign-in, whose sessions the tickets name.
22
21
  */
23
22
  const relayRuntime = (options, auth, deps) => {
24
- checkRelayOptions(options);
25
23
  if (!auth) throw new Error("relay needs the app's own sign-in (auth), whose sessions its tickets name and end");
26
24
  const models = relayModels(options, deps.registry.entries.map((entry) => entry.model));
27
25
  const ends = sessionEnd(auth);
@@ -1,8 +1,8 @@
1
- import { standardWebhookHeaders } from "./standard-webhooks.js";
2
1
  import { AddressRefusedError, pinnedRequest } from "./table/pinned-request.js";
3
2
  import { readLimited } from "./table/read-limited.js";
4
3
  import { invokeFunction } from "../functions/define-function.js";
5
4
  import { retryAfterMs } from "./retry-schedule.js";
5
+ import { standardWebhookHeaders } from "./standard-webhooks.js";
6
6
  import { subscriberSession } from "./subscriber-view.js";
7
7
  //#region src/webhooks/attempt.ts
8
8
  /** How long a receiver has to answer. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/server",
3
- "version": "0.124.1",
3
+ "version": "0.125.0",
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.124.1",
48
- "@protobase/query": "0.124.1",
49
- "@protobase/schema": "0.124.1",
50
- "@protobase/workflow-plugins": "0.124.1",
51
- "@protobase/workflows": "0.124.1",
47
+ "@protobase/layout": "0.125.0",
48
+ "@protobase/query": "0.125.0",
49
+ "@protobase/schema": "0.125.0",
50
+ "@protobase/workflow-plugins": "0.125.0",
51
+ "@protobase/workflows": "0.125.0",
52
52
  "@react-email/render": "^2.1.0",
53
53
  "@react-pdf/primitives": "^4.4.0",
54
54
  "@react-pdf/renderer": "^4.9.0",
@@ -1,14 +0,0 @@
1
- import "./personal-mailer.js";
2
- import { Locale } from "@protobase/schema/internal";
3
- //#region src/personal-mail/alias-checks.d.ts
4
- /** Where a check of a From address stands: its test message has not arrived yet, or arrived from that address, or from another. */
5
- export type AliasCheckResult = {
6
- status: 'waiting';
7
- } | {
8
- status: 'confirmed';
9
- from: string;
10
- } | {
11
- status: 'mismatch';
12
- from: string;
13
- };
14
- //#endregion
@@ -1,29 +0,0 @@
1
- import { messages } from "../locale/messages.js";
2
- //#region src/personal-mail/alias-checks.ts
3
- const text = messages("personal-mail");
4
- const aliasChecks = (service, mailOf) => ({
5
- start: async (userId, { id, address }, locale) => {
6
- const { token, address: to } = await service.issue();
7
- const say = text(locale);
8
- await mailOf(userId).send({
9
- sender_address_id: id,
10
- to,
11
- subject: say("ALIAS_CHECK_SUBJECT", { address }),
12
- text: say("ALIAS_CHECK_TEXT", { address })
13
- });
14
- return token;
15
- },
16
- result: async (token, address) => {
17
- const from = await service.received(token);
18
- if (from === void 0) return { status: "waiting" };
19
- return from.toLowerCase() === address.toLowerCase() ? {
20
- status: "confirmed",
21
- from
22
- } : {
23
- status: "mismatch",
24
- from
25
- };
26
- }
27
- });
28
- //#endregion
29
- export { aliasChecks };
@@ -1,41 +0,0 @@
1
- import { mailCheckHeaders } from "./mail-check-signing.js";
2
- import * as z$1 from "zod";
3
- //#region src/personal-mail/mail-check-service.ts
4
- /** The calls of the mail check service, under the URL the platform names. */
5
- const mailCheckPaths = (url) => ({
6
- issue: `${url}/alias-checks`,
7
- result: `${url}/alias-checks/result`
8
- });
9
- const issued = z$1.object({
10
- token: z$1.string().min(1),
11
- address: z$1.email()
12
- });
13
- const result = z$1.union([z$1.object({ received: z$1.literal(false) }), z$1.object({
14
- received: z$1.literal(true),
15
- from: z$1.string().min(1)
16
- })]);
17
- const mailCheckService = ({ url, platformSecret }, fetcher = (...args) => fetch(...args)) => {
18
- const paths = mailCheckPaths(url);
19
- const call = async (path, payload) => {
20
- const body = JSON.stringify(payload);
21
- const response = await fetcher(path, {
22
- method: "POST",
23
- headers: {
24
- ...await mailCheckHeaders(platformSecret, crypto.randomUUID(), body),
25
- "content-type": "application/json"
26
- },
27
- body
28
- });
29
- if (!response.ok) throw new Error(`The mail check service answered ${response.status} ${response.statusText} to ${path}`);
30
- return response.json();
31
- };
32
- return {
33
- issue: async () => issued.parse(await call(paths.issue, {})),
34
- received: async (token) => {
35
- const answer = result.parse(await call(paths.result, { token }));
36
- return answer.received ? answer.from : void 0;
37
- }
38
- };
39
- };
40
- //#endregion
41
- export { mailCheckPaths, mailCheckService };
@@ -1,18 +0,0 @@
1
- import { checkedUrl } from "../checked-url.js";
2
- //#region src/personal-mail/mail-check-settings.ts
3
- const mailCheckVariable = "PROTOBASE_MAIL_CHECK_URL";
4
- /**
5
- * The mail check service the platform names in `PROTOBASE_MAIL_CHECK_URL`, with `PROTOBASE_SECRET` to sign the calls;
6
- * without either, From addresses are not checked. A value that is no http(s) URL stops startup, naming the variable.
7
- */
8
- const readMailCheckSettings = (env) => {
9
- const url = env[mailCheckVariable]?.trim();
10
- if (!url) return;
11
- if (!env.PROTOBASE_SECRET) throw new Error(`${mailCheckVariable} signs its calls with the app's secret: set PROTOBASE_SECRET too`);
12
- return {
13
- url: checkedUrl(url, mailCheckVariable),
14
- platformSecret: env.PROTOBASE_SECRET
15
- };
16
- };
17
- //#endregion
18
- export { mailCheckVariable, readMailCheckSettings };
@@ -1,10 +0,0 @@
1
- //#region src/personal-mail/mail-check-signing.d.ts
2
- /**
3
- * The Standard Webhooks secret an app signs its calls to the mail check service with, derived from the platform
4
- * secret (`PROTOBASE_SECRET`) by HKDF, so no other use of that secret signs one and the secret itself never travels.
5
- * The service derives the same one from the app's secret and checks a call with `verifyStandardWebhook`.
6
- */
7
- export declare const mailCheckSecret: (platformSecret: string) => string;
8
- /** The headers that sign one call to the mail check service: `id`, unique per call, and the JSON `body`. */
9
- export declare const mailCheckHeaders: (platformSecret: string, id: string, body: string, now?: () => number) => Promise<Record<string, string>>;
10
- //#endregion
@@ -1,13 +0,0 @@
1
- import { standardWebhookHeaders } from "../webhooks/standard-webhooks.js";
2
- import { hkdfSync } from "node:crypto";
3
- //#region src/personal-mail/mail-check-signing.ts
4
- /**
5
- * The Standard Webhooks secret an app signs its calls to the mail check service with, derived from the platform
6
- * secret (`PROTOBASE_SECRET`) by HKDF, so no other use of that secret signs one and the secret itself never travels.
7
- * The service derives the same one from the app's secret and checks a call with `verifyStandardWebhook`.
8
- */
9
- const mailCheckSecret = (platformSecret) => `whsec_${Buffer.from(hkdfSync("sha256", platformSecret, /* @__PURE__ */ new Uint8Array(0), "protobase mail alias check", 32)).toString("base64")}`;
10
- /** The headers that sign one call to the mail check service: `id`, unique per call, and the JSON `body`. */
11
- const mailCheckHeaders = (platformSecret, id, body, now = Date.now) => standardWebhookHeaders(id, Math.floor(now() / 1e3), body, mailCheckSecret(platformSecret));
12
- //#endregion
13
- export { mailCheckHeaders, mailCheckSecret };