@protobase/server 0.124.2 → 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.
- package/dist/better-auth/auth-settings.d.ts +56 -70
- package/dist/better-auth/auth-settings.js +6 -1
- package/dist/better-auth/create-auth.d.ts +59 -69
- package/dist/better-auth/create-auth.js +15 -11
- package/dist/better-auth/names/modules/index.d.ts +83 -0
- package/dist/better-auth/names/modules/mail-senders.js +130 -69
- package/dist/better-auth/staff-checks.js +1 -1
- package/dist/better-auth/store/steps/index.js +3 -1
- package/dist/better-auth/store/steps/legacy-versions.js +4 -0
- package/dist/better-auth/store/steps/mail-senders/004-sender-verifications.js +41 -0
- package/dist/create-admin.js +1 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -3
- package/dist/locale/en.js +1 -5
- package/dist/locale/nl.js +1 -5
- package/dist/package.js +1 -1
- package/dist/personal-mail/listed-mail-senders.d.ts +16 -0
- package/dist/personal-mail/listed-mail-senders.js +18 -6
- package/dist/personal-mail/mail-sender.d.ts +1 -0
- package/dist/personal-mail/mail-sender.js +1 -1
- package/dist/personal-mail/mail-senders-plugin.js +44 -46
- package/dist/personal-mail/personal-mailer.js +7 -2
- package/dist/personal-mail/sender-address-state.js +8 -5
- package/dist/personal-mail/sender-store.d.ts +2 -1
- package/dist/personal-mail/verifiers/report-endpoint.js +40 -0
- package/dist/personal-mail/verifiers/sender-address-verifier.d.ts +62 -0
- package/dist/personal-mail/verifiers/sender-verifications.d.ts +6 -0
- package/dist/personal-mail/verifiers/sender-verifications.js +28 -0
- package/dist/personal-mail/verifiers/start-verification.d.ts +4 -0
- package/dist/personal-mail/verifiers/start-verification.js +34 -0
- package/dist/personal-mail/verifiers/verification-outcome.js +49 -0
- package/dist/personal-mail/verifiers/verification-secret.js +8 -0
- package/dist/personal-mail/verifiers/verification-store.d.ts +17 -0
- package/dist/personal-mail/verifiers/verification-store.js +130 -0
- package/dist/personal-mail/verifiers/verification-sweep.js +45 -0
- package/dist/personal-mail/verifiers/verifier-list.js +26 -0
- package/dist/personal-mail/verifiers/verify-tools.js +30 -0
- package/dist/webhooks/attempt.js +1 -1
- package/dist/webhooks/table/webhooks-module.d.ts +2 -2
- package/dist/workflows/workflows-module.d.ts +2 -2
- package/package.json +6 -6
- package/dist/personal-mail/alias-checks.d.ts +0 -14
- package/dist/personal-mail/alias-checks.js +0 -29
- package/dist/personal-mail/mail-check-service.js +0 -41
- package/dist/personal-mail/mail-check-settings.js +0 -18
- package/dist/personal-mail/mail-check-signing.d.ts +0 -10
- package/dist/personal-mail/mail-check-signing.js +0 -13
|
@@ -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
|
-
|
|
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([
|
|
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:
|
|
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 `
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
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,
|
|
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
|
-
|
|
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
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
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([
|
|
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
|
|
8
|
-
*
|
|
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
|
-
|
|
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,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,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
|
|
@@ -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 };
|