@jini-ai/platform 0.6.12 → 0.6.15-rc.2

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +54 -0
  3. package/dist/asset-cache.js +27 -13
  4. package/dist/command.d.ts +1 -1
  5. package/dist/command.js +11 -8
  6. package/dist/download.js +26 -32
  7. package/dist/fetch-with-timeout.d.ts +77 -0
  8. package/dist/fetch-with-timeout.js +148 -2
  9. package/dist/fs/directory-user-config.js +2 -1
  10. package/dist/fs/directory-workspace.js +3 -1
  11. package/dist/fs/guarded-reader.d.ts +19 -47
  12. package/dist/fs/guarded-reader.js +82 -13
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +1 -1
  15. package/dist/mail/adapter-module.d.ts +18 -0
  16. package/dist/mail/adapter-module.js +13 -1
  17. package/dist/mail/email-sender-registry.d.ts +15 -0
  18. package/dist/mail/email-sender-registry.js +22 -0
  19. package/dist/mail/email-sender.d.ts +109 -0
  20. package/dist/mail/email-sender.js +10 -0
  21. package/dist/mail/index.d.ts +16 -2
  22. package/dist/mail/index.js +9 -1
  23. package/dist/mail/mail-status-cache.d.ts +33 -0
  24. package/dist/mail/mail-status-cache.js +56 -0
  25. package/dist/mail/prepare-sender-email.d.ts +35 -0
  26. package/dist/mail/prepare-sender-email.js +68 -0
  27. package/dist/mail/provider.js +4 -1
  28. package/dist/mail/resolve-mailer.d.ts +95 -0
  29. package/dist/mail/resolve-mailer.js +348 -0
  30. package/dist/mail/senders.d.ts +5 -0
  31. package/dist/mail/senders.js +5 -0
  32. package/dist/secrets/credential-sets/vault.repo.memory.d.ts +1 -4
  33. package/dist/secrets/credential-sets/vault.repo.memory.js +3 -1
  34. package/dist/secrets/credential-sets/vault.service.d.ts +17 -9
  35. package/dist/secrets/credential-sets/vault.service.js +18 -9
  36. package/dist/secrets/credential-sets/vault.types.d.ts +10 -4
  37. package/package.json +8 -2
