@jini-ai/platform 0.7.3-next.1 → 0.7.3-next.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +13 -0
  3. package/dist/download-lock.d.ts +3 -1
  4. package/dist/download-lock.js +4 -4
  5. package/dist/download-maintenance.js +6 -6
  6. package/dist/download-state.js +17 -14
  7. package/dist/download-store.d.ts +34 -10
  8. package/dist/download-store.js +24 -20
  9. package/dist/download-target.d.ts +6 -2
  10. package/dist/download-target.js +7 -7
  11. package/dist/download-transfer.js +18 -12
  12. package/dist/download.js +4 -4
  13. package/dist/fetch-with-timeout.d.ts +0 -53
  14. package/dist/fetch-with-timeout.js +56 -6
  15. package/dist/fs/directory-running-lock.d.ts +4 -0
  16. package/dist/fs/directory-running-lock.js +8 -1
  17. package/dist/fs/directory-workspace.d.ts +2 -1
  18. package/dist/fs/directory-workspace.js +2 -2
  19. package/dist/fs/durable-json.d.ts +3 -16
  20. package/dist/fs/durable-json.js +4 -2
  21. package/dist/fs/guarded-reader.d.ts +10 -0
  22. package/dist/fs/guarded-reader.js +34 -1
  23. package/dist/fs/index.d.ts +4 -0
  24. package/dist/fs/index.js +4 -0
  25. package/dist/fs/leased-directory-move.d.ts +49 -0
  26. package/dist/fs/leased-directory-move.js +31 -0
  27. package/dist/fs/owned-temp-root.d.ts +74 -0
  28. package/dist/fs/owned-temp-root.js +203 -0
  29. package/dist/fs/recent-directories.d.ts +2 -1
  30. package/dist/fs/resolve-directory-target.d.ts +33 -0
  31. package/dist/fs/resolve-directory-target.js +58 -0
  32. package/dist/fs/staged-file.d.ts +40 -0
  33. package/dist/fs/staged-file.js +75 -0
  34. package/dist/fs/strict-containment.d.ts +14 -0
  35. package/dist/fs/strict-containment.js +14 -0
  36. package/dist/image/png-encode.d.ts +41 -0
  37. package/dist/image/png-encode.js +96 -0
  38. package/dist/index.d.ts +3 -1
  39. package/dist/mail/email-template-agent-tools.d.ts +150 -0
  40. package/dist/mail/email-template-agent-tools.js +86 -0
  41. package/dist/mail/email-template-tool-registrations.d.ts +73 -0
  42. package/dist/mail/email-template-tool-registrations.js +66 -0
  43. package/dist/mail/feedback-route.d.ts +50 -0
  44. package/dist/mail/feedback-route.js +46 -0
  45. package/dist/mail/feedback-setup.d.ts +44 -0
  46. package/dist/mail/feedback-setup.js +53 -0
  47. package/dist/mail/feedback-sources.d.ts +67 -0
  48. package/dist/mail/feedback-sources.js +42 -0
  49. package/dist/mail/index.d.ts +10 -1
  50. package/dist/mail/index.js +4 -0
  51. package/dist/mail/mail-status.d.ts +32 -0
  52. package/dist/mail/mail-status.js +2 -0
  53. package/dist/mail/positional-purpose-gate.d.ts +14 -0
  54. package/dist/mail/positional-purpose-gate.js +18 -0
  55. package/dist/mail/purpose-gate-probe.d.ts +18 -0
  56. package/dist/mail/purpose-gate-probe.js +22 -0
  57. package/dist/mail/resolve-mailer.d.ts +13 -1
  58. package/dist/mail/resolve-mailer.js +11 -5
  59. package/dist/mail/sql/activity.repo.d.ts +20 -0
  60. package/dist/mail/sql/activity.repo.js +133 -0
  61. package/dist/mail/sql/attempts.repo.d.ts +17 -0
  62. package/dist/mail/sql/attempts.repo.js +32 -0
  63. package/dist/mail/sql/capture.repo.d.ts +69 -0
  64. package/dist/mail/sql/capture.repo.js +119 -0
  65. package/dist/mail/sql/feedback-inbox.repo.d.ts +12 -0
  66. package/dist/mail/sql/feedback-inbox.repo.js +32 -0
  67. package/dist/mail/sql/index.d.ts +12 -0
  68. package/dist/mail/sql/index.js +12 -0
  69. package/dist/mail/sql/ledger.repo.d.ts +29 -0
  70. package/dist/mail/sql/ledger.repo.js +57 -0
  71. package/dist/mail/sql/retention.d.ts +23 -0
  72. package/dist/mail/sql/retention.js +53 -0
  73. package/dist/mail/sql/site-feedback-route.d.ts +18 -0
  74. package/dist/mail/sql/site-feedback-route.js +22 -0
  75. package/dist/mail/sql/suppression-admin.repo.d.ts +11 -0
  76. package/dist/mail/sql/suppression-admin.repo.js +76 -0
  77. package/dist/mail/sql/suppression.repo.d.ts +10 -0
  78. package/dist/mail/sql/suppression.repo.js +33 -0
  79. package/dist/mail/test-send.d.ts +147 -0
  80. package/dist/mail/test-send.js +201 -0
  81. package/dist/mail/use-readiness.d.ts +104 -0
  82. package/dist/mail/use-readiness.js +140 -0
  83. package/dist/object-store/local-fs.js +34 -1
  84. package/dist/object-store/site/artifact-provider.d.ts +65 -0
  85. package/dist/object-store/site/artifact-provider.js +37 -0
  86. package/dist/object-store/site/registry.d.ts +110 -0
  87. package/dist/object-store/site/registry.js +93 -0
  88. package/dist/object-store/site/setting.d.ts +34 -0
  89. package/dist/object-store/site/setting.js +32 -0
  90. package/dist/process-probes.d.ts +11 -4
  91. package/dist/process-probes.js +3 -3
  92. package/dist/process-top-footprint.d.ts +1 -1
  93. package/dist/process.d.ts +3 -17
  94. package/dist/process.js +3 -2
  95. package/dist/retention/index.d.ts +6 -0
  96. package/dist/retention/index.js +6 -0
  97. package/dist/retention/measure-tree.d.ts +68 -0
  98. package/dist/retention/measure-tree.js +205 -0
  99. package/dist/retention/preview-store.d.ts +10 -0
  100. package/dist/retention/preview-store.js +26 -0
  101. package/dist/retention/routes.d.ts +23 -0
  102. package/dist/retention/routes.js +24 -0
  103. package/dist/retention/runner.d.ts +103 -0
  104. package/dist/retention/runner.js +164 -0
  105. package/dist/secrets/credential-sets/index.d.ts +1 -0
  106. package/dist/secrets/credential-sets/index.js +1 -0
  107. package/dist/secrets/credential-sets/store-vault-guards.d.ts +26 -0
  108. package/dist/secrets/credential-sets/store-vault-guards.js +30 -0
  109. package/dist/secrets/credential-sets/vault.service.d.ts +1 -1
  110. package/dist/secrets/index.d.ts +1 -1
  111. package/dist/secrets/index.js +1 -1
  112. package/dist/secrets/keyring.env.d.ts +1 -1
  113. package/dist/secrets/keyring.env.js +3 -5
  114. package/dist/secrets/keyring.memory.d.ts +4 -1
  115. package/dist/secrets/keyring.memory.js +4 -1
  116. package/dist/secrets/legacy-codecs.d.ts +381 -0
  117. package/dist/secrets/legacy-codecs.js +468 -0
  118. package/dist/secrets/legacy-owner.d.ts +3 -11
  119. package/dist/secrets/root-key/ensure.d.ts +154 -0
  120. package/dist/secrets/root-key/ensure.js +328 -0
  121. package/dist/secrets/root-key/files.d.ts +104 -0
  122. package/dist/secrets/root-key/files.js +166 -0
  123. package/dist/secrets/root-key/material.d.ts +132 -0
  124. package/dist/secrets/root-key/material.js +116 -0
  125. package/dist/secrets/root-key/ordered-keyring.d.ts +157 -0
  126. package/dist/secrets/root-key/ordered-keyring.js +104 -0
  127. package/dist/secrets/root-key/reconcile.d.ts +50 -0
  128. package/dist/secrets/root-key/reconcile.js +147 -0
  129. package/dist/secrets/root-key/site-keyring-errors.d.ts +78 -0
  130. package/dist/secrets/root-key/site-keyring-errors.js +37 -0
  131. package/dist/secrets/root-key/sources.d.ts +79 -0
  132. package/dist/secrets/root-key/sources.js +119 -0
  133. package/dist/secrets/secret-sealer.aesgcm.d.ts +50 -2
  134. package/dist/secrets/secret-sealer.aesgcm.js +107 -19
  135. package/dist/web/tool-registrations.d.ts +67 -0
  136. package/dist/web/tool-registrations.js +44 -0
  137. package/package.json +139 -7
