@protobase/server 0.124.2 → 0.125.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) 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 +5 -3
  12. package/dist/index.d.ts +5 -4
  13. package/dist/index.js +3 -3
  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 +12 -6
  39. package/dist/relay/relay-options.js +11 -5
  40. package/dist/relay/relay-switch.d.ts +6 -0
  41. package/dist/relay/relay-switch.js +24 -0
  42. package/dist/webhooks/attempt.js +1 -1
  43. package/dist/webhooks/table/webhooks-module.d.ts +2 -2
  44. package/dist/workflows/workflows-module.d.ts +2 -2
  45. package/package.json +6 -6
  46. package/dist/personal-mail/alias-checks.d.ts +0 -14
  47. package/dist/personal-mail/alias-checks.js +0 -29
  48. package/dist/personal-mail/mail-check-service.js +0 -41
  49. package/dist/personal-mail/mail-check-settings.js +0 -18
  50. package/dist/personal-mail/mail-check-signing.d.ts +0 -10
  51. 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 };
@@ -47,8 +47,8 @@ export type RelayPresence = {
47
47
  status: string;
48
48
  /** Its timestamp field holding when the status began, such as `since`. */
49
49
  at: string;
50
- /** The bearer token the relay's presence reports carry, at least 32 characters. */
51
- key: string;
50
+ /** The bearer token the relay's presence reports carry, at least 32 characters; defaults to `relayVariables.presenceKey`. */
51
+ key?: string;
52
52
  };
53
53
  /**
54
54
  * The realtime relay the app hands its connections to (`realtime.relay` in `protobase.config.ts`). Its address, id
@@ -68,20 +68,26 @@ export type RealtimeRelayOptions = {
68
68
  /** Turns on presence: the relay reports who is online, away or offline, and the app keeps it in this resource. */
69
69
  presence?: RelayPresence;
70
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'>>;
71
+ /** `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'>> & {
73
+ presence?: RelayPresence & {
74
+ key: string;
75
+ };
76
+ };
73
77
  /** The variables a platform that runs the relay sets, which `realtime.relay`'s address, id and keys default to. */
74
78
  export declare const relayVariables: {
75
79
  readonly url: "PROTOBASE_RELAY_URL";
76
80
  readonly app: "PROTOBASE_RELAY_APP";
77
81
  readonly apiKey: "PROTOBASE_RELAY_API_KEY";
78
82
  readonly ticketKey: "PROTOBASE_RELAY_TICKET_KEY";
83
+ readonly presenceKey: "PROTOBASE_RELAY_PRESENCE_KEY";
79
84
  };
80
85
  /** The options, or an error naming what is wrong with their shape; `relayModels` checks them against the resources. */
81
86
  export declare const checkRelayOptions: (options: RealtimeRelayOptions) => RealtimeRelaySettings;
82
87
  /**
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.
88
+ * `realtime.relay` with each of its address, id and keys, the presence key included, the config leaves out taken from
89
+ * its variable in `env`, then checked: a value in the config wins, and one missing from both fails the check, naming
90
+ * the key and its variable.
85
91
  */
86
92
  export declare const relaySettings: (options: RealtimeRelayOptions, env: Record<string, string | undefined>) => RealtimeRelaySettings;
87
93
  //#endregion
@@ -4,7 +4,8 @@ const relayVariables = {
4
4
  url: "PROTOBASE_RELAY_URL",
5
5
  app: "PROTOBASE_RELAY_APP",
6
6
  apiKey: "PROTOBASE_RELAY_API_KEY",
7
- ticketKey: "PROTOBASE_RELAY_TICKET_KEY"
7
+ ticketKey: "PROTOBASE_RELAY_TICKET_KEY",
8
+ presenceKey: "PROTOBASE_RELAY_PRESENCE_KEY"
8
9
  };
9
10
  const appPattern = /^[a-z0-9_-]{1,64}$/;
