@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,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,198 @@
|
|
|
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 { outcome: "captured" };
|
|
83
|
+
if (!isMailDeliveryAvailable({ mailer: fromPositionalMailer({ mailer }) }))
|
|
84
|
+
return { outcome: "console" };
|
|
85
|
+
const redirectedTo = plan.redirectTo;
|
|
86
|
+
return redirectedTo === undefined ? { outcome: "accepted" } : { outcome: "redirected", redirectedTo };
|
|
87
|
+
}
|
|
88
|
+
function successResult({ common, plan, providerMessageId, mailer }, _options = {}) {
|
|
89
|
+
const result = outcomeOf({ plan: plan, providerMessageId: providerMessageId, mailer: mailer });
|
|
90
|
+
const { outcome } = result;
|
|
91
|
+
if (outcome === "captured" || outcome === "console")
|
|
92
|
+
return { ...common, outcome: "captured", where: outcome === "console" ? "console" : "capture", providerMessageId };
|
|
93
|
+
if (result.outcome === "redirected")
|
|
94
|
+
return { ...common, ...result, providerMessageId };
|
|
95
|
+
return { ...common, outcome: "accepted", providerMessageId };
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Send one test email as planned and report what is known. Refusals (local limiter, suppression,
|
|
99
|
+
* provider) come back as `outcome: "failed"` with their own code, never as a throw.
|
|
100
|
+
* @param required.plan - From {@link planMailTestSend}; re-validated permissions are the caller's job.
|
|
101
|
+
* @param required.ref - Stable id of this request (tool execution id or the route's request id): the
|
|
102
|
+
* idempotency key, so a retried request replays the ledger's answer instead of sending twice.
|
|
103
|
+
* @param optional.now - Clock for the result timestamp; defaults to `Date.now`.
|
|
104
|
+
* @complexity One limiter take and at most one delivery.
|
|
105
|
+
* @example await runMailTestSend({ deps, principalId, plan, ref: ctx.executionId })
|
|
106
|
+
*/
|
|
107
|
+
export async function runMailTestSend(required, optional = {}) {
|
|
108
|
+
const { deps } = required;
|
|
109
|
+
const key = `${required.principalId}:${required.ref}`;
|
|
110
|
+
const existing = deps.mailTestRequests?.get(key);
|
|
111
|
+
if (existing)
|
|
112
|
+
return existing;
|
|
113
|
+
const pending = performMailTestSend(required, optional);
|
|
114
|
+
if (deps.mailTestRequests && deps.mailTestRequests.size >= 4096) {
|
|
115
|
+
const oldest = deps.mailTestRequests.keys().next();
|
|
116
|
+
deps.mailTestRequests.delete(oldest.value);
|
|
117
|
+
}
|
|
118
|
+
deps.mailTestRequests?.set(key, pending);
|
|
119
|
+
// A failed dependency read has not dispatched a message and may be retried.
|
|
120
|
+
pending.catch(() => { if (deps.mailTestRequests?.get(key) === pending)
|
|
121
|
+
deps.mailTestRequests.delete(key); });
|
|
122
|
+
return pending;
|
|
123
|
+
}
|
|
124
|
+
/** Validate the frozen approval before any limiter take or dispatch. */
|
|
125
|
+
async function performMailTestSend(required, optional = {}) {
|
|
126
|
+
const { deps, plan } = required;
|
|
127
|
+
const fresh = await planMailTestSend({ ...{ principalId: required.principalId, to: plan.to }, deps: deps });
|
|
128
|
+
if (JSON.stringify(fresh.approval) !== JSON.stringify(plan.approval)) {
|
|
129
|
+
throw new ToolInputError({ message: "Mail configuration changed since approval. Prepare a new test-send approval; nothing was sent." });
|
|
130
|
+
}
|
|
131
|
+
const at = () => new Date((optional.now ?? Date.now)()).toISOString();
|
|
132
|
+
const from = fresh.approval.from;
|
|
133
|
+
const base = { to: plan.to, from: from.email, driver: plan.driver };
|
|
134
|
+
const taken = deps.mailTestSendLimiter?.tryTake({ principalId: required.principalId, to: plan.to.toLowerCase() }) ?? { ok: true };
|
|
135
|
+
if (!taken.ok)
|
|
136
|
+
return { ...base, at: at(), outcome: "failed", ...REFUSALS[taken.reason], retryable: true, retryAfterMs: taken.retryAfterMs };
|
|
137
|
+
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." },
|
|
138
|
+
// The operator is waiting on this message: transactional, interactive lane.
|
|
139
|
+
{ mailTestApproval: plan.approval, idempotencyKey: `mail:test:${required.principalId}:${required.ref}`, workspaceId: deps.workspaceId, sourceContext: { module: "mail", ref: required.ref }, purpose: "transactional", lane: "interactive" });
|
|
140
|
+
const common = { ...base, at: at() };
|
|
141
|
+
if (result.ok)
|
|
142
|
+
return successResult({ common: common, plan: plan, providerMessageId: result.providerMessageId, mailer: deps.mailer });
|
|
143
|
+
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 }) };
|
|
144
|
+
}
|
|
145
|
+
/** Only locally owned codes get specific copy; provider/SMTP text is never caller-safe. */
|
|
146
|
+
const SAFE_SEND_FAILURES = {
|
|
147
|
+
MAIL_TEST_DUPLICATE: REFUSALS.duplicate.message,
|
|
148
|
+
MAIL_TEST_RATE_LIMITED: REFUSALS.rate_limited.message,
|
|
149
|
+
MAIL_TEST_CAPTURE_UNAVAILABLE: "Capture mode is unavailable. Nothing was sent.",
|
|
150
|
+
MAIL_TEST_APPROVAL_CHANGED: "Mail configuration changed. Prepare a new approval; nothing was sent.",
|
|
151
|
+
MAIL_RECIPIENT_SUPPRESSED: "The recipient is on the do-not-send list. Nothing was sent.",
|
|
152
|
+
MAIL_RATE_LIMITED: "The mail delivery rate limit was reached. Try again later.",
|
|
153
|
+
MAIL_UNCONFIGURED: "No mail provider is configured. Nothing was sent.",
|
|
154
|
+
MAIL_PROVIDER_UNAVAILABLE: "The configured mail provider is unavailable. Check its configuration.",
|
|
155
|
+
};
|
|
156
|
+
/** Fixed copy by code, without reading the provider's message. @complexity O(1). */
|
|
157
|
+
function testSendFailureMessage({ errorCode }, _optional = {}) {
|
|
158
|
+
const safe = Object.hasOwn(SAFE_SEND_FAILURES, errorCode) ? SAFE_SEND_FAILURES[errorCode] : undefined;
|
|
159
|
+
return safe ?? `The provider refused the message (code ${errorCode}).`;
|
|
160
|
+
}
|
|
161
|
+
/** Defaults: 5 deliberate tests in a burst, one more every 12 minutes; a second click within 15 s is a duplicate. */
|
|
162
|
+
export const TEST_SEND_BURST = 5;
|
|
163
|
+
export const TEST_SEND_REFILL_MS = 12 * 60_000;
|
|
164
|
+
export const TEST_SEND_DUPLICATE_MS = 15_000;
|
|
165
|
+
/**
|
|
166
|
+
* One site-wide token bucket plus a per-(operator, recipient) duplicate-click guard, in memory.
|
|
167
|
+
* In memory is enough here: it protects inboxes and the provider quota from repeated clicks, and
|
|
168
|
+
* the send ledger's idempotency key already covers a replayed request.
|
|
169
|
+
* @param optional.now - Clock in ms; defaults to `Date.now`.
|
|
170
|
+
* @complexity O(1) amortized per take; the duplicate map keeps only entries inside the window.
|
|
171
|
+
* @example createMailTestSendLimiter({}, { now: () => 0 }).tryTake({ principalId: "p", to: "a@b.co" })
|
|
172
|
+
*/
|
|
173
|
+
export function createMailTestSendLimiter(_required = {}, optional = {}) {
|
|
174
|
+
const now = optional.now ?? Date.now;
|
|
175
|
+
const burst = optional.burst ?? TEST_SEND_BURST;
|
|
176
|
+
const refillMs = optional.refillMs ?? TEST_SEND_REFILL_MS;
|
|
177
|
+
const duplicateMs = optional.duplicateMs ?? TEST_SEND_DUPLICATE_MS;
|
|
178
|
+
const bucket = createMailLaneLimiter({ limit: { burst, perSecond: 1000 / refillMs } }, { now, reservedForTransactional: 0 });
|
|
179
|
+
const lastByKey = new Map();
|
|
180
|
+
return {
|
|
181
|
+
tryTake: ({ principalId, to }) => {
|
|
182
|
+
const at = now();
|
|
183
|
+
for (const [key, last] of lastByKey)
|
|
184
|
+
if (at - last >= duplicateMs)
|
|
185
|
+
lastByKey.delete(key);
|
|
186
|
+
const key = `${principalId}\u0000${to}`;
|
|
187
|
+
const last = lastByKey.get(key);
|
|
188
|
+
if (last !== undefined)
|
|
189
|
+
return { ok: false, reason: "duplicate", retryAfterMs: duplicateMs - (at - last) };
|
|
190
|
+
const taken = bucket.tryTake({ lane: "transactional" });
|
|
191
|
+
if (!taken.ok)
|
|
192
|
+
return { ...taken, reason: "rate_limited" };
|
|
193
|
+
lastByKey.set(key, at);
|
|
194
|
+
return { ok: true };
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
//# sourceMappingURL=test-send.js.map
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file **What uses email** (email phase 4): one readiness row per use of the site's mail, built
|
|
3
|
+
* from the checks each owning feature already runs, never a second copy of them.
|
|
4
|
+
*
|
|
5
|
+
* | Use | Owner checks reused |
|
|
6
|
+
* |---|---|
|
|
7
|
+
* | Sign-in links | the members sender (`mailSenderIdentity`, as `members/write-service.ts` resolves it), Jini's purpose gate on the interactive lane |
|
|
8
|
+
* | Confirmations | Newsletter's `evaluateLaunchGate` test-send subset (origin, production mailer) that `confirmation.ts` needs, the sender, the interactive gate |
|
|
9
|
+
* | Form notifications | Forms' definitions (`notify.enabled` + recipients, as `@jini-ai/cms/forms`' subscriber reads them), the sender, the notification-lane gate |
|
|
10
|
+
* | Newsletter | `evaluateLaunchGate` in full, the sender, the notification-lane gate |
|
|
11
|
+
*
|
|
12
|
+
* The purpose gate is asked through `platform/mail/purpose-gate-probe.ts`, so the production
|
|
13
|
+
* `durableOutboxReady` gate is surfaced as a blocker exactly as it decides, and is not changed here.
|
|
14
|
+
*
|
|
15
|
+
* State per row: blocked > not_configured > disabled > ready, every reason kept. A check that
|
|
16
|
+
* throws makes only its own row `unknown`. Evidence (the last observed outcome, from the activity
|
|
17
|
+
* projection) is separate: a ready row with a bounced last send is both, and a failed evidence read
|
|
18
|
+
* leaves the state standing with `evidence: null`.
|
|
19
|
+
*/
|
|
20
|
+
import { type MailSenderIdentityPort } from "./sender-identity.js";
|
|
21
|
+
import type { FormDefinitionRepoPort } from "@jini-ai/core/contracts/site/cms-forms";
|
|
22
|
+
import type { OriginRegistryPort } from "@jini-ai/core/contracts/server/verified-origin";
|
|
23
|
+
import type { PositionalMailer as MailerPort } from "@jini-ai/core/contracts/mail";
|
|
24
|
+
import type { MailActivityOutcome } from "./activity/vocabulary.js";
|
|
25
|
+
import type { MailActivityRepo } from "./activity/ports.js";
|
|
26
|
+
import type { MailPurposeGateProbe } from "./purpose-gate-probe.js";
|
|
27
|
+
import type { MailLaunchGateResult } from "@jini-ai/core/contracts/site/platform-mail";
|
|
28
|
+
export type MailUseState = "ready" | "blocked" | "disabled" | "not_configured" | "unknown";
|
|
29
|
+
export type MailUseId = "sign_in" | "newsletter_confirmation" | "form_notifications" | "newsletter";
|
|
30
|
+
export interface MailUseRow {
|
|
31
|
+
use: MailUseId;
|
|
32
|
+
label: string;
|
|
33
|
+
/** Jini's send lane: interactive sends bypass the durable-outbox gate, notifications do not. */
|
|
34
|
+
sendLane: "interactive" | "notification";
|
|
35
|
+
/** The delivery lane (suppression scope, provider capacity). */
|
|
36
|
+
mailLane: "transactional" | "bulk";
|
|
37
|
+
state: MailUseState;
|
|
38
|
+
/** Stable codes, in check order (e.g. `sender_not_configured`, `durable_outbox_not_ready`). */
|
|
39
|
+
reasons: string[];
|
|
40
|
+
/** The From this use would send with now; null when unresolved. */
|
|
41
|
+
sender: string | null;
|
|
42
|
+
/** The feature that owns this use's own settings (its admin screen links from here). */
|
|
43
|
+
owner: "members" | "newsletter" | "forms";
|
|
44
|
+
/** Configured form count, form notifications only. */
|
|
45
|
+
formsConfigured?: number;
|
|
46
|
+
evidence: {
|
|
47
|
+
outcome: MailActivityOutcome;
|
|
48
|
+
at: string;
|
|
49
|
+
} | null;
|
|
50
|
+
}
|
|
51
|
+
/** The structural slice of the host Newsletter gate's inputs that readiness builds and hands back to it. */
|
|
52
|
+
export interface MailUseLaunchGateDeps {
|
|
53
|
+
isSendingEnabled(workspaceId: string): Promise<boolean>;
|
|
54
|
+
/** `null` = unbound; the host gate checks presence only. */
|
|
55
|
+
consentCapability: unknown;
|
|
56
|
+
originRegistry: OriginRegistryPort;
|
|
57
|
+
mailer: MailerPort;
|
|
58
|
+
}
|
|
59
|
+
export interface MailUseReadinessReport {
|
|
60
|
+
checkedAt: string;
|
|
61
|
+
uses: MailUseRow[];
|
|
62
|
+
}
|
|
63
|
+
export interface MailUseReadinessDeps {
|
|
64
|
+
workspaceId: string;
|
|
65
|
+
mailer: MailerPort;
|
|
66
|
+
mailSenderIdentity?: MailSenderIdentityPort;
|
|
67
|
+
mailLaneReady?: (required: {
|
|
68
|
+
lane: "transactional" | "bulk";
|
|
69
|
+
}) => Promise<boolean>;
|
|
70
|
+
/** The live gate's probe; absent, gated rows report `purpose_gate_unavailable` as unknown. */
|
|
71
|
+
mailPurposeGate?: MailPurposeGateProbe;
|
|
72
|
+
formDefinitionRepo?: Pick<FormDefinitionRepoPort, "list">;
|
|
73
|
+
/** Present only when Newsletter is installed; absent, its two rows are omitted. */
|
|
74
|
+
newsletterLaunchGate?: MailUseLaunchGateDeps;
|
|
75
|
+
/** Host: Newsletter's launch gate evaluator (the one its send path runs); absent, Newsletter's rows are `newsletter_gate_unavailable` unknown. */
|
|
76
|
+
evaluateNewsletterLaunchGate?(required: {
|
|
77
|
+
deps: MailUseLaunchGateDeps;
|
|
78
|
+
workspaceId: string;
|
|
79
|
+
isTestSend: boolean;
|
|
80
|
+
}): Promise<Pick<MailLaunchGateResult, "unmetPreconditions">>;
|
|
81
|
+
mailActivity?: Pick<MailActivityRepo, "list">;
|
|
82
|
+
nowIso?: () => string;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Every use this site has, each checked independently and concurrently.
|
|
86
|
+
* @complexity One owner check and one evidence read per use (at most four).
|
|
87
|
+
* @example await readMailUseReadiness(deps)
|
|
88
|
+
*/
|
|
89
|
+
export declare function readMailUseReadiness(deps: MailUseReadinessDeps, _options?: Record<string, never>): Promise<MailUseReadinessReport>;
|
|
90
|
+
/** The host fields readiness reads; Newsletter's are optional so a root without it omits its rows. */
|
|
91
|
+
export type MailUseReadinessHostDeps = Omit<MailUseReadinessDeps, "newsletterLaunchGate"> & {
|
|
92
|
+
originRegistry?: MailUseLaunchGateDeps["originRegistry"];
|
|
93
|
+
newsletterCampaignRepo?: unknown;
|
|
94
|
+
membersConsentCapability?: MailUseLaunchGateDeps["consentCapability"];
|
|
95
|
+
newsletterSendingEnabled?: MailUseLaunchGateDeps["isSendingEnabled"];
|
|
96
|
+
};
|
|
97
|
+
/**
|
|
98
|
+
* Readiness deps from route/tool deps. Newsletter's launch-gate inputs map exactly as
|
|
99
|
+
* `features/newsletter/tool-registrations.ts`'s `toNewsletterSendPipelineDeps` maps them (an absent
|
|
100
|
+
* sending setting is the fail-closed `false`), so this reads the same gate the send path evaluates.
|
|
101
|
+
* @complexity O(1).
|
|
102
|
+
*/
|
|
103
|
+
export declare function mailUseReadinessDepsFrom(deps: MailUseReadinessHostDeps, _options?: Record<string, never>): MailUseReadinessDeps;
|
|
104
|
+
//# sourceMappingURL=use-readiness.d.ts.map
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file **What uses email** (email phase 4): one readiness row per use of the site's mail, built
|
|
3
|
+
* from the checks each owning feature already runs, never a second copy of them.
|
|
4
|
+
*
|
|
5
|
+
* | Use | Owner checks reused |
|
|
6
|
+
* |---|---|
|
|
7
|
+
* | Sign-in links | the members sender (`mailSenderIdentity`, as `members/write-service.ts` resolves it), Jini's purpose gate on the interactive lane |
|
|
8
|
+
* | Confirmations | Newsletter's `evaluateLaunchGate` test-send subset (origin, production mailer) that `confirmation.ts` needs, the sender, the interactive gate |
|
|
9
|
+
* | Form notifications | Forms' definitions (`notify.enabled` + recipients, as `@jini-ai/cms/forms`' subscriber reads them), the sender, the notification-lane gate |
|
|
10
|
+
* | Newsletter | `evaluateLaunchGate` in full, the sender, the notification-lane gate |
|
|
11
|
+
*
|
|
12
|
+
* The purpose gate is asked through `platform/mail/purpose-gate-probe.ts`, so the production
|
|
13
|
+
* `durableOutboxReady` gate is surfaced as a blocker exactly as it decides, and is not changed here.
|
|
14
|
+
*
|
|
15
|
+
* State per row: blocked > not_configured > disabled > ready, every reason kept. A check that
|
|
16
|
+
* throws makes only its own row `unknown`. Evidence (the last observed outcome, from the activity
|
|
17
|
+
* projection) is separate: a ready row with a bounced last send is both, and a failed evidence read
|
|
18
|
+
* leaves the state standing with `evidence: null`.
|
|
19
|
+
*/
|
|
20
|
+
import { createMailSenderIdentityResolver, SenderIdentityNotConfiguredError } from "./sender-identity.js";
|
|
21
|
+
import { isMailDeliveryAvailable } from "./delivery-availability.js";
|
|
22
|
+
import { fromPositionalMailer } from "./plugin-abi.js";
|
|
23
|
+
const RANK = ["blocked", "not_configured", "disabled"];
|
|
24
|
+
const SENDER_FALLBACK = { email: "no-reply@site.local" };
|
|
25
|
+
const SPECS = {
|
|
26
|
+
sign_in: { use: "sign_in", label: "Sign-in links", sendLane: "interactive", mailLane: "transactional", owner: "members", activityUse: "sign_in" },
|
|
27
|
+
newsletter_confirmation: { use: "newsletter_confirmation", label: "Subscription confirmations", sendLane: "interactive", mailLane: "transactional", owner: "newsletter", activityUse: "newsletter_confirmation" },
|
|
28
|
+
form_notifications: { use: "form_notifications", label: "Form notifications", sendLane: "notification", mailLane: "transactional", owner: "forms", activityUse: "form_notification" },
|
|
29
|
+
newsletter: { use: "newsletter", label: "Newsletter", sendLane: "notification", mailLane: "bulk", owner: "newsletter", activityUse: "newsletter" },
|
|
30
|
+
};
|
|
31
|
+
/** Newsletter's own precondition codes; a switched-off sending setting is Disabled, not Blocked. */
|
|
32
|
+
const LAUNCH_GATE_STATE = {
|
|
33
|
+
sending_enabled_false: "disabled",
|
|
34
|
+
consent_capability_unbound: "blocked",
|
|
35
|
+
origin_not_verified: "blocked",
|
|
36
|
+
mailer_adapter_not_production: "not_configured",
|
|
37
|
+
};
|
|
38
|
+
async function senderFinding(deps, _options = {}) {
|
|
39
|
+
const identity = deps.mailSenderIdentity ?? createMailSenderIdentityResolver({ readDriver: () => deps.mailer.capabilities().driver });
|
|
40
|
+
try {
|
|
41
|
+
return { sender: (await identity.resolve({ workspaceId: deps.workspaceId, fallback: SENDER_FALLBACK })).email, findings: [] };
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
if (err instanceof SenderIdentityNotConfiguredError)
|
|
45
|
+
return { sender: null, findings: [{ state: "blocked", reason: "sender_not_configured" }] };
|
|
46
|
+
throw err;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function gateFinding(deps, spec) {
|
|
50
|
+
if (!deps.mailPurposeGate)
|
|
51
|
+
throw new Error("purpose_gate_unavailable");
|
|
52
|
+
return (await deps.mailPurposeGate({ capabilityName: spec.owner, lane: spec.sendLane })) ? [] : [{ state: "blocked", reason: "durable_outbox_not_ready" }];
|
|
53
|
+
}
|
|
54
|
+
/** Delivery, sender and gate: what every use shares, in that order. */
|
|
55
|
+
async function sharedFindings(deps, spec) {
|
|
56
|
+
const available = deps.mailLaneReady ? await deps.mailLaneReady({ lane: spec.mailLane }) : isMailDeliveryAvailable({ mailer: fromPositionalMailer({ mailer: deps.mailer }) });
|
|
57
|
+
const delivery = available ? [] : [{ state: "not_configured", reason: "mail_delivery_unavailable" }];
|
|
58
|
+
const sender = await senderFinding(deps);
|
|
59
|
+
return { findings: [...delivery, ...sender.findings, ...(await gateFinding(deps, spec))], sender: sender.sender };
|
|
60
|
+
}
|
|
61
|
+
async function launchGateFindings({ deps, isTestSend }, _options = {}) {
|
|
62
|
+
if (!deps.evaluateNewsletterLaunchGate)
|
|
63
|
+
throw new Error("newsletter_gate_unavailable");
|
|
64
|
+
const result = await deps.evaluateNewsletterLaunchGate({ deps: deps.newsletterLaunchGate, workspaceId: deps.workspaceId, isTestSend });
|
|
65
|
+
// The shared delivery check already reports a console/memory mailer.
|
|
66
|
+
return result.unmetPreconditions.filter((code) => code !== "mailer_adapter_not_production").map((code) => ({ state: LAUNCH_GATE_STATE[code], reason: code }));
|
|
67
|
+
}
|
|
68
|
+
const CHECKS = {
|
|
69
|
+
sign_in: ({ deps }) => sharedFindings(deps, SPECS.sign_in),
|
|
70
|
+
newsletter_confirmation: async ({ deps }) => {
|
|
71
|
+
const own = await launchGateFindings({ deps, isTestSend: true });
|
|
72
|
+
const shared = await sharedFindings(deps, SPECS.newsletter_confirmation);
|
|
73
|
+
return { ...shared, findings: [...own, ...shared.findings] };
|
|
74
|
+
},
|
|
75
|
+
form_notifications: async ({ deps }) => {
|
|
76
|
+
if (!deps.formDefinitionRepo)
|
|
77
|
+
throw new Error("forms_unavailable");
|
|
78
|
+
const forms = await deps.formDefinitionRepo.list({ workspaceId: deps.workspaceId });
|
|
79
|
+
const formsConfigured = forms.filter((form) => form.notify.enabled && form.notify.recipients.length > 0).length;
|
|
80
|
+
if (formsConfigured === 0)
|
|
81
|
+
return { findings: [{ state: "not_configured", reason: "no_form_notifications" }], sender: null, formsConfigured };
|
|
82
|
+
return { ...(await sharedFindings(deps, SPECS.form_notifications)), formsConfigured };
|
|
83
|
+
},
|
|
84
|
+
newsletter: async ({ deps }) => {
|
|
85
|
+
const own = await launchGateFindings({ deps, isTestSend: false });
|
|
86
|
+
const shared = await sharedFindings(deps, SPECS.newsletter);
|
|
87
|
+
return { ...shared, findings: [...own, ...shared.findings] };
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
function stateOf({ findings }, _options = {}) {
|
|
91
|
+
return RANK.find((state) => findings.some((finding) => finding.state === state)) ?? "ready";
|
|
92
|
+
}
|
|
93
|
+
async function evidenceFor(deps, spec) {
|
|
94
|
+
if (!deps.mailActivity)
|
|
95
|
+
return null;
|
|
96
|
+
try {
|
|
97
|
+
const [last] = await deps.mailActivity.list({ workspaceId: deps.workspaceId, limit: 1 }, { use: spec.activityUse });
|
|
98
|
+
return last ? { outcome: last.outcome, at: last.updatedAt } : null;
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async function rowFor(deps, use) {
|
|
105
|
+
const spec = SPECS[use];
|
|
106
|
+
const base = { use, label: spec.label, sendLane: spec.sendLane, mailLane: spec.mailLane, owner: spec.owner };
|
|
107
|
+
const evidence = await evidenceFor(deps, spec);
|
|
108
|
+
try {
|
|
109
|
+
const check = await CHECKS[use]({ deps });
|
|
110
|
+
return { ...base, state: stateOf({ findings: check.findings }), reasons: check.findings.map((finding) => finding.reason), sender: check.sender,
|
|
111
|
+
...(check.formsConfigured === undefined ? {} : { formsConfigured: check.formsConfigured }), evidence };
|
|
112
|
+
}
|
|
113
|
+
catch (err) {
|
|
114
|
+
// Only this row is unknown; a known reason code is kept, anything else is a generic check failure.
|
|
115
|
+
const reason = err instanceof Error && /^[a-z_]+$/.test(err.message) ? err.message : "check_failed";
|
|
116
|
+
return { ...base, state: "unknown", reasons: [reason], sender: null, evidence };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Every use this site has, each checked independently and concurrently.
|
|
121
|
+
* @complexity One owner check and one evidence read per use (at most four).
|
|
122
|
+
* @example await readMailUseReadiness(deps)
|
|
123
|
+
*/
|
|
124
|
+
export async function readMailUseReadiness(deps, _options = {}) {
|
|
125
|
+
const uses = deps.newsletterLaunchGate ? ["sign_in", "newsletter_confirmation", "form_notifications", "newsletter"] : ["sign_in", "form_notifications"];
|
|
126
|
+
return { checkedAt: (deps.nowIso ?? (() => new Date().toISOString()))(), uses: await Promise.all(uses.map((use) => rowFor(deps, use))) };
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Readiness deps from route/tool deps. Newsletter's launch-gate inputs map exactly as
|
|
130
|
+
* `features/newsletter/tool-registrations.ts`'s `toNewsletterSendPipelineDeps` maps them (an absent
|
|
131
|
+
* sending setting is the fail-closed `false`), so this reads the same gate the send path evaluates.
|
|
132
|
+
* @complexity O(1).
|
|
133
|
+
*/
|
|
134
|
+
export function mailUseReadinessDepsFrom(deps, _options = {}) {
|
|
135
|
+
const { originRegistry, newsletterCampaignRepo, membersConsentCapability, newsletterSendingEnabled, ...rest } = deps;
|
|
136
|
+
if (newsletterCampaignRepo === undefined || originRegistry === undefined)
|
|
137
|
+
return rest;
|
|
138
|
+
return { ...rest, newsletterLaunchGate: { isSendingEnabled: newsletterSendingEnabled ?? (async () => false), consentCapability: membersConsentCapability ?? null, originRegistry, mailer: deps.mailer } };
|
|
139
|
+
}
|
|
140
|
+
//# sourceMappingURL=use-readiness.js.map
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
* planted as the object itself is refused rather than followed.
|
|
14
14
|
*/
|
|
15
15
|
import { constants } from 'node:fs';
|
|
16
|
-
import {
|
|
16
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
17
|
+
import { lstat, mkdir, open, readFile, realpath, rename, rm, writeFile } from 'node:fs/promises';
|
|
17
18
|
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
18
19
|
import { providerOk } from '@jini-ai/core/provider-registry';
|
|
19
20
|
/** Node's errno-carrying error, narrowed without a cast at each call site. */
|
|
@@ -76,6 +77,35 @@ async function physicallyContained(required) {
|
|
|
76
77
|
}
|
|
77
78
|
return path;
|
|
78
79
|
}
|
|
80
|
+
function createLocalStagedWriter({ pathOf }) {
|
|
81
|
+
return async ({ key, byteLength, sha256, openChunks }, { signal } = {}) => {
|
|
82
|
+
signal?.throwIfAborted();
|
|
83
|
+
const path = await pathOf(key);
|
|
84
|
+
await mkdir(dirname(path), { recursive: true });
|
|
85
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
86
|
+
const file = await open(temporary, CREATE_ONLY_FLAGS, 0o600);
|
|
87
|
+
try {
|
|
88
|
+
const hash = createHash('sha256');
|
|
89
|
+
let length = 0;
|
|
90
|
+
for await (const chunk of openChunks({}, signal ? { signal } : {})) {
|
|
91
|
+
signal?.throwIfAborted();
|
|
92
|
+
length += chunk.byteLength;
|
|
93
|
+
if (length > byteLength)
|
|
94
|
+
throw new Error('staged object length mismatch');
|
|
95
|
+
await file.writeFile(chunk);
|
|
96
|
+
hash.update(chunk);
|
|
97
|
+
}
|
|
98
|
+
if (length !== byteLength || hash.digest('hex') !== sha256)
|
|
99
|
+
throw new Error('staged object verification failed');
|
|
100
|
+
signal?.throwIfAborted();
|
|
101
|
+
await rename(temporary, path);
|
|
102
|
+
}
|
|
103
|
+
finally {
|
|
104
|
+
await file.close();
|
|
105
|
+
await rm(temporary, { force: true });
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
}
|
|
79
109
|
/**
|
|
80
110
|
* Creates a local-filesystem `ObjectStore` rooted at `rootDir`.
|
|
81
111
|
* @complexity Each call is O(1) syscalls beyond the read/write itself.
|
|
@@ -84,6 +114,9 @@ export function createLocalFsObjectStore(required, _optional = {}) {
|
|
|
84
114
|
const { rootDir } = required;
|
|
85
115
|
const pathOf = (key) => physicallyContained({ rootDir, key });
|
|
86
116
|
return {
|
|
117
|
+
async resolveStagedWriter(_required, _optional = {}) {
|
|
118
|
+
return createLocalStagedWriter({ pathOf });
|
|
119
|
+
},
|
|
87
120
|
async put({ key, bytes }, options = {}) {
|
|
88
121
|
const path = await pathOf(key);
|
|
89
122
|
await mkdir(dirname(path), { recursive: true });
|