@drfed/drfed 0.0.0-stage → 0.1.0-dev.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/LICENSE +661 -0
- package/README.md +1198 -2
- package/bin/drfed-account.mjs +20 -0
- package/bin/drfed-migrate.mjs +20 -0
- package/bin/drfed-server.mjs +20 -0
- package/bin/drfed-web.mjs +20 -0
- package/completions/bash/drfed-account +219 -0
- package/completions/bash/drfed-migrate +219 -0
- package/completions/bash/drfed-server +219 -0
- package/completions/bash/drfed-web +219 -0
- package/completions/fish/drfed-account.fish +264 -0
- package/completions/fish/drfed-migrate.fish +264 -0
- package/completions/fish/drfed-server.fish +264 -0
- package/completions/fish/drfed-web.fish +264 -0
- package/completions/nu/drfed-account.nu +293 -0
- package/completions/nu/drfed-migrate.nu +293 -0
- package/completions/nu/drfed-server.nu +293 -0
- package/completions/nu/drfed-web.nu +293 -0
- package/completions/pwsh/drfed-account.ps1 +183 -0
- package/completions/pwsh/drfed-migrate.ps1 +183 -0
- package/completions/pwsh/drfed-server.ps1 +183 -0
- package/completions/pwsh/drfed-web.ps1 +183 -0
- package/completions/zsh/_drfed-account +145 -0
- package/completions/zsh/_drfed-migrate +145 -0
- package/completions/zsh/_drfed-server +145 -0
- package/completions/zsh/_drfed-web +145 -0
- package/dist/api-mail-parser.d.mts +106 -0
- package/dist/api-mail-parser.d.mts.map +1 -0
- package/dist/api-mail-parser.mjs +145 -0
- package/dist/api-mail-parser.mjs.map +1 -0
- package/dist/api-mail-settings-BcGaqQ9f.d.mts +142 -0
- package/dist/api-mail-settings-BcGaqQ9f.d.mts.map +1 -0
- package/dist/api-mail-settings.d.mts +2 -0
- package/dist/api-mail-settings.mjs +272 -0
- package/dist/api-mail-settings.mjs.map +1 -0
- package/dist/bounded-mail-runtime.d.mts +9 -0
- package/dist/bounded-mail-runtime.d.mts.map +1 -0
- package/dist/bounded-mail-runtime.mjs +66 -0
- package/dist/bounded-mail-runtime.mjs.map +1 -0
- package/dist/commands/account-create.d.mts +37 -0
- package/dist/commands/account-create.d.mts.map +1 -0
- package/dist/commands/account-create.mjs +87 -0
- package/dist/commands/account-create.mjs.map +1 -0
- package/dist/commands/account-program.d.mts +223 -0
- package/dist/commands/account-program.d.mts.map +1 -0
- package/dist/commands/account-program.mjs +116 -0
- package/dist/commands/account-program.mjs.map +1 -0
- package/dist/commands/account.d.mts +6 -0
- package/dist/commands/account.d.mts.map +1 -0
- package/dist/commands/account.mjs +91 -0
- package/dist/commands/account.mjs.map +1 -0
- package/dist/commands/migrate-program.d.mts +219 -0
- package/dist/commands/migrate-program.d.mts.map +1 -0
- package/dist/commands/migrate-program.mjs +116 -0
- package/dist/commands/migrate-program.mjs.map +1 -0
- package/dist/commands/migrate.d.mts +6 -0
- package/dist/commands/migrate.d.mts.map +1 -0
- package/dist/commands/migrate.mjs +85 -0
- package/dist/commands/migrate.mjs.map +1 -0
- package/dist/commands/web-program.d.mts +213 -0
- package/dist/commands/web-program.d.mts.map +1 -0
- package/dist/commands/web-program.mjs +112 -0
- package/dist/commands/web-program.mjs.map +1 -0
- package/dist/commands/web.d.mts +6 -0
- package/dist/commands/web.d.mts.map +1 -0
- package/dist/commands/web.mjs +184 -0
- package/dist/commands/web.mjs.map +1 -0
- package/dist/configuration-DVVF7xNv.d.mts +432 -0
- package/dist/configuration-DVVF7xNv.d.mts.map +1 -0
- package/dist/configuration.d.mts +2 -0
- package/dist/configuration.mjs +469 -0
- package/dist/configuration.mjs.map +1 -0
- package/dist/data-path.d.mts +9 -0
- package/dist/data-path.d.mts.map +1 -0
- package/dist/data-path.mjs +21 -0
- package/dist/data-path.mjs.map +1 -0
- package/dist/database-runtime.d.mts +26 -0
- package/dist/database-runtime.d.mts.map +1 -0
- package/dist/database-runtime.mjs +92 -0
- package/dist/database-runtime.mjs.map +1 -0
- package/dist/database-settings.d.mts +36 -0
- package/dist/database-settings.d.mts.map +1 -0
- package/dist/database-settings.mjs +67 -0
- package/dist/database-settings.mjs.map +1 -0
- package/dist/diagnostics.d.mts +29 -0
- package/dist/diagnostics.d.mts.map +1 -0
- package/dist/diagnostics.mjs +61 -0
- package/dist/diagnostics.mjs.map +1 -0
- package/dist/index.d.mts +5 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +344 -0
- package/dist/index.mjs.map +1 -0
- package/dist/jmap-parser.d.mts +35 -0
- package/dist/jmap-parser.d.mts.map +1 -0
- package/dist/jmap-parser.mjs +42 -0
- package/dist/jmap-parser.mjs.map +1 -0
- package/dist/jmap-runtime.d.mts +10 -0
- package/dist/jmap-runtime.d.mts.map +1 -0
- package/dist/jmap-runtime.mjs +17 -0
- package/dist/jmap-runtime.mjs.map +1 -0
- package/dist/jmap-settings-BXNAF1ep.d.mts +41 -0
- package/dist/jmap-settings-BXNAF1ep.d.mts.map +1 -0
- package/dist/jmap-settings.d.mts +2 -0
- package/dist/jmap-settings.mjs +104 -0
- package/dist/jmap-settings.mjs.map +1 -0
- package/dist/logging.d.mts +33 -0
- package/dist/logging.d.mts.map +1 -0
- package/dist/logging.mjs +56 -0
- package/dist/logging.mjs.map +1 -0
- package/dist/mail-parser-DyI4wuQp.d.mts +246 -0
- package/dist/mail-parser-DyI4wuQp.d.mts.map +1 -0
- package/dist/mail-parser.d.mts +2 -0
- package/dist/mail-parser.mjs +100 -0
- package/dist/mail-parser.mjs.map +1 -0
- package/dist/mail-runtime-YROIQ8up.mjs +314 -0
- package/dist/mail-runtime-YROIQ8up.mjs.map +1 -0
- package/dist/mail-runtime.d.mts +68 -0
- package/dist/mail-runtime.d.mts.map +1 -0
- package/dist/mail-runtime.mjs +2 -0
- package/dist/mail-settings-BD1TQ0rt.mjs +427 -0
- package/dist/mail-settings-BD1TQ0rt.mjs.map +1 -0
- package/dist/mail-settings-DjWMAUaE.d.mts +80 -0
- package/dist/mail-settings-DjWMAUaE.d.mts.map +1 -0
- package/dist/mail-settings.d.mts +2 -0
- package/dist/mail-settings.mjs +2 -0
- package/dist/operations.d.mts +32 -0
- package/dist/operations.d.mts.map +1 -0
- package/dist/operations.mjs +55 -0
- package/dist/operations.mjs.map +1 -0
- package/dist/package-7FOUqcPO.mjs +6 -0
- package/dist/package-7FOUqcPO.mjs.map +1 -0
- package/dist/parser-DGIQTgS7.mjs +178 -0
- package/dist/parser-DGIQTgS7.mjs.map +1 -0
- package/dist/parser-TANGHRjL.d.mts +305 -0
- package/dist/parser-TANGHRjL.d.mts.map +1 -0
- package/dist/postgres-settings.d.mts +20 -0
- package/dist/postgres-settings.d.mts.map +1 -0
- package/dist/postgres-settings.mjs +60 -0
- package/dist/postgres-settings.mjs.map +1 -0
- package/dist/query-logger.d.mts +9 -0
- package/dist/query-logger.d.mts.map +1 -0
- package/dist/query-logger.mjs +17 -0
- package/dist/query-logger.mjs.map +1 -0
- package/dist/resources.d.mts +20 -0
- package/dist/resources.d.mts.map +1 -0
- package/dist/resources.mjs +34 -0
- package/dist/resources.mjs.map +1 -0
- package/dist/secret-source-BeZx72Ue.d.mts +21 -0
- package/dist/secret-source-BeZx72Ue.d.mts.map +1 -0
- package/dist/secret-source.d.mts +2 -0
- package/dist/secret-source.mjs +58 -0
- package/dist/secret-source.mjs.map +1 -0
- package/dist/serving.d.mts +82 -0
- package/dist/serving.d.mts.map +1 -0
- package/dist/serving.mjs +138 -0
- package/dist/serving.mjs.map +1 -0
- package/dist/smtp-settings.d.mts +11 -0
- package/dist/smtp-settings.d.mts.map +1 -0
- package/dist/smtp-settings.mjs +38 -0
- package/dist/smtp-settings.mjs.map +1 -0
- package/dist/valueparser.d.mts +46 -0
- package/dist/valueparser.d.mts.map +1 -0
- package/dist/valueparser.mjs +121 -0
- package/dist/valueparser.mjs.map +1 -0
- package/package.json +275 -3
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
import { resolveSecretSource } from "./secret-source.mjs";
|
|
2
|
+
import { bool } from "@optique/env";
|
|
3
|
+
import { isIP } from "node:net";
|
|
4
|
+
import { domainToASCII } from "node:url";
|
|
5
|
+
//#region src/api-mail-settings.ts
|
|
6
|
+
const priority = {
|
|
7
|
+
default: 0,
|
|
8
|
+
config: 1,
|
|
9
|
+
env: 2,
|
|
10
|
+
cli: 3
|
|
11
|
+
};
|
|
12
|
+
const rank = (input) => input?.value === void 0 ? -1 : priority[input.source];
|
|
13
|
+
/** Validate API token/key contents without exposing them in errors. */
|
|
14
|
+
function validateApiMailCredential(value) {
|
|
15
|
+
if (value === "" || /[^\x21-\x7e]/u.test(value)) throw new Error("Invalid mail API credential.");
|
|
16
|
+
}
|
|
17
|
+
function credential(raw, cwd, provider) {
|
|
18
|
+
const specific = {
|
|
19
|
+
lettermint: ["lettermintApiToken", "lettermintApiTokenFile"],
|
|
20
|
+
maileroo: ["mailerooApiKey", "mailerooApiKeyFile"],
|
|
21
|
+
mailtrap: ["mailtrapApiToken", "mailtrapApiTokenFile"],
|
|
22
|
+
sendgrid: ["sendgridApiKey", "sendgridApiKeyFile"],
|
|
23
|
+
mailgun: ["mailgunApiKey", "mailgunApiKeyFile"],
|
|
24
|
+
plunk: ["plunkApiKey", "plunkApiKeyFile"],
|
|
25
|
+
resend: ["resendApiKey", "resendApiKeyFile"]
|
|
26
|
+
}[provider].map((name, index) => [
|
|
27
|
+
name,
|
|
28
|
+
raw[name],
|
|
29
|
+
index === 1
|
|
30
|
+
]);
|
|
31
|
+
const variants = [
|
|
32
|
+
[
|
|
33
|
+
"mailApiKey",
|
|
34
|
+
raw.mailApiKey,
|
|
35
|
+
false
|
|
36
|
+
],
|
|
37
|
+
[
|
|
38
|
+
"mailApiKeyFile",
|
|
39
|
+
raw.mailApiKeyFile,
|
|
40
|
+
true
|
|
41
|
+
],
|
|
42
|
+
...specific
|
|
43
|
+
];
|
|
44
|
+
const highest = Math.max(...variants.map(([, input]) => rank(input)));
|
|
45
|
+
if (highest < 0) throw new Error(`${provider} requires an API credential.`);
|
|
46
|
+
const winners = variants.filter(([, input]) => rank(input) === highest);
|
|
47
|
+
if (winners.length !== 1) throw new Error("Conflicting mail API credential variants at the same source.");
|
|
48
|
+
const winner = winners[0];
|
|
49
|
+
const secret = resolveSecretSource(winner[2] ? void 0 : winner[1], winner[2] ? winner[1] : void 0, "mail API credential", cwd);
|
|
50
|
+
if (secret === void 0) throw new Error("Missing mail API credential.");
|
|
51
|
+
if (secret.type === "literal") validateApiMailCredential(secret.value);
|
|
52
|
+
return {
|
|
53
|
+
secret,
|
|
54
|
+
sources: Object.fromEntries(variants.map(([name, input]) => [name, name === winner[0] ? input : void 0]))
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
function endpoint(input, provider, fallback) {
|
|
58
|
+
if (input?.value === void 0) return fallback ?? (provider === "lettermint" ? "https://api.lettermint.co" : "https://smtp.maileroo.com/api/v2");
|
|
59
|
+
try {
|
|
60
|
+
const value = new URL(input.value);
|
|
61
|
+
const local = [
|
|
62
|
+
"localhost",
|
|
63
|
+
"127.0.0.1",
|
|
64
|
+
"[::1]"
|
|
65
|
+
].includes(value.hostname);
|
|
66
|
+
if (value.protocol !== "https:" && !(value.protocol === "http:" && local) || value.username !== "" || value.password !== "" || provider === "lettermint" && value.pathname !== "/" || /[?#]/u.test(value.href)) throw new Error();
|
|
67
|
+
return provider === "lettermint" ? value.origin : value.href.replace(/\/+$/u, "");
|
|
68
|
+
} catch {
|
|
69
|
+
throw new Error(provider === "lettermint" ? "Invalid Lettermint base origin; use HTTPS or local loopback HTTP without credentials." : `Invalid ${provider} API endpoint; use HTTPS or local loopback HTTP without credentials, query or fragment.`);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function number(input, fallback, minimum, maximum, field, provider = "lettermint") {
|
|
73
|
+
if (input?.value === void 0) return fallback;
|
|
74
|
+
const value = Number(input.value);
|
|
75
|
+
if (!/^\d+$/u.test(input.value) || !Number.isSafeInteger(value) || value < minimum || value > maximum) throw new Error(`Invalid ${provider === "sendgrid" ? "SendGrid" : provider[0].toUpperCase() + provider.slice(1)} ${field}.`);
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
function mailtrapSettings(raw, auth) {
|
|
79
|
+
const provider = "mailtrap";
|
|
80
|
+
const parsed = bool().parse(raw.mailtrapSandbox?.value ?? "false");
|
|
81
|
+
if (!parsed.success) throw new Error("Invalid Mailtrap sandbox setting.");
|
|
82
|
+
const sandbox = parsed.value;
|
|
83
|
+
const id = raw.mailtrapInboxId?.value;
|
|
84
|
+
if (sandbox && (id === void 0 || !/^[1-9]\d*$/u.test(id) || !Number.isSafeInteger(Number(id)))) throw new Error("Mailtrap sandbox requires a positive decimal inbox ID.");
|
|
85
|
+
const active = sandbox ? "mailtrapSandboxBaseUrl" : "mailtrapSendBaseUrl";
|
|
86
|
+
const inactive = sandbox ? "mailtrapSendBaseUrl" : "mailtrapSandboxBaseUrl";
|
|
87
|
+
const url = endpoint(raw[active], provider, sandbox ? "https://sandbox.api.mailtrap.io" : "https://send.api.mailtrap.io");
|
|
88
|
+
const connection = {
|
|
89
|
+
sandbox,
|
|
90
|
+
...sandbox ? {
|
|
91
|
+
inboxId: id,
|
|
92
|
+
sandboxBaseUrl: url
|
|
93
|
+
} : { sendBaseUrl: url },
|
|
94
|
+
timeout: number(raw.mailtrapTimeout, 3e4, 1, 2147483647, "delivery timeout", provider),
|
|
95
|
+
retries: 0,
|
|
96
|
+
validateSsl: true
|
|
97
|
+
};
|
|
98
|
+
return {
|
|
99
|
+
mail: {
|
|
100
|
+
transport: provider,
|
|
101
|
+
connection,
|
|
102
|
+
credential: auth.secret
|
|
103
|
+
},
|
|
104
|
+
sources: {
|
|
105
|
+
...auth.sources,
|
|
106
|
+
[inactive]: void 0,
|
|
107
|
+
...sandbox ? {} : { mailtrapInboxId: void 0 }
|
|
108
|
+
},
|
|
109
|
+
values: {
|
|
110
|
+
mailtrapSandbox: sandbox,
|
|
111
|
+
[active]: url,
|
|
112
|
+
mailtrapTimeout: connection.timeout,
|
|
113
|
+
...sandbox ? { mailtrapInboxId: id } : {}
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
function mailgunDomain(input) {
|
|
118
|
+
const original = input?.value;
|
|
119
|
+
if (original === void 0 || original === "" || /[\\/:@?#%\s]/u.test(original)) throw new Error("Invalid Mailgun sending domain.");
|
|
120
|
+
const value = domainToASCII(original).toLowerCase().replace(/\.$/u, "");
|
|
121
|
+
if (value.length > 253 || isIP(value) !== 0 || !value.split(".").every((label) => label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(label))) throw new Error("Invalid Mailgun sending domain.");
|
|
122
|
+
return value;
|
|
123
|
+
}
|
|
124
|
+
function mailgunSettings(raw, auth) {
|
|
125
|
+
const region = raw.mailgunRegion?.value ?? "us";
|
|
126
|
+
if (region !== "us" && region !== "eu") throw new Error("Invalid Mailgun region; use us or eu.");
|
|
127
|
+
const connection = {
|
|
128
|
+
domain: mailgunDomain(raw.mailgunDomain),
|
|
129
|
+
region,
|
|
130
|
+
baseUrl: endpoint(raw.mailgunBaseUrl, "mailgun", region === "eu" ? "https://api.eu.mailgun.net/v3" : "https://api.mailgun.net/v3"),
|
|
131
|
+
timeout: number(raw.mailgunTimeout, 3e4, 1, 2147483647, "delivery timeout", "mailgun"),
|
|
132
|
+
retries: 0,
|
|
133
|
+
validateSsl: true,
|
|
134
|
+
tracking: false,
|
|
135
|
+
clickTracking: false,
|
|
136
|
+
openTracking: false
|
|
137
|
+
};
|
|
138
|
+
return {
|
|
139
|
+
mail: {
|
|
140
|
+
transport: "mailgun",
|
|
141
|
+
connection,
|
|
142
|
+
credential: auth.secret
|
|
143
|
+
},
|
|
144
|
+
sources: auth.sources,
|
|
145
|
+
values: {
|
|
146
|
+
mailgunDomain: connection.domain,
|
|
147
|
+
mailgunRegion: region,
|
|
148
|
+
mailgunBaseUrl: connection.baseUrl,
|
|
149
|
+
mailgunTimeout: connection.timeout
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function plunkSettings(raw, auth) {
|
|
154
|
+
const connection = {
|
|
155
|
+
baseUrl: endpoint(raw.plunkBaseUrl, "plunk", "https://next-api.useplunk.com"),
|
|
156
|
+
timeout: number(raw.plunkTimeout, 3e4, 1, 2147483647, "delivery timeout", "plunk"),
|
|
157
|
+
retries: 0,
|
|
158
|
+
validateSsl: true
|
|
159
|
+
};
|
|
160
|
+
return {
|
|
161
|
+
mail: {
|
|
162
|
+
transport: "plunk",
|
|
163
|
+
connection,
|
|
164
|
+
credential: auth.secret
|
|
165
|
+
},
|
|
166
|
+
sources: auth.sources,
|
|
167
|
+
values: {
|
|
168
|
+
plunkBaseUrl: connection.baseUrl,
|
|
169
|
+
plunkTimeout: connection.timeout
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
function resendSettings(raw, auth) {
|
|
174
|
+
const connection = {
|
|
175
|
+
baseUrl: endpoint(raw.resendBaseUrl, "resend", "https://api.resend.com"),
|
|
176
|
+
timeout: number(raw.resendTimeout, 3e4, 1, 2147483647, "delivery timeout", "resend"),
|
|
177
|
+
retries: number(raw.resendRetries, 3, 0, 10, "retries", "resend"),
|
|
178
|
+
validateSsl: true
|
|
179
|
+
};
|
|
180
|
+
return {
|
|
181
|
+
mail: {
|
|
182
|
+
transport: "resend",
|
|
183
|
+
connection,
|
|
184
|
+
credential: auth.secret
|
|
185
|
+
},
|
|
186
|
+
sources: auth.sources,
|
|
187
|
+
values: {
|
|
188
|
+
resendBaseUrl: connection.baseUrl,
|
|
189
|
+
resendTimeout: connection.timeout,
|
|
190
|
+
resendRetries: connection.retries
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
function sendgridSettings(raw, auth) {
|
|
195
|
+
const connection = {
|
|
196
|
+
baseUrl: endpoint(raw.sendgridBaseUrl, "sendgrid", "https://api.sendgrid.com/v3"),
|
|
197
|
+
timeout: number(raw.sendgridTimeout, 3e4, 1, 2147483647, "delivery timeout", "sendgrid"),
|
|
198
|
+
retries: 0,
|
|
199
|
+
validateSsl: true,
|
|
200
|
+
clickTracking: false,
|
|
201
|
+
openTracking: false,
|
|
202
|
+
subscriptionTracking: false,
|
|
203
|
+
googleAnalytics: false
|
|
204
|
+
};
|
|
205
|
+
return {
|
|
206
|
+
mail: {
|
|
207
|
+
transport: "sendgrid",
|
|
208
|
+
connection,
|
|
209
|
+
credential: auth.secret
|
|
210
|
+
},
|
|
211
|
+
sources: auth.sources,
|
|
212
|
+
values: {
|
|
213
|
+
sendgridBaseUrl: connection.baseUrl,
|
|
214
|
+
sendgridTimeout: connection.timeout
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
/** Resolve only the selected API service; credentials remain unopened.
|
|
219
|
+
* @returns Prepared meaning, safe diagnostic values and effective source tags.
|
|
220
|
+
*/
|
|
221
|
+
function resolveApiMailSettings(raw, cwd, provider = "lettermint") {
|
|
222
|
+
const auth = credential(raw, cwd, provider);
|
|
223
|
+
if (provider === "plunk") return plunkSettings(raw, auth);
|
|
224
|
+
if (provider === "resend") return resendSettings(raw, auth);
|
|
225
|
+
if (provider === "sendgrid") return sendgridSettings(raw, auth);
|
|
226
|
+
if (provider === "mailgun") return mailgunSettings(raw, auth);
|
|
227
|
+
if (provider === "mailtrap") return mailtrapSettings(raw, auth);
|
|
228
|
+
if (provider === "maileroo") {
|
|
229
|
+
const connection = {
|
|
230
|
+
baseUrl: endpoint(raw.mailerooBaseUrl, provider),
|
|
231
|
+
timeout: number(raw.mailerooTimeout, 3e4, 1, 2147483647, "delivery timeout", provider),
|
|
232
|
+
retries: 0
|
|
233
|
+
};
|
|
234
|
+
return {
|
|
235
|
+
mail: {
|
|
236
|
+
transport: provider,
|
|
237
|
+
connection,
|
|
238
|
+
credential: auth.secret
|
|
239
|
+
},
|
|
240
|
+
sources: auth.sources,
|
|
241
|
+
values: {
|
|
242
|
+
mailerooBaseUrl: connection.baseUrl,
|
|
243
|
+
mailerooTimeout: connection.timeout
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
if (raw.lettermintRoute?.value === "" || raw.lettermintRoute?.value !== void 0 && /\p{Cc}/u.test(raw.lettermintRoute.value)) throw new Error("Invalid Lettermint route.");
|
|
248
|
+
const connection = {
|
|
249
|
+
baseUrl: endpoint(raw.lettermintBaseUrl, provider),
|
|
250
|
+
timeout: number(raw.lettermintTimeout, 3e4, 1, 2147483647, "delivery timeout"),
|
|
251
|
+
retries: number(raw.lettermintRetries, 3, 0, 10, "retries"),
|
|
252
|
+
...raw.lettermintRoute?.value === void 0 ? {} : { route: raw.lettermintRoute.value }
|
|
253
|
+
};
|
|
254
|
+
return {
|
|
255
|
+
mail: {
|
|
256
|
+
transport: "lettermint",
|
|
257
|
+
connection,
|
|
258
|
+
credential: auth.secret
|
|
259
|
+
},
|
|
260
|
+
sources: auth.sources,
|
|
261
|
+
values: {
|
|
262
|
+
lettermintBaseUrl: connection.baseUrl,
|
|
263
|
+
lettermintTimeout: connection.timeout,
|
|
264
|
+
lettermintRetries: connection.retries,
|
|
265
|
+
lettermintRoute: connection.route
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
//#endregion
|
|
270
|
+
export { resolveApiMailSettings, validateApiMailCredential };
|
|
271
|
+
|
|
272
|
+
//# sourceMappingURL=api-mail-settings.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"api-mail-settings.mjs","names":[],"sources":["../src/api-mail-settings.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { isIP } from \"node:net\";\nimport { domainToASCII } from \"node:url\";\n\nimport { bool } from \"@optique/env\";\nimport type { LettermintConfig } from \"@upyo/lettermint\";\nimport type { MailerooConfig } from \"@upyo/maileroo\";\nimport type { MailgunConfig } from \"@upyo/mailgun\";\nimport type { MailtrapConfig } from \"@upyo/mailtrap\";\nimport type { PlunkConfig } from \"@upyo/plunk\";\nimport type { ResendConfig } from \"@upyo/resend\";\nimport type { SendGridConfig } from \"@upyo/sendgrid\";\n\nimport type { Sourced } from \"./configuration.ts\";\nimport type { RawMailOptions } from \"./mail-parser.ts\";\nimport { type SecretSource, resolveSecretSource } from \"./secret-source.ts\";\n\n/** Selected API service configuration before secret files are opened. */\nexport type ApiMailSettings =\n | {\n readonly transport: \"lettermint\";\n readonly connection: Omit<\n LettermintConfig,\n \"apiToken\" | \"headers\" | \"tag\" | \"metadata\" | \"settings\"\n >;\n readonly credential: SecretSource;\n }\n | {\n readonly transport: \"maileroo\";\n readonly connection: Omit<\n MailerooConfig,\n \"apiKey\" | \"headers\" | \"tracking\" | \"tags\"\n >;\n readonly credential: SecretSource;\n }\n | {\n readonly transport: \"mailtrap\";\n readonly connection: Omit<\n MailtrapConfig,\n \"apiToken\" | \"metadata\" | \"headers\" | \"defaultCategory\" | \"userAgent\"\n >;\n readonly credential: SecretSource;\n }\n | {\n readonly transport: \"mailgun\";\n readonly connection: Omit<\n MailgunConfig,\n \"apiKey\" | \"headers\" | \"tracking\" | \"clickTracking\" | \"openTracking\"\n >;\n readonly credential: SecretSource;\n }\n | {\n readonly transport: \"plunk\";\n readonly connection: Omit<PlunkConfig, \"apiKey\" | \"headers\">;\n readonly credential: SecretSource;\n }\n | {\n readonly transport: \"resend\";\n readonly connection: Omit<ResendConfig, \"apiKey\" | \"headers\">;\n readonly credential: SecretSource;\n }\n | {\n readonly transport: \"sendgrid\";\n readonly connection: Omit<\n SendGridConfig,\n | \"apiKey\"\n | \"headers\"\n | \"clickTracking\"\n | \"openTracking\"\n | \"subscriptionTracking\"\n | \"googleAnalytics\"\n >;\n readonly credential: SecretSource;\n };\n\ntype Input = Sourced<string | undefined> | undefined;\nconst priority = { default: 0, config: 1, env: 2, cli: 3 } as const;\nconst rank = (input: Input) =>\n input?.value === undefined ? -1 : priority[input.source];\n\n/** Validate API token/key contents without exposing them in errors. */\nexport function validateApiMailCredential(value: string) {\n if (value === \"\" || /[^\\x21-\\x7e]/u.test(value)) {\n throw new Error(\"Invalid mail API credential.\");\n }\n}\n\nfunction credential(\n raw: RawMailOptions,\n cwd: string,\n provider: ApiMailSettings[\"transport\"],\n) {\n const names = {\n lettermint: [\"lettermintApiToken\", \"lettermintApiTokenFile\"],\n maileroo: [\"mailerooApiKey\", \"mailerooApiKeyFile\"],\n mailtrap: [\"mailtrapApiToken\", \"mailtrapApiTokenFile\"],\n sendgrid: [\"sendgridApiKey\", \"sendgridApiKeyFile\"],\n mailgun: [\"mailgunApiKey\", \"mailgunApiKeyFile\"],\n plunk: [\"plunkApiKey\", \"plunkApiKeyFile\"],\n resend: [\"resendApiKey\", \"resendApiKeyFile\"],\n } as const;\n const specific = names[provider].map(\n (name, index) => [name, raw[name], index === 1] as const,\n );\n const variants = [\n [\"mailApiKey\", raw.mailApiKey, false],\n [\"mailApiKeyFile\", raw.mailApiKeyFile, true],\n ...specific,\n ] as const;\n const highest = Math.max(...variants.map(([, input]) => rank(input)));\n if (highest < 0) throw new Error(`${provider} requires an API credential.`);\n const winners = variants.filter(([, input]) => rank(input) === highest);\n if (winners.length !== 1) {\n throw new Error(\n \"Conflicting mail API credential variants at the same source.\",\n );\n }\n const winner = winners[0]!;\n const secret = resolveSecretSource(\n winner[2] ? undefined : winner[1],\n winner[2] ? winner[1] : undefined,\n \"mail API credential\",\n cwd,\n );\n if (secret === undefined) throw new Error(\"Missing mail API credential.\");\n if (secret.type === \"literal\") validateApiMailCredential(secret.value);\n const sources: Record<string, Input> = Object.fromEntries(\n variants.map(([name, input]) => [\n name,\n name === winner[0] ? input : undefined,\n ]),\n );\n return { secret, sources };\n}\n\nfunction endpoint(\n input: Input,\n provider: ApiMailSettings[\"transport\"],\n fallback?: string,\n) {\n if (input?.value === undefined) {\n return (\n fallback ??\n (provider === \"lettermint\"\n ? \"https://api.lettermint.co\"\n : \"https://smtp.maileroo.com/api/v2\")\n );\n }\n try {\n const value = new URL(input.value);\n const local = [\"localhost\", \"127.0.0.1\", \"[::1]\"].includes(value.hostname);\n if (\n (value.protocol !== \"https:\" && !(value.protocol === \"http:\" && local)) ||\n value.username !== \"\" ||\n value.password !== \"\" ||\n (provider === \"lettermint\" && value.pathname !== \"/\") ||\n /[?#]/u.test(value.href)\n ) {\n throw new Error();\n }\n return provider === \"lettermint\"\n ? value.origin\n : value.href.replace(/\\/+$/u, \"\");\n } catch {\n throw new Error(\n provider === \"lettermint\"\n ? \"Invalid Lettermint base origin; use HTTPS or local loopback HTTP without credentials.\"\n : `Invalid ${provider} API endpoint; use HTTPS or local loopback HTTP without credentials, query or fragment.`,\n );\n }\n}\n\nfunction number(\n input: Input,\n fallback: number,\n minimum: number,\n maximum: number,\n field: string,\n provider: ApiMailSettings[\"transport\"] = \"lettermint\",\n) {\n if (input?.value === undefined) return fallback;\n const value = Number(input.value);\n if (\n !/^\\d+$/u.test(input.value) ||\n !Number.isSafeInteger(value) ||\n value < minimum ||\n value > maximum\n ) {\n throw new Error(\n `Invalid ${provider === \"sendgrid\" ? \"SendGrid\" : provider[0]!.toUpperCase() + provider.slice(1)} ${field}.`,\n );\n }\n return value;\n}\n\nfunction mailtrapSettings(\n raw: RawMailOptions,\n auth: ReturnType<typeof credential>,\n) {\n const provider = \"mailtrap\" as const;\n const parsed = bool().parse(raw.mailtrapSandbox?.value ?? \"false\");\n if (!parsed.success) throw new Error(\"Invalid Mailtrap sandbox setting.\");\n const sandbox = parsed.value;\n const id = raw.mailtrapInboxId?.value;\n if (\n sandbox &&\n (id === undefined ||\n !/^[1-9]\\d*$/u.test(id) ||\n !Number.isSafeInteger(Number(id)))\n ) {\n throw new Error(\"Mailtrap sandbox requires a positive decimal inbox ID.\");\n }\n const active = sandbox ? \"mailtrapSandboxBaseUrl\" : \"mailtrapSendBaseUrl\";\n const inactive = sandbox ? \"mailtrapSendBaseUrl\" : \"mailtrapSandboxBaseUrl\";\n const url = endpoint(\n raw[active],\n provider,\n sandbox\n ? \"https://sandbox.api.mailtrap.io\"\n : \"https://send.api.mailtrap.io\",\n );\n const connection = {\n sandbox,\n ...(sandbox ? { inboxId: id!, sandboxBaseUrl: url } : { sendBaseUrl: url }),\n timeout: number(\n raw.mailtrapTimeout,\n 30000,\n 1,\n 2147483647,\n \"delivery timeout\",\n provider,\n ),\n retries: 0,\n validateSsl: true,\n };\n const mail: ApiMailSettings = {\n transport: provider,\n connection,\n credential: auth.secret,\n };\n return {\n mail,\n sources: {\n ...auth.sources,\n [inactive]: undefined,\n ...(sandbox ? {} : { mailtrapInboxId: undefined }),\n },\n values: {\n mailtrapSandbox: sandbox,\n [active]: url,\n mailtrapTimeout: connection.timeout,\n ...(sandbox ? { mailtrapInboxId: id } : {}),\n },\n };\n}\n\nfunction mailgunDomain(input: Input) {\n const original = input?.value;\n if (\n original === undefined ||\n original === \"\" ||\n /[\\\\/:@?#%\\s]/u.test(original)\n ) {\n throw new Error(\"Invalid Mailgun sending domain.\");\n }\n const value = domainToASCII(original).toLowerCase().replace(/\\.$/u, \"\");\n if (\n value.length > 253 ||\n isIP(value) !== 0 ||\n !value\n .split(\".\")\n .every(\n (label) =>\n label.length <= 63 &&\n /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u.test(label),\n )\n ) {\n throw new Error(\"Invalid Mailgun sending domain.\");\n }\n return value;\n}\nfunction mailgunSettings(\n raw: RawMailOptions,\n auth: ReturnType<typeof credential>,\n) {\n const region = raw.mailgunRegion?.value ?? \"us\";\n if (region !== \"us\" && region !== \"eu\") {\n throw new Error(\"Invalid Mailgun region; use us or eu.\");\n }\n const connection: Omit<MailgunConfig, \"apiKey\"> = {\n domain: mailgunDomain(raw.mailgunDomain),\n region,\n baseUrl: endpoint(\n raw.mailgunBaseUrl,\n \"mailgun\",\n region === \"eu\"\n ? \"https://api.eu.mailgun.net/v3\"\n : \"https://api.mailgun.net/v3\",\n ),\n timeout: number(\n raw.mailgunTimeout,\n 30000,\n 1,\n 2147483647,\n \"delivery timeout\",\n \"mailgun\",\n ),\n retries: 0,\n validateSsl: true,\n tracking: false,\n clickTracking: false,\n openTracking: false,\n };\n const mail: ApiMailSettings = {\n transport: \"mailgun\",\n connection,\n credential: auth.secret,\n };\n return {\n mail,\n sources: auth.sources,\n values: {\n mailgunDomain: connection.domain,\n mailgunRegion: region,\n mailgunBaseUrl: connection.baseUrl,\n mailgunTimeout: connection.timeout,\n },\n };\n}\n\nfunction plunkSettings(\n raw: RawMailOptions,\n auth: ReturnType<typeof credential>,\n) {\n const connection = {\n baseUrl: endpoint(\n raw.plunkBaseUrl,\n \"plunk\",\n \"https://next-api.useplunk.com\",\n ),\n timeout: number(\n raw.plunkTimeout,\n 30000,\n 1,\n 2147483647,\n \"delivery timeout\",\n \"plunk\",\n ),\n retries: 0,\n validateSsl: true,\n };\n const mail: ApiMailSettings = {\n transport: \"plunk\",\n connection,\n credential: auth.secret,\n };\n return {\n mail,\n sources: auth.sources,\n values: {\n plunkBaseUrl: connection.baseUrl,\n plunkTimeout: connection.timeout,\n },\n };\n}\n\nfunction resendSettings(\n raw: RawMailOptions,\n auth: ReturnType<typeof credential>,\n) {\n const connection = {\n baseUrl: endpoint(raw.resendBaseUrl, \"resend\", \"https://api.resend.com\"),\n timeout: number(\n raw.resendTimeout,\n 30000,\n 1,\n 2147483647,\n \"delivery timeout\",\n \"resend\",\n ),\n retries: number(raw.resendRetries, 3, 0, 10, \"retries\", \"resend\"),\n validateSsl: true,\n };\n const mail: ApiMailSettings = {\n transport: \"resend\",\n connection,\n credential: auth.secret,\n };\n return {\n mail,\n sources: auth.sources,\n values: {\n resendBaseUrl: connection.baseUrl,\n resendTimeout: connection.timeout,\n resendRetries: connection.retries,\n },\n };\n}\n\nfunction sendgridSettings(\n raw: RawMailOptions,\n auth: ReturnType<typeof credential>,\n) {\n const connection = {\n baseUrl: endpoint(\n raw.sendgridBaseUrl,\n \"sendgrid\",\n \"https://api.sendgrid.com/v3\",\n ),\n timeout: number(\n raw.sendgridTimeout,\n 30000,\n 1,\n 2147483647,\n \"delivery timeout\",\n \"sendgrid\",\n ),\n retries: 0,\n validateSsl: true,\n clickTracking: false,\n openTracking: false,\n subscriptionTracking: false,\n googleAnalytics: false,\n };\n const mail: ApiMailSettings = {\n transport: \"sendgrid\",\n connection,\n credential: auth.secret,\n };\n return {\n mail,\n sources: auth.sources,\n values: {\n sendgridBaseUrl: connection.baseUrl,\n sendgridTimeout: connection.timeout,\n },\n };\n}\n\n/** Resolve only the selected API service; credentials remain unopened.\n * @returns Prepared meaning, safe diagnostic values and effective source tags.\n */\nexport function resolveApiMailSettings(\n raw: RawMailOptions,\n cwd: string,\n provider: ApiMailSettings[\"transport\"] = \"lettermint\",\n) {\n const auth = credential(raw, cwd, provider);\n if (provider === \"plunk\") return plunkSettings(raw, auth);\n if (provider === \"resend\") return resendSettings(raw, auth);\n if (provider === \"sendgrid\") return sendgridSettings(raw, auth);\n if (provider === \"mailgun\") return mailgunSettings(raw, auth);\n if (provider === \"mailtrap\") return mailtrapSettings(raw, auth);\n if (provider === \"maileroo\") {\n const connection = {\n baseUrl: endpoint(raw.mailerooBaseUrl, provider),\n timeout: number(\n raw.mailerooTimeout,\n 30000,\n 1,\n 2147483647,\n \"delivery timeout\",\n provider,\n ),\n retries: 0,\n };\n const mail: ApiMailSettings = {\n transport: provider,\n connection,\n credential: auth.secret,\n };\n return {\n mail,\n sources: auth.sources,\n values: {\n mailerooBaseUrl: connection.baseUrl,\n mailerooTimeout: connection.timeout,\n },\n };\n }\n if (\n raw.lettermintRoute?.value === \"\" ||\n (raw.lettermintRoute?.value !== undefined &&\n /\\p{Cc}/u.test(raw.lettermintRoute.value))\n ) {\n throw new Error(\"Invalid Lettermint route.\");\n }\n const connection = {\n baseUrl: endpoint(raw.lettermintBaseUrl, provider),\n timeout: number(\n raw.lettermintTimeout,\n 30_000,\n 1,\n 2_147_483_647,\n \"delivery timeout\",\n ),\n retries: number(raw.lettermintRetries, 3, 0, 10, \"retries\"),\n ...(raw.lettermintRoute?.value === undefined\n ? {}\n : { route: raw.lettermintRoute.value }),\n };\n const mail: ApiMailSettings = {\n transport: \"lettermint\",\n connection,\n credential: auth.secret,\n };\n return {\n mail,\n sources: auth.sources,\n values: {\n lettermintBaseUrl: connection.baseUrl,\n lettermintTimeout: connection.timeout,\n lettermintRetries: connection.retries,\n lettermintRoute: connection.route,\n },\n };\n}\n"],"mappings":";;;;;AA2FA,MAAM,WAAW;CAAE,SAAS;CAAG,QAAQ;CAAG,KAAK;CAAG,KAAK;AAAE;AACzD,MAAM,QAAQ,UACZ,OAAO,UAAU,KAAA,IAAY,KAAK,SAAS,MAAM;;AAGnD,SAAgB,0BAA0B,OAAe;CACvD,IAAI,UAAU,MAAM,gBAAgB,KAAK,KAAK,GAC5C,MAAM,IAAI,MAAM,8BAA8B;AAElD;AAEA,SAAS,WACP,KACA,KACA,UACA;CAUA,MAAM,WAAW;EARf,YAAY,CAAC,sBAAsB,wBAAwB;EAC3D,UAAU,CAAC,kBAAkB,oBAAoB;EACjD,UAAU,CAAC,oBAAoB,sBAAsB;EACrD,UAAU,CAAC,kBAAkB,oBAAoB;EACjD,SAAS,CAAC,iBAAiB,mBAAmB;EAC9C,OAAO,CAAC,eAAe,iBAAiB;EACxC,QAAQ,CAAC,gBAAgB,kBAAkB;CAExB,EAAE,SAAS,CAAC,KAC9B,MAAM,UAAU;EAAC;EAAM,IAAI;EAAO,UAAU;CAAC,CAChD;CACA,MAAM,WAAW;EACf;GAAC;GAAc,IAAI;GAAY;EAAK;EACpC;GAAC;GAAkB,IAAI;GAAgB;EAAI;EAC3C,GAAG;CACL;CACA,MAAM,UA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B,QAAQ;GAC/C,SAAS,OACP,IAAI,iBACJ,KACA,GACA,YACA,oBACA,QACF;GACA,SAAS;EACX;EAMA,OAAO;GACL,MAAA;IALA,WAAW;IACX;IACA,YAAY,KAAK;GAGd;GACH,SAAS,KAAK;GACd,QAAQ;IACN,iBAAiB,WAAW;IAC5B,iBAAiB,WAAW;GAC9B;EACF;CACF;CACA,IACE,IAAI,iBAAiB,UAAU,MAC9B,IAAI,iBAAiB,UAAU,KAAA,KAC9B,UAAU,KAAK,IAAI,gBAAgB,KAAK,GAE1C,MAAM,IAAI,MAAM,2BAA2B;CAE7C,MAAM,aAAa;EACjB,SAAS,SAAS,IAAI,mBAAmB,QAAQ;EACjD,SAAS,OACP,IAAI,mBACJ,KACA,GACA,YACA,kBACF;EACA,SAAS,OAAO,IAAI,mBAAmB,GAAG,GAAG,IAAI,SAAS;EAC1D,GAAI,IAAI,iBAAiB,UAAU,KAAA,IAC/B,CAAC,IACD,EAAE,OAAO,IAAI,gBAAgB,MAAM;CACzC;CAMA,OAAO;EACL,MAAA;GALA,WAAW;GACX;GACA,YAAY,KAAK;EAGd;EACH,SAAS,KAAK;EACd,QAAQ;GACN,mBAAmB,WAAW;GAC9B,mBAAmB,WAAW;GAC9B,mBAAmB,WAAW;GAC9B,iBAAiB,WAAW;EAC9B;CACF;AACF"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Transport } from "@upyo/core";
|
|
2
|
+
//#region src/bounded-mail-runtime.d.ts
|
|
3
|
+
/** Bound an owned HTTP mail transport through response-body parsing.
|
|
4
|
+
* @returns A transport owning its active sends and idempotent disposal.
|
|
5
|
+
*/
|
|
6
|
+
declare function createBoundedTransport<T extends string>(sdk: Transport<T>, timeout: number, label: string): Transport<T> & AsyncDisposable;
|
|
7
|
+
//#endregion
|
|
8
|
+
export { createBoundedTransport };
|
|
9
|
+
//# sourceMappingURL=bounded-mail-runtime.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bounded-mail-runtime.d.mts","names":[],"sources":["../src/bounded-mail-runtime.ts"],"mappings":";;;;;iBA2BgB,uBAAuB,kBACrC,KAAK,UAAU,IACf,iBACA,gBACC,UAAU,KAAK"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createFailedReceipt } from "@upyo/core";
|
|
2
|
+
//#region src/bounded-mail-runtime.ts
|
|
3
|
+
/** Bound an owned HTTP mail transport through response-body parsing.
|
|
4
|
+
* @returns A transport owning its active sends and idempotent disposal.
|
|
5
|
+
*/
|
|
6
|
+
function createBoundedTransport(sdk, timeout, label) {
|
|
7
|
+
const controllers = /* @__PURE__ */ new Set();
|
|
8
|
+
const pending = /* @__PURE__ */ new Set();
|
|
9
|
+
let closing;
|
|
10
|
+
function send(message, options) {
|
|
11
|
+
if (closing !== void 0) return Promise.reject(/* @__PURE__ */ new Error(`${label} transport is closed.`));
|
|
12
|
+
const controller = new AbortController();
|
|
13
|
+
const signal = options?.signal === void 0 ? controller.signal : AbortSignal.any([controller.signal, options.signal]);
|
|
14
|
+
const timer = setTimeout(() => controller.abort(new DOMException(`${label} delivery timed out.`, "TimeoutError")), timeout);
|
|
15
|
+
timer.unref();
|
|
16
|
+
controllers.add(controller);
|
|
17
|
+
const work = (async () => {
|
|
18
|
+
try {
|
|
19
|
+
const receipt = await sdk.send(message, { signal });
|
|
20
|
+
options?.signal?.throwIfAborted();
|
|
21
|
+
controller.signal.throwIfAborted();
|
|
22
|
+
return receipt;
|
|
23
|
+
} catch (error) {
|
|
24
|
+
options?.signal?.throwIfAborted();
|
|
25
|
+
if (controller.signal.aborted && controller.signal.reason instanceof DOMException && controller.signal.reason.name === "TimeoutError") return createFailedReceipt(`${label} delivery timed out.`, {
|
|
26
|
+
provider: sdk.id,
|
|
27
|
+
category: "timeout",
|
|
28
|
+
retryable: false
|
|
29
|
+
});
|
|
30
|
+
throw error;
|
|
31
|
+
} finally {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
controllers.delete(controller);
|
|
34
|
+
}
|
|
35
|
+
})();
|
|
36
|
+
pending.add(work);
|
|
37
|
+
const settled = () => {
|
|
38
|
+
pending.delete(work);
|
|
39
|
+
};
|
|
40
|
+
work.then(settled, settled);
|
|
41
|
+
return work;
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
id: sdk.id,
|
|
45
|
+
send,
|
|
46
|
+
async *sendMany(messages, options) {
|
|
47
|
+
for await (const message of messages) yield await send(message, options);
|
|
48
|
+
},
|
|
49
|
+
[Symbol.asyncDispose]() {
|
|
50
|
+
return closing ??= Promise.resolve().then(async () => {
|
|
51
|
+
for (const controller of controllers) controller.abort(/* @__PURE__ */ new Error(`${label} transport is closed.`));
|
|
52
|
+
await Promise.allSettled(pending);
|
|
53
|
+
const disposable = sdk;
|
|
54
|
+
try {
|
|
55
|
+
await disposable[Symbol.asyncDispose]?.();
|
|
56
|
+
} catch {
|
|
57
|
+
throw new Error("Mail transport cleanup failed.");
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { createBoundedTransport };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=bounded-mail-runtime.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bounded-mail-runtime.mjs","names":[],"sources":["../src/bounded-mail-runtime.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport {\n type Message,\n type Receipt,\n type Transport,\n type TransportOptions,\n createFailedReceipt,\n} from \"@upyo/core\";\n\n/** Bound an owned HTTP mail transport through response-body parsing.\n * @returns A transport owning its active sends and idempotent disposal.\n */\nexport function createBoundedTransport<T extends string>(\n sdk: Transport<T>,\n timeout: number,\n label: string,\n): Transport<T> & AsyncDisposable {\n const controllers = new Set<AbortController>();\n const pending = new Set<Promise<Receipt<T>>>();\n let closing: Promise<void> | undefined;\n function send(message: Message, options?: TransportOptions) {\n if (closing !== undefined) {\n return Promise.reject(new Error(`${label} transport is closed.`));\n }\n const controller = new AbortController();\n const signal =\n options?.signal === undefined\n ? controller.signal\n : AbortSignal.any([controller.signal, options.signal]);\n const timer = setTimeout(\n () =>\n controller.abort(\n new DOMException(`${label} delivery timed out.`, \"TimeoutError\"),\n ),\n timeout,\n );\n timer.unref();\n controllers.add(controller);\n const work = (async () => {\n try {\n const receipt = await sdk.send(message, { signal });\n options?.signal?.throwIfAborted();\n controller.signal.throwIfAborted();\n return receipt;\n } catch (error) {\n options?.signal?.throwIfAborted();\n if (\n controller.signal.aborted &&\n controller.signal.reason instanceof DOMException &&\n controller.signal.reason.name === \"TimeoutError\"\n ) {\n return createFailedReceipt(`${label} delivery timed out.`, {\n provider: sdk.id,\n category: \"timeout\",\n retryable: false,\n });\n }\n throw error;\n } finally {\n clearTimeout(timer);\n controllers.delete(controller);\n }\n })();\n pending.add(work);\n const settled = () => {\n pending.delete(work);\n };\n // Both handlers settle normally; no detached rejection is created.\n // oxlint-disable-next-line promise/prefer-await-to-then\n void work.then(settled, settled);\n return work;\n }\n return {\n id: sdk.id,\n send,\n async *sendMany(\n messages: Iterable<Message> | AsyncIterable<Message>,\n options?: TransportOptions,\n ) {\n for await (const message of messages) yield await send(message, options);\n },\n [Symbol.asyncDispose]() {\n // Memoize before abort callbacks can reenter disposal.\n // oxlint-disable-next-line promise/prefer-await-to-then\n return (closing ??= Promise.resolve().then(async () => {\n for (const controller of controllers) {\n controller.abort(new Error(`${label} transport is closed.`));\n }\n await Promise.allSettled(pending);\n const disposable = sdk as Transport<T> & Partial<AsyncDisposable>;\n try {\n await disposable[Symbol.asyncDispose]?.();\n } catch {\n throw new Error(\"Mail transport cleanup failed.\");\n }\n return undefined;\n }));\n },\n };\n}\n"],"mappings":";;;;;AA2BA,SAAgB,uBACd,KACA,SACA,OACgC;CAChC,MAAM,8BAAc,IAAI,IAAqB;CAC7C,MAAM,0BAAU,IAAI,IAAyB;CAC7C,IAAI;CACJ,SAAS,KAAK,SAAkB,SAA4B;EAC1D,IAAI,YAAY,KAAA,GACd,OAAO,QAAQ,uBAAO,IAAI,MAAM,GAAG,MAAM,sBAAsB,CAAC;EAElE,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,SACJ,SAAS,WAAW,KAAA,IAChB,WAAW,SACX,YAAY,IAAI,CAAC,WAAW,QAAQ,QAAQ,MAAM,CAAC;EACzD,MAAM,QAAQ,iBAEV,WAAW,MACT,IAAI,aAAa,GAAG,MAAM,uBAAuB,cAAc,CACjE,GACF,OACF;EACA,MAAM,MAAM;EACZ,YAAY,IAAI,UAAU;EAC1B,MAAM,QAAQ,YAAY;GACxB,IAAI;IACF,MAAM,UAAU,MAAM,IAAI,KAAK,SAAS,EAAE,OAAO,CAAC;IAClD,SAAS,QAAQ,eAAe;IAChC,WAAW,OAAO,eAAe;IACjC,OAAO;GACT,SAAS,OAAO;IACd,SAAS,QAAQ,eAAe;IAChC,IACE,WAAW,OAAO,WAClB,WAAW,OAAO,kBAAkB,gBACpC,WAAW,OAAO,OAAO,SAAS,gBAElC,OAAO,oBAAoB,GAAG,MAAM,uBAAuB;KACzD,UAAU,IAAI;KACd,UAAU;KACV,WAAW;IACb,CAAC;IAEH,MAAM;GACR,UAAU;IACR,aAAa,KAAK;IAClB,YAAY,OAAO,UAAU;GAC/B;EACF,EAAA,CAAG;EACH,QAAQ,IAAI,IAAI;EAChB,MAAM,gBAAgB;GACpB,QAAQ,OAAO,IAAI;EACrB;EAGA,KAAU,KAAK,SAAS,OAAO;EAC/B,OAAO;CACT;CACA,OAAO;EACL,IAAI,IAAI;EACR;EACA,OAAO,SACL,UACA,SACA;GACA,WAAW,MAAM,WAAW,UAAU,MAAM,MAAM,KAAK,SAAS,OAAO;EACzE;EACA,CAAC,OAAO,gBAAgB;GAGtB,OAAQ,YAAY,QAAQ,QAAQ,CAAC,CAAC,KAAK,YAAY;IACrD,KAAK,MAAM,cAAc,aACvB,WAAW,sBAAM,IAAI,MAAM,GAAG,MAAM,sBAAsB,CAAC;IAE7D,MAAM,QAAQ,WAAW,OAAO;IAChC,MAAM,aAAa;IACnB,IAAI;KACF,MAAM,WAAW,OAAO,aAAa,GAAG;IAC1C,QAAQ;KACN,MAAM,IAAI,MAAM,gCAAgC;IAClD;GAEF,CAAC;EACH;CACF;AACF"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { ValueParser } from "@optique/core/valueparser";
|
|
2
|
+
import { Database } from "@drfed/models";
|
|
3
|
+
//#region src/commands/account-create.d.ts
|
|
4
|
+
/** Email validation with the same case-preserving normalization as login. */
|
|
5
|
+
declare const accountEmail: ValueParser<"sync", string>;
|
|
6
|
+
/**
|
|
7
|
+
* Validate and normalize account inputs before database acquisition.
|
|
8
|
+
* @returns Email and trimmed name within the database column limits.
|
|
9
|
+
*/
|
|
10
|
+
declare function resolveAccountInput(email: string, name: string): {
|
|
11
|
+
email: string;
|
|
12
|
+
name: string;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Create an unprivileged account, preserving every existing account field.
|
|
16
|
+
* @returns Whether the account was created, with its stored public identity.
|
|
17
|
+
*/
|
|
18
|
+
declare function createAccount(db: Database, input: ReturnType<typeof resolveAccountInput>): Promise<{
|
|
19
|
+
status: "created";
|
|
20
|
+
account: {
|
|
21
|
+
id: `${string}-${string}-${string}-${string}-${string}`;
|
|
22
|
+
email: string;
|
|
23
|
+
name: string;
|
|
24
|
+
admin: boolean;
|
|
25
|
+
};
|
|
26
|
+
} | {
|
|
27
|
+
status: "exists";
|
|
28
|
+
account: {
|
|
29
|
+
admin: boolean;
|
|
30
|
+
email: string;
|
|
31
|
+
id: `${string}-${string}-${string}-${string}-${string}`;
|
|
32
|
+
name: string;
|
|
33
|
+
};
|
|
34
|
+
}>;
|
|
35
|
+
//#endregion
|
|
36
|
+
export { accountEmail, createAccount, resolveAccountInput };
|
|
37
|
+
//# sourceMappingURL=account-create.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"account-create.d.mts","names":[],"sources":["../../src/commands/account-create.ts"],"mappings":";;;;cA0Ba,cAAc;;;;;iBA+CX,oBAAoB,eAAe;EAexC;EAAwB;;;;;;iBAOb,cACpB,IAAI,UACJ,OAAO,kBAAkB,uBAAoB;EAmB1B;;;;;;;;EASF"}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { message } from "@optique/core/message";
|
|
2
|
+
import { schema } from "@drfed/models";
|
|
3
|
+
import { normalizeEmail } from "@drfed/models/email";
|
|
4
|
+
import { uuidV7 } from "@drfed/models/uuid";
|
|
5
|
+
//#region src/commands/account-create.ts
|
|
6
|
+
/** Email validation with the same case-preserving normalization as login. */
|
|
7
|
+
const accountEmail = {
|
|
8
|
+
mode: "sync",
|
|
9
|
+
metavar: "EMAIL",
|
|
10
|
+
placeholder: "user@example.com",
|
|
11
|
+
parse(input) {
|
|
12
|
+
try {
|
|
13
|
+
const value = input.trim();
|
|
14
|
+
const [local, host, extra] = value.split("@");
|
|
15
|
+
if (local == null || host == null || extra !== void 0 || /[\u0000-\u001f\u007f]/u.test(input) || /[\s/\\:#?%\[\]]/u.test(host) || !/^(?:[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*|"(?:[^"\\\u0000-\u001f\u007f]|\\[\u0020-\u007e])*")$/iu.test(local)) throw new Error();
|
|
16
|
+
const normalized = normalizeEmail(value);
|
|
17
|
+
const domain = normalized.slice(normalized.lastIndexOf("@") + 1);
|
|
18
|
+
if (domain.length > 253 || !domain.includes(".") || !domain.split(".").every((label) => label.length <= 63 && /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/iu.test(label))) throw new Error();
|
|
19
|
+
return {
|
|
20
|
+
success: true,
|
|
21
|
+
value: normalized
|
|
22
|
+
};
|
|
23
|
+
} catch {
|
|
24
|
+
return {
|
|
25
|
+
success: false,
|
|
26
|
+
error: message`Invalid account email.`
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
format: (value) => value
|
|
31
|
+
};
|
|
32
|
+
/**
|
|
33
|
+
* Validate and normalize account inputs before database acquisition.
|
|
34
|
+
* @returns Email and trimmed name within the database column limits.
|
|
35
|
+
*/
|
|
36
|
+
function resolveAccountInput(email, name) {
|
|
37
|
+
const parsed = accountEmail.parse(email);
|
|
38
|
+
if (!parsed.success) throw new Error("Invalid account email.");
|
|
39
|
+
const normalizedEmail = normalizeEmail(parsed.value);
|
|
40
|
+
const normalizedName = name.trim();
|
|
41
|
+
if (Array.from(normalizedEmail).length > 255) throw new Error("Account email must be at most 255 characters.");
|
|
42
|
+
if (!normalizedName || normalizedName.includes("\0") || Array.from(normalizedName).length > 100) throw new Error("Account name must contain 1 to 100 characters.");
|
|
43
|
+
return {
|
|
44
|
+
email: normalizedEmail,
|
|
45
|
+
name: normalizedName
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Create an unprivileged account, preserving every existing account field.
|
|
50
|
+
* @returns Whether the account was created, with its stored public identity.
|
|
51
|
+
*/
|
|
52
|
+
async function createAccount(db, input) {
|
|
53
|
+
const columns = {
|
|
54
|
+
id: schema.accounts.id,
|
|
55
|
+
email: schema.accounts.email,
|
|
56
|
+
name: schema.accounts.name,
|
|
57
|
+
admin: schema.accounts.admin
|
|
58
|
+
};
|
|
59
|
+
const [created] = await db.insert(schema.accounts).values({
|
|
60
|
+
id: uuidV7(),
|
|
61
|
+
email: input.email,
|
|
62
|
+
name: input.name,
|
|
63
|
+
admin: false
|
|
64
|
+
}).onConflictDoNothing({ target: schema.accounts.email }).returning(columns);
|
|
65
|
+
if (created !== void 0) return {
|
|
66
|
+
status: "created",
|
|
67
|
+
account: created
|
|
68
|
+
};
|
|
69
|
+
const existing = await db.query.accounts.findFirst({
|
|
70
|
+
columns: {
|
|
71
|
+
id: true,
|
|
72
|
+
email: true,
|
|
73
|
+
name: true,
|
|
74
|
+
admin: true
|
|
75
|
+
},
|
|
76
|
+
where: { email: input.email }
|
|
77
|
+
});
|
|
78
|
+
if (existing === void 0) throw new Error("Could not read the existing account.");
|
|
79
|
+
return {
|
|
80
|
+
status: "exists",
|
|
81
|
+
account: existing
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
//#endregion
|
|
85
|
+
export { accountEmail, createAccount, resolveAccountInput };
|
|
86
|
+
|
|
87
|
+
//# sourceMappingURL=account-create.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"account-create.mjs","names":[],"sources":["../../src/commands/account-create.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n// oxlint-disable no-control-regex no-useless-escape\n// Email syntax requires explicit control-character rejection and slash literals.\n\nimport { type Database, schema } from \"@drfed/models\";\nimport { normalizeEmail } from \"@drfed/models/email\";\nimport { uuidV7 } from \"@drfed/models/uuid\";\nimport { message } from \"@optique/core/message\";\nimport type { ValueParser } from \"@optique/core/valueparser\";\n\n/** Email validation with the same case-preserving normalization as login. */\nexport const accountEmail: ValueParser<\"sync\", string> = {\n mode: \"sync\",\n metavar: \"EMAIL\",\n placeholder: \"user@example.com\",\n parse(input) {\n try {\n const value = input.trim();\n const [local, host, extra] = value.split(\"@\");\n if (\n local == null ||\n host == null ||\n extra !== undefined ||\n /[\\u0000-\\u001f\\u007f]/u.test(input) ||\n /[\\s/\\\\:#?%\\[\\]]/u.test(host) ||\n !/^(?:[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+\\/=?^_`{|}~-]+)*|\"(?:[^\"\\\\\\u0000-\\u001f\\u007f]|\\\\[\\u0020-\\u007e])*\")$/iu.test(\n local,\n )\n ) {\n throw new Error();\n }\n const normalized = normalizeEmail(value);\n const domain = normalized.slice(normalized.lastIndexOf(\"@\") + 1);\n if (\n domain.length > 253 ||\n !domain.includes(\".\") ||\n !domain\n .split(\".\")\n .every(\n (label) =>\n label.length <= 63 &&\n /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/iu.test(label),\n )\n ) {\n throw new Error();\n }\n return { success: true, value: normalized };\n } catch {\n return { success: false, error: message`Invalid account email.` };\n }\n },\n format: (value) => value,\n};\n\n/**\n * Validate and normalize account inputs before database acquisition.\n * @returns Email and trimmed name within the database column limits.\n */\nexport function resolveAccountInput(email: string, name: string) {\n const parsed = accountEmail.parse(email);\n if (!parsed.success) throw new Error(\"Invalid account email.\");\n const normalizedEmail = normalizeEmail(parsed.value);\n const normalizedName = name.trim();\n if (Array.from(normalizedEmail).length > 255) {\n throw new Error(\"Account email must be at most 255 characters.\");\n }\n if (\n !normalizedName ||\n normalizedName.includes(\"\\0\") ||\n Array.from(normalizedName).length > 100\n ) {\n throw new Error(\"Account name must contain 1 to 100 characters.\");\n }\n return { email: normalizedEmail, name: normalizedName };\n}\n\n/**\n * Create an unprivileged account, preserving every existing account field.\n * @returns Whether the account was created, with its stored public identity.\n */\nexport async function createAccount(\n db: Database,\n input: ReturnType<typeof resolveAccountInput>,\n) {\n const columns = {\n id: schema.accounts.id,\n email: schema.accounts.email,\n name: schema.accounts.name,\n admin: schema.accounts.admin,\n };\n const [created] = await db\n .insert(schema.accounts)\n .values({\n id: uuidV7(),\n email: input.email,\n name: input.name,\n admin: false,\n })\n .onConflictDoNothing({ target: schema.accounts.email })\n .returning(columns);\n if (created !== undefined) {\n return { status: \"created\" as const, account: created };\n }\n const existing = await db.query.accounts.findFirst({\n columns: { id: true, email: true, name: true, admin: true },\n where: { email: input.email },\n });\n if (existing === undefined) {\n throw new Error(\"Could not read the existing account.\");\n }\n return { status: \"exists\" as const, account: existing };\n}\n"],"mappings":";;;;;;AA0BA,MAAa,eAA4C;CACvD,MAAM;CACN,SAAS;CACT,aAAa;CACb,MAAM,OAAO;EACX,IAAI;GACF,MAAM,QAAQ,MAAM,KAAK;GACzB,MAAM,CAAC,OAAO,MAAM,SAAS,MAAM,MAAM,GAAG;GAC5C,IACE,SAAS,QACT,QAAQ,QACR,UAAU,KAAA,KACV,yBAAyB,KAAK,KAAK,KACnC,mBAAmB,KAAK,IAAI,KAC5B,CAAC,+HAA+H,KAC9H,KACF,GAEA,MAAM,IAAI,MAAM;GAElB,MAAM,aAAa,eAAe,KAAK;GACvC,MAAM,SAAS,WAAW,MAAM,WAAW,YAAY,GAAG,IAAI,CAAC;GAC/D,IACE,OAAO,SAAS,OAChB,CAAC,OAAO,SAAS,GAAG,KACpB,CAAC,OACE,MAAM,GAAG,CAAC,CACV,OACE,UACC,MAAM,UAAU,MAChB,sCAAsC,KAAK,KAAK,CACpD,GAEF,MAAM,IAAI,MAAM;GAElB,OAAO;IAAE,SAAS;IAAM,OAAO;GAAW;EAC5C,QAAQ;GACN,OAAO;IAAE,SAAS;IAAO,OAAO,OAAO;GAAyB;EAClE;CACF;CACA,SAAS,UAAU;AACrB;;;;;AAMA,SAAgB,oBAAoB,OAAe,MAAc;CAC/D,MAAM,SAAS,aAAa,MAA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