10
11
  const minKeyLength = 32;
@@ -55,20 +56,25 @@ const checkRelayOptions = (options) => {
55
56
  const presence = options.presence;
56
57
  if (presence !== void 0) {
57
58
  if (!(nonEmpty(presence?.resource) && nonEmpty(presence.user) && nonEmpty(presence.status) && nonEmpty(presence.at))) throw new Error("realtime.relay.presence must be { resource, user, status, at, key }");
58
- if (typeof presence.key !== "string" || presence.key.length < minKeyLength) throw new Error(`realtime.relay.presence.key must be a string of at least ${minKeyLength} characters, such as from an environment variable`);
59
+ if (typeof presence.key !== "string" || presence.key.length < minKeyLength) throw new Error(`realtime.relay.presence.key or ${relayVariables.presenceKey} must be a string of at least ${minKeyLength} characters`);
59
60
  }
60
61
  return options;
61
62
  };
62
63
  /**
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.
64
+ * `realtime.relay` with each of its address, id and keys, the presence key included, the config leaves out taken from
65
+ * its variable in `env`, then checked: a value in the config wins, and one missing from both fails the check, naming
66
+ * the key and its variable.
65
67
  */
66
68
  const relaySettings = (options, env) => checkRelayOptions({
67
69
  ...options,
68
70
  url: options.url || env[relayVariables.url],
69
71
  app: options.app || env[relayVariables.app],
70
72
  apiKey: options.apiKey || env[relayVariables.apiKey],
71
- ticketKey: options.ticketKey || env[relayVariables.ticketKey]
73
+ ticketKey: options.ticketKey || env[relayVariables.ticketKey],
74
+ ...options.presence && { presence: {
75
+ ...options.presence,
76
+ key: options.presence.key || env[relayVariables.presenceKey]
77
+ } }
72
78
  });
73
79
  //#endregion
74
80
  export { checkRelayOptions, eventLimit, relaySettings, relayVariables };
