@jini-ai/platform 0.7.3-next.2 → 0.7.4
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 +7 -0
- package/README.md +13 -0
- package/dist/download-lock.d.ts +3 -1
- package/dist/download-lock.js +4 -6
- 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 +62 -13
- 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/email-template.js +3 -7
- 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/purpose-scoped-mailer.d.ts +4 -0
- package/dist/mail/purpose-scoped-mailer.js +4 -3
- 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 +198 -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-top-footprint.js +1 -3
- 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 +12 -0
- package/dist/retention/preview-store.js +28 -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 +138 -6
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/** @file SQL adapter for Jini's `MailCapturePort` (migration 0023): test/capture mode's message sink. */
|
|
2
|
+
import { isLoopbackHostname } from "@jini-ai/core/net";
|
|
3
|
+
import { OriginNotVerifiedError, } from "@jini-ai/core/contracts/server/verified-origin";
|
|
4
|
+
import { mailActivityUse } from "./activity.repo.js";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { sql } from "kysely";
|
|
7
|
+
export const DEFAULT_CAPTURE_LIST = 50;
|
|
8
|
+
export const MAX_CAPTURE_LIST = 200;
|
|
9
|
+
/** Ids per `DELETE ... IN (...)`, under every dialect's bound-parameter limit. */
|
|
10
|
+
const CLEAR_CHUNK = 500;
|
|
11
|
+
const clampLimit = ({ limit }, _optional = {}) => Math.min(MAX_CAPTURE_LIST, Math.max(1, Math.trunc(limit ?? DEFAULT_CAPTURE_LIST)));
|
|
12
|
+
/**
|
|
13
|
+
* Stores sign-in captures whole only for trusted loopback origins, so local/desktop operators
|
|
14
|
+
* can click their links. Public or missing origins retain routing metadata only: subject, body,
|
|
15
|
+
* headers, names and attachments may all contain credentials and must never reach storage.
|
|
16
|
+
* @complexity capture O(payload size); listCaptured O(returned payload size), with a bounded indexed row limit;
|
|
17
|
+
* reviewCaptured O(workspace captures + captured attempts), two workspace-scoped reads; clearReviewedCaptures
|
|
18
|
+
* O(reviewed ids) primary-key deletes in ceil(ids / 500) statements per table plus one indexed ledger
|
|
19
|
+
* update per deleted attempt, one transaction.
|
|
20
|
+
* @example createMailCaptureRepo({ db: kernel }).capture({ message, lane: "transactional", idempotencyKey })
|
|
21
|
+
*/
|
|
22
|
+
export function createMailCaptureRepo({ db, origin }, optional = {}) {
|
|
23
|
+
const nowIso = optional.nowIso ?? (() => new Date().toISOString());
|
|
24
|
+
const newId = optional.newId ?? randomUUID;
|
|
25
|
+
return {
|
|
26
|
+
async capture({ message, lane, idempotencyKey }) {
|
|
27
|
+
const stored = await capturePayload({ message, idempotencyKey, origin });
|
|
28
|
+
const id = newId();
|
|
29
|
+
await db.execute(sql `INSERT INTO mail_capture (id, workspace_id, lane, idempotency_key, to_address, subject, payload_json, created_at)
|
|
30
|
+
VALUES (${id}, ${message.workspaceId}, ${lane}, ${idempotencyKey}, ${stored.to.email}, ${stored.subject}, ${JSON.stringify(stored)}, ${nowIso()})`);
|
|
31
|
+
return { id };
|
|
32
|
+
},
|
|
33
|
+
async listCaptured({ workspaceId }, options = {}) {
|
|
34
|
+
const rows = await db.query(sql `SELECT id, lane, idempotency_key, to_address, subject, payload_json, created_at FROM mail_capture
|
|
35
|
+
WHERE workspace_id = ${workspaceId} ORDER BY created_at DESC, id DESC LIMIT ${clampLimit({ limit: options.limit })}`);
|
|
36
|
+
return rows.map((row) => ({
|
|
37
|
+
id: row.id, lane: row.lane, idempotencyKey: row.idempotency_key, to: row.to_address, subject: row.subject,
|
|
38
|
+
message: JSON.parse(row.payload_json), createdAt: row.created_at,
|
|
39
|
+
}));
|
|
40
|
+
},
|
|
41
|
+
async reviewCaptured({ workspaceId }) {
|
|
42
|
+
const captures = await db.query(sql `SELECT id, created_at, idempotency_key, to_address AS recipient FROM mail_capture WHERE workspace_id = ${workspaceId} ORDER BY id`);
|
|
43
|
+
const attempts = await db.query(sql `SELECT id, created_at, idempotency_key, recipient FROM mail_activity_attempts
|
|
44
|
+
WHERE workspace_id = ${workspaceId} AND outcome = 'captured' ORDER BY id`);
|
|
45
|
+
const captureIds = captures.map((row) => row.id);
|
|
46
|
+
const attemptIds = attempts.map((row) => row.id);
|
|
47
|
+
const newestAt = [...captures, ...attempts].reduce((max, row) => (max === null || row.created_at > max ? row.created_at : max), null);
|
|
48
|
+
return { plan: { count: distinctEmails({ rows: [...captures, ...attempts] }), newestAt }, captureIds, attemptIds, revision: captureSetRevision({ workspaceId, captureIds, attemptIds }) };
|
|
49
|
+
},
|
|
50
|
+
clearReviewedCaptures: ({ workspaceId, captureIds, attemptIds }) => db.transaction(() => deleteReviewedCaptureRows({ db, workspaceId, captureIds, attemptIds })),
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
async function deleteReviewedCaptureRows({ db, workspaceId, captureIds, attemptIds }) {
|
|
54
|
+
const removed = [];
|
|
55
|
+
for (let at = 0; at < captureIds.length; at += CLEAR_CHUNK) {
|
|
56
|
+
const ids = captureIds.slice(at, at + CLEAR_CHUNK);
|
|
57
|
+
// RETURNING reads deleted rows the same way on SQLite and Postgres.
|
|
58
|
+
removed.push(...await db.query(sql `DELETE FROM mail_capture WHERE workspace_id = ${workspaceId} AND id IN (${sql.join(ids)})
|
|
59
|
+
RETURNING id, created_at, idempotency_key, to_address AS recipient`));
|
|
60
|
+
}
|
|
61
|
+
for (let at = 0; at < attemptIds.length; at += CLEAR_CHUNK) {
|
|
62
|
+
const ids = attemptIds.slice(at, at + CLEAR_CHUNK);
|
|
63
|
+
// `outcome = 'captured'` again: an attempt upserted into a real send since the review is not a test email.
|
|
64
|
+
const rows = await db.query(sql `DELETE FROM mail_activity_attempts WHERE workspace_id = ${workspaceId} AND outcome = 'captured' AND id IN (${sql.join(ids)})
|
|
65
|
+
RETURNING id, created_at, idempotency_key, recipient`);
|
|
66
|
+
// The activity list falls back to a retained ledger row when its attempt is missing; retire it (as retention does) so the cleared send stays gone.
|
|
67
|
+
for (const row of rows) {
|
|
68
|
+
await db.execute(sql `UPDATE mail_send_ledger SET activity_retained = 0 WHERE workspace_id = ${workspaceId} AND idempotency_key = ${row.idempotency_key} AND recipient = ${row.recipient}`);
|
|
69
|
+
}
|
|
70
|
+
removed.push(...rows);
|
|
71
|
+
}
|
|
72
|
+
return { deleted: distinctEmails({ rows: removed }) };
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The revision of one workspace's reviewed capture set: a digest of its sorted ids, so two different
|
|
76
|
+
* sets with the same count and newest time never share a revision. @complexity O(ids log ids).
|
|
77
|
+
*/
|
|
78
|
+
function captureSetRevision(required, _optional = {}) {
|
|
79
|
+
const { workspaceId, captureIds, attemptIds } = required;
|
|
80
|
+
const digest = createHash("sha256").update(workspaceId);
|
|
81
|
+
for (const id of [...captureIds].sort())
|
|
82
|
+
digest.update("\nc:").update(id);
|
|
83
|
+
for (const id of [...attemptIds].sort())
|
|
84
|
+
digest.update("\na:").update(id);
|
|
85
|
+
return `captures-v2:${captureIds.length}:${attemptIds.length}:${digest.digest("base64url")}`;
|
|
86
|
+
}
|
|
87
|
+
/** One test email per (idempotency key, recipient): a test-mode capture and its activity row count once. @complexity O(rows). */
|
|
88
|
+
function distinctEmails({ rows }, _optional = {}) {
|
|
89
|
+
return new Set(rows.map((row) => `${row.idempotency_key}\n${row.recipient.trim().toLowerCase()}`)).size;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Redacts sign-in captures at the persistence boundary, before serialization. The activity owner
|
|
93
|
+
* classifies the host's purpose keys; Jini owns loopback detection. Missing evidence fails closed.
|
|
94
|
+
* @returns The original local/non-auth message, or an allowlisted public sign-in envelope.
|
|
95
|
+
* @throws Unexpected origin/storage failures propagate; no unredacted fallback is persisted.
|
|
96
|
+
* @complexity O(1), at most one origin read; redaction does not scan credential-bearing content.
|
|
97
|
+
*/
|
|
98
|
+
async function capturePayload(required, _options = {}) {
|
|
99
|
+
const { message, idempotencyKey, origin } = required;
|
|
100
|
+
if (mailActivityUse({ idempotencyKey }) !== "sign_in")
|
|
101
|
+
return message;
|
|
102
|
+
try {
|
|
103
|
+
const canonical = await origin?.canonicalOrigin({ workspaceId: message.workspaceId });
|
|
104
|
+
if (canonical && isLoopbackHostname({ hostname: canonical.host }))
|
|
105
|
+
return message;
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
if (!(err instanceof OriginNotVerifiedError))
|
|
109
|
+
throw err;
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
workspaceId: message.workspaceId,
|
|
113
|
+
to: { email: message.to.email },
|
|
114
|
+
from: { email: message.from.email },
|
|
115
|
+
subject: "Sign-in email (content redacted)",
|
|
116
|
+
text: "Authentication content is not stored on public sites.",
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
//# sourceMappingURL=capture.repo.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { MailFeedbackInboxPort } from "../feedback.js";
|
|
2
|
+
import type { MailRepoDeps, MailRepoOptions } from "./ledger.repo.js";
|
|
3
|
+
/**
|
|
4
|
+
* Provider feedback events, insert-if-absent on (provider, event id): a provider's replay of an
|
|
5
|
+
* event it already delivered is reported `duplicate`, so suppression is written once.
|
|
6
|
+
* Only a row whose `processed_at` is set (by `complete`, after suppression succeeded) counts as
|
|
7
|
+
* delivered: a replay of an unprocessed row is reported `inserted` so the ingest re-applies it.
|
|
8
|
+
* @complexity O(1) per event.
|
|
9
|
+
* @example createMailFeedbackInboxRepo({ db: kernel }).record({ providerId: "<mail-provider-id>", event })
|
|
10
|
+
*/
|
|
11
|
+
export declare function createMailFeedbackInboxRepo<DB>({ db }: MailRepoDeps<DB>, optional?: MailRepoOptions): MailFeedbackInboxPort;
|
|
12
|
+
//# sourceMappingURL=feedback-inbox.repo.d.ts.map
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** @file SQL adapter for Jini's `MailFeedbackInboxPort` (migrations 0023, 0025), one body for SQLite and Postgres. */
|
|
2
|
+
import { sql } from "kysely";
|
|
3
|
+
/**
|
|
4
|
+
* Provider feedback events, insert-if-absent on (provider, event id): a provider's replay of an
|
|
5
|
+
* event it already delivered is reported `duplicate`, so suppression is written once.
|
|
6
|
+
* Only a row whose `processed_at` is set (by `complete`, after suppression succeeded) counts as
|
|
7
|
+
* delivered: a replay of an unprocessed row is reported `inserted` so the ingest re-applies it.
|
|
8
|
+
* @complexity O(1) per event.
|
|
9
|
+
* @example createMailFeedbackInboxRepo({ db: kernel }).record({ providerId: "<mail-provider-id>", event })
|
|
10
|
+
*/
|
|
11
|
+
export function createMailFeedbackInboxRepo({ db }, optional = {}) {
|
|
12
|
+
const nowIso = optional.nowIso ?? (() => new Date().toISOString());
|
|
13
|
+
return {
|
|
14
|
+
async record({ providerId, event }) {
|
|
15
|
+
const inserted = await db.query(sql `INSERT INTO mail_feedback_inbox
|
|
16
|
+
(provider_id, event_id, workspace_id, recipient, kind, hard_bounce, provider_message_id, occurred_at, received_at)
|
|
17
|
+
VALUES (${providerId}, ${event.eventId}, ${event.workspaceId}, ${event.recipient}, ${event.kind}, ${event.hardBounce ? 1 : 0},
|
|
18
|
+
${event.providerMessageId}, ${event.occurredAt}, ${nowIso()})
|
|
19
|
+
ON CONFLICT (provider_id, event_id) DO NOTHING RETURNING event_id`);
|
|
20
|
+
if (inserted.length > 0)
|
|
21
|
+
return "inserted";
|
|
22
|
+
const [row] = await db.query(sql `SELECT processed_at FROM mail_feedback_inbox
|
|
23
|
+
WHERE provider_id = ${providerId} AND event_id = ${event.eventId}`);
|
|
24
|
+
// The INSERT conflicted, so the row exists; a workspace delete cascading in between is not retried.
|
|
25
|
+
return row.processed_at === null ? "inserted" : "duplicate";
|
|
26
|
+
},
|
|
27
|
+
async complete({ providerId, eventId }) {
|
|
28
|
+
await db.execute(sql `UPDATE mail_feedback_inbox SET processed_at = ${nowIso()} WHERE provider_id = ${providerId} AND event_id = ${eventId}`);
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
//# sourceMappingURL=feedback-inbox.repo.js.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** @file `@jini-ai/platform/mail/sql`: Kysely SQL adapters for the mail ports (ledgers, suppression,
|
|
2
|
+
* capture, activity, feedback inbox, retention). Opt-in: importing this subpath needs `kysely`. */
|
|
3
|
+
export { createMailSendLedgerRepo, type MailRepoDeps, type MailRepoOptions, type MailSqlKernel } from "./ledger.repo.js";
|
|
4
|
+
export { createMailSuppressionRepo } from "./suppression.repo.js";
|
|
5
|
+
export { createMailSuppressionAdminRepo } from "./suppression-admin.repo.js";
|
|
6
|
+
export { createMailFeedbackInboxRepo } from "./feedback-inbox.repo.js";
|
|
7
|
+
export { createMailCaptureRepo, DEFAULT_CAPTURE_LIST, MAX_CAPTURE_LIST, type CapturedMail, type MailCaptureRepo } from "./capture.repo.js";
|
|
8
|
+
export { createMailActivityRepo, mailActivityUse } from "./activity.repo.js";
|
|
9
|
+
export { createMailAttemptObserver, type MailAttemptObserver } from "./attempts.repo.js";
|
|
10
|
+
export { purgeExpiredMail, startMailRetention, type MailRetentionOptions, MAIL_ACTIVITY_RETENTION_MS, MAIL_CAPTURE_RETENTION_MS, MAIL_RETENTION_INTERVAL_MS } from "./retention.js";
|
|
11
|
+
export { createSiteMailFeedbackRoute } from "./site-feedback-route.js";
|
|
12
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** @file `@jini-ai/platform/mail/sql`: Kysely SQL adapters for the mail ports (ledgers, suppression,
|
|
2
|
+
* capture, activity, feedback inbox, retention). Opt-in: importing this subpath needs `kysely`. */
|
|
3
|
+
export { createMailSendLedgerRepo } from "./ledger.repo.js";
|
|
4
|
+
export { createMailSuppressionRepo } from "./suppression.repo.js";
|
|
5
|
+
export { createMailSuppressionAdminRepo } from "./suppression-admin.repo.js";
|
|
6
|
+
export { createMailFeedbackInboxRepo } from "./feedback-inbox.repo.js";
|
|
7
|
+
export { createMailCaptureRepo, DEFAULT_CAPTURE_LIST, MAX_CAPTURE_LIST } from "./capture.repo.js";
|
|
8
|
+
export { createMailActivityRepo, mailActivityUse } from "./activity.repo.js";
|
|
9
|
+
export { createMailAttemptObserver } from "./attempts.repo.js";
|
|
10
|
+
export { purgeExpiredMail, startMailRetention, MAIL_ACTIVITY_RETENTION_MS, MAIL_CAPTURE_RETENTION_MS, MAIL_RETENTION_INTERVAL_MS } from "./retention.js";
|
|
11
|
+
export { createSiteMailFeedbackRoute } from "./site-feedback-route.js";
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Kysely, RawBuilder } from "kysely";
|
|
2
|
+
import type { StorageKernel } from "@jini-ai/core/contracts/storage";
|
|
3
|
+
import type { MailSendLedgerPort } from "../ports.js";
|
|
4
|
+
/** The content database kernel. Generic so a typed `ContentKernel` fits: these tables are raw SQL,
|
|
5
|
+
* outside the generated Kysely types, so only `query`/`execute`/`transaction`/`lockKey` are used. */
|
|
6
|
+
export interface MailRepoDeps<DB = unknown> {
|
|
7
|
+
db: MailSqlKernel<DB>;
|
|
8
|
+
}
|
|
9
|
+
/** Core's storage kernel over a Kysely handle, plus raw `sql` statements: `query` returns rows,
|
|
10
|
+
* `execute` returns none. A host's Kysely-bound kernel (`@jini-ai/db/kernel`) fits structurally. */
|
|
11
|
+
export interface MailSqlKernel<DB = unknown> extends StorageKernel<Kysely<DB>, DB> {
|
|
12
|
+
query<Row>(statement: RawBuilder<Row>): Promise<Row[]>;
|
|
13
|
+
execute(statement: RawBuilder<unknown>): Promise<void>;
|
|
14
|
+
}
|
|
15
|
+
export interface MailRepoOptions {
|
|
16
|
+
/** Injected ISO clock; defaults to the wall clock. */
|
|
17
|
+
nowIso?: () => string;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Reserve → send → mark ledger. `reserve` inserts-if-absent, then flips a `failed` row (or, with
|
|
21
|
+
* `reclaimUnknown`, a same-content `unknown` row) back to `reserved` in one conditional UPDATE (a
|
|
22
|
+
* definitive failure sent nothing, so a retry under the same identity is safe), else returns the
|
|
23
|
+
* stored row. Both run under the identity's `lockKey`, so a
|
|
24
|
+
* concurrent `mark` cannot turn the row `failed` between the flip and the read.
|
|
25
|
+
* @complexity O(1) primary-key statements per call.
|
|
26
|
+
* @example createMailSendLedgerRepo({ db: kernel }).reserve({ workspaceId, idempotencyKey, recipient, payloadHash, lane: "transactional", providerId: "smtp" })
|
|
27
|
+
*/
|
|
28
|
+
export declare function createMailSendLedgerRepo<DB>({ db }: MailRepoDeps<DB>, optional?: MailRepoOptions): MailSendLedgerPort;
|
|
29
|
+
//# sourceMappingURL=ledger.repo.d.ts.map
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** @file SQL adapter for Jini's `MailSendLedgerPort` (migration 0023), one body for SQLite and Postgres. */
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { sql } from "kysely";
|
|
4
|
+
/** One advisory lock per ledger identity: reserve's read-after-write and mark never interleave. */
|
|
5
|
+
function lockName({ workspaceId, idempotencyKey, recipient }) {
|
|
6
|
+
return `mail-ledger:${workspaceId}:${idempotencyKey}:${recipient}`;
|
|
7
|
+
}
|
|
8
|
+
function existingOf(row) {
|
|
9
|
+
return {
|
|
10
|
+
status: "existing", outcome: row.outcome, payloadHash: row.payload_hash,
|
|
11
|
+
...(row.provider_message_id === null ? {} : { providerMessageId: row.provider_message_id }),
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Reserve → send → mark ledger. `reserve` inserts-if-absent, then flips a `failed` row (or, with
|
|
16
|
+
* `reclaimUnknown`, a same-content `unknown` row) back to `reserved` in one conditional UPDATE (a
|
|
17
|
+
* definitive failure sent nothing, so a retry under the same identity is safe), else returns the
|
|
18
|
+
* stored row. Both run under the identity's `lockKey`, so a
|
|
19
|
+
* concurrent `mark` cannot turn the row `failed` between the flip and the read.
|
|
20
|
+
* @complexity O(1) primary-key statements per call.
|
|
21
|
+
* @example createMailSendLedgerRepo({ db: kernel }).reserve({ workspaceId, idempotencyKey, recipient, payloadHash, lane: "transactional", providerId: "smtp" })
|
|
22
|
+
*/
|
|
23
|
+
export function createMailSendLedgerRepo({ db }, optional = {}) {
|
|
24
|
+
const nowIso = optional.nowIso ?? (() => new Date().toISOString());
|
|
25
|
+
const where = ({ workspaceId, idempotencyKey, recipient }) => sql `workspace_id = ${workspaceId} AND idempotency_key = ${idempotencyKey} AND recipient = ${recipient}`;
|
|
26
|
+
const reserve = async (required, _optional = {}) => {
|
|
27
|
+
const { workspaceId, idempotencyKey, recipient, payloadHash, lane, providerId, reclaimUnknown } = required;
|
|
28
|
+
await db.lockKey(lockName(required));
|
|
29
|
+
const at = nowIso();
|
|
30
|
+
const inserted = await db.query(sql `INSERT INTO mail_send_ledger (workspace_id, idempotency_key, recipient, payload_hash, lane, provider_id, outcome, created_at, updated_at, activity_id)
|
|
31
|
+
VALUES (${workspaceId}, ${idempotencyKey}, ${recipient}, ${payloadHash}, ${lane}, ${providerId}, 'reserved', ${at}, ${at}, ${randomUUID()})
|
|
32
|
+
ON CONFLICT (workspace_id, idempotency_key, recipient) DO NOTHING RETURNING outcome`);
|
|
33
|
+
if (inserted.length > 0)
|
|
34
|
+
return { status: "reserved" };
|
|
35
|
+
// A corrected retry after a definitive failure may carry new content, so the hash moves with it.
|
|
36
|
+
// A resendable `unknown` row is claimed only for the same content: the flip to `reserved` is the
|
|
37
|
+
// claim, so of two concurrent retries exactly one re-sends and the other sees `reserved`.
|
|
38
|
+
const unknown = reclaimUnknown ? sql `OR (outcome = 'unknown' AND payload_hash = ${payloadHash})` : sql ``;
|
|
39
|
+
const flipped = await db.query(sql `UPDATE mail_send_ledger SET outcome = 'reserved', payload_hash = ${payloadHash}, lane = ${lane},
|
|
40
|
+
provider_id = ${providerId}, provider_message_id = NULL, error_code = NULL, updated_at = ${at}
|
|
41
|
+
WHERE ${where(required)} AND (outcome = 'failed' ${unknown}) RETURNING outcome`);
|
|
42
|
+
if (flipped.length > 0)
|
|
43
|
+
return { status: "reserved" };
|
|
44
|
+
const [row] = await db.query(sql `SELECT outcome, payload_hash, provider_message_id FROM mail_send_ledger WHERE ${where(required)}`);
|
|
45
|
+
// The INSERT conflicted under the identity lock, so the row exists and is not `failed`.
|
|
46
|
+
return existingOf(row);
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
reserve: (required, optional = {}) => db.transaction(async () => reserve({ ...required, reclaimUnknown: optional.reclaimUnknown === true })),
|
|
50
|
+
mark: (required) => db.transaction(async () => {
|
|
51
|
+
await db.lockKey(lockName(required));
|
|
52
|
+
await db.execute(sql `UPDATE mail_send_ledger SET outcome = ${required.outcome}, provider_message_id = ${required.providerMessageId ?? null},
|
|
53
|
+
error_code = ${required.errorCode ?? null}, updated_at = ${nowIso()} WHERE ${where(required)}`);
|
|
54
|
+
}),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=ledger.repo.js.map
|
|
@@ -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
|