@@ -0,0 +1,348 @@
1
+ /**
2
+ * Explicit lane selection, live credential rotation and cached provider status.
3
+ * Saved keys never select a provider. Local fallback uses the catalog's console provider;
4
+ * production refuses. Host ports retain trusted loading, credential copy and configuration DTOs.
5
+ * capabilities() is synchronous and reports console until transactional resolution settles;
6
+ * sends always await their own lane. Invalidation detaches obsolete work without cancelling it.
7
+ */
8
+ import { ToolInputError } from "@jini-ai/core";
9
+ import { readMailDomain } from "./domain-read.js";
10
+ import { createTtlCache, MAIL_STATUS_TTL_MS } from "./mail-status-cache.js";
11
+ import { credentialSecrets, safeMailProviderText } from "./provider-error.js";
12
+ import { computeMailStatus, initialMailProviderSetting } from "./provider.js";
13
+ import { laneForPurpose } from "./policy.js";
14
+ import { createSenderDomainVerification } from "./sender-domain-verification.js";
15
+ const CONSOLE_CAPABILITIES = { driver: "console", supportsIdempotencyKey: false, supportsWebhookFeedback: false, maxBatchSize: 1, supportsAttachments: true };
16
+ /** Metadata identifies the exact saved version without decryption. @complexity O(1). */
17
+ function rowFingerprint(record) {
18
+ return record ? `${record.id}:${record.vaultRevision ?? ""}:${record.updatedAt}` : "absent";
19
+ }
20
+ /** Any failed recipient wins; only a wholly accepted, nonempty operation clears a send failure.
21
+ * Results and exceptions pass through unchanged. @complexity O(messages) time, O(1) space. */
22
+ function observeFailures(required) {
23
+ const { mailer, providerId, record, accepted } = required;
24
+ const seen = (results) => {
25
+ const failure = results.find(result => !result.ok);
26
+ if (failure && !failure.ok) {
27
+ record({ providerId, source: "send", code: failure.errorCode, message: failure.message });
28
+ return;
29
+ }
30
+ if (results.length > 0)
31
+ accepted();
32
+ };
33
+ return {
34
+ capabilities: () => mailer.capabilities({}),
35
+ send: async (input, options) => { const result = await mailer.send(input, options); seen([result]); return result; },
36
+ sendBatch: async (input, options) => { const results = await mailer.sendBatch(input, options); seen(results); return results; },
37
+ };
38
+ }
39
+ /** Refusals report console so availability checks never mistake them for delivery. @complexity O(messages) for batches. */
40
+ function refusingMailer(required) {
41
+ const result = { ok: false, retryable: false, errorCode: required.errorCode, message: required.message };
42
+ return { capabilities: () => CONSOLE_CAPABILITIES, send: async () => result, sendBatch: async ({ messages }) => messages.map(() => result) };
43
+ }
44
+ /** Diagnostic sinks cannot throw across the mail boundary; production warns once per reason. */
45
+ function warnOnce({ state, key, message }) {
46
+ if (state.deps.mode !== "production" || state.warned.has(key))
47
+ return;
48
+ state.warned.add(key);
49
+ try {
50
+ state.warn(message);
51
+ }
52
+ catch { /* Diagnostics cannot reject a send. */ }
53
+ }
54
+ /** Never retain provider/body details. Repeated checks must not hide a failed send. */
55
+ function recordError({ state, error }) {
56
+ const { providerId, source } = error;
57
+ if (source === "check" && state.lastError?.source === "send")
58
+ return;
59
+ state.lastError = { providerId, source, message: source === "send" ? "The provider did not confirm acceptance. Check provider configuration." : "The provider configuration check could not complete.", at: new Date(state.nowMs()).toISOString() };
60
+ }
61
+ /** First boot remains unconfigured even with saved keys; failed persistence is retried on a later read. */
62
+ async function initialize(state) {
63
+ const setting = initialMailProviderSetting({});
64
+ await state.deps.providerSetting.write({ setting }).catch(() => warnOnce({ state, key: "initialization", message: "[mail] the mail provider setting could not be saved; retrying on the next send" }));
65
+ return setting;
66
+ }
67
+ /** Only initialization is single-flight: every call still reads the current selection first. */
68
+ async function currentSetting(state) {
69
+ const stored = await state.deps.providerSetting.read({});
70
+ if (stored)
71
+ return stored;
72
+ state.initialization ??= initialize(state).finally(() => { state.initialization = undefined; });
73
+ return state.initialization;
74
+ }
75
+ /** Keyless providers never touch the credential metadata store. */
76
+ async function fingerprintFor({ state, label }) {
77
+ if (label === undefined)
78
+ return "";
79
+ return rowFingerprint(await state.deps.credentials.readFact({ label }));
80
+ }
81
+ /** The host catalog guarantees the built-in console provider. Its mailer shares the policy wrapper. */
82
+ async function consoleMailer({ state, catalog }) {
83
+ const provider = catalog.registry.get({ id: "console" }).provider;
84
+ const mailer = state.wrap({ providerId: "console", provider, mailer: state.deps.createProviderMailer({ provider, credential: { token: "" } }) });
85
+ state.resolved.set("console", { mailer, fingerprint: "" });
86
+ return mailer;
87
+ }
88
+ /** Local mode keeps working through console; production refuses and logs safe host copy once. */
89
+ async function fallback(required) {
90
+ const { state } = required;
91
+ if (state.deps.mode !== "production")
92
+ return state.resolved.get("console")?.mailer ?? consoleMailer(required);
93
+ warnOnce({ state, key: required.errorCode + required.message, message: required.message });
94
+ return refusingMailer(required);
95
+ }
96
+ /** A missing key or failed decrypt uses the host's established caller-safe refusal wording. */
97
+ async function credentialOrReason({ state, catalog, id, label }) {
98
+ try {
99
+ const credential = await state.deps.credentials.resolve({ catalog, id });
100
+ if (credential)
101
+ return { credential };
102
+ }
103
+ catch (err) {
104
+ return { reason: state.deps.credentialFailureReason({ label, err }) };
105
+ }
106
+ return { reason: state.deps.missingCredentialReason({ label }) };
107
+ }
108
+ /** A catalog label means a saved key is required; keyless providers receive an empty token. */
109
+ function providerCredential({ state, catalog, id }) {
110
+ const label = catalog.credentialLabelFor({ id });
111
+ return label === undefined ? Promise.resolve({ credential: { token: "" } }) : credentialOrReason({ state, catalog, id, label });
112
+ }
113
+ /** Preserve provider selection refusals, including the catalog's trusted plugin-load diagnostics. */
114
+ function unavailable(required) {
115
+ return fallback({ ...required, errorCode: "MAIL_PROVIDER_UNAVAILABLE", message: `[mail] the selected mail provider '${required.id}' ${required.detail}, so outbound mail is NOT being sent` });
116
+ }
117
+ /** A successful operation only clears a failure from the same provider. */
118
+ function acceptProvider({ state, id }) {
119
+ if (state.lastError?.source === "send" && state.lastError.providerId === id)
120
+ state.lastError = undefined;
121
+ }
122
+ /** Construct only after metadata/key/metadata agree; a generation change prevents caching obsolete work.
123
+ * @complexity One catalog load, two metadata reads and one decrypt per attempt; races retry in order. */
124
+ async function resolveProvider({ state, id, startedIn }) {
125
+ const catalog = await state.deps.loadCatalog({});
126
+ const entry = catalog.registry.get({ id });
127
+ if (!entry) {
128
+ const refusals = catalog.refusals.length > 0 ? ` (${catalog.refusals.join("; ")})` : "";
129
+ return unavailable({ state, catalog, id, detail: `is not installed${refusals}` });
130
+ }
131
+ // Fingerprint BEFORE reading the key: a rotation racing this read then re-resolves next send.
132
+ // An unreadable store leaves key lookup to report why; "unknown" re-resolves once it reads.
133
+ const label = catalog.credentialLabelFor({ id });
134
+ const fingerprint = await fingerprintFor({ state, label }).catch(() => "unknown");
135
+ const found = await providerCredential({ state, catalog, id });
136
+ if (!found.credential)
137
+ return unavailable({ state, catalog, id, detail: found.reason });
138
+ const credential = found.credential;
139
+ const latest = await fingerprintFor({ state, label }).catch(() => fingerprint);
140
+ if (latest !== fingerprint)
141
+ return resolveProvider({ state, id, startedIn: state.generation });
142
+ const observed = observeFailures({ mailer: state.deps.createProviderMailer({ provider: entry.provider, credential }), providerId: id,
143
+ record: error => recordError({ state, error }), accepted: () => acceptProvider({ state, id }) });
144
+ const mailer = state.wrap({ providerId: id, provider: entry.provider, mailer: observed });
145
+ if (startedIn === state.generation)
146
+ state.resolved.set(id, { mailer, fingerprint, ...(label === undefined ? {} : { label }) });
147
+ return mailer;
148
+ }
149
+ /** Boot and early sends share one resolution per provider. Old completions rejoin the current generation. */
150
+ function resolveOnce({ state, id }) {
151
+ const existing = state.inFlight.get(id);
152
+ if (existing)
153
+ return existing;
154
+ const startedIn = state.generation;
155
+ const started = resolveProvider({ state, id, startedIn }).then(mailer => startedIn === state.generation ? mailer : resolveOnce({ state, id }))
156
+ .finally(() => { if (state.inFlight.get(id) === started)
157
+ state.inFlight.delete(id); });
158
+ state.inFlight.set(id, started);
159
+ return started;
160
+ }
161
+ /** Reuse unchanged rows; metadata faults keep a usable cached mailer. @complexity One metadata read per send. */
162
+ async function currentMailer({ state, id }) {
163
+ const entry = state.resolved.get(id);
164
+ if (!entry)
165
+ return resolveOnce({ state, id });
166
+ if (entry.label === undefined)
167
+ return entry.mailer;
168
+ const fingerprint = await fingerprintFor({ state, label: entry.label }).catch(() => entry.fingerprint);
169
+ if (fingerprint === entry.fingerprint)
170
+ return entry.mailer;
171
+ if (state.resolved.get(id) === entry)
172
+ state.resolved.delete(id);
173
+ return resolveOnce({ state, id });
174
+ }
175
+ /** Fresh lane selection precedes every resolution and updates the synchronous transactional projection. */
176
+ async function mailerForLane({ state, lane }) {
177
+ const id = (await currentSetting(state))[lane];
178
+ const mailer = id === null
179
+ ? await fallback({ state, catalog: await state.deps.loadCatalog({}), errorCode: "MAIL_UNCONFIGURED", message: state.deps.unconfiguredMessage({ lane }) })
180
+ : await currentMailer({ state, id });
181
+ if (lane === "transactional")
182
+ state.lastTransactional = mailer;
183
+ return mailer;
184
+ }
185
+ /** Settings/catalog faults become a refusal rather than throwing across the routing boundary. */
186
+ function forLane(required) {
187
+ return mailerForLane(required).catch(() => refusingMailer({ errorCode: "MAIL_PROVIDER_UNAVAILABLE", message: "Mail provider selection failed; check configuration." }));
188
+ }
189
+ /** The public mailer preserves synchronous capability reporting and awaits the proper lane for sends. */
190
+ function createRouter(state) {
191
+ return {
192
+ capabilities: () => {
193
+ if (state.lastTransactional === undefined)
194
+ void forLane({ state, lane: "transactional" });
195
+ return state.lastTransactional?.capabilities({}) ?? CONSOLE_CAPABILITIES;
196
+ },
197
+ send: async (input, options = {}) => (await forLane({ state, lane: laneForPurpose({ purpose: options.purpose }) })).send(input, options),
198
+ sendBatch: async (input, options = {}) => (await forLane({ state, lane: laneForPurpose({ purpose: options.purpose }) })).sendBatch(input, options),
199
+ };
200
+ }
201
+ /** Sender settings errors count as unset; parsing retains the original lowercase/trim behavior. */
202
+ async function readSenderDomain(state) {
203
+ const email = await state.options.readSenderEmail?.().catch(() => undefined);
204
+ return email?.split("@")[1]?.trim().toLowerCase() || undefined;
205
+ }
206
+ /** Domain status shares selection/credentials with delivery, while keeping its own ordered reads. */
207
+ function createDomainVerification({ state, resolveDomainReadCredential }) {
208
+ return createSenderDomainVerification({
209
+ workspaceId: state.deps.workspaceId, httpClient: state.deps.httpClient,
210
+ findProvider: async ({ id }) => (await state.deps.loadCatalog({})).registry.get({ id })?.provider,
211
+ resolveCredential: async ({ id }) => state.deps.credentials.resolve({ catalog: await state.deps.loadCatalog({}), id }),
212
+ resolveDomainReadCredential,
213
+ readProviderId: async () => (await currentSetting(state)).transactional,
214
+ readSenderEmail: async () => state.options.readSenderEmail ? state.options.readSenderEmail() : undefined,
215
+ });
216
+ }
217
+ /** Separate requirements read with permission-only fallback; deadline covers provider calls, not setup.
218
+ * Registry validation guarantees domainRequirements when domainVerification is true.
219
+ * @complexity At most two provider calls; diagnostic output is capped at 1000 characters. */
220
+ async function requestDomainRequirements(required, optional = {}) {
221
+ const { ctx, providerId, provider, domain } = required;
222
+ let timer;
223
+ const timeout = new Promise((_resolve, reject) => {
224
+ timer = setTimeout(() => reject(new Error("The mail provider could not list its required DNS records.")), optional.timeoutMs ?? 5_000);
225
+ });
226
+ try {
227
+ const result = await Promise.race([readMailDomain({ ctx, providerId, read: context => provider.domainRequirements(context, { domain }), resolveDomainReadCredential: required.resolveDomainReadCredential }), timeout]);
228
+ if (result.status === "ok")
229
+ return result.value;
230
+ throw new ToolInputError({ message: safeMailProviderText({ text: `${result.error.code}: ${result.error.message}` }, { secrets: credentialSecrets({ credential: ctx.credential }) }) });
231
+ }
232
+ finally {
233
+ clearTimeout(timer);
234
+ }
235
+ }
236
+ /** Resolve requirements only for this workspace and its active transactional provider. */
237
+ async function domainRequirements(required) {
238
+ const { state, resolveDomainReadCredential } = required;
239
+ if (required.workspaceId !== state.deps.workspaceId)
240
+ return null;
241
+ const [setting, catalog, domain] = await Promise.all([currentSetting(state), state.deps.loadCatalog({}), readSenderDomain(state)]);
242
+ const id = setting.transactional;
243
+ const provider = id === null ? undefined : catalog.registry.get({ id })?.provider;
244
+ if (!domain || !provider?.capabilities.domainVerification)
245
+ return null;
246
+ const { credential } = await providerCredential({ state, catalog, id: id });
247
+ const ctx = credential ? { workspaceId: state.deps.workspaceId, mode: "live", credential, httpClient: state.deps.httpClient } : null;
248
+ return ctx ? requestDomainRequirements({ ctx, providerId: id, provider, domain, resolveDomainReadCredential }, { timeoutMs: state.options.domainRequirementsTimeoutMs }) : null;
249
+ }
250
+ /** Unique lane keys resolve in parallel; each failed lookup records a safe check note. @complexity O(lanes). */
251
+ async function laneCredentials(required) {
252
+ const { state, catalog, setting } = required;
253
+ const ids = [...new Set([setting.transactional, setting.bulk].filter((id) => id !== null))];
254
+ const lookup = (id) => state.deps.credentials.resolve({ catalog, id }).catch((err) => {
255
+ // Only a provider with a label reaches the store, so a thrown lookup has a defined label.
256
+ recordError({ state, error: { providerId: id, source: "check", message: state.deps.credentialFailureReason({ label: catalog.credentialLabelFor({ id }), err }) } });
257
+ return null;
258
+ });
259
+ const found = await Promise.all(ids.map(async (id) => [id, await lookup(id)]));
260
+ return new Map(found.filter((pair) => pair[1] !== null));
261
+ }
262
+ /** Row-list faults affect presence facts but do not prevent independent key resolution. */
263
+ function statusCredentialFacts({ state, deps }) {
264
+ return deps.listCredentialFacts({}).catch((err) => {
265
+ recordError({ state, error: { providerId: null, source: "check", message: `the saved mail credentials could not be listed (${err instanceof Error ? err.message : String(err)})` } });
266
+ return [];
267
+ });
268
+ }
269
+ /** Unanswered/unsupported checks produce no sender warning; only no_sender means unset. */
270
+ function statusDomainState(state) {
271
+ if (state === "no_sender")
272
+ return null;
273
+ return ["verified", "pending", "failed", "not_found"].includes(state) ? state : undefined;
274
+ }
275
+ /** Start independent reads together, then await lane keys and domain verification in that order.
276
+ * Null means no sender; an unanswered check stays undefined and must not claim a sender is missing.
277
+ * @complexity O(c + p) credential facts/providers, O(lanes) decrypts; domain work uses its own deadline. */
278
+ async function computeStatusReport(required) {
279
+ const { state, deps, senderDomainVerification } = required;
280
+ const checkedAt = new Date(state.nowMs()).toISOString();
281
+ const records = statusCredentialFacts({ state, deps });
282
+ const [setting, catalog, rows] = await Promise.all([currentSetting(state), state.deps.loadCatalog({}), records, readSenderDomain(state)]);
283
+ const credentials = await laneCredentials({ state, catalog, setting });
284
+ const verdict = await senderDomainVerification();
285
+ const domainState = statusDomainState(verdict.state);
286
+ if (verdict.state === "unknown")
287
+ recordError({ state, error: { providerId: verdict.providerId, source: "check", message: "Provider domain check unavailable." } });
288
+ const status = computeMailStatus({ setting, registry: catalog.registry, hasCredential: id => credentials.has(id) }, domainState === undefined ? {} : { senderDomainState: domainState });
289
+ const { providers } = deps.describeProviders({ catalog, records: rows, setting });
290
+ return { ...status, providers, refusals: catalog.refusals, checkedAt, senderDomainVerification: verdict };
291
+ }
292
+ /** Failed sends overlay cached status immediately; configuration alone never proves sending. */
293
+ function statusWithLastError({ state, report }) {
294
+ const sendFailed = state.lastError?.source === "send" && report.lanes.some(lane => lane.providerId === state.lastError?.providerId);
295
+ return state.lastError ? { ...report, state: sendFailed && report.state === "ready" ? "degraded" : report.state, lastError: state.lastError } : report;
296
+ }
297
+ /** Host descriptions receive fresh, parallel setting/catalog/metadata reads. Failures propagate. */
298
+ async function describeProviders({ state, deps }) {
299
+ const [setting, catalog, records] = await Promise.all([currentSetting(state), state.deps.loadCatalog({}), deps.listCredentialFacts({})]);
300
+ return deps.describeProviders({ catalog, records, setting });
301
+ }
302
+ /** Selection checks require a hosted provider and a usable key; they send nothing. */
303
+ async function checkProvider({ state, id }) {
304
+ const catalog = await state.deps.loadCatalog({});
305
+ const provider = catalog.registry.get({ id })?.provider;
306
+ if (!provider)
307
+ return { ok: false, reason: `'${id}' is not an installed mail provider (installed: ${catalog.registry.list().map(entry => entry.id).join(", ")})` };
308
+ if (!provider.capabilities.hosted)
309
+ return { ok: false, reason: `'${id}' only prints mail locally and never delivers it` };
310
+ const found = await providerCredential({ state, catalog, id });
311
+ return found.credential ? { ok: true, label: provider.label } : { ok: false, reason: `'${id}' ${found.reason}` };
312
+ }
313
+ /** Detach pending work and clear all provider/capability projections; errors retain their original precedence. */
314
+ function invalidate(state) {
315
+ state.generation += 1;
316
+ state.inFlight.clear();
317
+ state.resolved.clear();
318
+ state.lastTransactional = undefined;
319
+ }
320
+ /**
321
+ * Build a lane router and its control surface. The host binds catalogs, secrets, safe copy and DTOs.
322
+ * Each send reads selection and metadata; boot starts resolution synchronously. Selection faults
323
+ * refuse safely; status/description setup faults propagate and are never cached.
324
+ * @complexity O(providers) cached mailers/flights; status holds one report for its TTL.
325
+ * @example const control = createResolvedMailer(hostPorts, { clock }); await control.ready;
326
+ */
327
+ export function createResolvedMailer(required, optional = {}) {
328
+ const state = { deps: required, options: optional, nowMs: () => (optional.clock ?? { nowMs: () => Date.now() }).nowMs(),
329
+ warn: optional.warn ?? (message => console.warn(message)),
330
+ wrap: optional.wrapProviderMailer ?? (({ mailer }) => mailer), resolved: new Map(), inFlight: new Map(), warned: new Set(), generation: 0,
331
+ initialization: undefined, lastTransactional: undefined, lastError: undefined };
332
+ const ready = forLane({ state, lane: "transactional" }).then(() => undefined);
333
+ const mailer = createRouter(state);
334
+ const resolveDomainReadCredential = input => optional.resolveDomainReadCredential?.(input) ?? Promise.resolve(null);
335
+ const senderDomainVerification = createDomainVerification({ state, resolveDomainReadCredential });
336
+ const statusCache = createTtlCache({ load: () => computeStatusReport({ state, deps: required, senderDomainVerification }), ttlMs: optional.statusTtlMs ?? MAIL_STATUS_TTL_MS, nowMs: state.nowMs }, { minRefreshIntervalMs: 5_000 });
337
+ return {
338
+ mailer, ready, senderDomainVerification,
339
+ settle: async () => { await forLane({ state, lane: "transactional" }); },
340
+ status: async (options = {}) => statusWithLastError({ state, report: await statusCache.get(options) }),
341
+ describeProviders: () => describeProviders({ state, deps: required }),
342
+ invalidate: () => { invalidate(state); statusCache.invalidate(); },
343
+ laneReady: async ({ lane }) => (await forLane({ state, lane })).capabilities({}).driver !== "console",
344
+ checkProvider: input => checkProvider({ state, ...input }),
345
+ domainRequirements: input => domainRequirements({ state, ...input, resolveDomainReadCredential }),
346
+ };
347
+ }
348
+ //# sourceMappingURL=resolve-mailer.js.map
@@ -0,0 +1,5 @@
1
+ /** Universal sender surface: importing it never loads SMTP, delivery policy or Node crypto. */
2
+ export * from "./email-sender.js";
3
+ export * from "./email-sender-registry.js";
4
+ export * from "./prepare-sender-email.js";
5
+ //# sourceMappingURL=senders.d.ts.map
@@ -0,0 +1,5 @@
1
+ /** Universal sender surface: importing it never loads SMTP, delivery policy or Node crypto. */
2
+ export * from "./email-sender.js";
3
+ export * from "./email-sender-registry.js";
4
+ export * from "./prepare-sender-email.js";
5
+ //# sourceMappingURL=senders.js.map
@@ -24,10 +24,7 @@ export declare class InMemoryVaultRepo implements VaultRepoPort {
24
24
  /** O(n) memory scan, n stored rows; clones only the default, never its siblings. */
25
25
  findDefault(input: VaultDefaultQuery, _options?: VaultOptions): Promise<VaultRecord | null>;
26
26
  list(input: VaultQuery, _options?: VaultOptions): Promise<VaultRecord[]>;
27
- put(input: {
28
- record: VaultRecord;
29
- expectedRevision: number | null;
30
- }, _options?: VaultOptions): Promise<VaultRecord>;
27
+ put(input: Parameters<VaultRepoPort["put"]>[0], _options?: VaultOptions): Promise<VaultRecord>;
31
28
  /** Synchronous mutation owner shared with batch staging; default moves never re-seal. */
32
29
  private putRecord;
33
30
  patchMeta(input: {
@@ -81,7 +81,9 @@ export class InMemoryVaultRepo {
81
81
  const group = this.groupRows({ groupKey });
82
82
  if (group.some(row => row.id !== record.id && row.label === record.label))
83
83
  throw new VaultError({ code: "conflict" });
84
- const saved = structuredClone({ ...record, isDefault: record.isDefault || group.length === 0 });
84
+ // Auto-select the first row so an ordinary save is usable without a separate default action.
85
+ // Explicit false opts out, keeping unattached project keys from becoming vendor defaults.
86
+ const saved = structuredClone({ ...record, isDefault: record.isDefault ?? (group.length === 0) });
85
87
  // Clear first, matching a SQL partial UNIQUE index; no transient duplicate default is required.
86
88
  if (saved.isDefault)
87
89
  this.clearDefaults({ group });
@@ -1,5 +1,5 @@
1
1
  import type { KeyringPort, SecretSealerPort } from "../ports.js";
2
- import { type VaultContext, type VaultIdentity, type VaultMeta, type VaultMetaParsers, type VaultCopyResult, type VaultDefaultQuery, type VaultOptions, type VaultQuery, type VaultRecord, type VaultRepoPort, type VaultSummary } from "./vault.types.js";
2
+ import { type VaultContext, type VaultIdentity, type VaultMeta, type VaultMetaParsers, type VaultCopyResult, type VaultDefaultQuery, type VaultOptions, type VaultQuery, type VaultPutRecord, type VaultRepoPort, type VaultSummary } from "./vault.types.js";
3
3
  export interface VaultServiceDeps {
4
4
  repo: VaultRepoPort;
5
5
  keyring: KeyringPort;
@@ -24,10 +24,10 @@ export interface VaultPutInput extends VaultContext {
24
24
  * Creation requires a payload (which may be null). Payloads are always sealed JSON.
25
25
  */
26
26
  payload?: VaultMeta | null | undefined;
27
- /** Omitted preserves same-group default status; a provider move starts with false and the
28
- * repository applies its first-row rule. Explicit true selects the destination default.
27
+ /** Omitted preserves same-group default status; creation/provider moves let the repository
28
+ * apply its first-row rule. Explicit false opts out; true selects the destination default.
29
29
  */
30
- isDefault?: boolean;
30
+ isDefault?: boolean | undefined;
31
31
  /** A host-selected token, never a URI or serialized connection object. */
32
32
  hintToken?: string;
33
33
  }
@@ -50,6 +50,7 @@ export declare class SecretsVaultService {
50
50
  constructor(deps: VaultServiceDeps, _options?: VaultOptions);
51
51
  private authorize;
52
52
  private parse;
53
+ /** Resolve a matching identity; deletion can retain legacy metadata without interpreting it. */
53
54
  private find;
54
55
  private seal;
55
56
  private open;
@@ -61,14 +62,18 @@ export declare class SecretsVaultService {
61
62
  * Prepared records contain envelopes and stay private to the host, never a public read model.
62
63
  * @example const record = await vault.prepare(input); await repo.put({ record, expectedRevision: input.expectedRevision }); // inside the host transaction
63
64
  */
64
- prepare(input: VaultPutInput, _options?: VaultOptions): Promise<VaultRecord>;
65
+ prepare(input: VaultPutInput, _options?: VaultOptions): Promise<VaultPutRecord>;
65
66
  /** Resolve the target identity and apply the service-level CAS precheck. */
66
67
  private findForPut;
67
68
  private parsePutMeta;
68
69
  /** Omitted payload keeps the existing envelope and hints without opening or sealing. */
69
70
  private putEnvelope;
70
- /** Authorized runtime read; returns plaintext only to the caller that supplied exact ownership. */
71
- get(input: VaultIdentity, _options?: VaultOptions): Promise<{
71
+ /** Authorized runtime read; returns plaintext only to the caller that supplied exact ownership.
72
+ * `provider`, when given, must match the row's group before its envelope is opened (a stale
73
+ * selection never decrypts another group's secret). */
74
+ get(input: VaultIdentity, { provider }?: {
75
+ provider?: string;
76
+ }): Promise<{
72
77
  summary: VaultSummary;
73
78
  payload: VaultMeta | null;
74
79
  } | null>;
@@ -103,7 +108,8 @@ export declare class SecretsVaultService {
103
108
  private copyRow;
104
109
  /** Guarded read of the source row, then a CAS write of the resealed target row. */
105
110
  private transferRow;
106
- /** Overwrite keeps the target's default, revision chain and creation time. */
111
+ /** Overwrite keeps the target's default, revision chain and creation time. A new copy leaves
112
+ * placement unspecified, so the repo's first-row rule applies (never the source's default flag). */
107
113
  private writeCopy;
108
114
  /** Human-managed scoped inventory. No envelope or plaintext is opened or returned. */
109
115
  list(input: VaultQuery, _options?: VaultOptions): Promise<VaultSummary[]>;
@@ -116,7 +122,9 @@ export declare class SecretsVaultService {
116
122
  rotate(input: VaultIdentity & {
117
123
  expectedRevision: number;
118
124
  }, _options?: VaultOptions): Promise<VaultSummary>;
119
- /** Idempotent for missing rows; existing rows require matching context and revision. */
125
+ /** Idempotent for missing rows; existing rows require matching context and revision.
126
+ * Deletion needs no metadata interpretation, so unupgraded legacy rows remain removable.
127
+ */
120
128
  delete(input: VaultIdentity & {
121
129
  expectedRevision: number;
122
130
  }, _options?: VaultOptions): Promise<boolean>;
@@ -81,13 +81,15 @@ export class SecretsVaultService {
81
81
  assertContext(record);
82
82
  return { ...record, meta: this.deps.metaParsers[record.kind]({ meta: record.meta, provider: record.provider }) };
83
83
  }
84
- async find(input) {
84
+ /** Resolve a matching identity; deletion can retain legacy metadata without interpreting it. */
85
+ async find(input, { parseMeta = true } = {}) {
85
86
  const record = await this.deps.repo.find({ workspaceId: input.workspaceId, id: input.id });
86
87
  if (!record)
87
88
  return null;
88
89
  if (buildVaultAad(input) !== buildVaultAad(record))
89
90
  throw new VaultError({ code: "context" });
90
- return this.parse(record);
91
+ assertContext(record);
92
+ return parseMeta ? this.parse(record) : record;
91
93
  }
92
94
  async seal(input) {
93
95
  if (input.payload === null)
@@ -137,7 +139,7 @@ export class SecretsVaultService {
137
139
  const { sealed, last4, tokenLength } = await this.putEnvelope({ input, identity, existing });
138
140
  const now = this.deps.now({});
139
141
  return { ...identity, provider: input.provider, label: input.label, meta, sealed,
140
- isDefault: input.isDefault ?? (existing !== null && existing.provider === input.provider && existing.isDefault),
142
+ isDefault: input.isDefault ?? (existing !== null && existing.provider === input.provider ? existing.isDefault : undefined),
141
143
  revision: (input.expectedRevision ?? 0) + 1, last4, tokenLength,
142
144
  createdAt: existing === null ? now : existing.createdAt, updatedAt: now };
143
145
  }
@@ -174,11 +176,15 @@ export class SecretsVaultService {
174
176
  ? credentialTokenHint({ token: input.hintToken }) : null;
175
177
  return { sealed, last4: hint?.last4 ?? null, tokenLength: hint?.length ?? null };
176
178
  }
177
- /** Authorized runtime read; returns plaintext only to the caller that supplied exact ownership. */
178
- async get(input, _options = {}) {
179
+ /** Authorized runtime read; returns plaintext only to the caller that supplied exact ownership.
180
+ * `provider`, when given, must match the row's group before its envelope is opened (a stale
181
+ * selection never decrypts another group's secret). */
182
+ async get(input, { provider } = {}) {
179
183
  assertContext(input);
180
184
  await this.authorize({ action: "get", context: input });
181
185
  const record = await this.find(input);
186
+ if (record && provider !== undefined && record.provider !== provider)
187
+ throw new VaultError({ code: "context" });
182
188
  return record ? { summary: summary(record), payload: await this.open(record) } : null;
183
189
  }
184
190
  /** Singleton runtime read using one provider-independent lookup. Full expected ownership and
@@ -273,14 +279,15 @@ export class SecretsVaultService {
273
279
  const last4 = summary(await this.writeCopy({ source, record, targetIdentity, existing })).last4;
274
280
  return { status: "copied", ...(last4 ? { last4 } : {}) };
275
281
  }
276
- /** Overwrite keeps the target's default, revision chain and creation time. */
282
+ /** Overwrite keeps the target's default, revision chain and creation time. A new copy leaves
283
+ * placement unspecified, so the repo's first-row rule applies (never the source's default flag). */
277
284
  async writeCopy({ source, record, targetIdentity, existing }) {
278
285
  if (existing && !isCompatibleOverwrite({ existing, record }))
279
286
  throw new VaultError({ code: "context" });
280
287
  const now = this.deps.now({});
281
288
  const placement = existing
282
289
  ? { isDefault: existing.isDefault, revision: existing.revision + 1, createdAt: existing.createdAt }
283
- : { isDefault: false, revision: 1, createdAt: now };
290
+ : { isDefault: undefined, revision: 1, createdAt: now };
284
291
  const candidate = this.parse({ ...record, ...targetIdentity, ...placement, updatedAt: now });
285
292
  candidate.sealed = await this.seal({ context: targetIdentity, payload: await source.open(record) });
286
293
  // Reuse the source's hint policy without guessing a token field from a structured payload.
@@ -328,11 +335,13 @@ export class SecretsVaultService {
328
335
  return summary(this.parse(await this.deps.repo.put({ expectedRevision: input.expectedRevision,
329
336
  record: { ...existing, sealed, revision: existing.revision + 1, updatedAt: this.deps.now({}) } })));
330
337
  }
331
- /** Idempotent for missing rows; existing rows require matching context and revision. */
338
+ /** Idempotent for missing rows; existing rows require matching context and revision.
339
+ * Deletion needs no metadata interpretation, so unupgraded legacy rows remain removable.
340
+ */
332
341
  async delete(input, _options = {}) {
333
342
  assertContext(input);
334
343
  await this.authorize({ action: "delete", context: input });
335
- const existing = await this.find(input);
344
+ const existing = await this.find(input, { parseMeta: false });
336
345
  if (!existing)
337
346
  return false;
338
347
  if (existing.revision !== input.expectedRevision)
@@ -42,6 +42,12 @@ export interface VaultRecord extends VaultIdentity {
42
42
  export type VaultSummary = Omit<VaultRecord, "sealed"> & {
43
43
  configured: boolean;
44
44
  };
45
+ /** Unspecified placement lets the repo auto-default a group's first row; false opts out.
46
+ * Persisted records and read models always contain a concrete boolean.
47
+ */
48
+ export type VaultPutRecord = Omit<VaultRecord, "isDefault"> & {
49
+ isDefault?: boolean | undefined;
50
+ };
45
51
  export interface VaultQuery {
46
52
  workspaceId: string;
47
53
  kind: VaultKind;
@@ -65,7 +71,7 @@ export interface VaultSingletonQuery {
65
71
  /** Ordered CAS operations; default side effects affect later operations' revisions. */
66
72
  export type VaultBatchOp = {
67
73
  put: {
68
- record: VaultRecord;
74
+ record: VaultPutRecord;
69
75
  expectedRevision: number | null;
70
76
  };
71
77
  } | {
@@ -129,7 +135,7 @@ export interface VaultRepoPort {
129
135
  }, options?: VaultOptions): Promise<VaultBatchResult[]>;
130
136
  list(input: VaultQuery, options?: VaultOptions): Promise<VaultRecord[]>;
131
137
  put(input: {
132
- record: VaultRecord;
138
+ record: VaultPutRecord;
133
139
  expectedRevision: number | null;
134
140
  }, options?: VaultOptions): Promise<VaultRecord>;
135
141
  /** Service-validated patch: top-level keys are plain JSON-path identifiers. */
@@ -148,11 +154,11 @@ export interface VaultRepoPort {
148
154
  }
149
155
  /** Unambiguous scope encoding keeps adapter default/identity checks on the same contract. */
150
156
  export declare function vaultGroupKey({ record }: {
151
- record: VaultRecord;
157
+ record: VaultDefaultQuery;
152
158
  }, _options?: VaultOptions): string;
153
159
  /** Adapters guard CAS and immutable identity even for callers below the service. */
154
160
  export declare function assertVaultReplacement({ record, existing, expectedRevision }: {
155
- record: VaultRecord;
161
+ record: VaultPutRecord;
156
162
  existing: VaultRecord | null;
157
163
  expectedRevision: number | null;
158
164
  }, _options?: VaultOptions): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/platform",
3
- "version": "0.6.12",
3
+ "version": "0.6.15-rc.2",
4
4
  "description": "Generic OS/platform primitives: process exec and lifecycle, filesystem containment, HTTP readiness polling, toolchain discovery, blob storage, AWS signing, and an SSRF-safe asset cache.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -22,6 +22,7 @@
22
22
  "./secrets/testing": "node",
23
23
  "./http/guarded": "node",
24
24
  "./mail": "node",
25
+ "./mail/senders": "universal",
25
26
  "./mail/smtp": "node",
26
27
  "./fs/guarded-reader": "node",
27
28
  "./fs/durable-json": "node",
@@ -106,6 +107,11 @@
106
107
  "import": "./dist/mail/index.js",
107
108
  "default": "./dist/mail/index.js"
108
109
  },
110
+ "./mail/senders": {
111
+ "types": "./dist/mail/senders.d.ts",
112
+ "import": "./dist/mail/senders.js",
113
+ "default": "./dist/mail/senders.js"
114
+ },
109
115
  "./mail/smtp": {
110
116
  "types": "./dist/mail/smtp.d.ts",
111
117
  "import": "./dist/mail/smtp.js",
@@ -200,7 +206,7 @@
200
206
  "!dist/**/*.map"
201
207
  ],
202
208
  "dependencies": {
203
- "@jini-ai/core": "^0.6.12"
209
+ "@jini-ai/core": "^0.6.15-rc.2"
204
210
  },
205
211
  "publishConfig": {
206
212
  "access": "public",