@@ -0,0 +1,6 @@
1
+ //#region src/relay/relay-switch.d.ts
2
+ /** The variable with which a platform that runs the relay moves an app to it. */
3
+ export declare const relaySwitchVariable = "PROTOBASE_RELAY_ENABLED";
4
+ /** The switch: `true` or `false`, off when unset or empty; any other value stops the server at startup. */
5
+ export declare const readRelaySwitch: (env: Record<string, string | undefined>) => boolean;
6
+ //#endregion
@@ -0,0 +1,24 @@
1
+ import { relaySettings } from "./relay-options.js";
2
+ //#region src/relay/relay-switch.ts
3
+ /** The variable with which a platform that runs the relay moves an app to it. */
4
+ const relaySwitchVariable = "PROTOBASE_RELAY_ENABLED";
5
+ /** The switch: `true` or `false`, off when unset or empty; any other value stops the server at startup. */
6
+ const readRelaySwitch = (env) => {
7
+ const value = env[relaySwitchVariable];
8
+ if (!value) return false;
9
+ if (value !== "true" && value !== "false") throw new Error(`${relaySwitchVariable} must be true or false, not "${value}"`);
10
+ return value === "true";
11
+ };
12
+ /**
13
+ * The app's relay settings, or undefined without a relay: a config's `realtime.relay` turns it on whatever the switch
14
+ * says, with its address and keys defaulting to the platform's variables (`relaySettings`). The switch on without
15
+ * `realtime.relay` stops the server, as the channels and their members come only from the config.
16
+ */
17
+ const appRelaySettings = (declared, env) => {
18
+ const on = readRelaySwitch(env);
19
+ if (declared) return relaySettings(declared, env);
20
+ if (!on) return;
21
+ throw new Error(`${relaySwitchVariable} is true, but the config has no realtime.relay: declare realtime.relay.channels, whose members the relay's channels need`);
22
+ };
23
+ //#endregion
24
+ export { appRelaySettings, readRelaySwitch, relaySwitchVariable };
@@ -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. */
@@ -84,7 +84,7 @@ export declare const webhooksModule: (options?: WebhooksOptions) => {
84
84
  readonly tenant_id: import("@protobase/schema").Field<string | null>;
85
85
  readonly event_type: import("@protobase/schema").Field<string>;
86
86
  readonly event_id: import("@protobase/schema").Field<string>;
87
- readonly status: import("@protobase/schema").Field<"failed" | "waiting">;
87
+ readonly status: import("@protobase/schema").Field<"waiting" | "failed">;
88
88
  readonly attempt: import("@protobase/schema").Field<number>;
89
89
  readonly next_attempt: import("@protobase/schema").Field<string | null>;
90
90
  readonly last_error: import("@protobase/schema").Field<string | null>;
@@ -97,7 +97,7 @@ export declare const webhooksModule: (options?: WebhooksOptions) => {
97
97
  readonly tenant_id: import("@protobase/schema").Field<string | null>;
98
98
  readonly event_type: import("@protobase/schema").Field<string>;
99
99
  readonly event_id: import("@protobase/schema").Field<string>;
100
- readonly status: import("@protobase/schema").Field<"failed" | "waiting">;
100
+ readonly status: import("@protobase/schema").Field<"waiting" | "failed">;
101
101
  readonly attempt: import("@protobase/schema").Field<number>;
102
102
  readonly next_attempt: import("@protobase/schema").Field<string | null>;
103
103
  readonly last_error: import("@protobase/schema").Field<string | null>;
@@ -280,7 +280,7 @@ export declare const workflowsModule: (options?: Pick<WorkflowsOptions, "schema"
280
280
  readonly version: import("@protobase/schema").Field<number | null>;
281
281
  readonly input: import("@protobase/schema").Field<import("zod").JSONType>;
282
282
  readonly key: import("@protobase/schema").Field<string | null>;
283
- readonly status: import("@protobase/schema").Field<"failed" | "queued" | "running" | "waiting" | "succeeded">;
283
+ readonly status: import("@protobase/schema").Field<"waiting" | "failed" | "queued" | "running" | "succeeded">;
284
284
  readonly output: import("@protobase/schema").Field<import("zod").JSONType>;
285
285
  readonly error: import("@protobase/schema").Field<string | null>;
286
286
  readonly cause: import("@protobase/schema").Field<string | null>;
@@ -306,7 +306,7 @@ export declare const workflowsModule: (options?: Pick<WorkflowsOptions, "schema"
306
306
  readonly version: import("@protobase/schema").Field<number | null>;
307
307
  readonly input: import("@protobase/schema").Field<import("zod").JSONType>;
308
308
  readonly key: import("@protobase/schema").Field<string | null>;
309
- readonly status: import("@protobase/schema").Field<"failed" | "queued" | "running" | "waiting" | "succeeded">;
309
+ readonly status: import("@protobase/schema").Field<"waiting" | "failed" | "queued" | "running" | "succeeded">;
310
310
  readonly output: import("@protobase/schema").Field<import("zod").JSONType>;
311
311
  readonly error: import("@protobase/schema").Field<string | null>;
312
312
  readonly cause: import("@protobase/schema").Field<string | null>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@protobase/server",
3
- "version": "0.124.2",
3
+ "version": "0.125.1",
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.2",
48
- "@protobase/query": "0.124.2",
49
- "@protobase/schema": "0.124.2",
50
- "@protobase/workflow-plugins": "0.124.2",
51
- "@protobase/workflows": "0.124.2",
47
+ "@protobase/layout": "0.125.1",
48
+ "@protobase/query": "0.125.1",
49
+ "@protobase/schema": "0.125.1",
50
+ "@protobase/workflow-plugins": "0.125.1",
51
+ "@protobase/workflows": "0.125.1",
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 };