@@ -0,0 +1,73 @@
1
+ import { type AgentToolSideEffect, type ToolExecutionContext, type ToolRegistration } from "@jini-ai/core";
2
+ import type { ToolContributor } from "@jini-ai/core";
3
+ export interface EmailTemplateStorePort {
4
+ find(args: {
5
+ id: string;
6
+ }): Promise<{
7
+ id: string;
8
+ name: string;
9
+ html: string;
10
+ version: number;
11
+ updatedAt: string;
12
+ } | null>;
13
+ create(args: {
14
+ name: string;
15
+ seedHtml: string;
16
+ actorId: string;
17
+ }): Promise<{
18
+ id: string;
19
+ name: string;
20
+ html: string;
21
+ version: number;
22
+ updatedAt: string;
23
+ }>;
24
+ openHtml(args: {
25
+ id: string;
26
+ actorId: string;
27
+ }): Promise<{
28
+ version: number | null;
29
+ write(args: {
30
+ html: string;
31
+ }): Promise<boolean>;
32
+ }>;
33
+ rename(args: {
34
+ id: string;
35
+ name: string;
36
+ ifVersion: number;
37
+ }): Promise<boolean>;
38
+ listPage(args: {
39
+ limit: number;
40
+ before?: {
41
+ updatedAt: string;
42
+ id: string;
43
+ };
44
+ }): Promise<Array<{
45
+ id: string;
46
+ name: string;
47
+ html: string;
48
+ version: number;
49
+ updatedAt: string;
50
+ } | null>>;
51
+ }
52
+ export interface EmailTemplatesToolDeps {
53
+ workspaceId: string;
54
+ editHtmlPermission: string;
55
+ catalog: readonly import('@jini-ai/core').AgentToolDefinition[];
56
+ requirePermission(input: {
57
+ ctx: ToolExecutionContext;
58
+ name: string;
59
+ }): Promise<unknown>;
60
+ emailTemplateStore(): EmailTemplateStorePort;
61
+ ForbiddenError: abstract new (...args: never[]) => Error;
62
+ }
63
+ export declare const emailTemplatesDerivedRisk: ReadonlyMap<string, AgentToolSideEffect>;
64
+ /**
65
+ * The assistant half of email templates; every handler is a permission check plus one shared
66
+ * operation from `operations.ts`, the same call the admin route makes.
67
+ * @returns The five registrations.
68
+ * @complexity O(1) per call beyond the operation's own cost.
69
+ */
70
+ export declare function buildEmailTemplatesRegistrations(deps: EmailTemplatesToolDeps): ToolRegistration[];
71
+ /** Contributes the email-template tools; registered once by `tool-catalog-manifest.ts`. */
72
+ export declare function contributeEmailTemplatesTools(): ToolContributor<EmailTemplatesToolDeps, unknown>;
73
+ //# sourceMappingURL=email-template-tool-registrations.d.ts.map
@@ -0,0 +1,66 @@
1
+ import { requireExpectedVersion } from "@jini-ai/core/optimistic-concurrency";
2
+ import { toolMetadata } from "@jini-ai/core/tool-metadata/email-templates";
3
+ import { buildDomainRegistrations, indexCatalogById, requireInputRecord } from "@jini-ai/core";
4
+ import { forbiddenRule, withModelFacingErrors } from "@jini-ai/core/model-facing-tool-errors";
5
+ import { createEmailTemplate, editEmailTemplate, EmailTemplateInputError, EmailTemplateNotFoundError, EmailTemplateVersionConflictError, getEmailTemplate, listEmailTemplates, previewEmailTemplate, requireText, } from "@jini-ai/platform/mail/email-template-operations";
6
+ export const emailTemplatesDerivedRisk = new Map([
7
+ // -> postRepo.listHtmlByKind only.
8
+ ["email_template_list", "none"],
9
+ // -> postRepo.findById only.
10
+ ["email_template_get", "none"],
11
+ // -> postRepo.save + PagesHtmlDocumentStore.ensureHtmlFormat: one new draft row, its revisions.
12
+ ["email_template_create", "mutates-durable-state"],
13
+ // -> PagesHtmlDocumentStore.write: one compare-and-set body write plus its revision.
14
+ ["email_template_edit", "mutates-durable-state"],
15
+ // -> postRepo.findById at most; renders in memory and sends nothing.
16
+ ["email_template_preview", "none"],
17
+ ]);
18
+ function permission({ deps, ctx, name }, _options = {}) {
19
+ return deps.requirePermission({ ctx, name });
20
+ }
21
+ /**
22
+ * The assistant half of email templates; every handler is a permission check plus one shared
23
+ * operation from `operations.ts`, the same call the admin route makes.
24
+ * @returns The five registrations.
25
+ * @complexity O(1) per call beyond the operation's own cost.
26
+ */
27
+ export function buildEmailTemplatesRegistrations(deps) {
28
+ return buildDomainRegistrations({ metadata: toolMetadata, domain: "email-templates", catalogModule: "@jini-ai/platform/mail/email-template-agent-tools", catalog: indexCatalogById({ catalog: deps.catalog }), derivedRisk: emailTemplatesDerivedRisk, handlers: withModelFacingErrors({ handlers: {
29
+ email_template_list: async (ctx) => {
30
+ requireInputRecord({ input: ctx.input });
31
+ await permission({ deps, ctx, name: "content.read" });
32
+ return listEmailTemplates({ store: deps.emailTemplateStore(), input: requireInputRecord({ input: ctx.input }) });
33
+ },
34
+ email_template_get: async (ctx) => {
35
+ const input = requireInputRecord({ input: ctx.input });
36
+ await permission({ deps, ctx, name: "content.read" });
37
+ return getEmailTemplate({ store: deps.emailTemplateStore(), id: requireText({ value: input.id, key: "id", max: 200 }) });
38
+ },
39
+ email_template_create: async (ctx) => {
40
+ const input = requireInputRecord({ input: ctx.input });
41
+ await permission({ deps, ctx, name: deps.editHtmlPermission });
42
+ ctx.signal.throwIfAborted();
43
+ return createEmailTemplate({ store: deps.emailTemplateStore(), input, actorId: ctx.principal.id });
44
+ },
45
+ email_template_edit: async (ctx) => {
46
+ const input = requireInputRecord({ input: ctx.input });
47
+ await permission({ deps, ctx, name: deps.editHtmlPermission });
48
+ return editEmailTemplate({ store: deps.emailTemplateStore(), input: { ...input, expectedVersion: requireExpectedVersion({ value: input.expectedVersion, readToolId: "email_template_get" }) }, actorId: ctx.principal.id });
49
+ },
50
+ email_template_preview: async (ctx) => {
51
+ const input = requireInputRecord({ input: ctx.input });
52
+ await permission({ deps, ctx, name: "content.read" });
53
+ return previewEmailTemplate({ store: deps.emailTemplateStore(), input });
54
+ },
55
+ }, rules: [
56
+ forbiddenRule({ domainPrefix: "EMAIL_TEMPLATES", error: deps.ForbiddenError }),
57
+ { error: EmailTemplateNotFoundError, code: "EMAIL_TEMPLATES_NOT_FOUND" },
58
+ { error: EmailTemplateInputError, code: "EMAIL_TEMPLATES_INVALID_INPUT" },
59
+ { error: EmailTemplateVersionConflictError, code: "EMAIL_TEMPLATES_VERSION_CONFLICT" },
60
+ ] }) });
61
+ }
62
+ /** Contributes the email-template tools; registered once by `tool-catalog-manifest.ts`. */
63
+ export function contributeEmailTemplatesTools() {
64
+ return { domain: "email-templates", build: buildEmailTemplatesRegistrations, risk: emailTemplatesDerivedRisk };
65
+ }
66
+ //# sourceMappingURL=email-template-tool-registrations.js.map
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @file `POST /hooks/mail/:providerId` — framework-free handler over Jini's `createMailFeedbackIngest`.
3
+ *
4
+ * Features never import Express (`features/INFO.md`); the server mounts {@link MailFeedbackRoute}
5
+ * with a RAW body parser (signatures are over the exact bytes) ahead of the public JSON parser.
6
+ * Hardening lives in the Jini ingest: body cap (413), unverified-request rate limit (429), unknown
7
+ * provider (404), no secret configured (503), bad signature (401), replay dedup.
8
+ */
9
+ import { type MailFeedbackInboxPort, type MailFeedbackIngestOptions, type MailFeedbackResponse } from "./feedback.js";
10
+ import type { MailFeedbackParser } from "./provider.js";
11
+ import type { MailSuppressionRepoPort } from "./ports.js";
12
+ /** Default body cap; the server's raw parser uses the same number so both refuse alike. */
13
+ export declare const MAIL_FEEDBACK_MAX_BODY_BYTES: number;
14
+ export interface MailFeedbackRouteDeps {
15
+ /** The provider's feedback parser; undefined = unknown provider or no feedback support (404). May load plugins. */
16
+ parserFor: (required: {
17
+ providerId: string;
18
+ }) => MailFeedbackParser | undefined | Promise<MailFeedbackParser | undefined>;
19
+ /** Current + previous webhook secrets from the vault; empty = not configured (503). */
20
+ secretsFor: (required: {
21
+ providerId: string;
22
+ }) => Promise<readonly string[]>;
23
+ repos: {
24
+ inbox: MailFeedbackInboxPort;
25
+ suppression: MailSuppressionRepoPort;
26
+ };
27
+ /** The workspace this site's mail belongs to. */
28
+ resolveWorkspaceId: (required: Record<string, never>) => string | Promise<string>;
29
+ }
30
+ export interface MailFeedbackRequest {
31
+ providerId: string;
32
+ rawBody: Uint8Array;
33
+ /** Node-style headers (lower-case keys; repeated headers as arrays). */
34
+ headers: Readonly<Record<string, string | readonly string[] | undefined>>;
35
+ }
36
+ export interface MailFeedbackRoute {
37
+ readonly maxBodyBytes: number;
38
+ handle(required: MailFeedbackRequest): Promise<MailFeedbackResponse>;
39
+ }
40
+ /** Flattens Node headers to the parser's `Record<string, string>`; lower-cased keys, arrays joined. */
41
+ export declare function flattenHeaders({ headers }: {
42
+ headers: MailFeedbackRequest["headers"];
43
+ }, _optional?: Record<string, never>): Record<string, string>;
44
+ /**
45
+ * One ingest per process, so the unverified-request counter is shared across requests.
46
+ * @complexity O(events) inbox writes per request, plus one parser and one secrets lookup.
47
+ * @example createMailFeedbackRoute({ parserFor, secretsFor, repos: { inbox, suppression }, resolveWorkspaceId })
48
+ */
49
+ export declare function createMailFeedbackRoute(required: MailFeedbackRouteDeps, optional?: MailFeedbackIngestOptions): MailFeedbackRoute;
50
+ //# sourceMappingURL=feedback-route.d.ts.map
@@ -0,0 +1,46 @@
1
+ /**
2
+ * @file `POST /hooks/mail/:providerId` — framework-free handler over Jini's `createMailFeedbackIngest`.
3
+ *
4
+ * Features never import Express (`features/INFO.md`); the server mounts {@link MailFeedbackRoute}
5
+ * with a RAW body parser (signatures are over the exact bytes) ahead of the public JSON parser.
6
+ * Hardening lives in the Jini ingest: body cap (413), unverified-request rate limit (429), unknown
7
+ * provider (404), no secret configured (503), bad signature (401), replay dedup.
8
+ */
9
+ import { createMailFeedbackIngest, } from "./feedback.js";
10
+ /** Default body cap; the server's raw parser uses the same number so both refuse alike. */
11
+ export const MAIL_FEEDBACK_MAX_BODY_BYTES = 256 * 1024;
12
+ /** Flattens Node headers to the parser's `Record<string, string>`; lower-cased keys, arrays joined. */
13
+ export function flattenHeaders({ headers }, _optional = {}) {
14
+ const flat = {};
15
+ for (const [name, value] of Object.entries(headers)) {
16
+ if (value === undefined)
17
+ continue;
18
+ flat[name.toLowerCase()] = typeof value === "string" ? value : value.join(", ");
19
+ }
20
+ return flat;
21
+ }
22
+ /**
23
+ * One ingest per process, so the unverified-request counter is shared across requests.
24
+ * @complexity O(events) inbox writes per request, plus one parser and one secrets lookup.
25
+ * @example createMailFeedbackRoute({ parserFor, secretsFor, repos: { inbox, suppression }, resolveWorkspaceId })
26
+ */
27
+ export function createMailFeedbackRoute(required, optional = {}) {
28
+ const maxBodyBytes = optional.maxBodyBytes ?? MAIL_FEEDBACK_MAX_BODY_BYTES;
29
+ // The Jini ingest asks for its parser synchronously; the lookup here may be async (plugin load),
30
+ // so each request resolves first and the ingest reads the result in the same tick.
31
+ const parsers = new Map();
32
+ const ingest = createMailFeedbackIngest({ parserFor: ({ providerId }) => parsers.get(providerId), secretsFor: required.secretsFor, inbox: required.repos.inbox, suppression: required.repos.suppression }, { ...optional, maxBodyBytes });
33
+ return {
34
+ maxBodyBytes,
35
+ async handle({ providerId, rawBody, headers }) {
36
+ const workspaceId = await required.resolveWorkspaceId({});
37
+ const parser = await required.parserFor({ providerId });
38
+ if (parser)
39
+ parsers.set(providerId, parser);
40
+ else
41
+ parsers.delete(providerId);
42
+ return ingest.handle({ providerId, workspaceId, rawBody, headers: flattenHeaders({ headers }) });
43
+ },
44
+ };
45
+ }
46
+ //# sourceMappingURL=feedback-route.js.map
@@ -0,0 +1,44 @@
1
+ /**
2
+ * @file **Feedback setup** (email phase 5) behind `mail_get_feedback_setup` and
3
+ * `GET system/mail-feedback`: for each active provider, whether it can report deliveries, bounces
4
+ * and complaints, the webhook URL to paste into the provider, whether its signing secret is saved
5
+ * (current and previous rotation slots, `features/mail/feedback-sources.ts`), and the newest
6
+ * verified event.
7
+ *
8
+ * Presence only: the secret slots are read from the credential list by label, never decrypted, so
9
+ * this read cannot leak or even touch a secret. "No events yet" (`no_events_yet`) is reported apart
10
+ * from healthy ingestion (`receiving`), because a webhook nobody has called looks the same as a
11
+ * broken one until the first event arrives.
12
+ */
13
+ import type { OriginRegistryPort } from "@jini-ai/core/contracts/server/verified-origin";
14
+ import type { MailSuppressionAdminRepo } from "@jini-ai/core/contracts/site/platform-mail";
15
+ import type { MailProviderControl } from "./mail-status.js";
16
+ import type { MailFeedbackSetupReport } from "@jini-ai/core/contracts/site/platform-mail";
17
+ export interface MailFeedbackSetupDeps<TCredentialRepo = unknown> {
18
+ workspaceId: string;
19
+ mailProviderControl?: Pick<MailProviderControl, "describe">;
20
+ /** The host's credential store, handed back to {@link MailFeedbackSetupDeps.listCustomCredentials}. */
21
+ customCredentialSetRepo?: TCredentialRepo;
22
+ originRegistry?: Pick<OriginRegistryPort, "canonicalOrigin">;
23
+ mailSuppressionAdmin?: Pick<MailSuppressionAdminRepo, "lastFeedbackEvent">;
24
+ /** Host: safe summaries (label + update time, never a secret) of the saved credentials. */
25
+ listCustomCredentials(deps: {
26
+ repo: TCredentialRepo;
27
+ }, input: {
28
+ workspaceId: string;
29
+ }): Promise<readonly {
30
+ label: string;
31
+ updatedAt: string;
32
+ }[]>;
33
+ /** Host: the persisted current/previous signing-secret labels for a provider (product-prefixed). */
34
+ mailWebhookSecretLabels(required: {
35
+ providerLabel: string;
36
+ }): readonly [string, string];
37
+ }
38
+ /**
39
+ * Feedback setup for every provider that currently sends for a lane.
40
+ * @complexity One provider describe, one credential list, one origin read and one inbox probe per provider.
41
+ * @example await readMailFeedbackSetup(deps)
42
+ */
43
+ export declare function readMailFeedbackSetup(deps: MailFeedbackSetupDeps, _options?: Record<string, never>): Promise<MailFeedbackSetupReport>;
44
+ //# sourceMappingURL=feedback-setup.d.ts.map
@@ -0,0 +1,53 @@
1
+ /** Mirrors `features/newsletter/confirmation.ts`'s private `composeOriginUrl` (default ports elided). */
2
+ function originUrl(origin, _options = {}) {
3
+ const matchesDefaultPort = (origin.scheme === "https" && origin.port === 443) || (origin.scheme === "http" && origin.port === 80);
4
+ const isDefaultPort = origin.port === undefined || matchesDefaultPort;
5
+ const authority = isDefaultPort ? origin.host : `${origin.host}:${origin.port}`;
6
+ return `${origin.scheme}://${authority}${origin.basePath ?? ""}`;
7
+ }
8
+ async function siteOrigin(deps, _options = {}) {
9
+ if (!deps.originRegistry)
10
+ return null;
11
+ try {
12
+ return originUrl(await deps.originRegistry.canonicalOrigin({ workspaceId: deps.workspaceId }));
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ }
18
+ function slot({ label, saved }, _options = {}) {
19
+ return { label, configured: saved.has(label), updatedAt: saved.get(label) ?? null };
20
+ }
21
+ function stateOf(setup, _options = {}) {
22
+ if (!setup.supported)
23
+ return "unsupported";
24
+ if (!setup.signingSecret?.current.configured && !setup.signingSecret?.previous.configured)
25
+ return "secret_missing";
26
+ return setup.lastVerifiedEvent ? "receiving" : "no_events_yet";
27
+ }
28
+ async function providerSetup({ deps, provider, context }, _optional = {}) {
29
+ const supported = provider.capabilities.feedback;
30
+ const webhookPath = `/hooks/mail/${encodeURIComponent(provider.id)}`;
31
+ const [current, previous] = deps.mailWebhookSecretLabels({ providerLabel: provider.label });
32
+ const signingSecret = supported ? { current: slot({ label: current, saved: context.saved }), previous: slot({ label: previous, saved: context.saved }) } : null;
33
+ const lastVerifiedEvent = supported && deps.mailSuppressionAdmin ? await deps.mailSuppressionAdmin.lastFeedbackEvent({ workspaceId: deps.workspaceId, providerId: provider.id }) : null;
34
+ const setup = { providerId: provider.id, label: provider.label, lanes: provider.lanes, supported, webhookPath,
35
+ webhookUrl: supported && context.origin ? `${context.origin}${webhookPath}` : null, signingSecret, lastVerifiedEvent };
36
+ return { ...setup, state: stateOf(setup) };
37
+ }
38
+ /**
39
+ * Feedback setup for every provider that currently sends for a lane.
40
+ * @complexity One provider describe, one credential list, one origin read and one inbox probe per provider.
41
+ * @example await readMailFeedbackSetup(deps)
42
+ */
43
+ export async function readMailFeedbackSetup(deps, _options = {}) {
44
+ if (!deps.mailProviderControl?.describe)
45
+ return { available: false, providers: [] };
46
+ const report = await deps.mailProviderControl.describe();
47
+ const active = report.providers.filter((provider) => provider.lanes.length > 0);
48
+ const records = deps.customCredentialSetRepo ? await deps.listCustomCredentials({ repo: deps.customCredentialSetRepo }, { workspaceId: deps.workspaceId }) : [];
49
+ const saved = new Map(records.map((record) => [record.label, record.updatedAt]));
50
+ const origin = await siteOrigin(deps);
51
+ return { available: true, providers: await Promise.all(active.map((provider) => providerSetup({ deps, provider, context: { origin, saved } }))) };
52
+ }
53
+ //# sourceMappingURL=feedback-setup.js.map
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @file Where the feedback route finds a provider's parser and webhook secrets.
3
+ *
4
+ * Parsers come from the provider module's `.feedback` (Jini `MailProviderModule`), read off the
5
+ * plugin mail-adapter registry until the composition hands over a provider registry. Secrets live
6
+ * in the custom-credentials vault under fixed labels, one per provider, plus a `(previous)` label so
7
+ * a secret can rotate without dropping in-flight webhooks: save the new one as current, keep the old
8
+ * one as previous until the provider stops signing with it, then delete it.
9
+ */
10
+ import type { MailFeedbackParser } from "./provider.js";
11
+ /** Reads one saved vault credential by label (the host's custom-credentials store); `null` = not saved. */
12
+ export type MailWebhookSecretResolver<Credentials> = (credentials: Credentials, input: {
13
+ workspaceId: string;
14
+ label: string;
15
+ }) => Promise<{
16
+ connection: {
17
+ token: string;
18
+ };
19
+ } | null>;
20
+ /** The registry shape this needs (`MailAdapterRegistry` structurally); modules are untrusted values. */
21
+ export interface MailAdapterSource {
22
+ list(): readonly {
23
+ readonly descriptor: {
24
+ readonly id: string;
25
+ readonly label: string;
26
+ };
27
+ readonly module: unknown;
28
+ }[];
29
+ }
30
+ /** Vault labels for a provider's webhook signing secret: current first, then the rotation slot.
31
+ * `labelPrefix` is the host's product label; stored labels are persisted, so it never changes. */
32
+ export declare function mailWebhookSecretLabels({ providerLabel, labelPrefix }: {
33
+ providerLabel: string;
34
+ labelPrefix: string;
35
+ }): readonly [string, string];
36
+ /**
37
+ * Parser and label lookups over a freshly loaded adapter registry.
38
+ * @complexity O(a) adapters per lookup, plus one registry load.
39
+ */
40
+ export declare function createPluginMailFeedbackSources(required: {
41
+ loadAdapters: () => Promise<MailAdapterSource>;
42
+ }): {
43
+ parserFor: ({ providerId }: {
44
+ providerId: string;
45
+ }) => Promise<MailFeedbackParser | undefined>;
46
+ labelFor: ({ providerId }: {
47
+ providerId: string;
48
+ }) => Promise<string | undefined>;
49
+ };
50
+ /**
51
+ * `secretsFor` over the vault: the current then previous secret that are saved, in that order.
52
+ * A vault read failure propagates (the route answers 500 and the provider retries).
53
+ * @complexity Two label lookups per call.
54
+ */
55
+ export declare function createVaultMailWebhookSecrets<Credentials>(required: {
56
+ credentials: Credentials;
57
+ workspaceId: string;
58
+ labelFor: (required: {
59
+ providerId: string;
60
+ }) => Promise<string | undefined>;
61
+ /** The host's vault reader and label prefix (see {@link mailWebhookSecretLabels}). */
62
+ resolveByLabel: MailWebhookSecretResolver<Credentials>;
63
+ labelPrefix: string;
64
+ }, _optional?: Record<string, never>): ({ providerId }: {
65
+ providerId: string;
66
+ }) => Promise<readonly string[]>;
67
+ //# sourceMappingURL=feedback-sources.d.ts.map
@@ -0,0 +1,42 @@
1
+ /** Vault labels for a provider's webhook signing secret: current first, then the rotation slot.
2
+ * `labelPrefix` is the host's product label; stored labels are persisted, so it never changes. */
3
+ export function mailWebhookSecretLabels({ providerLabel, labelPrefix }) {
4
+ const current = `${labelPrefix} — ${providerLabel} Webhook Secret`;
5
+ return [current, `${current} (previous)`];
6
+ }
7
+ function asParser({ module }, _optional = {}) {
8
+ const feedback = module?.feedback;
9
+ return typeof feedback?.verify === "function" && typeof feedback.parse === "function" ? feedback : undefined;
10
+ }
11
+ /**
12
+ * Parser and label lookups over a freshly loaded adapter registry.
13
+ * @complexity O(a) adapters per lookup, plus one registry load.
14
+ */
15
+ export function createPluginMailFeedbackSources(required) {
16
+ const find = async ({ providerId }) => (await required.loadAdapters()).list().find((adapter) => adapter.descriptor.id === providerId);
17
+ return {
18
+ parserFor: async ({ providerId }) => asParser({ module: (await find({ providerId }))?.module }),
19
+ labelFor: async ({ providerId }) => (await find({ providerId }))?.descriptor.label,
20
+ };
21
+ }
22
+ /**
23
+ * `secretsFor` over the vault: the current then previous secret that are saved, in that order.
24
+ * A vault read failure propagates (the route answers 500 and the provider retries).
25
+ * @complexity Two label lookups per call.
26
+ */
27
+ export function createVaultMailWebhookSecrets(required, _optional = {}) {
28
+ const resolveByLabel = required.resolveByLabel;
29
+ return async ({ providerId }) => {
30
+ const providerLabel = await required.labelFor({ providerId });
31
+ if (providerLabel === undefined)
32
+ return [];
33
+ const secrets = [];
34
+ for (const label of mailWebhookSecretLabels({ providerLabel, labelPrefix: required.labelPrefix })) {
35
+ const saved = await resolveByLabel(required.credentials, { workspaceId: required.workspaceId, label });
36
+ if (saved && saved.connection.token !== "")
37
+ secrets.push(saved.connection.token);
38
+ }
39
+ return secrets;
40
+ };
41
+ }
42
+ //# sourceMappingURL=feedback-sources.js.map
@@ -25,7 +25,7 @@ export type { SenderDomainVerificationDeps } from "./sender-domain-verification.
25
25
  export { createMailPolicyWrapper } from "./delivery-wrapper.js";
26
26
  export type { MailPolicyWrapperDeps, MailPolicyWrapperOptions, MailPolicyWrapperInput } from "./delivery-wrapper.js";
27
27
  export { createResolvedMailer } from "./resolve-mailer.js";
28
- export type { ResolveMailerDeps, ResolveMailerOptions, ResolvedMailer } from "./resolve-mailer.js";
28
+ export type { ResolveMailerDeps, ResolveMailerOptions, ResolvedMailer, CreatedResolvedMailer } from "./resolve-mailer.js";
29
29
  export { createTtlCache, MAIL_STATUS_TTL_MS } from "./mail-status-cache.js";
30
30
  export type { TtlCache } from "./mail-status-cache.js";
31
31
  export * from "./senders.js";
@@ -36,4 +36,13 @@ export * from "./activity/vocabulary.js";
36
36
  export type * from "./activity/ports.js";
37
37
  export * from "./activity/activity.js";
38
38
  export * from "./activity/suppressions.js";
39
+ export { createMailPurposeGateProbe } from "./purpose-gate-probe.js";
40
+ export type { MailPurposeGateProbe } from "./purpose-gate-probe.js";
41
+ export { wrapPositionalMailerWithPurposeGate } from "./positional-purpose-gate.js";
42
+ export type { WrapPositionalMailerWithPurposeGateOptions } from "./positional-purpose-gate.js";
43
+ export type { MailProviderControl } from "./mail-status.js";
44
+ export { createMailFeedbackRoute, flattenHeaders, MAIL_FEEDBACK_MAX_BODY_BYTES } from "./feedback-route.js";
45
+ export type { MailFeedbackRequest, MailFeedbackRoute, MailFeedbackRouteDeps } from "./feedback-route.js";
46
+ export { createPluginMailFeedbackSources, createVaultMailWebhookSecrets, mailWebhookSecretLabels } from "./feedback-sources.js";
47
+ export type { MailAdapterSource, MailWebhookSecretResolver } from "./feedback-sources.js";
39
48
  //# sourceMappingURL=index.d.ts.map
@@ -20,4 +20,8 @@ export * from "./provider-mailer.js";
20
20
  export * from "./activity/vocabulary.js";
21
21
  export * from "./activity/activity.js";
22
22
  export * from "./activity/suppressions.js";
23
+ export { createMailPurposeGateProbe } from "./purpose-gate-probe.js";
24
+ export { wrapPositionalMailerWithPurposeGate } from "./positional-purpose-gate.js";
25
+ export { createMailFeedbackRoute, flattenHeaders, MAIL_FEEDBACK_MAX_BODY_BYTES } from "./feedback-route.js";
26
+ export { createPluginMailFeedbackSources, createVaultMailWebhookSecrets, mailWebhookSecretLabels } from "./feedback-sources.js";
23
27
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,32 @@
1
+ /** Shared safe status/configuration contracts are owned by Jini; the host retains selection control.
2
+ * The provider verdict remains separate from credential presence and delivery evidence.
3
+ * Setup copy is plugin/host data, and credential summaries expose presence without values.
4
+ */
5
+ import type { MailProviderConfigurationReport } from "./ports.js";
6
+ /** Explicit provider selection: `check` validates without sending, `select` writes both lanes. */
7
+ export interface MailProviderControl {
8
+ check(required: {
9
+ id: string;
10
+ }): Promise<{
11
+ ok: true;
12
+ label: string;
13
+ } | {
14
+ ok: false;
15
+ reason: string;
16
+ }>;
17
+ select(required: {
18
+ id: string;
19
+ principalId: string;
20
+ expectedRevisionSeq?: number;
21
+ }): Promise<void>;
22
+ /** Exact addressed setting value and revision, read before an access approval. */
23
+ readSelection?(): Promise<{
24
+ setting: MailProviderConfigurationReport["setting"];
25
+ revisionSeq: number;
26
+ }>;
27
+ /** The safe configuration DTO for every installed provider. Absent in older roots. */
28
+ describe?(): Promise<MailProviderConfigurationReport>;
29
+ /** Drops cached provider mailers and status so the next send and status read start fresh. */
30
+ invalidate?(): void;
31
+ }
32
+ //# sourceMappingURL=mail-status.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=mail-status.js.map
@@ -0,0 +1,14 @@
1
+ import type { PositionalMailer as MailerPort } from "./plugin-abi.js";
2
+ import type { RuntimeMode } from "@jini-ai/core/contracts/site/core-runtime-mode";
3
+ export interface WrapPositionalMailerWithPurposeGateOptions {
4
+ inner: MailerPort;
5
+ mode: RuntimeMode;
6
+ durableOutboxReady: (required: {
7
+ capabilityName: string;
8
+ }) => boolean;
9
+ }
10
+ /** Injects the host's durable-outbox readiness into Jini's fail-closed purpose gate.
11
+ * @example wrapPositionalMailerWithPurposeGate({ inner, mode, durableOutboxReady })
12
+ */
13
+ export declare function wrapPositionalMailerWithPurposeGate({ inner, mode, durableOutboxReady }: WrapPositionalMailerWithPurposeGateOptions): MailerPort;
14
+ //# sourceMappingURL=positional-purpose-gate.d.ts.map
@@ -0,0 +1,18 @@
1
+ /** Host adapters for Jini mail and the SPEC-022 durable notification gate.
2
+ * Jini preserves U-001: only explicit interactive sends bypass production readiness;
3
+ * local mode proceeds, and the supplied mode is never re-read from the environment.
4
+ */
5
+ import { wrapMailerWithPurposeGate as wrapJiniMailerWithPurposeGate, } from "./purpose-scoped-mailer.js";
6
+ import { fromPositionalMailer as toJiniMailer, toPositionalMailer as toHostMailer } from "./plugin-abi.js";
7
+ /** Injects the host's durable-outbox readiness into Jini's fail-closed purpose gate.
8
+ * @example wrapPositionalMailerWithPurposeGate({ inner, mode, durableOutboxReady })
9
+ */
10
+ export function wrapPositionalMailerWithPurposeGate({ inner, mode, durableOutboxReady }) {
11
+ const mailer = wrapJiniMailerWithPurposeGate({
12
+ inner: toJiniMailer({ mailer: inner }),
13
+ mode,
14
+ readiness: { isReady: ({ capabilityName }) => durableOutboxReady({ capabilityName }) },
15
+ });
16
+ return toHostMailer({ mailer });
17
+ }
18
+ //# sourceMappingURL=positional-purpose-gate.js.map
@@ -0,0 +1,18 @@
1
+ import type { RuntimeMode } from "@jini-ai/core/contracts/site/core-runtime-mode";
2
+ export type MailPurposeGateProbe = (required: {
3
+ capabilityName: string;
4
+ lane: "interactive" | "notification";
5
+ }) => Promise<boolean>;
6
+ /**
7
+ * @returns `true` when the gate would pass a send for that capability and lane, `false` when it refuses.
8
+ * @throws Anything else the gate throws (an unexpected failure is the caller's `unknown`, not a refusal).
9
+ * @complexity O(1); no I/O.
10
+ * @example await createMailPurposeGateProbe({ mode: "production", durableOutboxReady: () => false })({ capabilityName: "forms", lane: "notification" })
11
+ */
12
+ export declare function createMailPurposeGateProbe(required: {
13
+ mode: RuntimeMode;
14
+ durableOutboxReady: (required: {
15
+ capabilityName: string;
16
+ }) => boolean;
17
+ }): MailPurposeGateProbe;
18
+ //# sourceMappingURL=purpose-gate-probe.d.ts.map
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @file Asks Jini's purpose gate (`wrapMailerWithPurposeGate`, SPEC-022 C-005 / U-001) whether it
3
+ * would let a send through, without sending: the probe calls the gate's own predicate. The Email
4
+ * page's use readiness reads the real gate instead of restating its rules, so the two cannot drift.
5
+ *
6
+ * It is given the same `mode` and `durableOutboxReady` the composition root hands the live mailer's
7
+ * gate (`server/runtime/composition/deps.ts`); this file never decides readiness itself.
8
+ */
9
+ import { isPurposeGateOpen } from "./purpose-scoped-mailer.js";
10
+ /**
11
+ * @returns `true` when the gate would pass a send for that capability and lane, `false` when it refuses.
12
+ * @throws Anything else the gate throws (an unexpected failure is the caller's `unknown`, not a refusal).
13
+ * @complexity O(1); no I/O.
14
+ * @example await createMailPurposeGateProbe({ mode: "production", durableOutboxReady: () => false })({ capabilityName: "forms", lane: "notification" })
15
+ */
16
+ export function createMailPurposeGateProbe(required) {
17
+ // Validate at composition, as the previous gate wrapper did; no readiness read in local mode.
18
+ isPurposeGateOpen({ mode: required.mode, readiness: { isReady: () => false }, options: { lane: "interactive", sourceContext: { module: "unknown" } } });
19
+ return async ({ capabilityName, lane }) => isPurposeGateOpen({ mode: required.mode,
20
+ readiness: { isReady: ({ capabilityName }) => required.durableOutboxReady({ capabilityName }) }, options: { lane, sourceContext: { module: capabilityName } } });
21
+ }
22
+ //# sourceMappingURL=purpose-gate-probe.js.map
@@ -74,6 +74,16 @@ export interface ResolvedMailer {
74
74
  laneReady: (required: {
75
75
  lane: MailDeliveryLane;
76
76
  }) => Promise<boolean>;
77
+ /**
78
+ * The provider id the lane's policy-wrapped mailer is really built for, from the SAME resolution that
79
+ * routes a send: `"console"` when a chosen provider could not resolve and the local console fallback
80
+ * took over, the chosen id otherwise (production refusals keep it), `null` when nothing is chosen.
81
+ * A host planning a test-send approval reads this instead of re-reading settings, which could name a
82
+ * provider the send never used. Optional so hosts that implement this interface keep compiling.
83
+ */
84
+ readonly effectiveProviderId?: (required: {
85
+ lane: MailDeliveryLane;
86
+ }) => Promise<string | null>;
77
87
  senderDomainVerification: SenderDomainVerificationPort;
78
88
  /** Whether `id` may be selected: a registered hosted provider whose saved key resolves. Sends nothing. */
79
89
  checkProvider: (required: {
@@ -85,6 +95,8 @@ export interface ResolvedMailer {
85
95
  workspaceId: string;
86
96
  }) => Promise<DomainRequirement | null>;
87
97
  }
98
+ /** What `createResolvedMailer` returns: the resolver always supplies the optional `effectiveProviderId`. */
99
+ export type CreatedResolvedMailer = ResolvedMailer & Required<Pick<ResolvedMailer, "effectiveProviderId">>;
88
100
  /**
89
101
  * Build a lane router and its control surface. The host binds catalogs, secrets, safe copy and DTOs.
90
102
  * Each send reads selection and metadata; boot starts resolution synchronously. Selection faults
@@ -92,5 +104,5 @@ export interface ResolvedMailer {
92
104
  * @complexity O(providers) cached mailers/flights; status holds one report for its TTL.
93
105
  * @example const control = createResolvedMailer(hostPorts, { clock }); await control.ready;
94
106
  */
95
- export declare function createResolvedMailer<TRecord extends MailCredentialFact = MailCredentialFact>(required: ResolveMailerDeps<TRecord>, optional?: ResolveMailerOptions): ResolvedMailer;
107
+ export declare function createResolvedMailer<TRecord extends MailCredentialFact = MailCredentialFact>(required: ResolveMailerDeps<TRecord>, optional?: ResolveMailerOptions): CreatedResolvedMailer;
96
108
  //# sourceMappingURL=resolve-mailer.d.ts.map