@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
@@ -1,6 +1,17 @@
1
1
  import { stateIn } from "./mail-sender.js";
2
2
  //#region src/personal-mail/listed-mail-senders.ts
3
- const listedSender = (book, row) => {
3
+ const iso = (at) => new Date(at).toISOString();
4
+ const listedVerification = (row) => ({
5
+ verifier: row.verifier,
6
+ state: row.state,
7
+ ...row.state === "pending" && { expiresAt: iso(row.expiresAt) },
8
+ ...row.settledAt && { settledAt: iso(row.settledAt) },
9
+ ...row.validUntil && { validUntil: iso(row.validUntil) },
10
+ ...row.errorCode && { errorCode: row.errorCode },
11
+ ...row.error && { error: row.error }
12
+ });
13
+ /** `row` as the account page lists it, with its latest `verifications` when the app has verifiers. */
14
+ const listedSender = (book, row, verifications) => {
4
15
  const state = stateIn(book, row);
5
16
  if (state === "removed") return;
6
17
  return {
@@ -11,13 +22,14 @@ const listedSender = (book, row) => {
11
22
  isDefault: row.isDefault,
12
23
  state,
13
24
  ...state !== "detached" && row.connectionId && { connection: row.connectionId },
14
- ...row.listedAt && { listedAt: new Date(row.listedAt).toISOString() }
25
+ ...row.listedAt && { listedAt: new Date(row.listedAt).toISOString() },
26
+ ...verifications && { verifications: verifications.filter(({ senderId }) => senderId === row.id).map(listedVerification) }
15
27
  };
16
28
  };
17
- /** The person's addresses and connections, as `GET /account/mail-senders` answers them. */
18
- const listedMailSenders = (book) => ({
29
+ /** The person's addresses and connections, as `GET /account/mail-senders` answers them, with their latest `verifications` when the app has verifiers. */
30
+ const listedMailSenders = (book, verifications) => ({
19
31
  ...book.ownAddress && { address: book.ownAddress },
20
- senders: book.rows.flatMap((row) => listedSender(book, row) ?? []),
32
+ senders: book.rows.flatMap((row) => listedSender(book, row, verifications) ?? []),
21
33
  connections: book.connections.map(({ account, provider }) => ({
22
34
  id: account.id,
23
35
  provider: provider.id,
@@ -27,4 +39,4 @@ const listedMailSenders = (book) => ({
27
39
  }))
28
40
  });
29
41
  //#endregion
30
- export { listedMailSenders, listedSender };
42
+ export { listedMailSenders, listedSender, listedVerification };
@@ -1,3 +1,4 @@
1
+ import "./verifiers/verification-store.js";
1
2
  import "./sender-store.js";
2
3
  import { SenderAddressState } from "./sender-address-state.js";
3
4
  import "./mailbox-connections.js";
@@ -4,7 +4,7 @@ import { senderRowState } from "./sender-address-state.js";
4
4
  //#region src/personal-mail/mail-sender.ts
5
5
  const connected = (book, row) => book.connections.some(({ account }) => account.id === row.connectionId);
6
6
  /** The state of a row of `book`'s (`senderRowState`). */
7
- const stateIn = (book, row) => senderRowState(row, connected(book, row));
7
+ const stateIn = (book, row) => senderRowState(row, connected(book, row), book.proofs?.find(({ senderId }) => senderId === row.id)?.settledAt);
8
8
  /** The rows a person may choose: neither removed nor detached, oldest first. */
9
9
  const usableRows = (book) => book.rows.flatMap((row) => {
10
10
  const state = stateIn(book, row);
@@ -1,11 +1,13 @@
1
1
  import { senderAddressInput } from "./sender-address-input.js";
2
2
  import { isRemoved } from "./sender-address-state.js";
3
+ import { stateIn } from "./mail-sender.js";
3
4
  import { linkedMailbox } from "./personal-mailer.js";
4
5
  import { headersLocale } from "../locale/request-locale.js";
5
6
  import { storeSqlOf } from "../better-auth/store/store-sql.js";
6
7
  import { linkedAccountsOf, senderBook } from "./mail-sender-book.js";
7
- import { listedMailSenders, listedSender } from "./listed-mail-senders.js";
8
+ import { listedMailSenders, listedSender, listedVerification } from "./listed-mail-senders.js";
8
9
  import { mailSenderModel, sqlSenderStore } from "./sender-store.js";
10
+ import { reportEndpoint } from "./verifiers/report-endpoint.js";
9
11
  import * as z$1 from "zod";
10
12
  import { APIError, createAuthEndpoint, createAuthMiddleware, getSessionFromCtx, sessionMiddleware } from "better-auth/api";
11
13
  //#region src/personal-mail/mail-senders-plugin.ts
@@ -16,8 +18,7 @@ const mailSenderPaths = {
16
18
  update: "/account/mail-senders/update",
17
19
  remove: "/account/mail-senders/remove",
18
20
  refresh: "/account/mail-senders/refresh",
19
- check: "/account/mail-senders/check",
20
- checkResult: "/account/mail-senders/check-result"
21
+ verify: "/account/mail-senders/verify"
21
22
  };
22
23
  /** The longest signature, in characters: a closing and a few lines of contact details. */
23
24
  const maxSignatureLength = 2e3;
@@ -41,15 +42,22 @@ const unlinkPath = "/unlink-account";
41
42
  const signatureField = z$1.string().max(maxSignatureLength).transform((value) => value.trim() ? value : null);
42
43
  const nameField = z$1.string().max(100).regex(/^[^\r\n]*$/).transform((value) => value.trim() || null);
43
44
  const idField = z$1.string().min(1).max(200);
44
- const bookOf = async (ctx, providers) => {
45
+ const bookOf = async (ctx, providers, verifications) => {
45
46
  const userId = ctx.context.session.user.id;
46
47
  const store = sqlSenderStore(async () => storeSqlOf(ctx.context));
47
- const [rows, accounts] = await Promise.all([store.ofUser(userId), ctx.context.internalAdapter.findAccounts(userId)]);
48
+ const [rows, accounts, proofs] = await Promise.all([
49
+ store.ofUser(userId),
50
+ ctx.context.internalAdapter.findAccounts(userId),
51
+ verifications ? verifications.proofsOf(userId) : []
52
+ ]);
48
53
  return {
49
54
  userId,
50
55
  store,
51
56
  accounts,
52
- book: senderBook(userId, rows, accounts, providers)
57
+ book: {
58
+ ...senderBook(userId, rows, accounts, providers),
59
+ proofs
60
+ }
53
61
  };
54
62
  };
55
63
  const ownRow = (rows, id) => {
@@ -70,12 +78,12 @@ const ownRow = (rows, id) => {
70
78
  * the app hold an address (`inUse`), removing it, or disconnecting the mailbox whose own address it is
71
79
  * (`/unlink-account`), is refused with a 409, and changes nothing.
72
80
  *
73
- * With `checks`, the list says `checks: true`, and `POST /account/mail-senders/check { id }` sends a test message from
74
- * one of the person's addresses through their mailbox and answers `{ status: 'waiting', check }`; `POST
75
- * /account/mail-senders/check-result { id, check }` answers where it stands (`AliasCheckResult`). Without, the check
76
- * answers `{ status: 'unchecked' }` and sends nothing.
81
+ * With the app's `verifications` (`add_verifier`), the list says `verifiers: true` and gives each address its latest
82
+ * verification by each verifier; `POST /account/mail-senders/verify { id }` starts every verifier on one of the
83
+ * person's addresses on a connection they can send through, and answers that address's `verifications`; and
84
+ * `POST /mail-sender-verifications/report` settles one from outside (`reportEndpoint`). Without, neither path exists.
77
85
  */
78
- const mailSendersPlugin = (providers, names, mailOf, inUse, checks) => ({
86
+ const mailSendersPlugin = (providers, names, mailOf, inUse, verifications) => ({
79
87
  id: "protobase-mail-senders",
80
88
  schema: names.tables(mailSenderModel),
81
89
  hooks: { before: [{
@@ -93,10 +101,11 @@ const mailSendersPlugin = (providers, names, mailOf, inUse, checks) => ({
93
101
  method: "GET",
94
102
  use: [sessionMiddleware]
95
103
  }, async (ctx) => {
96
- const { book } = await bookOf(ctx, providers);
104
+ const { userId, book } = await bookOf(ctx, providers, verifications);
105
+ const latest = verifications ? await verifications.latestOf(userId) : void 0;
97
106
  return ctx.json({
98
- ...listedMailSenders(book),
99
- checks: Boolean(checks)
107
+ ...listedMailSenders(book, latest),
108
+ verifiers: Boolean(verifications)
100
109
  });
101
110
  }),
102
111
  addMailSender: createAuthEndpoint(mailSenderPaths.add, {
@@ -109,7 +118,7 @@ const mailSendersPlugin = (providers, names, mailOf, inUse, checks) => ({
109
118
  connection: idField.optional()
110
119
  })
111
120
  }, async (ctx) => {
112
- const { userId, store, book } = await bookOf(ctx, providers);
121
+ const { userId, store, book } = await bookOf(ctx, providers, verifications);
113
122
  const { address, name = null, signature = null, connection } = ctx.body;
114
123
  const chosen = connection === void 0 ? linkedMailbox(book.connections.map(({ account }) => account), providers) : book.connections.find(({ account }) => account.id === connection);
115
124
  if (!chosen) throw new APIError(connection === void 0 ? "BAD_REQUEST" : "NOT_FOUND", noMailbox);
@@ -138,7 +147,7 @@ const mailSendersPlugin = (providers, names, mailOf, inUse, checks) => ({
138
147
  isDefault: z$1.boolean().optional()
139
148
  })
140
149
  }, async (ctx) => {
141
- const { userId, store, book } = await bookOf(ctx, providers);
150
+ const { userId, store, book } = await bookOf(ctx, providers, verifications);
142
151
  const { id, isDefault, ...update } = ctx.body;
143
152
  ownRow(book.rows, id);
144
153
  if (isDefault === true) await store.clearDefault(userId);
@@ -167,36 +176,25 @@ const mailSendersPlugin = (providers, names, mailOf, inUse, checks) => ({
167
176
  const connections = await mailOf(ctx.context.session.user.id).refresh();
168
177
  return ctx.json({ connections });
169
178
  }),
170
- checkMailSender: createAuthEndpoint(mailSenderPaths.check, {
171
- method: "POST",
172
- use: [sessionMiddleware],
173
- body: z$1.object({ id: idField })
174
- }, async (ctx) => {
175
- const { userId, book } = await bookOf(ctx, providers);
176
- const row = ownRow(book.rows, ctx.body.id);
177
- if (!checks) return ctx.json({ status: "unchecked" });
178
- const check = await checks.start(userId, {
179
- id: row.id,
180
- address: row.address
181
- }, headersLocale(ctx.headers));
182
- return ctx.json({
183
- status: "waiting",
184
- check
185
- });
186
- }),
187
- checkMailSenderResult: createAuthEndpoint(mailSenderPaths.checkResult, {
188
- method: "POST",
189
- use: [sessionMiddleware],
190
- body: z$1.object({
191
- id: idField,
192
- check: z$1.string().min(1).max(200)
193
- })
194
- }, async (ctx) => {
195
- const { book } = await bookOf(ctx, providers);
196
- const row = ownRow(book.rows, ctx.body.id);
197
- if (!checks) return ctx.json({ status: "unchecked" });
198
- return ctx.json(await checks.result(ctx.body.check, row.address));
199
- })
179
+ ...verifications && {
180
+ verifyMailSender: createAuthEndpoint(mailSenderPaths.verify, {
181
+ method: "POST",
182
+ use: [sessionMiddleware],
183
+ body: z$1.object({ id: idField })
184
+ }, async (ctx) => {
185
+ const { userId, book } = await bookOf(ctx, providers, verifications);
186
+ const row = ownRow(book.rows, ctx.body.id);
187
+ if (stateIn(book, row) === "detached") throw new APIError("NOT_FOUND", notFound);
188
+ await verifications.start(userId, {
189
+ id: row.id,
190
+ address: row.address,
191
+ name: row.name
192
+ }, headersLocale(ctx.headers));
193
+ const latest = await verifications.latestOf(userId);
194
+ return ctx.json({ verifications: latest.filter(({ senderId }) => senderId === row.id).map(listedVerification) });
195
+ }),
196
+ reportMailSenderVerification: reportEndpoint(verifications)
197
+ }
200
198
  }
201
199
  });
202
200
  //#endregion
@@ -37,13 +37,18 @@ const personalMailer = (accounts, providers, senders, userId, now = () => /* @__
37
37
  now
38
38
  };
39
39
  const bookOf = async () => {
40
- const [rows, linked] = await Promise.all([senders.ofUser(userId), accounts.accounts(userId)]);
40
+ const [rows, linked, proofs] = await Promise.all([
41
+ senders.ofUser(userId),
42
+ accounts.accounts(userId),
43
+ senders.proofsOf ? senders.proofsOf(userId) : []
44
+ ]);
41
45
  const ownAddress = linkedMailbox(linked, providers)?.account.address;
42
46
  return {
43
47
  userId,
44
48
  rows,
45
49
  connections: mailboxConnections(linked, providers),
46
- ...ownAddress && { ownAddress }
50
+ ...ownAddress && { ownAddress },
51
+ proofs
47
52
  };
48
53
  };
49
54
  const sendThrough = async ({ account, provider }, message, row) => {
@@ -4,17 +4,20 @@ const isRemoved = ({ removedAt, typedAt }) => removedAt !== null && (typedAt ===
4
4
  /** Whether a listing read the address after its owner last removed it: an older listing no longer counts. */
5
5
  const hasListing = ({ providerStateReadAt, removedAt }) => providerStateReadAt !== null && (removedAt === null || providerStateReadAt > removedAt);
6
6
  /**
7
- * The state of `row`, with `connected` whether its connection is still one of its owner's that can send. Only a
8
- * provider state of `verified` or `pending` makes a claim: any other value, as an unknown one, makes none.
7
+ * The state of `row`, with `connected` whether its connection is still one of its owner's that can send, and `provedAt`
8
+ * when a verifier last proved it, by a verification that still counts. Only a provider state of `verified` or
9
+ * `pending` makes a claim: any other value, as an unknown one, makes none. Where the provider makes none, a proof since
10
+ * the address was last removed makes it `verified`; it never outweighs what the provider says.
9
11
  */
10
- const senderRowState = (row, connected) => {
12
+ const senderRowState = (row, connected, provedAt) => {
11
13
  if (isRemoved(row)) return "removed";
12
14
  if (!connected) return "detached";
13
- if (!hasListing(row)) return "unverified";
15
+ const proved = provedAt !== void 0 && (row.removedAt === null || provedAt > row.removedAt);
16
+ if (!hasListing(row)) return proved ? "verified" : "unverified";
14
17
  if (row.listedAt === null) return "failed";
15
18
  if (row.providerState === "verified") return "verified";
16
19
  if (row.providerState === "pending") return "pending";
17
- return "unverified";
20
+ return proved ? "verified" : "unverified";
18
21
  };
19
22
  //#endregion
20
23
  export { hasListing, isRemoved, senderRowState };
@@ -1 +1,2 @@
1
- import "../better-auth/store/store-sql.js";
1
+ import "../better-auth/store/store-sql.js";
2
+ import "./verifiers/verification-store.js";
@@ -0,0 +1,40 @@
1
+ import { settledOutcome, validOutcome } from "./verification-outcome.js";
2
+ import * as z$1 from "zod";
3
+ import { APIError, createAuthEndpoint } from "better-auth/api";
4
+ //#region src/personal-mail/verifiers/report-endpoint.ts
5
+ /** Where a verifier's outside service settles a verification, under the auth base path. */
6
+ const reportVerificationPath = "/mail-sender-verifications/report";
7
+ /**
8
+ * The one answer to every report that settles nothing: a missing or wrong secret, another verifier's, one that settled
9
+ * or expired. It says nothing of whether the verification exists or what it is.
10
+ */
11
+ const reportRefused = {
12
+ code: "VERIFICATION_REFUSED",
13
+ message: "This report is not accepted."
14
+ };
15
+ const invalid = {
16
+ code: "INVALID_VERIFICATION_OUTCOME",
17
+ message: "The outcome is not valid."
18
+ };
19
+ const body = settledOutcome.and(z$1.object({
20
+ verifier: z$1.string().max(64),
21
+ secret: z$1.string().max(256).optional()
22
+ }));
23
+ /**
24
+ * `POST /api/auth/mail-sender-verifications/report { verifier, secret, state, valid_until | error_code, error? }`:
25
+ * settles the pending verification whose secret the JSON body gives, as `verifier`, the one that started it, reports.
26
+ * No session is needed or used: the secret alone admits it, read from the body only. A malformed outcome answers 400
27
+ * before anything is looked up; every other report that settles nothing answers the same 403 (`reportRefused`).
28
+ */
29
+ const reportEndpoint = (verifications) => createAuthEndpoint(reportVerificationPath, {
30
+ method: "POST",
31
+ body
32
+ }, async (ctx) => {
33
+ const { verifier, secret, ...given } = ctx.body;
34
+ const outcome = validOutcome(given, /* @__PURE__ */ new Date(), false);
35
+ if (!outcome || outcome.state === "pending") throw new APIError("BAD_REQUEST", invalid);
36
+ if (!await verifications.report(verifier, secret, outcome)) throw new APIError("FORBIDDEN", reportRefused);
37
+ return ctx.json({ settled: true });
38
+ });
39
+ //#endregion
40
+ export { reportEndpoint, reportRefused, reportVerificationPath };
@@ -0,0 +1,62 @@
1
+ import { Locale } from "@protobase/schema/internal";
2
+ //#region src/personal-mail/verifiers/sender-address-verifier.d.ts
3
+ /** The From address a verification proves, as a verifier reads it. */
4
+ export type VerificationInput = {
5
+ /** The verification's own record id: readable, never a credential. */
6
+ verification_id: string;
7
+ address: string;
8
+ name?: string;
9
+ };
10
+ /**
11
+ * What `verify` is given besides the address: `secret`, at least 128 random bits minted for this verification alone,
12
+ * the only credential that settles it through `POST /api/auth/mail-sender-verifications/report`. The app keeps only its
13
+ * hash, so it is never handed out again. `locale`: the language of the person who asked, for the test message.
14
+ */
15
+ export type VerifyInput = VerificationInput & {
16
+ secret: string;
17
+ locale: Locale;
18
+ };
19
+ /** A test message: always one recipient, sent through the address's own mailbox, From that address. */
20
+ export type VerificationMessage = {
21
+ to: string;
22
+ subject: string;
23
+ text: string;
24
+ html?: string;
25
+ };
26
+ export type VerifyTools = {
27
+ /** Sends one test message; a second send in the same `verify` is refused. */
28
+ send: (message: VerificationMessage) => Promise<void>;
29
+ };
30
+ /**
31
+ * Where a verification stands after `verify` or `check`: `pending` until `expires_at` (required from `verify`, which the
32
+ * app caps at 24 hours after the verification started; `check` cannot move it), checked again at `check_after`, a
33
+ * minute on at the soonest (default a minute on); `verified` until `valid_until` (required, capped at 28 days); `failed` with an `error_code`
34
+ * such as `from_rewritten`, and an optional `error` text of at most 500 characters, shown as plain text.
35
+ */
36
+ export type VerificationOutcome = {
37
+ state: 'pending';
38
+ expires_at?: Date;
39
+ check_after?: Date;
40
+ } | {
41
+ state: 'verified';
42
+ valid_until: Date;
43
+ } | {
44
+ state: 'failed';
45
+ error_code: string;
46
+ error?: string;
47
+ };
48
+ /**
49
+ * A way to prove that mail from a From address goes out from it, which the app's own trusted code plugs in with
50
+ * `add_verifier`, such as a hosting platform's test-mail check. `id` is stored on each verification, so it stays the
51
+ * same across releases. `verify` starts one, and may send a single test message with `tools.send`; `check`, when given,
52
+ * is called by the app's sweep each minute a verification is due, until it settles or expires. A verification can also
53
+ * be settled from outside with its secret (see `VerifyInput`).
54
+ */
55
+ export type SenderAddressVerifier = {
56
+ id: string;
57
+ verify: (input: VerifyInput, tools: VerifyTools) => Promise<VerificationOutcome>;
58
+ check?: (input: VerificationInput) => Promise<VerificationOutcome>;
59
+ };
60
+ /** Registers a verifier: from the project's `auth/hooks.ts` `senderVerifiers`, or the host's runtime. */
61
+ export type AddVerifier = (verifier: SenderAddressVerifier) => void;
62
+ //#endregion
@@ -0,0 +1,6 @@
1
+ import "./sender-address-verifier.js";
2
+ import "./verification-store.js";
3
+ import "../personal-mailer.js";
4
+ import "./start-verification.js";
5
+ import "../../index.js";
6
+ import { Locale } from "@protobase/schema/internal";
@@ -0,0 +1,28 @@
1
+ import { secretHash } from "./verification-secret.js";
2
+ import { startVerification } from "./start-verification.js";
3
+ import { verificationSweepJob } from "./verification-sweep.js";
4
+ //#region src/personal-mail/verifiers/sender-verifications.ts
5
+ /**
6
+ * The app's verifiers at work: `start` runs each on an address of `userId`'s through their own mailbox; `report`
7
+ * settles the verification whose secret it gives, only for the verifier that started it, answering whether it did;
8
+ * `latestOf` and `proofsOf` read what they found; `jobs` holds the sweep.
9
+ */
10
+ const senderVerifications = (verifiers, store, mailOf) => {
11
+ const ids = verifiers.map(({ id }) => id);
12
+ return {
13
+ ids,
14
+ start: async (userId, sender, locale) => {
15
+ const mail = mailOf(userId);
16
+ for (const verifier of verifiers) await startVerification(verifier, store, mail, sender, locale);
17
+ },
18
+ report: async (verifier, secret, outcome) => {
19
+ if (!secret || !ids.includes(verifier)) return false;
20
+ return store.settle({ secretHash: await secretHash(secret) }, verifier, outcome);
21
+ },
22
+ latestOf: (userId) => store.latestOf(userId, ids),
23
+ proofsOf: (userId) => store.proofsOf(userId, ids),
24
+ jobs: [verificationSweepJob(verifiers, store)]
25
+ };
26
+ };
27
+ //#endregion
28
+ export { senderVerifications };
@@ -0,0 +1,4 @@
1
+ import "./sender-address-verifier.js";
2
+ import "./verification-store.js";
3
+ import "../personal-mailer.js";
4
+ import { Locale } from "@protobase/schema/internal";
@@ -0,0 +1,34 @@
1
+ import { validOutcome, verifierError } from "./verification-outcome.js";
2
+ import { mintSecret, secretHash } from "./verification-secret.js";
3
+ import { verifyTools } from "./verify-tools.js";
4
+ //#region src/personal-mail/verifiers/start-verification.ts
5
+ const failedVerify = {
6
+ state: "failed",
7
+ error_code: verifierError
8
+ };
9
+ /**
10
+ * Starts a verification of `sender` by `verifier`, unless one is pending already: a pending one whose time ran out,
11
+ * as when its `verify` never returned, fails as expired first, so this one takes its place. The verification is
12
+ * stored before `verify` runs, so two starts at once run one `verify`. Its outcome is recorded; an invalid one, or a
13
+ * throw, fails the verification as `verifier_error`, and the throw goes on to the caller.
14
+ */
15
+ const startVerification = async (verifier, store, mail, sender, locale) => {
16
+ await store.expireOverdue(sender.id, verifier.id);
17
+ const secret = mintSecret();
18
+ const id = await store.start(sender.id, verifier.id, await secretHash(secret));
19
+ if (!id) return;
20
+ const input = {
21
+ verification_id: id,
22
+ address: sender.address,
23
+ ...sender.name && { name: sender.name },
24
+ secret,
25
+ locale
26
+ };
27
+ const outcome = await verifier.verify(input, verifyTools(mail, sender.id)).catch(async (error) => {
28
+ await store.settle({ id }, verifier.id, failedVerify);
29
+ throw error;
30
+ });
31
+ await store.settle({ id }, verifier.id, validOutcome(outcome, /* @__PURE__ */ new Date(), true) ?? failedVerify, true);
32
+ };
33
+ //#endregion
34
+ export { startVerification };
@@ -0,0 +1,49 @@
1
+ import * as z$1 from "zod";
2
+ /** How long a verification may stay pending, from when it started. */
3
+ const maxPendingMs = 864e5;
4
+ /** How long a verified outcome may count, from when it settled: four weeks, so an address is proved again each month. */
5
+ const maxValidMs = 24192e5;
6
+ /** How long a started verification waits for `verify`'s first outcome before the next verify supersedes it. */
7
+ const verifyLeaseMs = 3e5;
8
+ /** How long the sweep waits before checking a pending verification again, when its verifier names no time. */
9
+ const checkIntervalMs = 6e4;
10
+ /** The codes the app settles a verification with itself: it ran out of time, or its verifier failed or answered nothing valid. */
11
+ const verificationExpired = "verification_expired";
12
+ const verifierError = "verifier_error";
13
+ const time = z$1.union([z$1.date(), z$1.iso.datetime({ offset: true })]).transform((value) => new Date(value));
14
+ const errorText = z$1.string().max(500).regex(/^[^\u0000-\u0008\u000b-\u001f\u007f]*$/);
15
+ const verified = z$1.object({
16
+ state: z$1.literal("verified"),
17
+ valid_until: time
18
+ });
19
+ const failed = z$1.object({
20
+ state: z$1.literal("failed"),
21
+ error_code: z$1.string().regex(/^[a-z][a-z0-9_]{0,63}$/),
22
+ error: errorText.optional()
23
+ });
24
+ const pending = z$1.object({
25
+ state: z$1.literal("pending"),
26
+ expires_at: time.optional(),
27
+ check_after: time.optional()
28
+ });
29
+ /** A settling outcome, as a report states it. */
30
+ const settledOutcome = z$1.discriminatedUnion("state", [verified, failed]);
31
+ const anyOutcome = z$1.discriminatedUnion("state", [
32
+ pending,
33
+ verified,
34
+ failed
35
+ ]);
36
+ /**
37
+ * `value` as a valid outcome of `verify` (`first`, whose pending outcome must name `expires_at`) or `check`, or none.
38
+ * A `valid_until` must lie after `now`. Longer error text is refused, never cut short.
39
+ */
40
+ const validOutcome = (value, now, first) => {
41
+ const parsed = anyOutcome.safeParse(value);
42
+ if (!parsed.success) return;
43
+ const outcome = parsed.data;
44
+ if (outcome.state === "pending" && first && !outcome.expires_at) return;
45
+ if (outcome.state === "verified" && outcome.valid_until <= now) return;
46
+ return outcome;
47
+ };
48
+ //#endregion
49
+ export { checkIntervalMs, maxPendingMs, maxValidMs, settledOutcome, validOutcome, verificationExpired, verifierError, verifyLeaseMs };
@@ -0,0 +1,8 @@
1
+ import { sha256Hex } from "../../hash.js";
2
+ //#region src/personal-mail/verifiers/verification-secret.ts
3
+ /** A new verification's secret: 256 random bits, base64url, from the platform's CSPRNG. */
4
+ const mintSecret = () => Buffer.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32))).toString("base64url");
5
+ /** What a verification keeps of its secret: its SHA-256, so a read of the store cannot settle one. */
6
+ const secretHash = (secret) => sha256Hex(secret);
7
+ //#endregion
8
+ export { mintSecret, secretHash };
@@ -0,0 +1,17 @@
1
+ import "../../better-auth/store/store-sql.js";
2
+ import "./sender-address-verifier.js";
3
+ //#region src/personal-mail/verifiers/verification-store.d.ts
4
+ /** A verification as the app reads it back: never its secret's hash. */
5
+ export type VerificationRow = {
6
+ id: string;
7
+ senderId: string;
8
+ verifier: string;
9
+ state: 'pending' | 'verified' | 'failed';
10
+ createdAt: Date;
11
+ expiresAt: Date;
12
+ settledAt: Date | null;
13
+ validUntil: Date | null;
14
+ errorCode: string | null;
15
+ error: string | null;
16
+ };
17
+ //#endregion