@jini-ai/platform 0.7.3-next.1 → 0.7.3-next.3
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/CHANGELOG.md +6 -0
- package/README.md +13 -0
- package/dist/download-lock.d.ts +3 -1
- package/dist/download-lock.js +4 -4
- package/dist/download-maintenance.js +6 -6
- package/dist/download-state.js +17 -14
- package/dist/download-store.d.ts +34 -10
- package/dist/download-store.js +24 -20
- package/dist/download-target.d.ts +6 -2
- package/dist/download-target.js +7 -7
- package/dist/download-transfer.js +18 -12
- package/dist/download.js +4 -4
- package/dist/fetch-with-timeout.d.ts +0 -53
- package/dist/fetch-with-timeout.js +56 -6
- package/dist/fs/directory-running-lock.d.ts +4 -0
- package/dist/fs/directory-running-lock.js +8 -1
- package/dist/fs/directory-workspace.d.ts +2 -1
- package/dist/fs/directory-workspace.js +2 -2
- package/dist/fs/durable-json.d.ts +3 -16
- package/dist/fs/durable-json.js +4 -2
- package/dist/fs/guarded-reader.d.ts +10 -0
- package/dist/fs/guarded-reader.js +34 -1
- package/dist/fs/index.d.ts +4 -0
- package/dist/fs/index.js +4 -0
- package/dist/fs/leased-directory-move.d.ts +49 -0
- package/dist/fs/leased-directory-move.js +31 -0
- package/dist/fs/owned-temp-root.d.ts +74 -0
- package/dist/fs/owned-temp-root.js +203 -0
- package/dist/fs/recent-directories.d.ts +2 -1
- package/dist/fs/resolve-directory-target.d.ts +33 -0
- package/dist/fs/resolve-directory-target.js +58 -0
- package/dist/fs/staged-file.d.ts +40 -0
- package/dist/fs/staged-file.js +75 -0
- package/dist/fs/strict-containment.d.ts +14 -0
- package/dist/fs/strict-containment.js +14 -0
- package/dist/image/png-encode.d.ts +41 -0
- package/dist/image/png-encode.js +96 -0
- package/dist/index.d.ts +3 -1
- package/dist/mail/email-template-agent-tools.d.ts +150 -0
- package/dist/mail/email-template-agent-tools.js +86 -0
- package/dist/mail/email-template-tool-registrations.d.ts +73 -0
- package/dist/mail/email-template-tool-registrations.js +66 -0
- package/dist/mail/feedback-route.d.ts +50 -0
- package/dist/mail/feedback-route.js +46 -0
- package/dist/mail/feedback-setup.d.ts +44 -0
- package/dist/mail/feedback-setup.js +53 -0
- package/dist/mail/feedback-sources.d.ts +67 -0
- package/dist/mail/feedback-sources.js +42 -0
- package/dist/mail/index.d.ts +10 -1
- package/dist/mail/index.js +4 -0
- package/dist/mail/mail-status.d.ts +32 -0
- package/dist/mail/mail-status.js +2 -0
- package/dist/mail/positional-purpose-gate.d.ts +14 -0
- package/dist/mail/positional-purpose-gate.js +18 -0
- package/dist/mail/purpose-gate-probe.d.ts +18 -0
- package/dist/mail/purpose-gate-probe.js +22 -0
- package/dist/mail/resolve-mailer.d.ts +13 -1
- package/dist/mail/resolve-mailer.js +11 -5
- package/dist/mail/sql/activity.repo.d.ts +20 -0
- package/dist/mail/sql/activity.repo.js +133 -0
- package/dist/mail/sql/attempts.repo.d.ts +17 -0
- package/dist/mail/sql/attempts.repo.js +32 -0
- package/dist/mail/sql/capture.repo.d.ts +69 -0
- package/dist/mail/sql/capture.repo.js +119 -0
- package/dist/mail/sql/feedback-inbox.repo.d.ts +12 -0
- package/dist/mail/sql/feedback-inbox.repo.js +32 -0
- package/dist/mail/sql/index.d.ts +12 -0
- package/dist/mail/sql/index.js +12 -0
- package/dist/mail/sql/ledger.repo.d.ts +29 -0
- package/dist/mail/sql/ledger.repo.js +57 -0
- package/dist/mail/sql/retention.d.ts +23 -0
- package/dist/mail/sql/retention.js +53 -0
- package/dist/mail/sql/site-feedback-route.d.ts +18 -0
- package/dist/mail/sql/site-feedback-route.js +22 -0
- package/dist/mail/sql/suppression-admin.repo.d.ts +11 -0
- package/dist/mail/sql/suppression-admin.repo.js +76 -0
- package/dist/mail/sql/suppression.repo.d.ts +10 -0
- package/dist/mail/sql/suppression.repo.js +33 -0
- package/dist/mail/test-send.d.ts +147 -0
- package/dist/mail/test-send.js +201 -0
- package/dist/mail/use-readiness.d.ts +104 -0
- package/dist/mail/use-readiness.js +140 -0
- package/dist/object-store/local-fs.js +34 -1
- package/dist/object-store/site/artifact-provider.d.ts +65 -0
- package/dist/object-store/site/artifact-provider.js +37 -0
- package/dist/object-store/site/registry.d.ts +110 -0
- package/dist/object-store/site/registry.js +93 -0
- package/dist/object-store/site/setting.d.ts +34 -0
- package/dist/object-store/site/setting.js +32 -0
- package/dist/process-probes.d.ts +11 -4
- package/dist/process-probes.js +3 -3
- package/dist/process-top-footprint.d.ts +1 -1
- package/dist/process.d.ts +3 -17
- package/dist/process.js +3 -2
- package/dist/retention/index.d.ts +6 -0
- package/dist/retention/index.js +6 -0
- package/dist/retention/measure-tree.d.ts +68 -0
- package/dist/retention/measure-tree.js +205 -0
- package/dist/retention/preview-store.d.ts +10 -0
- package/dist/retention/preview-store.js +26 -0
- package/dist/retention/routes.d.ts +23 -0
- package/dist/retention/routes.js +24 -0
- package/dist/retention/runner.d.ts +103 -0
- package/dist/retention/runner.js +164 -0
- package/dist/secrets/credential-sets/index.d.ts +1 -0
- package/dist/secrets/credential-sets/index.js +1 -0
- package/dist/secrets/credential-sets/store-vault-guards.d.ts +26 -0
- package/dist/secrets/credential-sets/store-vault-guards.js +30 -0
- package/dist/secrets/credential-sets/vault.service.d.ts +1 -1
- package/dist/secrets/index.d.ts +1 -1
- package/dist/secrets/index.js +1 -1
- package/dist/secrets/keyring.env.d.ts +1 -1
- package/dist/secrets/keyring.env.js +3 -5
- package/dist/secrets/keyring.memory.d.ts +4 -1
- package/dist/secrets/keyring.memory.js +4 -1
- package/dist/secrets/legacy-codecs.d.ts +381 -0
- package/dist/secrets/legacy-codecs.js +468 -0
- package/dist/secrets/legacy-owner.d.ts +3 -11
- package/dist/secrets/root-key/ensure.d.ts +154 -0
- package/dist/secrets/root-key/ensure.js +328 -0
- package/dist/secrets/root-key/files.d.ts +104 -0
- package/dist/secrets/root-key/files.js +166 -0
- package/dist/secrets/root-key/material.d.ts +132 -0
- package/dist/secrets/root-key/material.js +116 -0
- package/dist/secrets/root-key/ordered-keyring.d.ts +157 -0
- package/dist/secrets/root-key/ordered-keyring.js +104 -0
- package/dist/secrets/root-key/reconcile.d.ts +50 -0
- package/dist/secrets/root-key/reconcile.js +147 -0
- package/dist/secrets/root-key/site-keyring-errors.d.ts +78 -0
- package/dist/secrets/root-key/site-keyring-errors.js +37 -0
- package/dist/secrets/root-key/sources.d.ts +79 -0
- package/dist/secrets/root-key/sources.js +119 -0
- package/dist/secrets/secret-sealer.aesgcm.d.ts +50 -2
- package/dist/secrets/secret-sealer.aesgcm.js +107 -19
- package/dist/web/tool-registrations.d.ts +67 -0
- package/dist/web/tool-registrations.js +44 -0
- package/package.json +139 -7
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { MailRepoDeps } from "./ledger.repo.js";
|
|
2
|
+
export declare const MAIL_ACTIVITY_RETENTION_MS: number;
|
|
3
|
+
export declare const MAIL_CAPTURE_RETENTION_MS: number;
|
|
4
|
+
export declare const MAIL_RETENTION_INTERVAL_MS = 60000;
|
|
5
|
+
/** The clock and both windows a purge pass reads; each defaults to the owner policy above. */
|
|
6
|
+
export interface MailRetentionOptions {
|
|
7
|
+
now?: () => number;
|
|
8
|
+
activityRetentionMs?: number;
|
|
9
|
+
captureRetentionMs?: number;
|
|
10
|
+
}
|
|
11
|
+
/** One atomic privacy pass; the clock and the windows are injected for deterministic boundary tests.
|
|
12
|
+
* Rows strictly older than their window are expired, across every workspace (owner process pass).
|
|
13
|
+
* @complexity Five statements using 0031 timestamp-leading indexes; work is proportional to expired candidates, no body reads. */
|
|
14
|
+
export declare function purgeExpiredMail<DB>({ db }: MailRepoDeps<DB>, options?: MailRetentionOptions): Promise<void>;
|
|
15
|
+
/** Reuse the store's owner/close lifecycle. There is no existing mail purge or general sweep runner.
|
|
16
|
+
* Boot and minute passes never overlap; disposal stops ticks and drains the active transaction.
|
|
17
|
+
* A failed pass is reported only through the host's `onError` (its log line is the host's); without one it stays silent. */
|
|
18
|
+
export declare function startMailRetention<DB>(required: MailRepoDeps<DB>, options?: MailRetentionOptions & {
|
|
19
|
+
intervalMs?: number;
|
|
20
|
+
onError?: () => void;
|
|
21
|
+
every?: (run: () => void, ms: number) => () => void;
|
|
22
|
+
}): () => Promise<void>;
|
|
23
|
+
//# sourceMappingURL=retention.d.ts.map
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/** Owner policy (2026-11-23, bt2-todos G7-6/847 + G7-7/848): sent-email records (activity and final
|
|
2
|
+
* send identities) are kept 30 days, captured test emails 7 days. A row exactly one window old is
|
|
3
|
+
* kept; one millisecond older is deleted (the activity list shows the same `>=` boundary).
|
|
4
|
+
* Unresolved reservations and verified feedback event IDs retain their replay protection. */
|
|
5
|
+
import { sql } from "kysely";
|
|
6
|
+
export const MAIL_ACTIVITY_RETENTION_MS = 30 * 24 * 60 * 60_000;
|
|
7
|
+
export const MAIL_CAPTURE_RETENTION_MS = 7 * 24 * 60 * 60_000;
|
|
8
|
+
export const MAIL_RETENTION_INTERVAL_MS = 60_000;
|
|
9
|
+
/** One atomic privacy pass; the clock and the windows are injected for deterministic boundary tests.
|
|
10
|
+
* Rows strictly older than their window are expired, across every workspace (owner process pass).
|
|
11
|
+
* @complexity Five statements using 0031 timestamp-leading indexes; work is proportional to expired candidates, no body reads. */
|
|
12
|
+
export async function purgeExpiredMail({ db }, options = {}) {
|
|
13
|
+
const now = options.now ?? Date.now;
|
|
14
|
+
const activityBefore = new Date(now() - (options.activityRetentionMs ?? MAIL_ACTIVITY_RETENTION_MS)).toISOString();
|
|
15
|
+
const captureBefore = new Date(now() - (options.captureRetentionMs ?? MAIL_CAPTURE_RETENTION_MS)).toISOString();
|
|
16
|
+
await db.transaction(async () => {
|
|
17
|
+
await db.execute(sql `DELETE FROM mail_capture WHERE created_at < ${captureBefore}`);
|
|
18
|
+
await db.execute(sql `DELETE FROM mail_activity_attempts WHERE created_at < ${activityBefore}`);
|
|
19
|
+
// No caller requires final-result replay beyond 30 days. A recent retry still needs its window:
|
|
20
|
+
// created_at is the original reservation time; updated_at is the last reserve/mark time.
|
|
21
|
+
await db.execute(sql `DELETE FROM mail_send_ledger WHERE created_at < ${activityBefore}
|
|
22
|
+
AND updated_at < ${activityBefore} AND outcome IN ('sent', 'failed', 'unknown')`);
|
|
23
|
+
// In-flight reservations cannot be deleted: that would authorize a duplicate delivery.
|
|
24
|
+
await db.execute(sql `UPDATE mail_send_ledger SET activity_retained = 0, provider_message_id = NULL, error_code = NULL
|
|
25
|
+
WHERE created_at < ${activityBefore} AND activity_retained = 1`);
|
|
26
|
+
// Keep verified event IDs and suppression state; discard completed feedback's activity metadata.
|
|
27
|
+
await db.execute(sql `UPDATE mail_feedback_inbox SET recipient = '', provider_message_id = '', occurred_at = received_at
|
|
28
|
+
WHERE received_at < ${activityBefore} AND processed_at IS NOT NULL AND (recipient <> '' OR provider_message_id <> '')`);
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
/** Reuse the store's owner/close lifecycle. There is no existing mail purge or general sweep runner.
|
|
32
|
+
* Boot and minute passes never overlap; disposal stops ticks and drains the active transaction.
|
|
33
|
+
* A failed pass is reported only through the host's `onError` (its log line is the host's); without one it stays silent. */
|
|
34
|
+
export function startMailRetention(required, options = {}) {
|
|
35
|
+
const intervalMs = options.intervalMs ?? MAIL_RETENTION_INTERVAL_MS;
|
|
36
|
+
if (!Number.isSafeInteger(intervalMs) || intervalMs <= 0)
|
|
37
|
+
throw new RangeError("mail retention interval must be positive");
|
|
38
|
+
let active;
|
|
39
|
+
let stopped = false;
|
|
40
|
+
const pass = () => {
|
|
41
|
+
if (stopped || active)
|
|
42
|
+
return;
|
|
43
|
+
active = purgeExpiredMail(required, options).catch(() => { try {
|
|
44
|
+
options.onError?.();
|
|
45
|
+
}
|
|
46
|
+
catch { /* Logging cannot reject timer work. */ } }).finally(() => { active = undefined; });
|
|
47
|
+
};
|
|
48
|
+
const every = options.every ?? ((run, ms) => { const timer = setInterval(run, ms); timer.unref(); return () => clearInterval(timer); });
|
|
49
|
+
pass();
|
|
50
|
+
const cancel = every(pass, intervalMs);
|
|
51
|
+
return async () => { stopped = true; cancel(); await active; };
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=retention.js.map
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type MailFeedbackRoute } from "../feedback-route.js";
|
|
2
|
+
import { type MailAdapterSource, type MailWebhookSecretResolver } from "../feedback-sources.js";
|
|
3
|
+
import type { MailSqlKernel } from "./ledger.repo.js";
|
|
4
|
+
/**
|
|
5
|
+
* One composition call for the composition roots, so they add a single line. Parsers come from the
|
|
6
|
+
* plugin mail-adapter registry until a mail provider registry exists (see `feedback-sources.ts`).
|
|
7
|
+
* The host passes its vault reader and the product label prefix of its persisted secret labels.
|
|
8
|
+
* @example createSiteMailFeedbackRoute({ db: kernel, workspaceId, credentials: { repo, sealer }, loadAdapters, resolveByLabel, labelPrefix })
|
|
9
|
+
*/
|
|
10
|
+
export declare function createSiteMailFeedbackRoute<DB, Credentials>(required: {
|
|
11
|
+
db: MailSqlKernel<DB>;
|
|
12
|
+
workspaceId: string;
|
|
13
|
+
credentials: Credentials;
|
|
14
|
+
loadAdapters: () => Promise<MailAdapterSource>;
|
|
15
|
+
resolveByLabel: MailWebhookSecretResolver<Credentials>;
|
|
16
|
+
labelPrefix: string;
|
|
17
|
+
}): MailFeedbackRoute;
|
|
18
|
+
//# sourceMappingURL=site-feedback-route.d.ts.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** @file The site's mail feedback route from its content kernel, vault and plugin mail adapters. */
|
|
2
|
+
import { createMailFeedbackInboxRepo } from "./feedback-inbox.repo.js";
|
|
3
|
+
import { createMailFeedbackRoute } from "../feedback-route.js";
|
|
4
|
+
import { createPluginMailFeedbackSources, createVaultMailWebhookSecrets } from "../feedback-sources.js";
|
|
5
|
+
import { createMailSuppressionRepo } from "./suppression.repo.js";
|
|
6
|
+
/**
|
|
7
|
+
* One composition call for the composition roots, so they add a single line. Parsers come from the
|
|
8
|
+
* plugin mail-adapter registry until a mail provider registry exists (see `feedback-sources.ts`).
|
|
9
|
+
* The host passes its vault reader and the product label prefix of its persisted secret labels.
|
|
10
|
+
* @example createSiteMailFeedbackRoute({ db: kernel, workspaceId, credentials: { repo, sealer }, loadAdapters, resolveByLabel, labelPrefix })
|
|
11
|
+
*/
|
|
12
|
+
export function createSiteMailFeedbackRoute(required) {
|
|
13
|
+
const { db, workspaceId, credentials, loadAdapters, resolveByLabel, labelPrefix } = required;
|
|
14
|
+
const sources = createPluginMailFeedbackSources({ loadAdapters });
|
|
15
|
+
return createMailFeedbackRoute({
|
|
16
|
+
parserFor: sources.parserFor,
|
|
17
|
+
secretsFor: createVaultMailWebhookSecrets({ credentials, workspaceId, labelFor: sources.labelFor, resolveByLabel, labelPrefix }),
|
|
18
|
+
repos: { inbox: createMailFeedbackInboxRepo({ db }), suppression: createMailSuppressionRepo({ db }) },
|
|
19
|
+
resolveWorkspaceId: () => workspaceId,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=site-feedback-route.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { MailSuppressionAdminRepo } from "../activity/ports.js";
|
|
2
|
+
import type { MailRepoDeps } from "./ledger.repo.js";
|
|
3
|
+
/**
|
|
4
|
+
* @complexity One indexed page read per list; O(1) primary-key statements per find/remove.
|
|
5
|
+
* @example createMailSuppressionAdminRepo({ db: kernel }).list({ workspaceId, limit: 26 }, { search: "example.com" })
|
|
6
|
+
*/
|
|
7
|
+
export declare function createMailSuppressionAdminRepo<DB>({ db }: MailRepoDeps<DB>, optional?: {
|
|
8
|
+
nowIso?: () => string;
|
|
9
|
+
newId?: () => string;
|
|
10
|
+
}): MailSuppressionAdminRepo;
|
|
11
|
+
//# sourceMappingURL=suppression-admin.repo.d.ts.map
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The operator side of the do-not-send list and the feedback inbox (email phase 5, migration
|
|
3
|
+
* 0030): list and search suppressions, remove one with an audit record, and read the newest
|
|
4
|
+
* verified feedback event per provider. One SQL body for SQLite and Postgres.
|
|
5
|
+
*
|
|
6
|
+
* The send-time side stays `suppression.repo.ts` (Jini's `MailSuppressionRepoPort`), untouched: a
|
|
7
|
+
* removal deletes the 0023 row so send-time checks remain one primary-key probe, and the audit row
|
|
8
|
+
* written in the same transaction keeps what was removed, by whom, when and why.
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from "node:crypto";
|
|
11
|
+
import { sql } from "kysely";
|
|
12
|
+
const toEntry = (row) => ({ address: row.normalized_address, scope: row.scope, reason: row.reason, createdAt: row.created_at, revision: row.revision });
|
|
13
|
+
const normalize = ({ address }, _optional = {}) => address.trim().toLowerCase();
|
|
14
|
+
const likeLiteral = ({ term }, _optional = {}) => {
|
|
15
|
+
const escaped = normalize({ address: term }).replace(/[\\%_]/g, (c) => `\\${c}`);
|
|
16
|
+
return `%${escaped}%`;
|
|
17
|
+
};
|
|
18
|
+
function conditions({ workspaceId }, optional) {
|
|
19
|
+
const where = [sql `workspace_id = ${workspaceId}`];
|
|
20
|
+
if (optional.search)
|
|
21
|
+
where.push(sql `normalized_address LIKE ${likeLiteral({ term: optional.search })} ESCAPE '\\'`);
|
|
22
|
+
if (optional.scope)
|
|
23
|
+
where.push(sql `scope = ${optional.scope}`);
|
|
24
|
+
if (optional.reason)
|
|
25
|
+
where.push(sql `reason = ${optional.reason}`);
|
|
26
|
+
if (optional.before)
|
|
27
|
+
where.push(sql `(created_at < ${optional.before.createdAt} OR (created_at = ${optional.before.createdAt} AND revision < ${optional.before.key}))`);
|
|
28
|
+
return where;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* @complexity One indexed page read per list; O(1) primary-key statements per find/remove.
|
|
32
|
+
* @example createMailSuppressionAdminRepo({ db: kernel }).list({ workspaceId, limit: 26 }, { search: "example.com" })
|
|
33
|
+
*/
|
|
34
|
+
export function createMailSuppressionAdminRepo({ db }, optional = {}) {
|
|
35
|
+
const nowIso = optional.nowIso ?? (() => new Date().toISOString());
|
|
36
|
+
const newId = optional.newId ?? randomUUID;
|
|
37
|
+
const find = async ({ workspaceId, address, scope }) => {
|
|
38
|
+
const [row] = await db.query(sql `SELECT normalized_address, scope, reason, created_at, revision FROM mail_suppression
|
|
39
|
+
WHERE workspace_id = ${workspaceId} AND normalized_address = ${normalize({ address })} AND scope = ${scope}`);
|
|
40
|
+
return row ? toEntry(row) : null;
|
|
41
|
+
};
|
|
42
|
+
return {
|
|
43
|
+
async list(required, filter = {}) {
|
|
44
|
+
const rows = await db.query(sql `SELECT normalized_address, scope, reason, created_at, revision FROM mail_suppression
|
|
45
|
+
WHERE ${sql.join(conditions({ workspaceId: required.workspaceId }, filter), sql ` AND `)}
|
|
46
|
+
ORDER BY created_at DESC, revision DESC LIMIT ${required.limit}`);
|
|
47
|
+
return rows.map(toEntry);
|
|
48
|
+
},
|
|
49
|
+
find,
|
|
50
|
+
remove: (required) => db.transaction(async () => {
|
|
51
|
+
await db.lockKey(`mail-suppression:${required.workspaceId}:${normalize({ address: required.address })}:${required.scope}`);
|
|
52
|
+
// DELETE claims the reviewed incarnation. A replacement cannot inherit an old approval;
|
|
53
|
+
// RETURNING also ensures only the winning transaction can write an audit record.
|
|
54
|
+
const [row] = await db.query(sql `DELETE FROM mail_suppression
|
|
55
|
+
WHERE workspace_id = ${required.workspaceId} AND normalized_address = ${normalize({ address: required.address })}
|
|
56
|
+
AND scope = ${required.scope} AND revision = ${required.revision}
|
|
57
|
+
RETURNING normalized_address, scope, reason, created_at, revision`);
|
|
58
|
+
if (!row)
|
|
59
|
+
return null;
|
|
60
|
+
const entry = toEntry(row);
|
|
61
|
+
const removal = {
|
|
62
|
+
id: newId(), address: entry.address, scope: entry.scope, suppressionReason: entry.reason, suppressedAt: entry.createdAt,
|
|
63
|
+
removalReason: required.removalReason, removedBy: required.removedBy, removedAt: nowIso(),
|
|
64
|
+
};
|
|
65
|
+
await db.execute(sql `INSERT INTO mail_suppression_removals (id, workspace_id, normalized_address, scope, suppression_reason, suppressed_at, removal_reason, removed_by, removed_at)
|
|
66
|
+
VALUES (${removal.id}, ${required.workspaceId}, ${removal.address}, ${removal.scope}, ${removal.suppressionReason}, ${removal.suppressedAt}, ${removal.removalReason}, ${removal.removedBy}, ${removal.removedAt})`);
|
|
67
|
+
return removal;
|
|
68
|
+
}),
|
|
69
|
+
async lastFeedbackEvent({ workspaceId, providerId }) {
|
|
70
|
+
const [row] = await db.query(sql `SELECT kind, received_at FROM mail_feedback_inbox
|
|
71
|
+
WHERE workspace_id = ${workspaceId} AND provider_id = ${providerId} AND processed_at IS NOT NULL ORDER BY received_at DESC, event_id DESC LIMIT 1`);
|
|
72
|
+
return row ? { kind: row.kind, receivedAt: row.received_at } : null;
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
//# sourceMappingURL=suppression-admin.repo.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { MailSuppressionRepoPort } from "../ports.js";
|
|
2
|
+
import type { MailRepoDeps, MailRepoOptions } from "./ledger.repo.js";
|
|
3
|
+
/**
|
|
4
|
+
* The do-not-send list. Keyed by address and scope, never provider, so it survives a provider
|
|
5
|
+
* switch. A repeat suppression keeps the first row (its reason and time).
|
|
6
|
+
* @complexity O(1) primary-key lookups/inserts.
|
|
7
|
+
* @example createMailSuppressionRepo({ db: kernel }).isSuppressed({ workspaceId, normalizedAddress, lane: "bulk" })
|
|
8
|
+
*/
|
|
9
|
+
export declare function createMailSuppressionRepo<DB>({ db }: MailRepoDeps<DB>, optional?: MailRepoOptions): MailSuppressionRepoPort;
|
|
10
|
+
//# sourceMappingURL=suppression.repo.d.ts.map
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** @file SQL adapter for Jini's `MailSuppressionRepoPort` (migration 0023), one body for SQLite and Postgres. */
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { sql } from "kysely";
|
|
4
|
+
/** `transactional` is blocked only by `all` (a complainer still gets sign-in links); `bulk` by both. */
|
|
5
|
+
const BLOCKING_SCOPES = {
|
|
6
|
+
transactional: ["all"],
|
|
7
|
+
bulk: ["all", "bulk"],
|
|
8
|
+
};
|
|
9
|
+
/** Addresses are keyed case-insensitively; callers normalize too, this keeps the key honest. */
|
|
10
|
+
const normalize = ({ address }, _optional = {}) => address.trim().toLowerCase();
|
|
11
|
+
/**
|
|
12
|
+
* The do-not-send list. Keyed by address and scope, never provider, so it survives a provider
|
|
13
|
+
* switch. A repeat suppression keeps the first row (its reason and time).
|
|
14
|
+
* @complexity O(1) primary-key lookups/inserts.
|
|
15
|
+
* @example createMailSuppressionRepo({ db: kernel }).isSuppressed({ workspaceId, normalizedAddress, lane: "bulk" })
|
|
16
|
+
*/
|
|
17
|
+
export function createMailSuppressionRepo({ db }, optional = {}) {
|
|
18
|
+
const nowIso = optional.nowIso ?? (() => new Date().toISOString());
|
|
19
|
+
return {
|
|
20
|
+
async isSuppressed({ workspaceId, normalizedAddress, lane }) {
|
|
21
|
+
const scopes = sql.join(BLOCKING_SCOPES[lane].map((scope) => sql `${scope}`));
|
|
22
|
+
const rows = await db.query(sql `SELECT 1 AS hit FROM mail_suppression
|
|
23
|
+
WHERE workspace_id = ${workspaceId} AND normalized_address = ${normalize({ address: normalizedAddress })} AND scope IN (${scopes}) LIMIT 1`);
|
|
24
|
+
return rows.length > 0;
|
|
25
|
+
},
|
|
26
|
+
async suppress({ workspaceId, normalizedAddress, scope, reason }) {
|
|
27
|
+
await db.execute(sql `INSERT INTO mail_suppression (workspace_id, normalized_address, scope, reason, created_at, revision)
|
|
28
|
+
VALUES (${workspaceId}, ${normalize({ address: normalizedAddress })}, ${scope}, ${reason}, ${nowIso()}, ${randomUUID()})
|
|
29
|
+
ON CONFLICT (workspace_id, normalized_address, scope) DO NOTHING`);
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=suppression.repo.js.map
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import type { UserRepoPort } from "@jini-ai/core/contracts/site/user-management";
|
|
2
|
+
import type { MailTestModeSetting } from "@jini-ai/core/contracts/mail";
|
|
3
|
+
import { type MailSenderIdentityPort } from "./sender-identity.js";
|
|
4
|
+
import type { PositionalMailer as MailerPort, MailTestApproval } from "@jini-ai/core/contracts/mail";
|
|
5
|
+
/** A local limiter refusal: `duplicate` is a second click inside the guard window. */
|
|
6
|
+
export type MailTestSendRefusal = {
|
|
7
|
+
ok: false;
|
|
8
|
+
reason: "duplicate" | "rate_limited";
|
|
9
|
+
retryAfterMs: number;
|
|
10
|
+
};
|
|
11
|
+
/** Deliberate test sends per site; separate from (and in front of) the provider's own bucket. */
|
|
12
|
+
export interface MailTestSendLimiter {
|
|
13
|
+
tryTake(required: {
|
|
14
|
+
principalId: string;
|
|
15
|
+
to: string;
|
|
16
|
+
}): {
|
|
17
|
+
ok: true;
|
|
18
|
+
} | MailTestSendRefusal;
|
|
19
|
+
}
|
|
20
|
+
/** Ports the operation reads; the field names match `RouteDeps`, so a route can pass its deps through. */
|
|
21
|
+
export interface MailTestSendDeps {
|
|
22
|
+
workspaceId: string;
|
|
23
|
+
mailer: MailerPort;
|
|
24
|
+
/** Await current transactional resolution before freezing synchronous capabilities. */
|
|
25
|
+
mailLaneReady?: (required: {
|
|
26
|
+
lane: "transactional" | "bulk";
|
|
27
|
+
}) => Promise<boolean>;
|
|
28
|
+
/** The operator's account, for the default recipient. */
|
|
29
|
+
userRepo?: Pick<UserRepoPort, "findByPrincipalId">;
|
|
30
|
+
/** The site's system-mail From (`platform/mail/sender-identity.ts`). */
|
|
31
|
+
mailSenderIdentity?: MailSenderIdentityPort;
|
|
32
|
+
/** Host copy: the placeholder From for a non-delivering mailer, whose `name` also fills a configured
|
|
33
|
+
* sender's missing name. Absent: `no-reply@mail.local` named "Site". */
|
|
34
|
+
mailTestFallbackSender?: {
|
|
35
|
+
email: string;
|
|
36
|
+
name: string;
|
|
37
|
+
};
|
|
38
|
+
/** Shared by the route and the tool (one per site, `deps.ts`); absent (hermetic roots), only the
|
|
39
|
+
* provider's own limits apply. */
|
|
40
|
+
mailTestSendLimiter?: MailTestSendLimiter;
|
|
41
|
+
/** Fresh `core.mail.testMode`, so a redirect is reported as one. Absent: treated as off. */
|
|
42
|
+
mailTestMode?: () => Promise<MailTestModeSetting>;
|
|
43
|
+
mailTestProvider?: () => Promise<string | null>;
|
|
44
|
+
/** Site-owned request results, shared by HTTP and tools; no token is taken on replay. */
|
|
45
|
+
mailTestRequests?: Map<string, Promise<MailTestSendResult>>;
|
|
46
|
+
}
|
|
47
|
+
/** Where the message is meant to go, frozen before any approval card or send. */
|
|
48
|
+
export interface MailTestSendPlan {
|
|
49
|
+
to: string;
|
|
50
|
+
/** True when the caller chose the recipient; false for the operator's own address. */
|
|
51
|
+
chosen: boolean;
|
|
52
|
+
approval: MailTestApproval;
|
|
53
|
+
driver: string;
|
|
54
|
+
/** Set when test mode will rewrite the recipient. */
|
|
55
|
+
redirectTo?: string;
|
|
56
|
+
/** True when test mode keeps the message locally instead of sending it. */
|
|
57
|
+
capture?: boolean;
|
|
58
|
+
}
|
|
59
|
+
interface Common {
|
|
60
|
+
to: string;
|
|
61
|
+
from: string;
|
|
62
|
+
driver: string;
|
|
63
|
+
at: string;
|
|
64
|
+
}
|
|
65
|
+
export type MailTestSendResult =
|
|
66
|
+
/** The provider accepted the message for delivery; delivery itself is not yet known. */
|
|
67
|
+
Common & {
|
|
68
|
+
outcome: "accepted";
|
|
69
|
+
providerMessageId: string;
|
|
70
|
+
}
|
|
71
|
+
/** Nothing left this machine: kept by test-mode capture or printed by the local console driver. */
|
|
72
|
+
| Common & {
|
|
73
|
+
outcome: "captured";
|
|
74
|
+
where: "capture" | "console";
|
|
75
|
+
providerMessageId: string;
|
|
76
|
+
}
|
|
77
|
+
/** Test mode sent it to another address instead of `to`. */
|
|
78
|
+
| Common & {
|
|
79
|
+
outcome: "redirected";
|
|
80
|
+
redirectedTo: string;
|
|
81
|
+
providerMessageId: string;
|
|
82
|
+
}
|
|
83
|
+
/** Refused or failed; the code and message are the mailer's caller-safe ones. */
|
|
84
|
+
| Common & {
|
|
85
|
+
outcome: "failed" | "unknown";
|
|
86
|
+
errorCode: string;
|
|
87
|
+
message: string;
|
|
88
|
+
retryable: boolean;
|
|
89
|
+
retryAfterMs?: number;
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* A chosen recipient, or a caller error. Only one plain address is accepted.
|
|
93
|
+
* @complexity O(address length).
|
|
94
|
+
*/
|
|
95
|
+
export declare function readTestRecipient(required: {
|
|
96
|
+
value: unknown;
|
|
97
|
+
}, _options?: Record<string, never>): string | undefined;
|
|
98
|
+
/**
|
|
99
|
+
* Resolve the recipient and say where the message will really go. Sends nothing.
|
|
100
|
+
* @param required.principalId - The operator; their account address is the default recipient.
|
|
101
|
+
* @param required.to - An already validated chosen recipient ({@link readTestRecipient}).
|
|
102
|
+
* @complexity One user lookup and one settings read.
|
|
103
|
+
* @example await planMailTestSend({ deps, principalId, to: "ops@example.com" })
|
|
104
|
+
*/
|
|
105
|
+
export declare function planMailTestSend(required: {
|
|
106
|
+
principalId: string;
|
|
107
|
+
to?: string;
|
|
108
|
+
deps: MailTestSendDeps;
|
|
109
|
+
}, _options?: Record<string, never>): Promise<MailTestSendPlan>;
|
|
110
|
+
/**
|
|
111
|
+
* Send one test email as planned and report what is known. Refusals (local limiter, suppression,
|
|
112
|
+
* provider) come back as `outcome: "failed"` with their own code, never as a throw.
|
|
113
|
+
* @param required.plan - From {@link planMailTestSend}; re-validated permissions are the caller's job.
|
|
114
|
+
* @param required.ref - Stable id of this request (tool execution id or the route's request id): the
|
|
115
|
+
* idempotency key, so a retried request replays the ledger's answer instead of sending twice.
|
|
116
|
+
* @param optional.now - Clock for the result timestamp; defaults to `Date.now`.
|
|
117
|
+
* @complexity One limiter take and at most one delivery.
|
|
118
|
+
* @example await runMailTestSend({ deps, principalId, plan, ref: ctx.executionId })
|
|
119
|
+
*/
|
|
120
|
+
export declare function runMailTestSend(required: {
|
|
121
|
+
deps: MailTestSendDeps;
|
|
122
|
+
principalId: string;
|
|
123
|
+
plan: MailTestSendPlan;
|
|
124
|
+
ref: string;
|
|
125
|
+
}, optional?: {
|
|
126
|
+
now?: () => number;
|
|
127
|
+
}): Promise<MailTestSendResult>;
|
|
128
|
+
/** Defaults: 5 deliberate tests in a burst, one more every 12 minutes; a second click within 15 s is a duplicate. */
|
|
129
|
+
export declare const TEST_SEND_BURST = 5;
|
|
130
|
+
export declare const TEST_SEND_REFILL_MS: number;
|
|
131
|
+
export declare const TEST_SEND_DUPLICATE_MS = 15000;
|
|
132
|
+
/**
|
|
133
|
+
* One site-wide token bucket plus a per-(operator, recipient) duplicate-click guard, in memory.
|
|
134
|
+
* In memory is enough here: it protects inboxes and the provider quota from repeated clicks, and
|
|
135
|
+
* the send ledger's idempotency key already covers a replayed request.
|
|
136
|
+
* @param optional.now - Clock in ms; defaults to `Date.now`.
|
|
137
|
+
* @complexity O(1) amortized per take; the duplicate map keeps only entries inside the window.
|
|
138
|
+
* @example createMailTestSendLimiter({}, { now: () => 0 }).tryTake({ principalId: "p", to: "a@b.co" })
|
|
139
|
+
*/
|
|
140
|
+
export declare function createMailTestSendLimiter(_required?: Record<string, never>, optional?: {
|
|
141
|
+
now?: () => number;
|
|
142
|
+
burst?: number;
|
|
143
|
+
refillMs?: number;
|
|
144
|
+
duplicateMs?: number;
|
|
145
|
+
}): MailTestSendLimiter;
|
|
146
|
+
export {};
|
|
147
|
+
//# sourceMappingURL=test-send.d.ts.map
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The ONE test-send operation behind `mail_send_test` and
|
|
3
|
+
* `POST /api/admin/v1/workspaces/:workspaceId/system/mail-test-send` (email design, phase 3:
|
|
4
|
+
* "shared callable test operation + HTTP adapter; optional chosen recipient").
|
|
5
|
+
*
|
|
6
|
+
* The message goes through the site's normal mailer, so suppression, test mode, the provider's own
|
|
7
|
+
* rate limit and the send ledger all still apply; this file adds only what a deliberate,
|
|
8
|
+
* person-triggered test needs on top: a validated recipient (the operator's own address by
|
|
9
|
+
* default), Jini token accounting plus a duplicate-click guard, and a truthful outcome. A result says
|
|
10
|
+
* what is KNOWN at send time (accepted by the provider, captured locally, redirected by test mode,
|
|
11
|
+
* or failed); it never says "delivered", because only later provider feedback could.
|
|
12
|
+
*/
|
|
13
|
+
import { createMailLaneLimiter } from "./rate-limit.js";
|
|
14
|
+
import { ToolInputError } from "@jini-ai/core";
|
|
15
|
+
import { isMailDeliveryAvailable } from "./delivery-availability.js";
|
|
16
|
+
import { fromPositionalMailer } from "./plugin-abi.js";
|
|
17
|
+
import { createMailSenderIdentityResolver } from "./sender-identity.js";
|
|
18
|
+
/** Placeholder From for a non-delivering mailer; a real provider gets the site's configured sender. */
|
|
19
|
+
const TEST_FALLBACK_SENDER = { email: "no-reply@mail.local", name: "Site" };
|
|
20
|
+
/** The host's placeholder From, else the neutral one. @complexity O(1). */
|
|
21
|
+
function fallbackSenderOf({ deps }, _optional = {}) {
|
|
22
|
+
return deps.mailTestFallbackSender ?? TEST_FALLBACK_SENDER;
|
|
23
|
+
}
|
|
24
|
+
const MAX_ADDRESS = 254;
|
|
25
|
+
// One mailbox, no display name, no list: anything else is refused rather than guessed at.
|
|
26
|
+
const ADDRESS = /^[^\s@<>()[\]",;:\\]+@[^\s@<>()[\]",;:\\]+$/;
|
|
27
|
+
/**
|
|
28
|
+
* A chosen recipient, or a caller error. Only one plain address is accepted.
|
|
29
|
+
* @complexity O(address length).
|
|
30
|
+
*/
|
|
31
|
+
export function readTestRecipient(required, _options = {}) {
|
|
32
|
+
if (required.value === undefined)
|
|
33
|
+
return undefined;
|
|
34
|
+
const value = typeof required.value === "string" ? required.value.trim() : "";
|
|
35
|
+
const domain = value.slice(value.indexOf("@") + 1);
|
|
36
|
+
// Keep the plain-mailbox grammar while finding the domain dot without regex backtracking.
|
|
37
|
+
const hasDomainDot = domain.lastIndexOf(".", domain.length - 2) > 0;
|
|
38
|
+
if (value.length === 0 || value.length > MAX_ADDRESS || !ADDRESS.test(value) || !hasDomainDot) {
|
|
39
|
+
throw new ToolInputError({ message: "to must be one email address, such as owner@example.com. Nothing was sent." });
|
|
40
|
+
}
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The signed-in operator's own address: the account email, else a username that is an address.
|
|
45
|
+
* @throws {ToolInputError} When the account has no address and no recipient was chosen.
|
|
46
|
+
*/
|
|
47
|
+
async function operatorAddress({ deps, principalId }, _options = {}) {
|
|
48
|
+
const user = await deps.userRepo?.findByPrincipalId({ workspaceId: deps.workspaceId, principalId });
|
|
49
|
+
const address = [user?.email, user?.username].find((value) => typeof value === "string" && value.includes("@"));
|
|
50
|
+
if (!address)
|
|
51
|
+
throw new ToolInputError({ message: "Your account has no email address, so there is nowhere to send a test by default. Enter a recipient, or add an address to your user profile. Nothing was sent." });
|
|
52
|
+
return address;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Resolve the recipient and say where the message will really go. Sends nothing.
|
|
56
|
+
* @param required.principalId - The operator; their account address is the default recipient.
|
|
57
|
+
* @param required.to - An already validated chosen recipient ({@link readTestRecipient}).
|
|
58
|
+
* @complexity One user lookup and one settings read.
|
|
59
|
+
* @example await planMailTestSend({ deps, principalId, to: "ops@example.com" })
|
|
60
|
+
*/
|
|
61
|
+
export async function planMailTestSend(required, _options = {}) {
|
|
62
|
+
const { deps } = required;
|
|
63
|
+
await deps.mailLaneReady?.({ lane: "transactional" });
|
|
64
|
+
const to = required.to ?? await operatorAddress({ deps: deps, principalId: required.principalId });
|
|
65
|
+
const mode = deps.mailTestMode ? await deps.mailTestMode() : { mode: "off" };
|
|
66
|
+
const identity = deps.mailSenderIdentity ?? createMailSenderIdentityResolver({ readDriver: () => deps.mailer.capabilities().driver });
|
|
67
|
+
const from = await identity.resolve({ workspaceId: deps.workspaceId, fallback: fallbackSenderOf({ deps }) });
|
|
68
|
+
const providerId = deps.mailTestProvider ? await deps.mailTestProvider() : null;
|
|
69
|
+
return {
|
|
70
|
+
to, chosen: required.to !== undefined, driver: deps.mailer.capabilities().driver,
|
|
71
|
+
approval: { providerId, driver: deps.mailer.capabilities().driver, from, mode: mode.mode, effectiveRecipient: mode.mode === "redirect" ? mode.to : to },
|
|
72
|
+
...(mode.mode === "redirect" ? { redirectTo: mode.to } : {}), ...(mode.mode === "capture" ? { capture: true } : {}),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
const REFUSALS = {
|
|
76
|
+
duplicate: { errorCode: "MAIL_TEST_DUPLICATE", message: "A test email to this address was just sent; wait a moment before sending another." },
|
|
77
|
+
rate_limited: { errorCode: "MAIL_TEST_RATE_LIMITED", message: "Too many test emails were sent recently; try again later." },
|
|
78
|
+
};
|
|
79
|
+
/** What the mailer's answer means for this plan, most local explanation first. */
|
|
80
|
+
function outcomeOf({ plan, providerMessageId, mailer }, _options = {}) {
|
|
81
|
+
if (providerMessageId.startsWith("captured:"))
|
|
82
|
+
return "captured";
|
|
83
|
+
if (!isMailDeliveryAvailable({ mailer: fromPositionalMailer({ mailer }) }))
|
|
84
|
+
return "console";
|
|
85
|
+
return plan.redirectTo === undefined ? "accepted" : "redirected";
|
|
86
|
+
}
|
|
87
|
+
function successResult({ common, plan, providerMessageId, mailer }, _options = {}) {
|
|
88
|
+
const outcome = outcomeOf({ plan: plan, providerMessageId: providerMessageId, mailer: mailer });
|
|
89
|
+
if (outcome === "captured" || outcome === "console")
|
|
90
|
+
return { ...common, outcome: "captured", where: outcome === "console" ? "console" : "capture", providerMessageId };
|
|
91
|
+
if (outcome === "redirected") {
|
|
92
|
+
if (plan.redirectTo === undefined)
|
|
93
|
+
throw new Error("Redirected test mail has no recipient");
|
|
94
|
+
return { ...common, outcome, redirectedTo: plan.redirectTo, providerMessageId };
|
|
95
|
+
}
|
|
96
|
+
return { ...common, outcome: "accepted", providerMessageId };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Send one test email as planned and report what is known. Refusals (local limiter, suppression,
|
|
100
|
+
* provider) come back as `outcome: "failed"` with their own code, never as a throw.
|
|
101
|
+
* @param required.plan - From {@link planMailTestSend}; re-validated permissions are the caller's job.
|
|
102
|
+
* @param required.ref - Stable id of this request (tool execution id or the route's request id): the
|
|
103
|
+
* idempotency key, so a retried request replays the ledger's answer instead of sending twice.
|
|
104
|
+
* @param optional.now - Clock for the result timestamp; defaults to `Date.now`.
|
|
105
|
+
* @complexity One limiter take and at most one delivery.
|
|
106
|
+
* @example await runMailTestSend({ deps, principalId, plan, ref: ctx.executionId })
|
|
107
|
+
*/
|
|
108
|
+
export async function runMailTestSend(required, optional = {}) {
|
|
109
|
+
const { deps } = required;
|
|
110
|
+
const key = `${required.principalId}:${required.ref}`;
|
|
111
|
+
const existing = deps.mailTestRequests?.get(key);
|
|
112
|
+
if (existing)
|
|
113
|
+
return existing;
|
|
114
|
+
const pending = performMailTestSend(required, optional);
|
|
115
|
+
if (deps.mailTestRequests && deps.mailTestRequests.size >= 4096) {
|
|
116
|
+
const oldest = deps.mailTestRequests.keys().next();
|
|
117
|
+
if (oldest.done)
|
|
118
|
+
throw new Error("Test mail request cache has no oldest entry");
|
|
119
|
+
deps.mailTestRequests.delete(oldest.value);
|
|
120
|
+
}
|
|
121
|
+
deps.mailTestRequests?.set(key, pending);
|
|
122
|
+
// A failed dependency read has not dispatched a message and may be retried.
|
|
123
|
+
pending.catch(() => { if (deps.mailTestRequests?.get(key) === pending)
|
|
124
|
+
deps.mailTestRequests.delete(key); });
|
|
125
|
+
return pending;
|
|
126
|
+
}
|
|
127
|
+
/** Validate the frozen approval before any limiter take or dispatch. */
|
|
128
|
+
async function performMailTestSend(required, optional = {}) {
|
|
129
|
+
const { deps, plan } = required;
|
|
130
|
+
const fresh = await planMailTestSend({ ...{ principalId: required.principalId, to: plan.to }, deps: deps });
|
|
131
|
+
if (JSON.stringify(fresh.approval) !== JSON.stringify(plan.approval)) {
|
|
132
|
+
throw new ToolInputError({ message: "Mail configuration changed since approval. Prepare a new test-send approval; nothing was sent." });
|
|
133
|
+
}
|
|
134
|
+
const at = () => new Date((optional.now ?? Date.now)()).toISOString();
|
|
135
|
+
const from = fresh.approval.from;
|
|
136
|
+
const base = { to: plan.to, from: from.email, driver: plan.driver };
|
|
137
|
+
const taken = deps.mailTestSendLimiter?.tryTake({ principalId: required.principalId, to: plan.to.toLowerCase() }) ?? { ok: true };
|
|
138
|
+
if (!taken.ok)
|
|
139
|
+
return { ...base, at: at(), outcome: "failed", ...REFUSALS[taken.reason], retryable: true, retryAfterMs: taken.retryAfterMs };
|
|
140
|
+
const result = await deps.mailer.send({ workspaceId: deps.workspaceId, to: { email: plan.to }, from, subject: "Test email from your site", text: "This is a test email sent at your request. If you can read it, your site can deliver email." },
|
|
141
|
+
// The operator is waiting on this message: transactional, interactive lane.
|
|
142
|
+
{ mailTestApproval: plan.approval, idempotencyKey: `mail:test:${required.principalId}:${required.ref}`, workspaceId: deps.workspaceId, sourceContext: { module: "mail", ref: required.ref }, purpose: "transactional", lane: "interactive" });
|
|
143
|
+
const common = { ...base, at: at() };
|
|
144
|
+
if (result.ok)
|
|
145
|
+
return successResult({ common: common, plan: plan, providerMessageId: result.providerMessageId, mailer: deps.mailer });
|
|
146
|
+
return { ...common, outcome: result.unknown ? "unknown" : "failed", errorCode: result.errorCode, message: testSendFailureMessage({ errorCode: result.errorCode }), retryable: result.unknown ? false : result.retryable, ...(result.retryAfterMs === undefined ? {} : { retryAfterMs: result.retryAfterMs }) };
|
|
147
|
+
}
|
|
148
|
+
/** Only locally owned codes get specific copy; provider/SMTP text is never caller-safe. */
|
|
149
|
+
const SAFE_SEND_FAILURES = {
|
|
150
|
+
MAIL_TEST_DUPLICATE: REFUSALS.duplicate.message,
|
|
151
|
+
MAIL_TEST_RATE_LIMITED: REFUSALS.rate_limited.message,
|
|
152
|
+
MAIL_TEST_CAPTURE_UNAVAILABLE: "Capture mode is unavailable. Nothing was sent.",
|
|
153
|
+
MAIL_TEST_APPROVAL_CHANGED: "Mail configuration changed. Prepare a new approval; nothing was sent.",
|
|
154
|
+
MAIL_RECIPIENT_SUPPRESSED: "The recipient is on the do-not-send list. Nothing was sent.",
|
|
155
|
+
MAIL_RATE_LIMITED: "The mail delivery rate limit was reached. Try again later.",
|
|
156
|
+
MAIL_UNCONFIGURED: "No mail provider is configured. Nothing was sent.",
|
|
157
|
+
MAIL_PROVIDER_UNAVAILABLE: "The configured mail provider is unavailable. Check its configuration.",
|
|
158
|
+
};
|
|
159
|
+
/** Fixed copy by code, without reading the provider's message. @complexity O(1). */
|
|
160
|
+
function testSendFailureMessage({ errorCode }, _optional = {}) {
|
|
161
|
+
const safe = Object.hasOwn(SAFE_SEND_FAILURES, errorCode) ? SAFE_SEND_FAILURES[errorCode] : undefined;
|
|
162
|
+
return safe ?? `The provider refused the message (code ${errorCode}).`;
|
|
163
|
+
}
|
|
164
|
+
/** Defaults: 5 deliberate tests in a burst, one more every 12 minutes; a second click within 15 s is a duplicate. */
|
|
165
|
+
export const TEST_SEND_BURST = 5;
|
|
166
|
+
export const TEST_SEND_REFILL_MS = 12 * 60_000;
|
|
167
|
+
export const TEST_SEND_DUPLICATE_MS = 15_000;
|
|
168
|
+
/**
|
|
169
|
+
* One site-wide token bucket plus a per-(operator, recipient) duplicate-click guard, in memory.
|
|
170
|
+
* In memory is enough here: it protects inboxes and the provider quota from repeated clicks, and
|
|
171
|
+
* the send ledger's idempotency key already covers a replayed request.
|
|
172
|
+
* @param optional.now - Clock in ms; defaults to `Date.now`.
|
|
173
|
+
* @complexity O(1) amortized per take; the duplicate map keeps only entries inside the window.
|
|
174
|
+
* @example createMailTestSendLimiter({}, { now: () => 0 }).tryTake({ principalId: "p", to: "a@b.co" })
|
|
175
|
+
*/
|
|
176
|
+
export function createMailTestSendLimiter(_required = {}, optional = {}) {
|
|
177
|
+
const now = optional.now ?? Date.now;
|
|
178
|
+
const burst = optional.burst ?? TEST_SEND_BURST;
|
|
179
|
+
const refillMs = optional.refillMs ?? TEST_SEND_REFILL_MS;
|
|
180
|
+
const duplicateMs = optional.duplicateMs ?? TEST_SEND_DUPLICATE_MS;
|
|
181
|
+
const bucket = createMailLaneLimiter({ limit: { burst, perSecond: 1000 / refillMs } }, { now, reservedForTransactional: 0 });
|
|
182
|
+
const lastByKey = new Map();
|
|
183
|
+
return {
|
|
184
|
+
tryTake: ({ principalId, to }) => {
|
|
185
|
+
const at = now();
|
|
186
|
+
for (const [key, last] of lastByKey)
|
|
187
|
+
if (at - last >= duplicateMs)
|
|
188
|
+
lastByKey.delete(key);
|
|
189
|
+
const key = `${principalId}\u0000${to}`;
|
|
190
|
+
const last = lastByKey.get(key);
|
|
191
|
+
if (last !== undefined)
|
|
192
|
+
return { ok: false, reason: "duplicate", retryAfterMs: duplicateMs - (at - last) };
|
|
193
|
+
const taken = bucket.tryTake({ lane: "transactional" });
|
|
194
|
+
if (!taken.ok)
|
|
195
|
+
return { ...taken, reason: "rate_limited" };
|
|
196
|
+
lastByKey.set(key, at);
|
|
197
|
+
return { ok: true };
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
//# sourceMappingURL=test-send.js.map
|