@happyvertical/smrt-messages 0.66.1 → 0.68.0
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/dist/chunks/{AttachmentCollection-DO_FHrQu.js → AttachmentCollection-AJXaT9sn.js} +4 -4
- package/dist/chunks/{AttachmentCollection-DO_FHrQu.js.map → AttachmentCollection-AJXaT9sn.js.map} +1 -1
- package/dist/chunks/{Email-Bf2YPJoZ.js → Email-CgwEgIqu.js} +6 -6
- package/dist/chunks/{Email-Bf2YPJoZ.js.map → Email-CgwEgIqu.js.map} +1 -1
- package/dist/chunks/{EmailAccountCollection-DWRDwHg9.js → EmailAccountCollection-I5pIN-r2.js} +19 -19
- package/dist/chunks/{EmailAccountCollection-DWRDwHg9.js.map → EmailAccountCollection-I5pIN-r2.js.map} +1 -1
- package/dist/chunks/{EmailCollection--VQjBsSi.js → EmailCollection-BHmKvRuX.js} +3 -3
- package/dist/chunks/{EmailCollection--VQjBsSi.js.map → EmailCollection-BHmKvRuX.js.map} +1 -1
- package/dist/chunks/{EmailFolder-By45ofY5.js → EmailFolder-I_HneZH4.js} +6 -6
- package/dist/chunks/{EmailFolder-By45ofY5.js.map → EmailFolder-I_HneZH4.js.map} +1 -1
- package/dist/chunks/{EmailFolderCollection-D-UUwhfN.js → EmailFolderCollection-KcqROvEm.js} +2 -2
- package/dist/chunks/{EmailFolderCollection-D-UUwhfN.js.map → EmailFolderCollection-KcqROvEm.js.map} +1 -1
- package/dist/chunks/{EmailSender-KW0zLvqh.js → EmailSender-DjCFXHDv.js} +2 -2
- package/dist/chunks/{EmailSender-KW0zLvqh.js.map → EmailSender-DjCFXHDv.js.map} +1 -1
- package/dist/chunks/{Message-BPUu5s55.js → Message-BsHWNjSp.js} +6 -6
- package/dist/chunks/{Message-BPUu5s55.js.map → Message-BsHWNjSp.js.map} +1 -1
- package/dist/chunks/{MessageCollection-CRVpTj6j.js → MessageCollection-DbgpV2ne.js} +2 -2
- package/dist/chunks/{MessageCollection-CRVpTj6j.js.map → MessageCollection-DbgpV2ne.js.map} +1 -1
- package/dist/chunks/{MessagingEndpointCollection-DNrPr6gu.js → MessagingEndpointCollection-PpqxujnP.js} +2 -2
- package/dist/chunks/{MessagingEndpointCollection-DNrPr6gu.js.map → MessagingEndpointCollection-PpqxujnP.js.map} +1 -1
- package/dist/connect.js +1 -1
- package/dist/index.js +18 -18
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/migrations/profileRecipients.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +3 -3
- package/package.json +12 -12
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["registered","username","password","rest","hits","message","route"],"sources":["../src/access-enforcement.ts","../src/mail-drafts.ts","../src/mail-sync-jobs.ts","../src/models/Correspondent.ts","../src/collections/CorrespondentCollection.ts","../src/models/NotificationDelivery.ts","../src/collections/NotificationDeliveryCollection.ts","../src/models/NotificationOptOut.ts","../src/collections/NotificationOptOutCollection.ts","../src/models/PersonaMessageRoute.ts","../src/collections/PersonaMessageRouteCollection.ts","../src/models/UserNotification.ts","../src/collections/UserNotificationCollection.ts","../src/models/EmailAttachment.ts","../src/collections/EmailAttachmentCollection.ts","../src/models/Blacklist.ts","../src/collections/BlacklistCollection.ts","../src/models/Whitelist.ts","../src/collections/WhitelistCollection.ts","../src/models/SlackAccount.ts","../src/models/SlackMessage.ts","../src/models/TelegramAccount.ts","../src/models/Tweet.ts","../src/models/TwitterAccount.ts","../src/models/ZulipAccount.ts","../src/services/MessagingSettingsService.ts","../src/services/MailSearchService.ts","../src/services/CorrespondentService.ts","../src/services/NotificationOptOutService.ts","../src/migrations/profileRecipients.ts","../src/services/NotificationOutboxService.ts","../src/services/PersonaMessagingService.ts","../src/services/UserNotificationService.ts","../src/recipes.ts","../src/index.ts"],"sourcesContent":["/**\n * Collection-layer enforcement of per-account mail access (see `access.ts`).\n *\n * Registered once at package load as a `GlobalInterceptors` entry, so every\n * list/get/count/raw read of an owned account's emails, folders and\n * attachments is filtered in the collection, not in a component. Matching is\n * by STI ancestry, so an app subclass of `Email` is governed too.\n *\n * Account rows themselves are not filtered here: senders, routes and the\n * outbox read them without a principal, and the content (emails, folders,\n * attachments) is what an account grant protects.\n *\n * @packageDocumentation\n */\n\nimport {\n type CollectionInterceptor,\n GlobalInterceptors,\n type InterceptorContext,\n type ListOptions,\n ObjectRegistry,\n type QueryInterceptResult,\n type QueryOptions,\n type SmrtObject,\n} from '@happyvertical/smrt-core';\nimport {\n assertHydratedMailAccess,\n deniedMailAccountIds,\n getEffectiveMailAccessConfigs,\n inMailSystemAccess,\n learnMailAccessOptions,\n MailAccessError,\n runWithMailSystemAccess,\n} from './access.js';\nimport { Account } from './models/Account.js';\nimport { Attachment } from './models/Attachment.js';\nimport { EmailFolder } from './models/EmailFolder.js';\nimport { Message } from './models/Message.js';\n\ntype Kind = 'message' | 'folder' | 'attachment' | 'account';\n\nconst NAME_FALLBACK: Record<string, Kind> = {\n Message: 'message',\n Email: 'message',\n EmailFolder: 'folder',\n Attachment: 'attachment',\n Account: 'account',\n EmailAccount: 'account',\n EmailAttachment: 'attachment',\n};\n\nfunction descends(ctor: unknown, base: unknown): boolean {\n if (typeof ctor !== 'function') return false;\n return (\n ctor === base ||\n (ctor as { prototype: object }).prototype instanceof\n (base as new () => object)\n );\n}\n\nfunction kindOf(className: string, context: InterceptorContext): Kind | null {\n const registered =\n ObjectRegistry.getClass(context.qualifiedClassName ?? className) ??\n ObjectRegistry.getClass(className);\n const ctor = registered?.constructor;\n if (ctor) {\n if (descends(ctor, Message)) return 'message';\n if (descends(ctor, EmailFolder)) return 'folder';\n if (descends(ctor, Attachment)) return 'attachment';\n if (descends(ctor, Account)) return 'account';\n return null;\n }\n return NAME_FALLBACK[className] ?? null;\n}\n\n/** SQL parameter budget for one exclusion list; beyond it, fail closed. */\nconst MAX_EXCLUDED_IDS = 900;\n\nfunction restrict(\n where: ListOptions['where'],\n denied: string[],\n unaccounted: Record<string, unknown>[],\n): ListOptions['where'] {\n const groups: Record<string, unknown>[][] = Array.isArray(where)\n ? where\n : [[where ?? {}]];\n // NOT IN drops NULL accountIds, so rows with no account are added back\n // explicitly, and only the shapes that are provably not a mailbox's.\n return groups.flatMap((group) => [\n [...group, { 'accountId not in': denied }],\n ...unaccounted.map((extra) => [...group, extra]),\n ]);\n}\n\ntype Row = {\n accountId?: string | null;\n messageId?: string | null;\n options?: unknown;\n};\n\nasync function allowedInstance(\n kind: Kind,\n instance: SmrtObject,\n): Promise<boolean> {\n const row = instance as unknown as Row;\n try {\n await assertHydratedMailAccess(\n kind === 'attachment'\n ? row\n : { accountId: row.accountId, options: row.options },\n );\n return true;\n } catch (error) {\n if (error instanceof MailAccessError) return false;\n throw error;\n }\n}\n\nexport const MAIL_ACCESS_INTERCEPTOR_NAME = 'smrt-messages-account-access';\n\nexport function createMailAccessInterceptor(): CollectionInterceptor {\n return {\n name: MAIL_ACCESS_INTERCEPTOR_NAME,\n // After tenancy (100) so tenant scoping has already narrowed the read.\n priority: 50,\n\n onCollectionReady(className, collection, context) {\n // Every read path starts here, whichever collection class serves the\n // item (a default collection for an app subclass or Tweet included), so\n // the database is registered before any filtering decision.\n if (!kindOf(className, context)) return;\n learnMailAccessOptions({\n ...(collection.options as object),\n db: collection.db,\n } as never);\n },\n\n async beforeList(className, options, context) {\n if (!getEffectiveMailAccessConfigs().length || inMailSystemAccess()) {\n return options;\n }\n const kind = kindOf(className, context);\n if (!kind || kind === 'account') return options;\n const denied = await deniedMailAccountIds('read');\n if (!denied.length) return options;\n if (denied.length > MAX_EXCLUDED_IDS) {\n throw new MailAccessError('read', 'denied');\n }\n const unaccounted =\n kind === 'attachment'\n ? [\n { accountId: null, messageId: null },\n { accountId: null, messageId: '' },\n ]\n : [{ accountId: null }];\n return {\n ...options,\n where: restrict(options.where, denied, unaccounted),\n };\n },\n\n async beforeSave(instance, context) {\n const kind = kindOf(instance.constructor.name, context);\n if (kind === 'account') {\n learnMailAccessOptions((instance as unknown as Row).options as never);\n return;\n }\n if (kind !== 'attachment') return;\n const row = instance as unknown as Row;\n // Always derive the account from the message: a caller-supplied\n // accountId (for instance through a generated create) is never trusted.\n row.accountId = null;\n if (!row.messageId || !row.options) return;\n const { MessageCollection } = await import(\n './collections/MessageCollection.js'\n );\n const message = await runWithMailSystemAccess(async () =>\n (await MessageCollection.create(row.options as never)).get({\n id: row.messageId as string,\n }),\n );\n row.accountId = message?.accountId || null;\n },\n\n async afterList(className, results, context) {\n if (inMailSystemAccess()) return results;\n const kind = kindOf(className, context);\n if (!kind) return results;\n if (kind === 'account') {\n for (const item of results) {\n learnMailAccessOptions((item as unknown as Row).options as never);\n }\n return results;\n }\n // Filters hydrated rows (the only filter for legacy attachments) and\n // defends rows that reached here by another path.\n const kept: typeof results = [];\n const cache = new Map<string, boolean>();\n for (const item of results) {\n const row = item as unknown as Row;\n const key = `${kind}:${row.accountId ?? ''}:${row.messageId ?? ''}`;\n let ok = cache.get(key);\n if (ok === undefined) {\n ok = await allowedInstance(kind, item);\n cache.set(key, ok);\n }\n if (ok) kept.push(item);\n }\n return kept;\n },\n\n async afterGet(className, instance, context) {\n if (!instance || inMailSystemAccess()) return instance;\n const kind = kindOf(className, context);\n if (!kind) return instance;\n if (kind === 'account') {\n learnMailAccessOptions((instance as unknown as Row).options as never);\n return instance;\n }\n return (await allowedInstance(kind, instance)) ? instance : null;\n },\n\n async beforeQuery(\n className,\n options: QueryOptions,\n context,\n ): Promise<QueryInterceptResult> {\n const unchanged = { sql: options.sql, params: options.params };\n if (!getEffectiveMailAccessConfigs().length || inMailSystemAccess()) {\n return unchanged;\n }\n const kind = kindOf(className, context);\n if (!kind || kind === 'account') return unchanged;\n // Raw SQL cannot be narrowed to granted accounts. When any account is\n // closed to the principal, refuse rather than leak its rows.\n if ((await deniedMailAccountIds('read')).length) {\n throw new MailAccessError('read', 'denied');\n }\n return unchanged;\n },\n };\n}\n\nlet registered = false;\n\n/** Idempotent; called at package load. */\nexport function ensureMailAccessEnforcementRegistered(): void {\n if (registered) return;\n registered = true;\n GlobalInterceptors.register(createMailAccessInterceptor());\n}\n","/**\n * Mail drafts for people and agents (smrt#5141, Epic I).\n *\n * `MailDraftService.save()` creates or updates a local draft `Email` on one\n * mail account, under the host-supplied acting principal:\n *\n * - The principal needs the `draft` scope on the account (and `read` to reply\n * to a message there). Fail closed, like every mail access decision.\n * - The draft is always from the account's own address: sending as another\n * person is not possible through this service.\n * - Only an unsent draft (`isDraft`, `sendStatus` `draft`) of the same\n * account can be updated. Updating a draft that waits for approval changes\n * its content, so the waiting approval no longer applies to it.\n * - The acting principal is recorded as \"handled by\".\n *\n * `submit()` sends the draft through `Message.send()`, so the account's agent\n * send policy decides whether an agent's draft leaves or waits for a person.\n * Drafts are local rows; writing them to the mail server is a later step.\n *\n * @packageDocumentation\n */\n\nimport {\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport {\n assertMailAccess,\n MailAccessError,\n resolveMailPrincipal,\n runWithMailSystemAccess,\n withoutListBounds,\n} from './access.js';\nimport type { Email } from './models/Email.js';\nimport type { EmailAccount } from './models/EmailAccount.js';\nimport { auditMailAction, stampHandledBy } from './send-approval.js';\nimport type { MessageSendResult, SendEmailOptions } from './types.js';\n\ntype Recipient = { address: string; name?: string };\n\nexport interface MailDraftInput {\n /** The mail account the draft is sent from. */\n accountId: string;\n /** Update this draft instead of creating one. */\n draftId?: string;\n /** Create a reply to this message (new drafts only). */\n inReplyToMessageId?: string;\n /** With `inReplyToMessageId`: copy the original To and Cc. */\n replyAll?: boolean;\n subject?: string;\n textBody?: string;\n htmlBody?: string;\n toAddresses?: Recipient[];\n ccAddresses?: Recipient[];\n bccAddresses?: Recipient[];\n}\n\nexport class MailDraftError extends Error {\n readonly status: number;\n constructor(message: string, status = 400) {\n super(message);\n this.name = 'MailDraftError';\n this.status = status;\n }\n}\n\nfunction assertRecipients(value: unknown, label: string): void {\n if (value === undefined) return;\n if (\n !Array.isArray(value) ||\n value.some(\n (entry) =>\n !entry ||\n typeof entry.address !== 'string' ||\n !entry.address.includes('@') ||\n (entry.name !== undefined && typeof entry.name !== 'string'),\n )\n ) {\n throw new MailDraftError(`${label} must be a list of { address, name? }.`);\n }\n}\n\nexport class MailDraftService {\n constructor(private readonly options: SmrtClassOptions) {}\n\n private async account(accountId: string): Promise<EmailAccount> {\n const { EmailAccountCollection } = await import(\n './collections/EmailAccountCollection.js'\n );\n const account = (await runWithMailSystemAccess(async () =>\n (\n await EmailAccountCollection.create(withoutListBounds(this.options))\n ).get({ id: accountId }),\n )) as EmailAccount | null;\n if (!account?.id) {\n throw new MailDraftError('Mail account not found.', 404);\n }\n return account;\n }\n\n private async stored(id: string): Promise<Email | null> {\n const { EmailCollection } = await import(\n './collections/EmailCollection.js'\n );\n return (await runWithMailSystemAccess(async () =>\n (await EmailCollection.create(this.options as never)).get({ id }),\n )) as Email | null;\n }\n\n /** Create or update a draft. Returns the saved draft. */\n async save(input: MailDraftInput): Promise<Email> {\n assertRecipients(input.toAddresses, 'toAddresses');\n assertRecipients(input.ccAddresses, 'ccAddresses');\n assertRecipients(input.bccAddresses, 'bccAddresses');\n const account = await this.account(input.accountId);\n const principal = await resolveMailPrincipal();\n if (\n principal &&\n account.tenantId &&\n principal.tenantId !== account.tenantId\n ) {\n throw new MailAccessError('draft', 'tenant_mismatch');\n }\n await assertMailAccess(account, 'draft');\n\n let draft: Email;\n if (input.draftId) {\n const existing = await this.stored(input.draftId);\n if (!existing || existing.accountId !== account.id) {\n throw new MailDraftError('Draft not found.', 404);\n }\n if (!existing.isDraft || existing.sendStatus !== 'draft') {\n throw new MailDraftError('Only an unsent draft can be changed.', 409);\n }\n draft = existing;\n } else if (input.inReplyToMessageId) {\n await assertMailAccess(account, 'read');\n const original = await this.stored(input.inReplyToMessageId);\n if (!original || original.accountId !== account.id) {\n throw new MailDraftError('Message not found.', 404);\n }\n draft = original.createReply({ replyAll: input.replyAll === true });\n await draft.initialize();\n } else {\n const { Email: EmailClass } = await import('./models/Email.js');\n const Draft = ObjectRegistry.resolveEffectiveConstructor(EmailClass);\n draft = new Draft({\n ...(this.options as Record<string, unknown>),\n tenantId: account.tenantId,\n accountId: account.id as string,\n isDraft: true,\n sendStatus: 'draft',\n isRead: true,\n toAddresses: '[]',\n ccAddresses: '[]',\n bccAddresses: '[]',\n });\n await draft.initialize();\n }\n\n if (input.subject !== undefined) draft.subject = input.subject;\n if (input.textBody !== undefined) {\n draft.textBody = input.textBody;\n draft.body = input.textBody;\n }\n if (input.htmlBody !== undefined) draft.htmlBody = input.htmlBody;\n if (input.toAddresses !== undefined)\n draft.toAddresses = JSON.stringify(input.toAddresses);\n if (input.ccAddresses !== undefined)\n draft.ccAddresses = JSON.stringify(input.ccAddresses);\n if (input.bccAddresses !== undefined)\n draft.bccAddresses = JSON.stringify(input.bccAddresses);\n // Always from the account's own address (no sending as someone else).\n draft.fromAddress = account.email;\n draft.tenantId = account.tenantId;\n draft.accountId = account.id as string;\n draft.isDraft = true;\n draft.sendStatus = 'draft';\n draft.updatedAt = new Date();\n stampHandledBy(draft, principal);\n await draft.save();\n await auditMailAction('messages.draft.save', draft);\n return draft;\n }\n\n /**\n * Send a draft. The account's agent send policy applies: an agent's draft\n * normally comes back with `pendingApproval` and waits for a person.\n */\n async submit(\n draftId: string,\n options?: SendEmailOptions,\n ): Promise<MessageSendResult> {\n const draft = await this.stored(draftId);\n if (!draft?.accountId || !draft.isDraft) {\n throw new MailDraftError('Draft not found.', 404);\n }\n const account = await this.account(draft.accountId);\n await assertMailAccess(account, 'draft');\n return await draft.send(options);\n }\n}\n","/**\n * Mail sync as an idempotent background job (Epic I, #5130).\n *\n * The job is `EmailAccount.syncChanges()` on one account, run by the\n * `@happyvertical/smrt-jobs` TaskRunner. One account has one lane: the job is\n * deduplicated per tenant and account, so asking twice while a run is pending\n * or running returns the same job. Runs are at-least-once and safe to repeat:\n * the change-feed cursor only moves after a batch is applied.\n *\n * `@happyvertical/smrt-jobs` is a regular dependency, loaded lazily on first use. A host\n * that schedules mail sync installs it and runs a TaskRunner on the\n * {@link MAIL_SYNC_QUEUE} queue (and calls these helpers from its scheduler).\n *\n * @packageDocumentation\n */\n\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport type { MailSyncOptions } from './mail-sync.js';\nimport type { EmailAccount } from './models/EmailAccount';\n\n/** Queue the mail sync jobs run on. */\nexport const MAIL_SYNC_QUEUE = 'mail-sync';\n\n/** Providers whose server offers the change feed. */\nexport const CHANGE_FEED_PROVIDERS: readonly string[] = ['jmap'];\n\nexport interface EnqueueMailSyncOptions extends MailSyncOptions {\n /** When to run. Default: now. */\n runAt?: Date;\n /** Job priority (higher runs sooner). */\n priority?: number;\n /** Attempts before the job fails for good. Default 3. */\n maxAttempts?: number;\n /** Job timeout in milliseconds. Default 15 minutes. */\n timeout?: number;\n}\n\n/** The dedupe key that makes one account one lane. */\nexport function mailSyncDedupeKey(accountId: string): string {\n return `mail-sync:${accountId}`;\n}\n\nfunction accountClassName(): string {\n const registered =\n ObjectRegistry.getClass('EmailAccount') ??\n ObjectRegistry.getClassByQualifiedName(\n '@happyvertical/smrt-messages:EmailAccount',\n );\n return registered?.qualifiedName ?? registered?.name ?? 'EmailAccount';\n}\n\n/**\n * Queue a sync of one account. Returns the queued (or already pending/running)\n * job, or null when the account is closed to sync (inactive, needing\n * reconnection, no change feed): nothing is queued for it.\n */\nexport async function enqueueMailSync(\n account: EmailAccount,\n options: EnqueueMailSyncOptions = {},\n) {\n if (!account.id) throw new Error('enqueueMailSync needs a persisted account');\n if (!account.isActive || account.needsReconnect) return null;\n if (!CHANGE_FEED_PROVIDERS.includes(account.providerType)) return null;\n const { SmrtJobCollection } = await import('@happyvertical/smrt-jobs');\n const db = account.db as DatabaseInterface;\n const jobs = await SmrtJobCollection.create({ db });\n const args: Record<string, unknown> = {};\n if (options.limit !== undefined) args.limit = options.limit;\n if (options.maxBatches !== undefined) args.maxBatches = options.maxBatches;\n if (options.since !== undefined) {\n args.since = options.since ? new Date(options.since).toISOString() : null;\n }\n return jobs.enqueueJob({\n dedupeKey: mailSyncDedupeKey(account.id),\n tenantId: account.tenantId ?? null,\n queue: MAIL_SYNC_QUEUE,\n objectType: accountClassName(),\n objectId: account.id,\n method: 'syncChanges',\n // The runner calls the method with this object as its one argument.\n args,\n runAt: options.runAt,\n priority: options.priority,\n maxAttempts: options.maxAttempts ?? 3,\n timeout: options.timeout ?? 15 * 60 * 1000,\n });\n}\n\n/**\n * Queue a sync for every active account that is due (never synced, or last\n * synced at least its `syncIntervalMinutes` ago). Safe to call on every\n * scheduler tick: accounts that already have a job queued are not duplicated.\n */\nexport async function enqueueDueMailSyncs(\n accounts: EmailAccount[],\n options: EnqueueMailSyncOptions & { now?: Date } = {},\n): Promise<string[]> {\n const now = (options.now ?? new Date()).getTime();\n const queued: string[] = [];\n for (const account of accounts) {\n const due =\n !account.lastSyncAt ||\n now - account.lastSyncAt.getTime() >=\n (account.syncIntervalMinutes || 0) * 60_000;\n if (!due) continue;\n const job = await enqueueMailSync(account, options);\n if (job?.id) queued.push(String(job.id));\n }\n return queued;\n}\n","import type { SmrtObjectOptions } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n crossPackageRef,\n field,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\n\nexport interface CorrespondentOptions extends SmrtObjectOptions {\n tenantId?: string;\n ownerUserId?: string;\n address?: string;\n displayName?: string;\n messageCount?: number;\n sentCount?: number;\n receivedCount?: number;\n firstContactAt?: Date | null;\n lastContactAt?: Date | null;\n accountIds?: string;\n accountBreakdown?: string;\n profileId?: string | null;\n}\n\n/**\n * Someone one person writes to or hears from, derived from that person's\n * synced mail (#5132). Private to its owner: every row belongs to one\n * `ownerUserId`, is never shared across the tenant, and is read and changed\n * only through `CorrespondentService`, which filters on the acting user. The\n * generated REST/MCP/CLI surfaces are off for that reason.\n *\n * Everything but the address is optional: a correspondent has no name until\n * mail carries one, and no `profileId` until the owner links a smrt-profiles\n * `Profile` on purpose. Deriving never creates or links a `Profile`.\n * `accountIds` (JSON array) records which of the owner's readable mail\n * accounts the address was seen in, so the service can hide a correspondent\n * once the owner loses read access to every one of them.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'correspondents',\n api: false,\n mcp: false,\n cli: false,\n conflictColumns: ['tenant_id', 'owner_user_id', 'address'],\n indexes: [\n {\n name: 'correspondents_owner_last_contact_idx',\n columns: ['tenantId', 'ownerUserId', 'lastContactAt'],\n },\n ],\n})\nexport class Correspondent extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n /** The one person this row is private to (`smrt-users:User`, uuid). */\n @crossPackageRef('@happyvertical/smrt-users:User', {\n required: true,\n requiredFor: 'identity',\n })\n ownerUserId = '';\n\n /** Lower-cased email address. */\n @field({ required: true, requiredFor: 'identity' })\n address = '';\n\n /** The most recent name mail used for this address; may be empty. */\n displayName = '';\n\n /** Messages the owner can read that mention this address. */\n messageCount = 0;\n /** Of those, messages sent by this address. */\n sentCount = 0;\n /** Of those, messages sent to or copied to this address. */\n receivedCount = 0;\n\n firstContactAt: Date | null = null;\n lastContactAt: Date | null = null;\n\n /** JSON array of mail account ids the address was seen in. */\n accountIds = '[]';\n\n /**\n * JSON object keyed by mail account id with that account's own sent and\n * received counts, first/last contact, and latest name. The service builds\n * every view from the accounts the viewer can read only; the top-level\n * counts above are totals kept for storage and are never shown on their own.\n */\n accountBreakdown = '{}';\n\n /** Optional link to a smrt-profiles `Profile`, set only by the owner. */\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', { nullable: true })\n profileId: string | null = null;\n\n constructor(options: CorrespondentOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.ownerUserId !== undefined)\n this.ownerUserId = options.ownerUserId;\n if (options.address !== undefined) this.address = options.address;\n if (options.displayName !== undefined)\n this.displayName = options.displayName;\n if (options.messageCount !== undefined)\n this.messageCount = options.messageCount;\n if (options.sentCount !== undefined) this.sentCount = options.sentCount;\n if (options.receivedCount !== undefined)\n this.receivedCount = options.receivedCount;\n if (options.firstContactAt !== undefined)\n this.firstContactAt = options.firstContactAt;\n if (options.lastContactAt !== undefined)\n this.lastContactAt = options.lastContactAt;\n if (options.accountIds !== undefined) this.accountIds = options.accountIds;\n if (options.accountBreakdown !== undefined)\n this.accountBreakdown = options.accountBreakdown;\n if (options.profileId !== undefined) this.profileId = options.profileId;\n }\n\n /** Account ids this address was seen in (empty on unreadable JSON). */\n get seenInAccountIds(): string[] {\n try {\n const parsed = JSON.parse(this.accountIds || '[]');\n return Array.isArray(parsed)\n ? parsed.filter((id): id is string => typeof id === 'string')\n : [];\n } catch {\n return [];\n }\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { Correspondent } from '../models/Correspondent.js';\n\nexport class CorrespondentCollection extends SmrtCollection<Correspondent> {\n static readonly _itemClass = Correspondent;\n}\n","import type {\n SmrtObjectOptions,\n SmrtSaveOptions,\n} from '@happyvertical/smrt-core';\nimport { isDeepStrictEqual } from '../host.js';\nimport { assertNotificationRecipientIdentity } from '../notification-recipient-identity.js';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n type CollectionInterceptor,\n crossPackageRef,\n field,\n foreignKey,\n GlobalInterceptors,\n SmrtObject,\n smrt,\n usesEmbeddedRevisionFallback,\n withEmbeddedWriteQueue,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\n\n/** Channels the notification outbox can deliver through. */\nexport type NotificationDeliveryChannel = 'email';\n\nexport const NOTIFICATION_DELIVERY_CHANNELS: readonly NotificationDeliveryChannel[] =\n ['email'];\n\n/**\n * Where a delivery is in its lifecycle.\n *\n * - `pending`: waiting for `nextAttemptAt`.\n * - `sending`: leased by one dispatcher until `leaseExpiresAt`.\n * - `sent`: the provider accepted it (terminal).\n * - `failed`: rejected for good or out of attempts (terminal).\n * - `uncertain`: handed to a provider whose outcome is unknown; waits for\n * reconciliation and is never resent automatically.\n * - `cancelled`: suppressed by the host before handoff (terminal).\n */\nexport type NotificationDeliveryStatus =\n | 'pending'\n | 'sending'\n | 'sent'\n | 'failed'\n | 'uncertain'\n | 'cancelled';\n\nexport interface NotificationDeliveryOptions extends SmrtObjectOptions {\n tenantId?: string;\n recipientUserId?: string | null;\n recipientProfileId?: string | null;\n recipientKind?: 'user' | 'profile';\n channel?: NotificationDeliveryChannel;\n sourceRef?: string;\n kind?: string;\n requiredDispatchPolicy?: string;\n dispatchPolicyBinding?: string;\n subject?: string;\n textBody?: string;\n href?: string;\n recipientAddress?: string;\n recipientName?: string;\n accountId?: string;\n messageId?: string | null;\n status?: NotificationDeliveryStatus;\n stateVersion?: number;\n transitionId?: string;\n attempts?: number;\n maxAttempts?: number;\n nextAttemptAt?: Date;\n leaseToken?: string | null;\n leaseExpiresAt?: Date | null;\n handedOffAt?: Date | null;\n deliveredAt?: Date | null;\n providerMessageId?: string;\n lastError?: string;\n}\n\n/** Column values a lease transition may change (camelCase field names). */\nexport type NotificationDeliveryTransition = Partial<\n Pick<\n NotificationDelivery,\n | 'messageId'\n | 'status'\n | 'attempts'\n | 'nextAttemptAt'\n | 'leaseToken'\n | 'leaseExpiresAt'\n | 'handedOffAt'\n | 'deliveredAt'\n | 'providerMessageId'\n | 'lastError'\n >\n>;\n\nconst TRANSITION_COLUMNS: Record<keyof NotificationDeliveryTransition, string> =\n {\n messageId: 'message_id',\n status: 'status',\n attempts: 'attempts',\n nextAttemptAt: 'next_attempt_at',\n leaseToken: 'lease_token',\n leaseExpiresAt: 'lease_expires_at',\n handedOffAt: 'handed_off_at',\n deliveredAt: 'delivered_at',\n providerMessageId: 'provider_message_id',\n lastError: 'last_error',\n };\n\n// Private owning-policy snapshots reach Core's final INSERT/UPDATE predicate.\n// An unnamed interceptor is retained by reference: reloaded module instances\n// cannot replace another active save's lexical WeakMap with a fresh empty map.\nconst saveGuards = new WeakMap<SmrtObject, Record<string, unknown>>();\nconst activeSaves = new WeakSet<SmrtObject>();\nconst saveGuardInterceptor: CollectionInterceptor = {\n writeGuard: (instance) => saveGuards.get(instance),\n bulkMutation: {\n compatible: (className) =>\n className !== 'NotificationDelivery' &&\n className !== '@happyvertical/smrt-messages:NotificationDelivery',\n },\n};\n\n/**\n * One durable, source-keyed notification delivery to one person over one\n * external channel (the outbox row behind `NotificationOutboxService`).\n *\n * `sourceRef` is the idempotency key: one row per\n * `(tenant, recipient, channel, sourceRef)` (the conflict identity), and that\n * row produces at most one outbound `Message`. The recipient address is a\n * snapshot taken from the host's recipient resolver at enqueue time, never a\n * caller-chosen address.\n *\n * Every state change after creation goes through {@link transition}, a\n * compare-and-set on `stateVersion`, so concurrent dispatchers cannot both\n * hold the lease or overwrite each other's outcome. Generated REST/MCP/CLI\n * are off: rows carry recipient addresses and are reached only through the\n * service.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'notification_deliveries',\n api: false,\n mcp: false,\n cli: false,\n conflictColumns: [\n 'tenant_id',\n 'recipient_kind',\n 'recipient_user_id',\n 'recipient_profile_id',\n 'channel',\n 'source_ref',\n ],\n indexes: [\n {\n name: 'notification_deliveries_user_identity',\n columns: ['tenantId', 'recipientUserId', 'channel', 'sourceRef'],\n unique: true,\n },\n {\n name: 'notification_deliveries_profile_identity',\n columns: ['tenantId', 'recipientProfileId', 'channel', 'sourceRef'],\n unique: true,\n },\n {\n name: 'notification_deliveries_due_idx',\n columns: ['status', 'nextAttemptAt'],\n },\n {\n name: 'notification_deliveries_lease_idx',\n columns: ['status', 'leaseExpiresAt'],\n },\n ],\n})\nexport class NotificationDelivery extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n /** The person being told (`smrt-users:User`, uuid). */\n @crossPackageRef('@happyvertical/smrt-users:User', { nullable: true })\n recipientUserId: string | null = null;\n\n /** Stable external contact identity; never a fabricated auth account. */\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', { nullable: true })\n recipientProfileId: string | null = null;\n\n /**\n * Exactly one of `recipientUserId` and `recipientProfileId` is set, and this\n * says which. Neither column is required alone: the either/or rule is a\n * cross-field check (`assertNotificationRecipientIdentity`, run on every\n * save). Legacy rows remain users.\n */\n @field({ required: true, requiredFor: 'identity' })\n recipientKind: 'user' | 'profile' = 'user';\n\n /** Delivery channel; only `email` today. */\n @field({ required: true, requiredFor: 'identity' })\n channel: NotificationDeliveryChannel = 'email';\n\n /** Idempotency key for the underlying event (see class docs). */\n @field({ required: true, requiredFor: 'idempotency' })\n sourceRef = '';\n\n /** Host-defined type, e.g. `project-question.asked`. */\n @field({ required: true, requiredFor: 'identity' })\n kind = '';\n\n /** Trusted host policy required at every provider handoff; empty is legacy ordinary mail. */\n requiredDispatchPolicy = '';\n\n /** Immutable host-approved resource/version/digest binding, serialized JSON. */\n @field({ type: 'json' })\n dispatchPolicyBinding = '{}';\n\n /** Email subject line. */\n @field()\n subject = '';\n\n /** Plain-text body; the deep link is appended on its own line. */\n @field()\n textBody = '';\n\n /** Absolute deep link on the host's configured origin (no credentials). */\n @field()\n href = '';\n\n /** Address snapshot from the host recipient resolver. */\n @field({ required: true, requiredFor: 'identity' })\n recipientAddress = '';\n\n /** Display name snapshot from the host recipient resolver. */\n recipientName = '';\n\n /** Sender `EmailAccount` in the same tenant. */\n @foreignKey('Account')\n accountId = '';\n\n /** The single outbound `Message` (created under the first lease). */\n @foreignKey('Message')\n messageId: string | null = null;\n\n status: NotificationDeliveryStatus = 'pending';\n\n /** Compare-and-set counter; bumped by every transition. */\n stateVersion = 0;\n\n /** Unique id of the transition that wrote the current state. */\n transitionId = '';\n\n /** Leases acquired so far (provider handoffs are a subset). */\n attempts = 0;\n\n /** Lease budget before the delivery fails for good. */\n maxAttempts = 5;\n\n /** Earliest time a dispatcher may lease a `pending` row. */\n nextAttemptAt = new Date();\n\n /** Proof of the current lease holder; cleared when the lease ends. */\n leaseToken: string | null = null;\n\n /** When the current lease lapses and the row becomes recoverable. */\n leaseExpiresAt: Date | null = null;\n\n /** Set just before the current attempt reaches the provider. */\n handedOffAt: Date | null = null;\n\n /** When the provider accepted the message. */\n deliveredAt: Date | null = null;\n\n /** Provider message id, when the provider returns one. */\n providerMessageId = '';\n\n /** The latest failure or uncertainty reason. */\n lastError = '';\n\n constructor(options: NotificationDeliveryOptions = {}) {\n super(options);\n const assign = <K extends keyof NotificationDeliveryOptions>(key: K) => {\n if (options[key] !== undefined) {\n (this as unknown as Record<string, unknown>)[key as string] =\n options[key];\n }\n };\n for (const key of [\n 'tenantId',\n 'recipientUserId',\n 'recipientProfileId',\n 'recipientKind',\n 'channel',\n 'sourceRef',\n 'kind',\n 'requiredDispatchPolicy',\n 'dispatchPolicyBinding',\n 'subject',\n 'textBody',\n 'href',\n 'recipientAddress',\n 'recipientName',\n 'accountId',\n 'messageId',\n 'status',\n 'stateVersion',\n 'transitionId',\n 'attempts',\n 'maxAttempts',\n 'nextAttemptAt',\n 'leaseToken',\n 'leaseExpiresAt',\n 'handedOffAt',\n 'deliveredAt',\n 'providerMessageId',\n 'lastError',\n ] as const) {\n assign(key);\n }\n }\n\n /** Protected consent and document bindings cannot be downgraded by ordinary saves. */\n override async save(options?: SmrtSaveOptions): Promise<this> {\n if (activeSaves.has(this))\n throw new Error(\n 'Concurrent saves of one notification delivery are not supported.',\n );\n activeSaves.add(this);\n try {\n return await this.saveWithGuard(options);\n } finally {\n saveGuards.delete(this);\n activeSaves.delete(this);\n }\n }\n\n private async saveWithGuard(options?: SmrtSaveOptions): Promise<this> {\n assertNotificationRecipientIdentity(this);\n\n if (\n this.kind.startsWith('protected:') &&\n (!this.requiredDispatchPolicy ||\n this.kind !== `protected:${this.requiredDispatchPolicy}`)\n ) {\n throw new Error(\n 'Protected notification kinds require their exact dispatch policy.',\n );\n }\n // Use Core's existing missing-schema contract before any protection query.\n // Initialization defers table verification and must not load over patches.\n await this.verifyStorageReady();\n let stored: Record<string, unknown> | undefined;\n if (this.id) {\n const { rows } = await this.db.query(\n 'SELECT tenant_id, required_dispatch_policy, dispatch_policy_binding, source_ref, recipient_user_id, recipient_profile_id, recipient_kind, recipient_address, account_id, kind, subject, text_body, href, recipient_name, channel, status, state_version, transition_id, attempts, max_attempts, next_attempt_at, lease_token, lease_expires_at, handed_off_at, delivered_at, provider_message_id, last_error, message_id FROM notification_deliveries WHERE id = ?',\n this.id,\n );\n stored = rows[0] as Record<string, unknown> | undefined;\n }\n if (!stored) {\n // A new-ID clone can still upsert the same natural identity. Authorize against that row too.\n const existing = await this.db.query(\n 'SELECT * FROM notification_deliveries WHERE tenant_id=? AND recipient_kind=? AND recipient_user_id IS NOT DISTINCT FROM ? AND recipient_profile_id IS NOT DISTINCT FROM ? AND channel=? AND source_ref=?',\n this.tenantId,\n this.recipientKind,\n this.recipientUserId,\n this.recipientProfileId,\n this.channel,\n this.sourceRef,\n );\n stored = existing.rows[0] as Record<string, unknown> | undefined;\n }\n if (\n stored &&\n (stored.required_dispatch_policy || this.requiredDispatchPolicy)\n ) {\n const binding = (value: unknown) =>\n typeof value === 'string' ? JSON.parse(value) : value;\n const instant = (value: unknown) =>\n value == null ? null : new Date(value as string | Date).getTime();\n if (\n stored.status !== this.status ||\n Number(stored.state_version) !== this.stateVersion ||\n stored.transition_id !== this.transitionId ||\n Number(stored.attempts) !== this.attempts ||\n Number(stored.max_attempts) !== this.maxAttempts ||\n stored.lease_token !== this.leaseToken ||\n stored.message_id !== this.messageId ||\n stored.provider_message_id !== this.providerMessageId ||\n stored.last_error !== this.lastError ||\n instant(stored.next_attempt_at) !== instant(this.nextAttemptAt) ||\n instant(stored.lease_expires_at) !== instant(this.leaseExpiresAt) ||\n instant(stored.handed_off_at) !== instant(this.handedOffAt) ||\n instant(stored.delivered_at) !== instant(this.deliveredAt)\n ) {\n throw new Error(\n 'Protected notification lifecycle changes require a guarded transition.',\n );\n }\n\n if (\n stored.tenant_id !== this.tenantId ||\n stored.required_dispatch_policy !== this.requiredDispatchPolicy ||\n !isDeepStrictEqual(\n binding(stored.dispatch_policy_binding),\n binding(this.dispatchPolicyBinding),\n ) ||\n stored.source_ref !== this.sourceRef ||\n stored.recipient_user_id !== this.recipientUserId ||\n stored.recipient_profile_id !== this.recipientProfileId ||\n stored.recipient_kind !== this.recipientKind ||\n stored.recipient_address !== this.recipientAddress ||\n stored.account_id !== this.accountId ||\n stored.channel !== this.channel ||\n stored.recipient_name !== this.recipientName ||\n stored.kind !== this.kind ||\n stored.subject !== this.subject ||\n stored.text_body !== this.textBody ||\n stored.href !== this.href\n ) {\n throw new Error(\n 'Protected notification consent and dispatch policy are immutable.',\n );\n }\n }\n const guard =\n stored?.required_dispatch_policy || this.requiredDispatchPolicy\n ? Object.fromEntries(\n [\n 'tenant_id',\n 'required_dispatch_policy',\n 'dispatch_policy_binding',\n 'source_ref',\n 'recipient_user_id',\n 'recipient_profile_id',\n 'recipient_kind',\n 'recipient_address',\n 'recipient_name',\n 'account_id',\n 'kind',\n 'channel',\n 'subject',\n 'text_body',\n 'href',\n 'status',\n 'state_version',\n 'transition_id',\n 'attempts',\n 'max_attempts',\n 'lease_token',\n 'message_id',\n 'provider_message_id',\n 'last_error',\n ].map((column) => [\n column,\n stored\n ? stored[column]\n : (this as unknown as Record<string, unknown>)[\n column.replace(/_([a-z])/g, (_, letter: string) =>\n letter.toUpperCase(),\n )\n ],\n ]),\n )\n : {\n // Bind the observed legacy NULL exactly; a new ordinary row uses ''.\n required_dispatch_policy: stored\n ? stored.required_dispatch_policy\n : '',\n kind: stored ? stored.kind : this.kind,\n };\n if (!stored && this.requiredDispatchPolicy) this.requireInsertOnSave();\n saveGuards.set(this, guard);\n if (!GlobalInterceptors.getAll().includes(saveGuardInterceptor))\n GlobalInterceptors.register(saveGuardInterceptor);\n // Core preserves supplied options/revision guards and applies this mandatory\n // predicate at the final write. State/version covers lifecycle dates without\n // comparing lossy hydrated PostgreSQL timestamps.\n return super.save(options);\n }\n\n /** Protected history must survive mutable caller flags and uncertain outcomes. */\n override async delete(): Promise<void> {\n const stored = this.id\n ? await this.db.get(this.tableName, { id: this.id })\n : null;\n if (\n stored?.required_dispatch_policy ||\n String(stored?.kind ?? '').startsWith('protected:')\n )\n throw new Error(\n 'Protected notification delivery history cannot be deleted.',\n );\n return super.delete();\n }\n\n /** Whether no further automatic work will happen on this row. */\n get isSettled(): boolean {\n return (\n this.status === 'sent' ||\n this.status === 'failed' ||\n this.status === 'cancelled' ||\n this.status === 'uncertain'\n );\n }\n\n /**\n * Apply `changes` only if the stored row is still at `stateVersion` (and,\n * when `leaseToken` is given, still held by that lease). Returns whether\n * this caller won; on success the instance reflects the stored row.\n *\n * PostgreSQL and remote LibSQL evaluate the guard in one conditional\n * UPDATE; local embedded engines use the process write queue, matching\n * `Message.send()`'s claim. The durable row is re-read either way, and the\n * write is recognised by its unique `transitionId`, because DuckDB's update\n * result over-reports affected rows.\n */\n async transition(\n changes: NotificationDeliveryTransition,\n expected: { leaseToken?: string } = {},\n ): Promise<boolean> {\n if (!this.id) throw new Error('Cannot transition an unsaved delivery.');\n const fromVersion = this.stateVersion;\n const nextVersion = fromVersion + 1;\n const transitionId = crypto.randomUUID();\n const values: Record<string, unknown> = {\n state_version: nextVersion,\n transition_id: transitionId,\n updated_at: new Date(),\n };\n for (const [key, value] of Object.entries(changes)) {\n const column =\n TRANSITION_COLUMNS[key as keyof NotificationDeliveryTransition];\n if (!column) throw new Error(`'${key}' is not a transition field.`);\n values[column] = value;\n }\n\n const matches = (row: Record<string, unknown> | null) =>\n row !== null &&\n Number(row.state_version) === fromVersion &&\n (expected.leaseToken === undefined ||\n row.lease_token === expected.leaseToken);\n\n const useEmbeddedFallback = usesEmbeddedRevisionFallback(this.db);\n await withEmbeddedWriteQueue(this.db, useEmbeddedFallback, async () => {\n if (useEmbeddedFallback) {\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n if (!matches(current)) return;\n await this.db.upsert(this.tableName, ['id'], {\n ...current,\n ...values,\n });\n return;\n }\n await this.db.update(\n this.tableName,\n {\n id: this.id,\n tenant_id: this.tenantId,\n state_version: fromVersion,\n ...(expected.leaseToken === undefined\n ? {}\n : { lease_token: expected.leaseToken }),\n },\n values,\n );\n });\n\n const verified = await this.getCanonicalPersistedRow({ id: this.id });\n // The transition id, not the version, proves this caller's write won:\n // a losing caller would see the winner's identical next version.\n if (!verified || verified.transition_id !== transitionId) return false;\n await this.completePersistedUpdate(verified);\n return true;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { NotificationDelivery } from '../models/NotificationDelivery.js';\n\nexport class NotificationDeliveryCollection extends SmrtCollection<NotificationDelivery> {\n static readonly _itemClass = NotificationDelivery;\n}\n","import type { SmrtObjectOptions } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n crossPackageRef,\n field,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport type { NotificationDeliveryChannel } from './NotificationDelivery.js';\n\n/** `*` (everything in the tenant) or a host key such as `project:<uuid>`. */\nexport const NOTIFICATION_OPT_OUT_SCOPE_PATTERN =\n /^(?:\\*|[a-z][a-z0-9-]*:[A-Za-z0-9._:-]{1,200})$/;\n\n/** The scope that matches every notification of the channel in the tenant. */\nexport const NOTIFICATION_OPT_OUT_ALL_SCOPE = '*';\n\nexport function isValidNotificationOptOutScope(\n scope: unknown,\n): scope is string {\n return (\n typeof scope === 'string' && NOTIFICATION_OPT_OUT_SCOPE_PATTERN.test(scope)\n );\n}\n\nexport interface NotificationOptOutOptions extends SmrtObjectOptions {\n tenantId?: string;\n recipientUserId?: string;\n channel?: NotificationDeliveryChannel;\n scope?: string;\n optedOutAt?: Date | null;\n updatedBy?: string;\n}\n\n/**\n * One person's opt-out of one notification channel for one scope, in one\n * tenant: the preference store behind the outbox's `isSuppressed` hook.\n *\n * Identity is `(tenant, recipient, channel, scope)` (the conflict identity).\n * `optedOutAt` is set while the person is opted out and cleared by an opt-in,\n * so the row keeps its history. `scope` is a host-defined key validated by\n * {@link NOTIFICATION_OPT_OUT_SCOPE_PATTERN}. Read and change rows through\n * `NotificationOptOutService`; the generated REST/MCP/CLI are off because the\n * service is the authorization boundary.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'notification_opt_outs',\n api: false,\n mcp: false,\n cli: false,\n conflictColumns: ['tenant_id', 'recipient_user_id', 'channel', 'scope'],\n})\nexport class NotificationOptOut extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n /** The person who opted out (`smrt-users:User`, uuid). */\n @crossPackageRef('@happyvertical/smrt-users:User', {\n required: true,\n requiredFor: 'identity',\n })\n recipientUserId = '';\n\n /** Channel opted out of; only `email` today. */\n @field({ required: true })\n channel: NotificationDeliveryChannel = 'email';\n\n /** `*` or a host key such as `project:<uuid>`. */\n @field({ required: true, requiredFor: 'identity' })\n scope = '';\n\n /** When the opt-out took effect; null once the person opted back in. */\n optedOutAt: Date | null = null;\n\n /** Who last changed the row: the person's user id, or `system` for host code. */\n updatedBy = '';\n\n constructor(options: NotificationOptOutOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.recipientUserId !== undefined)\n this.recipientUserId = options.recipientUserId;\n if (options.channel !== undefined) this.channel = options.channel;\n if (options.scope !== undefined) this.scope = options.scope;\n if (options.optedOutAt !== undefined) this.optedOutAt = options.optedOutAt;\n if (options.updatedBy !== undefined) this.updatedBy = options.updatedBy;\n }\n\n get isOptedOut(): boolean {\n return this.optedOutAt !== null;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { NotificationOptOut } from '../models/NotificationOptOut.js';\n\nexport class NotificationOptOutCollection extends SmrtCollection<NotificationOptOut> {\n static readonly _itemClass = NotificationOptOut;\n}\n","import {\n crossPackageRef,\n field,\n foreignKey,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport type { PersonaMessageRouteOptions } from '../types.js';\n\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'persona_message_routes',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n conflictColumns: [\n 'tenant_id',\n 'persona_id',\n 'account_id',\n 'endpoint_id',\n 'purpose',\n ],\n})\nexport class PersonaMessageRoute extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n @crossPackageRef('@happyvertical/smrt-personas:AgentPersona', {\n required: true,\n requiredFor: 'identity',\n })\n personaId = '';\n\n @foreignKey('Account', { required: true, requiredFor: 'identity' })\n accountId = '';\n\n @foreignKey('MessagingEndpoint', { required: true, requiredFor: 'identity' })\n endpointId = '';\n\n @field({ required: true })\n purpose = 'default';\n\n priority = 0;\n enabled = true;\n createdAt = new Date();\n updatedAt = new Date();\n\n constructor(options: PersonaMessageRouteOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.personaId !== undefined) this.personaId = options.personaId;\n if (options.accountId !== undefined) this.accountId = options.accountId;\n if (options.endpointId !== undefined) this.endpointId = options.endpointId;\n if (options.purpose !== undefined) this.purpose = options.purpose;\n if (options.priority !== undefined) this.priority = options.priority;\n if (options.enabled !== undefined) this.enabled = options.enabled;\n if (options.createdAt !== undefined) this.createdAt = options.createdAt;\n if (options.updatedAt !== undefined) this.updatedAt = options.updatedAt;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { PersonaMessageRoute } from '../models/PersonaMessageRoute.js';\n\nexport class PersonaMessageRouteCollection extends SmrtCollection<PersonaMessageRoute> {\n static readonly _itemClass = PersonaMessageRoute;\n\n async forPersona(personaId: string): Promise<PersonaMessageRoute[]> {\n return this.list({ where: { personaId, enabled: true } });\n }\n}\n","import type { SmrtObjectOptions } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n crossPackageRef,\n field,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\n\n/** How much a notification matters to its recipient. */\nexport type UserNotificationSeverity = 'info' | 'success' | 'warning' | 'error';\n\nexport const USER_NOTIFICATION_SEVERITIES: readonly UserNotificationSeverity[] =\n ['info', 'success', 'warning', 'error'];\n\nexport interface UserNotificationOptions extends SmrtObjectOptions {\n tenantId?: string;\n recipientUserId?: string;\n kind?: string;\n title?: string;\n body?: string;\n href?: string | null;\n severity?: UserNotificationSeverity;\n sourceRef?: string;\n occurredAt?: Date;\n readAt?: Date | null;\n dismissedAt?: Date | null;\n}\n\n/**\n * One in-app notification for one person, with its own read state.\n *\n * The in-app channel of smrt-messages: where `Message` is delivered through\n * an external provider, a `UserNotification` is stored for a user and shown\n * by the host (a bell, a notifications page). Create, list, and change read\n * state through `UserNotificationService`, which checks the recipient on\n * every write; the generated REST/MCP/CLI surfaces are off because a plain\n * tenant-scoped list would show every member's notifications.\n *\n * `sourceRef` is the dedupe key: one row per `(tenant, recipient, sourceRef)`\n * (the conflict identity), so re-deriving the same event (a failed social\n * post, a failed render) never notifies twice. The service generates a unique\n * ref when the caller has none.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'user_notifications',\n api: false,\n mcp: false,\n cli: false,\n conflictColumns: ['tenant_id', 'recipient_user_id', 'source_ref'],\n // The bell reads a recipient's newest rows in one tenant.\n indexes: [\n {\n name: 'user_notifications_recipient_occurred_idx',\n columns: ['tenantId', 'recipientUserId', 'occurredAt'],\n },\n ],\n})\nexport class UserNotification extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n /** The person this notification is for (`smrt-users:User`, uuid). */\n @crossPackageRef('@happyvertical/smrt-users:User', {\n required: true,\n requiredFor: 'identity',\n })\n recipientUserId = '';\n\n /** Host-defined type, e.g. `social-post.failed` (used for icons/filters). */\n @field()\n kind = '';\n\n /** One short plain sentence. */\n @field()\n title = '';\n\n /** Optional detail line. */\n body = '';\n\n /** Where the notification leads (host-relative path or URL). */\n href: string | null = null;\n\n severity: UserNotificationSeverity = 'info';\n\n /** Dedupe key, unique per tenant and recipient (see class docs). */\n @field({ required: true, requiredFor: 'idempotency' })\n sourceRef = '';\n\n /** When the underlying event happened (sort key). */\n occurredAt = new Date();\n\n /** Set when the recipient has seen it. */\n readAt: Date | null = null;\n\n /** Set when the recipient has cleared it; dismissed rows are hidden. */\n dismissedAt: Date | null = null;\n\n constructor(options: UserNotificationOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.recipientUserId !== undefined)\n this.recipientUserId = options.recipientUserId;\n if (options.kind !== undefined) this.kind = options.kind;\n if (options.title !== undefined) this.title = options.title;\n if (options.body !== undefined) this.body = options.body;\n if (options.href !== undefined) this.href = options.href;\n if (options.severity !== undefined) this.severity = options.severity;\n if (options.sourceRef !== undefined) this.sourceRef = options.sourceRef;\n if (options.occurredAt !== undefined) this.occurredAt = options.occurredAt;\n if (options.readAt !== undefined) this.readAt = options.readAt;\n if (options.dismissedAt !== undefined)\n this.dismissedAt = options.dismissedAt;\n }\n\n get isRead(): boolean {\n return this.readAt !== null;\n }\n\n get isDismissed(): boolean {\n return this.dismissedAt !== null;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { UserNotification } from '../models/UserNotification.js';\n\nexport class UserNotificationCollection extends SmrtCollection<UserNotification> {\n static readonly _itemClass = UserNotification;\n}\n","/**\n * EmailAttachment - Backward-compatible alias for Attachment\n *\n * @deprecated Use Attachment instead. EmailAttachment is preserved for backward compatibility.\n */\n\nimport type { EmailAttachmentOptions } from '../types';\nimport { Attachment } from './Attachment';\n\n/**\n * @deprecated Use Attachment instead\n */\nexport class EmailAttachment extends Attachment {\n /**\n * Legacy emailId field — maps to messageId\n */\n get emailId(): string {\n return this.messageId;\n }\n\n set emailId(value: string) {\n this.messageId = value;\n }\n\n constructor(options: EmailAttachmentOptions = {}) {\n // Map emailId to messageId for backward compat\n const mappedOptions = {\n ...options,\n messageId: options.emailId || options.messageId || '',\n };\n super(mappedOptions);\n }\n\n /**\n * Get the email this attachment belongs to\n * @deprecated Use getMessage() instead\n */\n async getEmail() {\n if (!this.messageId) return null;\n\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n return await collection.get({ id: this.messageId });\n }\n}\n","/**\n * EmailAttachmentCollection - Backward-compatible collection for EmailAttachment\n *\n * @deprecated Use AttachmentCollection instead\n */\n\nimport { queryGlobal, queryWithGlobals } from '../host.js';\nimport { EmailAttachment } from '../models/EmailAttachment';\nimport { AttachmentCollection } from './AttachmentCollection';\n\n/**\n * @deprecated Use AttachmentCollection instead\n */\nexport class EmailAttachmentCollection extends AttachmentCollection {\n static override readonly _itemClass = EmailAttachment;\n\n /**\n * Get attachments for an email\n * @deprecated Use getByMessage() instead\n */\n async getByEmail(emailId: string): Promise<EmailAttachment[]> {\n return (await this.getByMessage(emailId)) as EmailAttachment[];\n }\n\n /**\n * Get image attachments\n */\n override async getImages(emailId?: string): Promise<EmailAttachment[]> {\n return (await super.getImages(emailId)) as EmailAttachment[];\n }\n\n /**\n * Get PDF attachments\n */\n override async getPdfs(emailId?: string): Promise<EmailAttachment[]> {\n return (await super.getPdfs(emailId)) as EmailAttachment[];\n }\n\n /**\n * Get inline attachments\n */\n override async getInline(emailId: string): Promise<EmailAttachment[]> {\n return (await super.getInline(emailId)) as EmailAttachment[];\n }\n\n /**\n * Get regular attachments\n */\n override async getRegular(emailId: string): Promise<EmailAttachment[]> {\n return (await super.getRegular(emailId)) as EmailAttachment[];\n }\n\n /**\n * Delete all attachments for an email\n * @deprecated Use deleteByMessage() instead\n */\n async deleteByEmail(emailId: string): Promise<number> {\n return await this.deleteByMessage(emailId);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n override async findByTenant(tenantId: string): Promise<EmailAttachment[]> {\n return this.list({ where: { tenantId } }) as Promise<EmailAttachment[]>;\n }\n\n // EmailAttachment is a CTI subclass of the @TenantScoped Attachment (own\n // `email_attachments` table, no `_meta_type`) and inherits its recognition\n // (#1596); route global / cross-global lookups through the raw helpers.\n override async findGlobal(): Promise<EmailAttachment[]> {\n return queryGlobal<EmailAttachment>(this);\n }\n\n override async findWithGlobals(tenantId: string): Promise<EmailAttachment[]> {\n return queryWithGlobals<EmailAttachment>(\n this,\n tenantId,\n 'EmailAttachment.findWithGlobals',\n );\n }\n}\n","import { SmrtObject, smrt } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport type { BlacklistOptions } from '../types';\n\n/**\n * Blacklist - Block entries for email filtering\n *\n * Supports three pattern types:\n * - email: Exact email address (spam@example.com)\n * - domain: Entire domain (*@spam.com)\n * - regex: Custom regex pattern\n */\n@smrt({\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n cli: { skipApiCheck: true },\n tenantScoped: true,\n})\nexport class Blacklist extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n pattern: string = '';\n type: 'email' | 'domain' | 'regex' = 'email';\n reason: string = '';\n autoArchive: boolean = true;\n\n constructor(options: BlacklistOptions = {}) {\n super(options);\n\n if (options.pattern !== undefined) {\n this.pattern = options.pattern;\n }\n if (options.type !== undefined) {\n this.type = options.type;\n }\n }\n\n /**\n * Check if an email address matches this blacklist entry\n */\n matches(email: string): boolean {\n const normalizedEmail = email.toLowerCase().trim();\n\n switch (this.type) {\n case 'email':\n return normalizedEmail === this.pattern.toLowerCase().trim();\n\n case 'domain': {\n const domain = normalizedEmail.split('@')[1];\n return domain === this.pattern.toLowerCase().trim();\n }\n\n case 'regex': {\n const pattern = this.pattern.trim();\n if (!pattern) {\n return false;\n }\n try {\n const regex = new RegExp(pattern, 'i');\n return regex.test(normalizedEmail);\n } catch {\n return false;\n }\n }\n\n default:\n return false;\n }\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { Blacklist } from '../models/Blacklist.js';\n\nexport class BlacklistCollection extends SmrtCollection<Blacklist> {\n static readonly _itemClass = Blacklist;\n\n /**\n * Check if an email is blacklisted\n */\n async isBlacklisted(email: string): Promise<boolean> {\n const entries = await this.list({});\n\n for (const entry of entries) {\n if (entry.matches(email)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Get the matching blacklist entry for an email\n */\n async getMatchingEntry(email: string): Promise<Blacklist | null> {\n const entries = await this.list({});\n\n for (const entry of entries) {\n if (entry.matches(email)) {\n return entry;\n }\n }\n\n return null;\n }\n}\n","import { SmrtObject, smrt } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport type { WhitelistOptions } from '../types';\n\n/**\n * Whitelist - Allow-only entries for email filtering\n *\n * Supports three pattern types:\n * - email: Exact email address (user@example.com)\n * - domain: Entire domain (*@example.com)\n * - regex: Custom regex pattern\n */\n@smrt({\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n cli: { skipApiCheck: true },\n tenantScoped: true,\n})\nexport class Whitelist extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n pattern: string = '';\n type: 'email' | 'domain' | 'regex' = 'email';\n category: string | null = null;\n description: string = '';\n\n constructor(options: WhitelistOptions = {}) {\n super(options);\n\n if (options.pattern !== undefined) {\n this.pattern = options.pattern;\n }\n if (options.type !== undefined) {\n this.type = options.type;\n }\n }\n\n /**\n * Check if an email address matches this whitelist entry\n */\n matches(email: string): boolean {\n const normalizedEmail = email.toLowerCase().trim();\n\n switch (this.type) {\n case 'email':\n return normalizedEmail === this.pattern.toLowerCase().trim();\n\n case 'domain': {\n const domain = normalizedEmail.split('@')[1];\n return domain === this.pattern.toLowerCase().trim();\n }\n\n case 'regex': {\n const pattern = this.pattern.trim();\n if (!pattern) {\n return false;\n }\n try {\n const regex = new RegExp(pattern, 'i');\n return regex.test(normalizedEmail);\n } catch {\n return false;\n }\n }\n\n default:\n return false;\n }\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { Whitelist } from '../models/Whitelist.js';\n\nexport class WhitelistCollection extends SmrtCollection<Whitelist> {\n static readonly _itemClass = Whitelist;\n\n /**\n * Check if an email is whitelisted for a specific category\n */\n async isWhitelisted(email: string, category?: string): Promise<boolean> {\n const entries = await this.list({});\n\n for (const entry of entries) {\n if (!entry.matches(email)) {\n continue;\n }\n\n if (!category) {\n return true;\n }\n\n if (entry.category === category || entry.category === null) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Get the matching whitelist entry for an email\n */\n async getMatchingEntry(email: string): Promise<Whitelist | null> {\n const entries = await this.list({});\n\n for (const entry of entries) {\n if (entry.matches(email)) {\n return entry;\n }\n }\n\n return null;\n }\n\n /**\n * Get whitelist entries by category\n */\n async getByCategory(category: string): Promise<Whitelist[]> {\n return await this.list({\n where: { category },\n });\n }\n}\n","/**\n * SlackAccount model - Slack workspace account extending the Account STI base\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { field, smrt } from '@happyvertical/smrt-core';\nimport type { MessageSenderInterface, SlackAccountOptions } from '../types';\nimport { Account } from './Account';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n})\nexport class SlackAccount extends Account { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @field({ description: 'The identifier of the connected workspace.' })\n workspaceId = '';\n @field({ description: 'The name of the connected workspace.' })\n workspaceName = '';\n @field({\n description: 'The bot user your application posts as in this workspace.',\n })\n botUserId = '';\n\n constructor(options: SlackAccountOptions = {}) {\n super(options);\n\n if (options.workspaceId !== undefined)\n this.workspaceId = options.workspaceId;\n if (options.workspaceName !== undefined)\n this.workspaceName = options.workspaceName;\n if (options.botUserId !== undefined) this.botUserId = options.botUserId;\n\n // Default provider type\n if (!this.providerType) this.providerType = 'slack';\n this.channelType = 'slack';\n }\n\n /**\n * Create a sender for this Slack account\n */\n override async createSender(): Promise<MessageSenderInterface> {\n const { SlackSender } = await import('../senders/SlackSender');\n return new SlackSender(this);\n }\n}\n","/**\n * SlackMessage model - Slack message extending the Message STI base\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { field, smrt } from '@happyvertical/smrt-core';\nimport type { SlackMessageOptions } from '../types';\nimport { Message } from './Message';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get', 'create'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n // Message is read-only over REST; this provider type is writable there.\n widenParentExposure: { api: ['create'] },\n})\nexport class SlackMessage extends Message { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @field({ description: 'The identifier of the channel this message is in.' })\n channelId = '';\n @field({ description: 'The name of the channel this message was posted in.' })\n channelName = '';\n @field({ description: \"The workspace's own reference for this message.\" })\n slackTs = ''; // Slack message timestamp (unique ID)\n @field({\n description:\n \"The workspace's own reference for the thread this message belongs to.\",\n })\n slackThreadTs = ''; // Thread parent timestamp\n @field({ description: 'The reactions people added to this message.' })\n reactions = ''; // JSON array of {name, count, users[]}\n @field({ description: 'Whether this message was edited after posting.' })\n isEdited = false;\n @field({\n description: 'The kind of message, such as one from a person or a bot.',\n })\n messageType = ''; // 'message', 'bot_message', etc.\n @field({\n description: 'The rich layout of the message as the workspace stores it.',\n })\n blocks = ''; // JSON - Slack Block Kit blocks\n\n constructor(options: SlackMessageOptions = {}) {\n super(options);\n\n if (options.channelId !== undefined) this.channelId = options.channelId;\n if (options.channelName !== undefined)\n this.channelName = options.channelName;\n if (options.slackTs !== undefined) this.slackTs = options.slackTs;\n if (options.slackThreadTs !== undefined)\n this.slackThreadTs = options.slackThreadTs;\n if (options.reactions !== undefined) this.reactions = options.reactions;\n if (options.isEdited !== undefined) this.isEdited = options.isEdited;\n if (options.messageType !== undefined)\n this.messageType = options.messageType;\n if (options.blocks !== undefined) this.blocks = options.blocks;\n }\n\n /**\n * Reply in the same channel and thread. `channelId` is routing identity\n * (SlackSender posts to it), so it is restored after the base draft reset;\n * a reply to a top-level message starts that message's thread.\n */\n override createReply(options?: { replyAll?: boolean }): SlackMessage {\n const reply = super.createReply(options) as SlackMessage;\n reply.channelId = this.channelId;\n reply.channelName = this.channelName;\n reply.slackThreadTs = this.slackThreadTs || this.slackTs;\n return reply;\n }\n\n /** Forward into the same channel, outside the original's thread. */\n override createForward(): SlackMessage {\n const forward = super.createForward() as SlackMessage;\n forward.channelId = this.channelId;\n forward.channelName = this.channelName;\n return forward;\n }\n\n /**\n * Get reactions as parsed array\n */\n getReactions(): Array<{ name: string; count: number; users?: string[] }> {\n if (!this.reactions) return [];\n try {\n return JSON.parse(this.reactions);\n } catch {\n return [];\n }\n }\n\n /**\n * Get blocks as parsed array\n */\n getBlocks(): Record<string, unknown>[] {\n if (!this.blocks) return [];\n try {\n return JSON.parse(this.blocks);\n } catch {\n return [];\n }\n }\n\n /**\n * Check if message is in a thread\n */\n isInThread(): boolean {\n return !!this.slackThreadTs && this.slackThreadTs !== this.slackTs;\n }\n\n /**\n * Get total reaction count\n */\n getTotalReactions(): number {\n return this.getReactions().reduce((sum, r) => sum + r.count, 0);\n }\n}\n","import { smrt } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport type { AccountOptions } from '../types.js';\nimport { Account } from './Account.js';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n})\nexport class TelegramAccount extends Account { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n constructor(options: AccountOptions = {}) {\n super(options);\n this.providerType = 'telegram';\n this.channelType = 'telegram';\n }\n}\n","/**\n * Tweet model - Twitter/X message extending the Message STI base\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { smrt } from '@happyvertical/smrt-core';\nimport type { TweetOptions } from '../types';\nimport { Message } from './Message';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get', 'create'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n // Message is read-only over REST; this provider type is writable there.\n widenParentExposure: { api: ['create'] },\n})\nexport class Tweet extends Message { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n tweetId = '';\n retweetCount = 0;\n likeCount = 0;\n replyCount = 0;\n isRetweet = false;\n isReply = false;\n mediaUrls = ''; // JSON array\n hashtags = ''; // JSON array\n mentions = ''; // JSON array\n\n constructor(options: TweetOptions = {}) {\n super(options);\n\n if (options.tweetId !== undefined) this.tweetId = options.tweetId;\n if (options.retweetCount !== undefined)\n this.retweetCount = options.retweetCount;\n if (options.likeCount !== undefined) this.likeCount = options.likeCount;\n if (options.replyCount !== undefined) this.replyCount = options.replyCount;\n if (options.isRetweet !== undefined) this.isRetweet = options.isRetweet;\n if (options.isReply !== undefined) this.isReply = options.isReply;\n if (options.mediaUrls !== undefined) this.mediaUrls = options.mediaUrls;\n if (options.hashtags !== undefined) this.hashtags = options.hashtags;\n if (options.mentions !== undefined) this.mentions = options.mentions;\n }\n\n /**\n * Get media URLs as parsed array\n */\n getMediaUrls(): string[] {\n if (!this.mediaUrls) return [];\n try {\n return JSON.parse(this.mediaUrls);\n } catch {\n return [];\n }\n }\n\n /**\n * Get hashtags as parsed array\n */\n getHashtags(): string[] {\n if (!this.hashtags) return [];\n try {\n return JSON.parse(this.hashtags);\n } catch {\n return [];\n }\n }\n\n /**\n * Get mentions as parsed array\n */\n getMentions(): string[] {\n if (!this.mentions) return [];\n try {\n return JSON.parse(this.mentions);\n } catch {\n return [];\n }\n }\n\n /**\n * Get total engagement count\n */\n getEngagement(): number {\n return this.retweetCount + this.likeCount + this.replyCount;\n }\n}\n","/**\n * TwitterAccount model - Twitter/X account extending the Account STI base\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { smrt } from '@happyvertical/smrt-core';\nimport type { MessageSenderInterface, TwitterAccountOptions } from '../types';\nimport { Account } from './Account';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n})\nexport class TwitterAccount extends Account { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n handle = '';\n twitterUserId = '';\n\n constructor(options: TwitterAccountOptions = {}) {\n super(options);\n\n if (options.handle !== undefined) this.handle = options.handle;\n if (options.twitterUserId !== undefined)\n this.twitterUserId = options.twitterUserId;\n\n // Default provider type\n if (!this.providerType) this.providerType = 'twitter';\n this.channelType = 'twitter';\n }\n\n /**\n * Create a sender for this Twitter account\n */\n override async createSender(): Promise<MessageSenderInterface> {\n const { TweetSender } = await import('../senders/TweetSender');\n return new TweetSender(this);\n }\n}\n","import { smrt } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport type { AccountOptions } from '../types.js';\nimport { Account } from './Account.js';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n})\nexport class ZulipAccount extends Account { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n constructor(options: AccountOptions = {}) {\n super(options);\n this.providerType = 'zulip';\n this.channelType = 'zulip';\n }\n}\n","import {\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport {\n decideMailAccess,\n getMailAccessConfig,\n MAIL_ACCOUNT_RESOURCE_TYPE,\n MAIL_SCOPES,\n type MailPrincipal,\n type MailScope,\n runWithMailSystemAccess,\n withoutListBounds,\n} from '../access.js';\nimport { AccountCollection } from '../collections/AccountCollection.js';\nimport { AttachmentCollection } from '../collections/AttachmentCollection.js';\nimport { EmailFolderCollection } from '../collections/EmailFolderCollection.js';\nimport { MessageCollection } from '../collections/MessageCollection.js';\nimport { MessagingEndpointCollection } from '../collections/MessagingEndpointCollection.js';\nimport { PersonaMessageRouteCollection } from '../collections/PersonaMessageRouteCollection.js';\nimport { withTenant } from '../host.js';\nimport { Account } from '../models/Account.js';\nimport { EmailAccount } from '../models/EmailAccount.js';\nimport { MessagingEndpoint } from '../models/MessagingEndpoint.js';\nimport { PersonaMessageRoute } from '../models/PersonaMessageRoute.js';\nimport { TelegramAccount } from '../models/TelegramAccount.js';\nimport { ZulipAccount } from '../models/ZulipAccount.js';\nimport {\n assertMessagingPermission,\n MANAGE_MESSAGE_CREDENTIALS_PERMISSION,\n MANAGE_MESSAGE_ROUTES_PERMISSION,\n type MessagingPrincipal,\n} from '../permissions.js';\nimport {\n getMessagingProvider,\n listMessagingProviders,\n type MessagingProviderDefinition,\n type MessagingProviderField,\n type MessagingProviderFunctionKey,\n} from '../providers.js';\nimport type { MessagingChannel } from '../types.js';\n\nexport interface MessagingAccountInput {\n id?: string;\n name: string;\n providerId: string;\n configuration: Record<string, unknown>;\n /** Omit on update to leave the stored secret unchanged. */\n credentials?: Record<string, unknown>;\n active?: boolean;\n /**\n * The new account's owner (create only; must be the acting principal).\n * Ownership changes later go through `MailAccessService.setOwner`.\n */\n ownerUserId?: string | null;\n /** A short name shown beside the account, such as Support. */\n label?: string | null;\n}\n\n/** A mailbox connected with a write-only secret such as an app password. */\nexport interface MailboxConnectInput {\n /** Reconnect an existing mailbox: replaces its credential. */\n id?: string;\n name: string;\n label?: string | null;\n providerId: string;\n /** Non-secret connection settings, including this account's own endpoint. */\n configuration: Record<string, unknown>;\n /** Write-only: validated, stored in smrt-secrets, never returned. */\n credentials: Record<string, unknown>;\n}\n\n/** What `connectMailbox` hands to the validator before anything is stored. */\nexport interface MailboxValidationRequest {\n provider: MessagingProviderDefinition;\n configuration: Record<string, unknown>;\n /** The normalized secret payload exactly as it would be stored. */\n credentials: Record<string, unknown>;\n}\n\nexport interface MessagingEndpointInput {\n id?: string;\n label: string;\n providerId: string;\n profileId?: string | null;\n address: Record<string, unknown>;\n active?: boolean;\n}\n\nexport interface PersonaMessageRouteInput {\n id?: string;\n personaId: string;\n accountId: string;\n endpointId: string;\n purpose?: string;\n priority?: number;\n enabled?: boolean;\n}\n\nexport interface MessagingAccountView {\n id: string;\n name: string;\n providerId: string;\n channel: MessagingChannel;\n configuration: Record<string, unknown>;\n hasCredentials: boolean;\n active: boolean;\n ownerUserId: string | null;\n label: string | null;\n connectionStatus: string | null;\n statusMessage: string | null;\n}\n\n/** An account the acting principal owns or holds a grant on. */\nexport interface MessagingAccountListing extends MessagingAccountView {\n /** `owner` administers the account; `shared` holds only grants. */\n relation: 'owner' | 'shared';\n /** Effective scopes: the owner holds all four, a grantee what grants allow. */\n scopes: MailScope[];\n}\n\nexport interface ListAccountsOptions {\n /** Page size, 1 to 200. Default 50. */\n limit?: number;\n /** The `nextCursor` of the previous page. */\n cursor?: string | null;\n}\n\nexport interface ListAccountsResult {\n accounts: MessagingAccountListing[];\n /** Pass as `cursor` for the next page; null when there are no more. */\n nextCursor: string | null;\n}\n\nconst LIST_ACCOUNTS_DEFAULT_LIMIT = 50;\nconst LIST_ACCOUNTS_MAX_LIMIT = 200;\nconst CANDIDATE_PAGE = 500;\n\nexport interface MessagingEndpointView {\n id: string;\n label: string;\n channel: MessagingChannel;\n profileId: string | null;\n maskedAddress: string;\n active: boolean;\n verified: boolean;\n}\n\n/** Permission-gated server API for a schema-driven messaging settings page. */\nexport class MessagingSettingsService {\n constructor(\n private readonly options: {\n db: SmrtClassOptions['db'];\n tenantId: string;\n principal: MessagingPrincipal;\n /** Cross-package ownership check supplied by the host/personas layer. */\n resolvePersonaTenantId: (personaId: string) => Promise<string | null>;\n /**\n * Opens a session with the candidate credential before `connectMailbox`\n * stores anything. Defaults to the provider's email client; reject to\n * refuse the connection.\n */\n validateMailbox?: (request: MailboxValidationRequest) => Promise<void>;\n /**\n * Hostnames the built-in validator may connect to: exact names or\n * `*.suffix`. Without this list (and without a custom `validateMailbox`)\n * connecting a mailbox is refused, so a permission holder cannot make\n * the server probe arbitrary hosts. Private, loopback and link-local\n * addresses are refused even when listed.\n */\n allowedMailHosts?: readonly string[];\n /** Ports the built-in validator may use. Default: standard mail ports. */\n allowedMailPorts?: readonly number[];\n },\n ) {}\n\n getProviderDefinitions(options: { includeUnavailable?: boolean } = {}) {\n return listMessagingProviders(options).map(\n ({\n createSender: _createSender,\n createEmailClient: _createEmailClient,\n createMessageClient: _createMessageClient,\n ...provider\n }) => provider,\n );\n }\n\n async list(personaId: string): Promise<{\n providers: Array<\n Omit<MessagingProviderDefinition, MessagingProviderFunctionKey>\n >;\n accounts: MessagingAccountView[];\n endpoints: MessagingEndpointView[];\n routes: PersonaMessageRoute[];\n }> {\n this.assert(MANAGE_MESSAGE_ROUTES_PERMISSION);\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const accounts = await AccountCollection.create({ db: this.options.db });\n const endpoints = await MessagingEndpointCollection.create({\n db: this.options.db,\n });\n const routes = await PersonaMessageRouteCollection.create({\n db: this.options.db,\n });\n const [accountRows, endpointRows, routeRows] = await Promise.all([\n accounts.list({}),\n endpoints.list({}),\n routes.list({ where: { personaId } }),\n ]);\n return {\n providers: this.getProviderDefinitions({ includeUnavailable: true }),\n accounts: accountRows.map((account) => this.accountView(account)),\n endpoints: endpointRows.map((endpoint) => this.endpointView(endpoint)),\n routes: routeRows,\n };\n });\n }\n\n /**\n * Stores account settings only: it never opens a connection, so it is not an\n * SSRF vector by itself (connecting goes through `connectMailbox`, which is\n * allowlisted). The SMTP host/port it stores predate this change and are\n * used later by the sender; hosts that need an outbound allowlist apply it\n * there.\n */\n async saveAccount(\n input: MessagingAccountInput,\n ): Promise<MessagingAccountView> {\n return this.persistAccount(input, false);\n }\n\n /**\n * `receiveOnly` admits providers that are not outbound transports (IMAP,\n * POP3): a mailbox can be connected for reading without being a sender.\n */\n private async persistAccount(\n input: MessagingAccountInput,\n receiveOnly: boolean,\n ): Promise<MessagingAccountView> {\n this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);\n const provider = this.requireProvider(input.providerId);\n if (!provider.available && !(receiveOnly && provider.channel === 'email'))\n throw new Error(`Provider '${provider.id}' is not available.`);\n this.validateFields(\n input.configuration,\n provider.configurationFields,\n 'configuration',\n );\n if (input.credentials) {\n this.validateFields(\n input.credentials,\n provider.credentialFields,\n 'credentials',\n );\n }\n\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const collection = await AccountCollection.create({\n db: this.options.db,\n });\n let account = input.id ? await collection.get({ id: input.id }) : null;\n const isNew = !account;\n if (account && account.tenantId !== this.options.tenantId) {\n throw new Error('Messaging account belongs to another tenant.');\n }\n if (account && account.providerType !== provider.id) {\n throw new Error(\n 'A messaging account provider cannot be changed in place.',\n );\n }\n if (account) this.assertMayManage(account);\n if (account && input.ownerUserId !== undefined) {\n if ((input.ownerUserId ?? null) !== (account.ownerUserId ?? null)) {\n throw new Error(\n 'Change a mail account owner with MailAccessService.setOwner.',\n );\n }\n }\n if (\n !account &&\n input.ownerUserId &&\n input.ownerUserId !== this.actingUserId\n ) {\n throw new Error('A new mail account can only be owned by its creator.');\n }\n if (\n isNew &&\n !input.credentials &&\n provider.credentialFields.some((field) => field.required)\n ) {\n throw new Error(\n `Credentials are required for new ${provider.label} accounts.`,\n );\n }\n\n if (!account) {\n account = this.newAccount(provider, input);\n await account.initialize();\n }\n\n account.name = input.name.trim();\n if (isNew && input.ownerUserId) account.ownerUserId = input.ownerUserId;\n if (input.label !== undefined)\n account.label = input.label?.trim() || null;\n account.isActive = input.active ?? account.isActive;\n account.channelType = provider.channel;\n const configuration = this.normalizeConfiguration(\n provider,\n input.configuration,\n );\n account.setConfiguration(configuration);\n if (account instanceof EmailAccount) {\n account.email = String(configuration.email ?? '');\n }\n account.updatedAt = new Date();\n await account.save();\n\n if (input.credentials) {\n await account.setCredentials(\n this.normalizeCredentials(provider, input.credentials),\n );\n }\n\n return this.accountView(account);\n });\n }\n\n /**\n * Connect a mailbox with a write-only secret (an app password). The\n * credential is validated by opening a session first; a refusal leaves no\n * account and no secret behind. The connecting user becomes the owner.\n */\n async connectMailbox(\n input: MailboxConnectInput,\n ): Promise<MessagingAccountView> {\n this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);\n // A connected mailbox always has an owner: without a user to own it the\n // account would silently be readable tenant-wide.\n if (!this.actingUserId) {\n throw new Error('Connecting a mailbox needs a signed-in user.');\n }\n if (input.id) {\n // Reconnect, never create-by-id: fails before any server is contacted.\n await withTenant({ tenantId: this.options.tenantId }, async () => {\n this.assertMayManage(await this.loadAccount(input.id as string));\n });\n }\n const provider = this.requireProvider(input.providerId);\n if (provider.channel !== 'email') {\n throw new Error(`Provider '${provider.id}' cannot connect a mailbox.`);\n }\n this.validateFields(\n input.configuration,\n provider.configurationFields,\n 'configuration',\n );\n this.validateFields(\n input.credentials,\n provider.credentialFields,\n 'credentials',\n );\n const configuration = this.normalizeConfiguration(\n provider,\n input.configuration,\n );\n const credentials = this.normalizeCredentials(provider, input.credentials);\n await this.validateConnection({ provider, configuration, credentials });\n const view = await this.persistAccount(\n {\n id: input.id,\n name: input.name,\n label: input.label,\n providerId: input.providerId,\n configuration: input.configuration,\n credentials: input.credentials,\n active: true,\n ownerUserId: input.id ? undefined : (this.actingUserId ?? null),\n },\n true,\n );\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const account = await this.loadAccount(view.id);\n await account.markConnected();\n return this.accountView(account);\n });\n }\n\n /** Pause or resume a mailbox without touching its credential. */\n async setAccountActive(\n accountId: string,\n active: boolean,\n ): Promise<MessagingAccountView> {\n this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const account = await this.loadAccount(accountId);\n this.assertMayManage(account);\n account.isActive = active;\n account.updatedAt = new Date();\n await account.save();\n return this.accountView(account);\n });\n }\n\n /**\n * Remove a mailbox: its stored credential, its synced emails, folders and\n * attachments, and the account itself.\n */\n async removeAccount(accountId: string): Promise<void> {\n this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);\n await withTenant({ tenantId: this.options.tenantId }, async () => {\n const account = await this.loadAccount(accountId);\n this.assertMayManage(account);\n await runWithMailSystemAccess(async () => {\n const db = this.options.db;\n const messages = await MessageCollection.create({ db });\n const attachments = await AttachmentCollection.create({ db });\n const folders = await EmailFolderCollection.create({ db });\n for (const message of await messages.list({ where: { accountId } })) {\n if (message.id) {\n for (const attachment of await attachments.list({\n where: { messageId: message.id },\n })) {\n await attachment.delete();\n }\n }\n await message.delete();\n }\n for (const folder of await folders.list({ where: { accountId } })) {\n await folder.delete();\n }\n });\n await account.removeCredentials();\n await account.delete();\n });\n }\n\n async saveEndpoint(\n input: MessagingEndpointInput,\n ): Promise<MessagingEndpointView> {\n this.assert(MANAGE_MESSAGE_ROUTES_PERMISSION);\n const provider = this.requireProvider(input.providerId);\n if (!provider.available)\n throw new Error(`Provider '${provider.id}' is not available.`);\n this.validateFields(input.address, provider.endpointFields, 'endpoint');\n\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const collection = await MessagingEndpointCollection.create({\n db: this.options.db,\n });\n let endpoint = input.id ? await collection.get({ id: input.id }) : null;\n if (endpoint && endpoint.tenantId !== this.options.tenantId) {\n throw new Error('Messaging endpoint belongs to another tenant.');\n }\n if (!endpoint) {\n endpoint = new (ObjectRegistry.resolveEffectiveConstructor(\n MessagingEndpoint,\n ))({\n db: this.options.db,\n tenantId: this.options.tenantId,\n });\n await endpoint.initialize();\n }\n endpoint.label = input.label.trim();\n if (input.profileId !== undefined) {\n endpoint.profileId = input.profileId;\n }\n endpoint.channel = provider.channel;\n endpoint.isActive = input.active ?? endpoint.isActive;\n endpoint.setAddress(input.address);\n endpoint.updatedAt = new Date();\n await endpoint.save();\n return this.endpointView(endpoint);\n });\n }\n\n async saveRoute(\n input: PersonaMessageRouteInput,\n ): Promise<PersonaMessageRoute> {\n this.assert(MANAGE_MESSAGE_ROUTES_PERMISSION);\n const personaTenantId = await this.options.resolvePersonaTenantId(\n input.personaId,\n );\n if (personaTenantId !== this.options.tenantId) {\n throw new Error('Messaging persona was not found in this tenant.');\n }\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const accounts = await AccountCollection.create({ db: this.options.db });\n const endpoints = await MessagingEndpointCollection.create({\n db: this.options.db,\n });\n const routes = await PersonaMessageRouteCollection.create({\n db: this.options.db,\n });\n const [account, endpoint] = await Promise.all([\n accounts.get({ id: input.accountId }),\n endpoints.get({ id: input.endpointId }),\n ]);\n if (!account || account.tenantId !== this.options.tenantId) {\n throw new Error('Messaging account was not found in this tenant.');\n }\n if (!endpoint || endpoint.tenantId !== this.options.tenantId) {\n throw new Error('Messaging endpoint was not found in this tenant.');\n }\n const accountProvider = getMessagingProvider(account.providerType);\n if (\n !accountProvider?.available ||\n accountProvider.channel !== account.channelType\n ) {\n throw new Error(\n 'Messaging account provider is not available for outbound delivery.',\n );\n }\n if (account.channelType !== endpoint.channel) {\n throw new Error(\n 'Messaging account and endpoint channels do not match.',\n );\n }\n\n let route = input.id ? await routes.get({ id: input.id }) : null;\n if (route && route.tenantId !== this.options.tenantId) {\n throw new Error('Messaging route belongs to another tenant.');\n }\n if (!route) {\n route = new (ObjectRegistry.resolveEffectiveConstructor(\n PersonaMessageRoute,\n ))({\n db: this.options.db,\n tenantId: this.options.tenantId,\n });\n await route.initialize();\n }\n route.personaId = input.personaId;\n route.accountId = input.accountId;\n route.endpointId = input.endpointId;\n route.purpose = input.purpose?.trim() || 'default';\n route.priority = input.priority ?? 0;\n route.enabled = input.enabled ?? route.enabled;\n route.updatedAt = new Date();\n await route.save();\n return route;\n });\n }\n\n /**\n * Accounts the acting principal owns or holds an active grant on, in this\n * service's tenant, with the effective scopes per account. It never lists\n * unowned (tenant-wide) accounts or accounts of other users. Every decision\n * goes through `decideMailAccess`, so ownership, grants, the tenant\n * `messages.<scope>` ceiling and tenant isolation are the same as for mail\n * reads; no separate authorization path exists here. Fail closed: no\n * principal user, a principal of another tenant, or an unconfigured mail\n * access policy (`configureMailAccess`, which owned accounts need to be\n * decided at all) yields an empty list. Paged by account id.\n */\n async listAccounts(\n options: ListAccountsOptions = {},\n ): Promise<ListAccountsResult> {\n const empty: ListAccountsResult = { accounts: [], nextCursor: null };\n const userId = this.actingUserId;\n const { tenantId, principal } = this.options;\n if (!userId || !tenantId) return empty;\n if (principal.tenantId && principal.tenantId !== tenantId) return empty;\n // Owned accounts are only decidable under an explicit policy; a database\n // merely learned from mail rows must not open them up.\n if (!getMailAccessConfig()) return empty;\n const requested = Number.isFinite(options.limit)\n ? Math.trunc(options.limit as number)\n : LIST_ACCOUNTS_DEFAULT_LIMIT;\n const limit = Math.min(Math.max(requested, 1), LIST_ACCOUNTS_MAX_LIMIT);\n const subject: MailPrincipal = {\n id: principal.id ?? userId,\n userId,\n tenantId,\n // The host's limits (an agent credential's allow-list and scopes) ride\n // on the principal and are applied by decideMailAccess below.\n ...(principal.scopes ? { scopes: principal.scopes } : {}),\n ...(principal.accountIds ? { accountIds: principal.accountIds } : {}),\n };\n return withTenant({ tenantId }, async () => {\n const candidates = await this.accountCandidateIds(userId);\n if (subject.accountIds) {\n for (const id of [...candidates]) {\n if (!subject.accountIds.includes(id)) candidates.delete(id);\n }\n }\n const accounts = await AccountCollection.create(\n withoutListBounds({ db: this.options.db }),\n );\n const sorted = [...candidates].sort();\n const start = options.cursor\n ? sorted.findIndex((id) => id > (options.cursor as string))\n : 0;\n const out: MessagingAccountListing[] = [];\n let lastId: string | null = null;\n let more = false;\n for (const id of start < 0 ? [] : sorted.slice(start)) {\n if (out.length >= limit) {\n more = true;\n break;\n }\n const account = await accounts.get({ id });\n if (!account || account.tenantId !== tenantId) continue;\n lastId = id;\n const scopes: MailScope[] = [];\n let owner = false;\n for (const scope of MAIL_SCOPES) {\n const decision = await decideMailAccess(\n {\n id: account.id,\n tenantId: account.tenantId,\n ownerUserId: account.ownerUserId,\n },\n scope,\n subject,\n );\n if (decision.reason === 'owner' && decision.allowed) owner = true;\n if (\n decision.allowed &&\n (decision.reason === 'owner' || decision.reason === 'grant')\n ) {\n scopes.push(scope);\n }\n }\n if (!scopes.length) continue;\n out.push({\n ...this.accountView(account),\n relation: owner ? 'owner' : 'shared',\n scopes,\n });\n }\n return { accounts: out, nextCursor: more ? lastId : null };\n });\n }\n\n /** Ids of accounts the user owns or holds a grant row on (tenant scoped). */\n private async accountCandidateIds(userId: string): Promise<Set<string>> {\n const { tenantId, db } = this.options;\n const ids = new Set<string>();\n const accounts = await AccountCollection.create(withoutListBounds({ db }));\n const { ResourceGrantCollection } = await import(\n '@happyvertical/smrt-users'\n );\n const grants = await ResourceGrantCollection.create(\n withoutListBounds({ db }),\n );\n for (let offset = 0; ; offset += CANDIDATE_PAGE) {\n const rows = await accounts.list({\n where: { tenantId, ownerUserId: userId },\n limit: CANDIDATE_PAGE,\n offset,\n orderBy: 'id ASC',\n });\n for (const row of rows) if (row.id) ids.add(row.id);\n if (rows.length < CANDIDATE_PAGE) break;\n }\n for (let offset = 0; ; offset += CANDIDATE_PAGE) {\n const rows = await grants.list({\n where: { tenantId, userId, resourceType: MAIL_ACCOUNT_RESOURCE_TYPE },\n limit: CANDIDATE_PAGE,\n offset,\n orderBy: 'id ASC',\n });\n for (const row of rows) {\n if (row.isActive() && row.effect === 'grant') ids.add(row.resourceId);\n }\n if (rows.length < CANDIDATE_PAGE) break;\n }\n return ids;\n }\n\n /** The user who owns accounts this principal creates; null when unknown. */\n private get actingUserId(): string | null {\n return this.options.principal.userId ?? this.options.principal.id ?? null;\n }\n\n private async loadAccount(accountId: string): Promise<Account> {\n const accounts = await AccountCollection.create({ db: this.options.db });\n const account = await accounts.get({ id: accountId });\n if (!account || account.tenantId !== this.options.tenantId) {\n throw new Error('Messaging account was not found in this tenant.');\n }\n return account;\n }\n\n /** An owned mailbox is managed by its owner only; unowned ones by admins. */\n private assertMayManage(account: Account): void {\n if (account.ownerUserId && account.ownerUserId !== this.actingUserId) {\n throw new Error('Only the mail account owner can change this account.');\n }\n }\n\n private async validateConnection(\n request: MailboxValidationRequest,\n ): Promise<void> {\n try {\n if (this.options.validateMailbox) {\n await this.options.validateMailbox(request);\n return;\n }\n this.assertAllowedTarget(request.configuration);\n const create = request.provider.createEmailClient;\n if (!create) {\n throw new Error('this provider cannot check a mailbox sign-in');\n }\n const settings: Record<string, unknown> = {\n ...request.configuration,\n ...request.credentials,\n };\n delete settings.email;\n const client = await create({\n type: request.provider.id,\n ...settings,\n } as Parameters<typeof create>[0]);\n try {\n await client.connect();\n } finally {\n await client.disconnect().catch(() => undefined);\n }\n } catch {\n // Never echo server or network detail: it would let a permission\n // holder map internal hosts, and it can carry the secret.\n throw new Error('The mail server did not accept this connection.');\n }\n }\n\n /**\n * Host and port allowlist for the built-in validator (SSRF guard).\n *\n * Names are checked, not resolved: an allowlisted name that resolves (or is\n * rebound) to a private address is the host's allowlist responsibility, so\n * list only names you control, or pass a `validateMailbox` that resolves and\n * pins the address it connects to.\n */\n private assertAllowedTarget(configuration: Record<string, unknown>): void {\n // Every target-bearing field present is checked, so a permitted `host`\n // cannot shelter a different `url` or `endpoint` (the JMAP provider's\n // session URL is `url`).\n const targets: Array<{ host: string; port: number | undefined }> = [];\n if (typeof configuration.host === 'string' && configuration.host) {\n targets.push({\n host: configuration.host,\n port:\n typeof configuration.port === 'number'\n ? configuration.port\n : undefined,\n });\n }\n for (const key of ['endpoint', 'url'] as const) {\n const value = configuration[key];\n if (value === undefined || value === null || value === '') continue;\n if (typeof value !== 'string') throw new Error('refused');\n const url = new URL(value);\n // https only, and never credentials in the URL.\n if (url.protocol !== 'https:' || url.username || url.password) {\n throw new Error('refused');\n }\n targets.push({\n host: url.hostname,\n port: url.port ? Number(url.port) : 443,\n });\n }\n if (!targets.length) throw new Error('refused');\n const allowed = this.options.allowedMailHosts ?? [];\n const ports = this.options.allowedMailPorts ?? [\n 143, 443, 465, 587, 993, 995,\n ];\n for (const target of targets) {\n const host = target.host.toLowerCase().replace(/^\\[|\\]$/g, '');\n const listed = allowed.some((entry) => {\n const pattern = entry.toLowerCase();\n return pattern.startsWith('*.')\n ? host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1\n : host === pattern;\n });\n if (!host || !listed || isPrivateMailHost(host)) {\n throw new Error('refused');\n }\n if (target.port !== undefined && !ports.includes(target.port)) {\n throw new Error('refused');\n }\n }\n }\n\n private assert(permission: string): void {\n assertMessagingPermission(\n this.options.principal,\n this.options.tenantId,\n permission,\n );\n }\n\n private requireProvider(providerId: string): MessagingProviderDefinition {\n const provider = getMessagingProvider(providerId);\n if (!provider)\n throw new Error(`Unknown messaging provider '${providerId}'.`);\n return provider;\n }\n\n private validateFields(\n values: Record<string, unknown>,\n fields: MessagingProviderField[],\n kind: string,\n ): void {\n const allowed = new Set(fields.map((field) => field.id));\n for (const key of Object.keys(values)) {\n if (!allowed.has(key)) {\n throw new Error(`Unknown ${kind} field '${key}'.`);\n }\n }\n for (const field of fields) {\n const value = values[field.id];\n const missing = value === undefined || value === '';\n if (field.required && (missing || value === null)) {\n throw new Error(`${field.label} is required in ${kind}.`);\n }\n if (missing) continue;\n\n if (\n field.type === 'number' &&\n (typeof value !== 'number' || !Number.isFinite(value))\n ) {\n throw new Error(`${field.label} must be a finite number in ${kind}.`);\n }\n if (field.type === 'boolean' && typeof value !== 'boolean') {\n throw new Error(`${field.label} must be a boolean in ${kind}.`);\n }\n if (\n field.type !== 'number' &&\n field.type !== 'boolean' &&\n typeof value !== 'string'\n ) {\n throw new Error(`${field.label} must be a string in ${kind}.`);\n }\n if (\n field.type === 'select' &&\n field.options?.length &&\n !field.options.some((option) => option.value === value)\n ) {\n throw new Error(`${field.label} has an invalid option in ${kind}.`);\n }\n }\n }\n\n private newAccount(\n provider: MessagingProviderDefinition,\n input: MessagingAccountInput,\n ): Account {\n const options = {\n db: this.options.db,\n tenantId: this.options.tenantId,\n name: input.name.trim(),\n providerType: provider.id,\n channelType: provider.channel,\n };\n if (provider.id === 'zulip')\n return new (ObjectRegistry.resolveEffectiveConstructor(ZulipAccount))(\n options,\n );\n if (provider.id === 'telegram')\n return new (ObjectRegistry.resolveEffectiveConstructor(TelegramAccount))(\n options,\n );\n if (provider.channel === 'email') {\n return new (ObjectRegistry.resolveEffectiveConstructor(EmailAccount))({\n ...options,\n providerType: provider.id as 'smtp' | 'imap' | 'pop3' | 'gmail',\n });\n }\n return new (ObjectRegistry.resolveEffectiveConstructor(Account))(options);\n }\n\n private normalizeCredentials(\n provider: MessagingProviderDefinition,\n credentials: Record<string, unknown>,\n ): Record<string, unknown> {\n if (provider.channel !== 'email') return credentials;\n if (provider.id === 'gmail') {\n return { auth: credentials };\n }\n if (provider.id === 'jmap') {\n // JMAP signs in with a bearer token or a user and password, as one\n // `auth` value; a token must not be shadowed by an empty user/pass.\n const { username, password, token, ...rest } = credentials;\n if (typeof token === 'string' && token) {\n return { ...rest, auth: { type: 'bearer', token } };\n }\n return { ...rest, auth: { user: username, pass: password } };\n }\n const { username, password, ...rest } = credentials;\n return {\n ...rest,\n auth: { user: username, pass: password },\n };\n }\n\n private normalizeConfiguration(\n provider: MessagingProviderDefinition,\n configuration: Record<string, unknown>,\n ): Record<string, unknown> {\n if (provider.channel !== 'email' || configuration.secure === undefined) {\n return configuration;\n }\n return {\n ...configuration,\n secure: configuration.secure === true || configuration.secure === 'true',\n };\n }\n\n private accountView(account: Account): MessagingAccountView {\n return {\n id: account.id ?? '',\n name: account.name,\n providerId: account.providerType,\n channel: account.channelType,\n configuration: account.getConfiguration(),\n hasCredentials: account.hasCredentials,\n active: account.isActive,\n ownerUserId: account.ownerUserId,\n label: account.label,\n connectionStatus: account.connectionStatus,\n statusMessage: account.statusMessage,\n };\n }\n\n private endpointView(endpoint: MessagingEndpoint): MessagingEndpointView {\n return {\n id: endpoint.id ?? '',\n label: endpoint.label,\n channel: endpoint.channel,\n profileId: endpoint.profileId,\n maskedAddress: endpoint.getMaskedAddress(),\n active: endpoint.isActive,\n verified: endpoint.verifiedAt !== null,\n };\n }\n}\n\n/** Loopback, private, link-local and unspecified addresses and names. */\nfunction isPrivateMailHost(host: string): boolean {\n if (host === 'localhost' || host.endsWith('.localhost')) return true;\n const v4 = host.match(/^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/);\n if (v4) {\n const [a, b] = [Number(v4[1]), Number(v4[2])];\n return (\n a === 0 ||\n a === 10 ||\n a === 127 ||\n (a === 100 && b >= 64 && b <= 127) ||\n (a === 169 && b === 254) ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168)\n );\n }\n if (host.includes(':')) {\n return (\n host === '::' ||\n host === '::1' ||\n /^f[cd]/.test(host) ||\n /^fe[89ab]/.test(host) ||\n host.startsWith('::ffff:')\n );\n }\n return false;\n}\n","/**\n * Per-account mail search (Epic I, I6, #5132).\n *\n * `MailSearchService` searches the mail a principal may read and nothing else:\n *\n * - The searchable accounts are exactly `MessagingSettingsService.listAccounts`\n * with the `read` scope, so the decision is `decideMailAccess` (owner, grant,\n * tenant ceiling, the host's scope and account ceilings) and fails closed\n * without a principal, on a tenant mismatch or without `configureMailAccess`.\n * An `accountIds` filter can only narrow that set; unreadable ids are dropped.\n * - Every local read is constrained to those account ids in the query itself\n * and then runs as trusted code (`runWithMailSystemAccess`), because the\n * decision was already made here with the explicit principal.\n * - Local search is a keyword scan over a bounded, newest-first candidate\n * window (case-insensitive on every database), with optional semantic\n * ranking through core `semanticSearchIds()` when `Email` embeddings are\n * available. Provider search asks each account's own server through the\n * SDK's `search()` and falls back to the local index, per account, when the\n * provider cannot or does not answer.\n *\n * @packageDocumentation\n */\n\nimport type { SearchCriteria } from '@happyvertical/email';\nimport type { SmrtClassOptions } from '@happyvertical/smrt-core';\nimport { runWithMailSystemAccess } from '../access.js';\nimport { EmailAccountCollection } from '../collections/EmailAccountCollection.js';\nimport { EmailCollection } from '../collections/EmailCollection.js';\nimport { withTenant } from '../host.js';\nimport type { Email } from '../models/Email.js';\nimport type { EmailAccount } from '../models/EmailAccount.js';\nimport type { MessagingPrincipal } from '../permissions.js';\nimport {\n type MessagingAccountListing,\n MessagingSettingsService,\n} from './MessagingSettingsService.js';\n\nexport interface MailSearchServiceOptions {\n db: SmrtClassOptions['db'];\n tenantId: string;\n /** The acting principal, as for `MessagingSettingsService`. */\n principal: MessagingPrincipal;\n}\n\n/** Filters shared by local and provider search. */\nexport interface MailSearchQuery {\n /** Free text matched against subject, body, sender name and address. */\n text?: string;\n /** Narrow to these accounts; ids the principal cannot read are ignored. */\n accountIds?: readonly string[];\n /** Sender address or name contains. */\n from?: string;\n /** A recipient (to or cc) address or name contains. */\n to?: string;\n subject?: string;\n /** Mailbox label or folder name or path (exact, case-insensitive). */\n label?: string;\n hasAttachment?: boolean;\n isRead?: boolean;\n isFlagged?: boolean;\n /** Sent on or after. */\n since?: Date;\n /** Sent before. */\n before?: Date;\n /** Page size, 1 to 100. Default 25. */\n limit?: number;\n /** The previous page's `nextCursor`. */\n cursor?: string | null;\n /**\n * `keyword` (default) never calls an embedding model. `semantic` ranks by\n * meaning and falls back to keyword when embeddings are unavailable;\n * `semanticUsed` on the result says which happened.\n */\n mode?: 'keyword' | 'semantic';\n}\n\nexport interface MailSearchHit {\n accountId: string;\n /** Local `Email` row id; null for a provider hit not yet synced. */\n emailId: string | null;\n providerMessageId: string;\n threadId: string;\n subject: string;\n fromAddress: string;\n fromName: string;\n date: Date | null;\n snippet: string;\n isRead: boolean;\n isFlagged: boolean;\n hasAttachments: boolean;\n labels: string[];\n /** Where the hit came from. */\n source: 'local' | 'provider';\n /** Similarity in 0..1 when ranked semantically. */\n similarity?: number;\n}\n\nexport interface MailSearchPage {\n hits: MailSearchHit[];\n nextCursor: string | null;\n /** Accounts that were searched (readable and, if given, requested). */\n accountIds: string[];\n /** True when the scan window ended before every candidate was examined. */\n truncated: boolean;\n semanticUsed: boolean;\n}\n\nexport interface MailProviderSearchResult {\n hits: MailSearchHit[];\n /** Accounts answered by the provider. */\n providerAccountIds: string[];\n /** Accounts answered from the local index instead, with the reason. */\n fallbackAccounts: Array<{ accountId: string; reason: string }>;\n accountIds: string[];\n truncated: boolean;\n}\n\nconst DEFAULT_LIMIT = 25;\nconst MAX_LIMIT = 100;\nconst SCAN_BATCH = 200;\n/** Upper bound on rows examined by one local search call. */\nconst SCAN_LIMIT = 5000;\nconst SNIPPET_LENGTH = 200;\n\nfunction clampLimit(limit: number | undefined): number {\n if (limit === undefined) return DEFAULT_LIMIT;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new Error('Mail search limit must be a positive integer.');\n }\n return Math.min(limit, MAX_LIMIT);\n}\n\nfunction parseCursor(cursor: string | null | undefined): number {\n if (!cursor) return 0;\n const n = Number(cursor);\n if (!Number.isInteger(n) || n < 0) {\n throw new Error('Invalid mail search cursor.');\n }\n return n;\n}\n\nconst lower = (v: string | null | undefined) => (v ?? '').toLowerCase();\n\n/** Addresses of a JSON `[{address, name}]` column as lower-cased haystacks. */\nexport function recipientHaystack(json: string | null | undefined): string {\n if (!json) return '';\n try {\n const parsed = JSON.parse(json);\n if (!Array.isArray(parsed)) return lower(json);\n return parsed\n .map((p) =>\n typeof p === 'string' ? p : `${p?.address ?? ''} ${p?.name ?? ''}`,\n )\n .join(' ')\n .toLowerCase();\n } catch {\n return lower(json);\n }\n}\n\nfunction labelsOf(email: Email): string[] {\n const out = new Set<string>();\n for (const raw of [email.labels]) {\n try {\n const parsed = JSON.parse(raw || '[]');\n if (Array.isArray(parsed))\n for (const l of parsed) if (typeof l === 'string') out.add(l);\n } catch {\n // unreadable labels are treated as none\n }\n }\n if (email.folderPath) out.add(email.folderPath);\n return [...out];\n}\n\nfunction toHit(email: Email, similarity?: number): MailSearchHit {\n const body = (email.textBody || email.body || '').replace(/\\s+/g, ' ');\n return {\n accountId: email.accountId,\n emailId: email.id ?? null,\n providerMessageId: email.providerMessageId,\n threadId: email.threadId,\n subject: email.subject,\n fromAddress: email.fromAddress,\n fromName: email.fromName,\n date: email.date ?? null,\n snippet: body.slice(0, SNIPPET_LENGTH),\n isRead: email.isRead,\n isFlagged: email.isFlagged,\n hasAttachments: email.hasAttachments,\n labels: labelsOf(email),\n source: 'local',\n ...(similarity === undefined ? {} : { similarity }),\n };\n}\n\nfunction matches(email: Email, q: MailSearchQuery): boolean {\n if (q.from) {\n const f = q.from.toLowerCase();\n if (!`${lower(email.fromAddress)} ${lower(email.fromName)}`.includes(f))\n return false;\n }\n if (q.to) {\n const t = q.to.toLowerCase();\n if (\n !`${recipientHaystack(email.toAddresses)} ${recipientHaystack(email.ccAddresses)}`.includes(\n t,\n )\n )\n return false;\n }\n if (q.subject && !lower(email.subject).includes(q.subject.toLowerCase()))\n return false;\n if (q.label) {\n const wanted = q.label.toLowerCase();\n if (!labelsOf(email).some((l) => l.toLowerCase() === wanted)) return false;\n }\n if (q.text) {\n const t = q.text.toLowerCase();\n const hay = `${lower(email.subject)} ${lower(email.textBody)} ${lower(\n email.body,\n )} ${lower(email.fromAddress)} ${lower(email.fromName)}`;\n // Every word must appear somewhere (order-free).\n for (const word of t.split(/\\s+/).filter(Boolean)) {\n if (!hay.includes(word)) return false;\n }\n }\n return true;\n}\n\n/** SQL-expressible part of the query, always bound to the readable accounts. */\nfunction structuredWhere(\n q: MailSearchQuery,\n tenantId: string,\n accountIds: string[],\n): Record<string, unknown> {\n const where: Record<string, unknown> = {\n tenantId,\n 'accountId in': accountIds,\n };\n if (q.hasAttachment !== undefined) where.hasAttachments = q.hasAttachment;\n if (q.isRead !== undefined) where.isRead = q.isRead;\n if (q.isFlagged !== undefined) where.isFlagged = q.isFlagged;\n if (q.since) where['date >='] = q.since;\n if (q.before) where['date <'] = q.before;\n return where;\n}\n\nexport class MailSearchService {\n constructor(private readonly options: MailSearchServiceOptions) {}\n\n /** Accounts the principal may search: owner or `read` grant, nothing else. */\n async searchableAccounts(): Promise<MessagingAccountListing[]> {\n return readableMailAccounts(this.options);\n }\n\n private async scope(\n requested: readonly string[] | undefined,\n ): Promise<{ ids: string[]; accounts: MessagingAccountListing[] }> {\n const accounts = await this.searchableAccounts();\n const wanted = requested ? new Set(requested) : null;\n const chosen = accounts.filter((a) => !wanted || wanted.has(a.id));\n return { ids: chosen.map((a) => a.id), accounts: chosen };\n }\n\n /** Search the local index across every readable account. */\n async search(query: MailSearchQuery = {}): Promise<MailSearchPage> {\n const limit = clampLimit(query.limit);\n const start = parseCursor(query.cursor);\n const { ids } = await this.scope(query.accountIds);\n const empty: MailSearchPage = {\n hits: [],\n nextCursor: null,\n accountIds: ids,\n truncated: false,\n semanticUsed: false,\n };\n if (!ids.length) return empty;\n const { tenantId, db } = this.options;\n\n return withTenant({ tenantId }, () =>\n runWithMailSystemAccess(async () => {\n const emails = await EmailCollection.create({ db });\n const where = structuredWhere(query, tenantId, ids);\n\n if (query.mode === 'semantic' && query.text) {\n const ranked = await emails.semanticMatches(query.text, where);\n if (ranked?.length) {\n const hits: MailSearchHit[] = [];\n for (const match of ranked) {\n const email = (\n (await emails.list({\n where: { ...where, id: match.id },\n limit: 1,\n })) as Email[]\n )[0];\n if (email && matches(email, { ...query, text: undefined })) {\n hits.push(toHit(email, match.similarity));\n }\n }\n const page = hits.slice(start, start + limit);\n return {\n hits: page,\n nextCursor:\n start + limit < hits.length ? String(start + limit) : null,\n accountIds: ids,\n truncated: false,\n semanticUsed: true,\n };\n }\n }\n\n const hits: MailSearchHit[] = [];\n let scanned = start;\n let exhausted = false;\n while (hits.length < limit + 1 && scanned - start < SCAN_LIMIT) {\n const batch = (await emails.list({\n where,\n orderBy: ['date DESC', 'id ASC'],\n limit: SCAN_BATCH,\n offset: scanned,\n })) as Email[];\n for (const email of batch) {\n scanned += 1;\n if (matches(email, query)) hits.push(toHit(email));\n if (hits.length > limit) break;\n }\n if (batch.length < SCAN_BATCH) {\n exhausted = true;\n break;\n }\n if (hits.length > limit) break;\n }\n const more = hits.length > limit;\n const pageHits = hits.slice(0, limit);\n // Resume exactly after the last returned hit: re-scan is cheaper than\n // skipping results, so the cursor is the position of the first\n // unreturned candidate.\n let nextCursor: string | null = null;\n let truncated = false;\n if (more) {\n nextCursor = String(scanned - 1);\n } else if (!exhausted) {\n truncated = true;\n nextCursor = String(scanned);\n }\n return {\n hits: pageHits,\n nextCursor,\n accountIds: ids,\n truncated,\n semanticUsed: false,\n };\n }),\n );\n }\n\n /**\n * Ask each readable account's own server (SDK `search()`), falling back to\n * the local index for accounts whose provider cannot search or fails. One\n * account's failure never blocks the others. Provider hits that are already\n * synced carry their local `emailId`.\n */\n async searchProvider(\n query: MailSearchQuery = {},\n ): Promise<MailProviderSearchResult> {\n const limit = clampLimit(query.limit);\n const { ids, accounts } = await this.scope(query.accountIds);\n const result: MailProviderSearchResult = {\n hits: [],\n providerAccountIds: [],\n fallbackAccounts: [],\n accountIds: ids,\n truncated: false,\n };\n if (!ids.length) return result;\n const { tenantId, db } = this.options;\n const criteria = toSearchCriteria(query);\n\n for (const listing of accounts) {\n let answered = false;\n let reason = 'provider search unavailable';\n try {\n const hits = await withTenant({ tenantId }, () =>\n runWithMailSystemAccess(async () => {\n const emailAccounts = await EmailAccountCollection.create({ db });\n const account = (await emailAccounts.get({\n id: listing.id,\n tenantId,\n })) as EmailAccount | null;\n if (!account) throw new Error('account not found');\n const client = await account.createClient();\n try {\n await client.connect();\n const caps = await client.getCapabilities();\n if (!caps.search) {\n reason = 'provider does not support search';\n return null;\n }\n // IMAP searches only the selected mailbox and a fresh client\n // has none, so it answers [] for everything: never report that\n // as a successful provider search; use the local index.\n if (client.getAdapter() === 'imap') {\n reason = 'provider search needs a selected mailbox';\n return null;\n }\n const found = await client.search(criteria);\n const emails = await EmailCollection.create({ db });\n const out: MailSearchHit[] = [];\n for (const msg of found) {\n if (!matchesFlags(msg, query)) continue;\n if (out.length >= limit) {\n result.truncated = true;\n break;\n }\n const local = msg.id\n ? ((\n await emails.list({\n where: {\n tenantId,\n accountId: listing.id,\n providerMessageId: msg.id,\n },\n limit: 1,\n })\n )[0] as Email | undefined)\n : undefined;\n out.push(\n local\n ? { ...toHit(local), source: 'provider' as const }\n : {\n accountId: listing.id,\n emailId: null,\n providerMessageId: msg.id ?? '',\n threadId: msg.threadId ?? '',\n subject: msg.subject ?? '',\n fromAddress: msg.from?.address ?? '',\n fromName: msg.from?.name ?? '',\n date: msg.date ?? null,\n snippet: (msg.text ?? '')\n .replace(/\\s+/g, ' ')\n .slice(0, SNIPPET_LENGTH),\n isRead: (msg.flags ?? []).includes('\\\\Seen' as never),\n isFlagged: (msg.flags ?? []).includes(\n '\\\\Flagged' as never,\n ),\n hasAttachments: (msg.attachments?.length ?? 0) > 0,\n labels: msg.labels ?? [],\n source: 'provider' as const,\n },\n );\n }\n return out;\n } finally {\n await client.disconnect().catch(() => undefined);\n }\n }),\n );\n if (hits) {\n result.hits.push(...hits);\n result.providerAccountIds.push(listing.id);\n answered = true;\n }\n } catch (error) {\n // Provider text can carry account details; report a fixed reason.\n reason = 'provider search failed';\n }\n if (!answered) {\n result.fallbackAccounts.push({ accountId: listing.id, reason });\n const local = await this.search({\n ...query,\n accountIds: [listing.id],\n cursor: null,\n mode: 'keyword',\n });\n result.hits.push(...local.hits);\n if (local.truncated) result.truncated = true;\n }\n }\n result.hits.sort(\n (a, b) => (b.date?.getTime() ?? 0) - (a.date?.getTime() ?? 0),\n );\n if (result.hits.length > limit) {\n result.hits = result.hits.slice(0, limit);\n result.truncated = true;\n }\n return result;\n }\n}\n\nfunction toSearchCriteria(q: MailSearchQuery): SearchCriteria {\n return {\n ...(q.text ? { q: q.text } : {}),\n ...(q.from ? { from: q.from } : {}),\n ...(q.to ? { to: q.to } : {}),\n ...(q.subject ? { subject: q.subject } : {}),\n ...(q.since ? { since: q.since } : {}),\n ...(q.before ? { before: q.before } : {}),\n ...(q.isRead === false ? { unread: true } : {}),\n ...(q.isFlagged ? { flagged: true } : {}),\n };\n}\n\n/**\n * Filters the SDK criteria cannot express (label, attachments, read and\n * flagged state in both directions) applied to provider hits.\n */\nfunction matchesFlags(\n msg: {\n flags?: readonly string[];\n attachments?: unknown[];\n labels?: string[];\n folder?: string;\n folders?: string[];\n },\n q: MailSearchQuery,\n): boolean {\n const flags = new Set((msg.flags ?? []).map((f) => String(f).toLowerCase()));\n if (q.hasAttachment !== undefined) {\n if ((msg.attachments?.length ?? 0) > 0 !== q.hasAttachment) return false;\n }\n if (q.isRead !== undefined && flags.has('\\\\seen') !== q.isRead) return false;\n if (q.isFlagged !== undefined && flags.has('\\\\flagged') !== q.isFlagged)\n return false;\n if (q.label) {\n const wanted = q.label.toLowerCase();\n const names = [\n ...(msg.labels ?? []),\n ...(msg.folders ?? []),\n ...(msg.folder ? [msg.folder] : []),\n ];\n if (!names.some((n) => n.toLowerCase() === wanted)) return false;\n }\n return true;\n}\n\n/**\n * Accounts on which the principal holds `read`, paged out of\n * `listAccounts()` (the one account-discovery decision).\n */\nexport async function readableMailAccounts(\n options: MailSearchServiceOptions,\n): Promise<MessagingAccountListing[]> {\n const settings = new MessagingSettingsService({\n db: options.db,\n tenantId: options.tenantId,\n principal: options.principal,\n resolvePersonaTenantId: async () => null,\n });\n const out: MessagingAccountListing[] = [];\n let cursor: string | null = null;\n do {\n const page = await settings.listAccounts({ limit: 200, cursor });\n for (const account of page.accounts) {\n if (account.scopes.includes('read')) out.push(account);\n }\n cursor = page.nextCursor;\n } while (cursor);\n return out;\n}\n","/**\n * Private correspondents (Epic I, I6, #5132).\n *\n * `CorrespondentService` derives and serves one person's correspondents from\n * the mail that person can read:\n *\n * - Private by construction. Every read and write filters on the acting\n * user's id and the explicit tenant; there is no tenant-wide listing and no\n * way to name another owner. A principal with no user id gets nothing.\n * - Derived, never invented. `refresh()` scans the readable accounts' mail\n * (the same decision as search: `listAccounts` with `read`) and stores\n * address, latest display name, counts, first and last contact and the\n * accounts the address was seen in. It never creates or links a\n * smrt-profiles `Profile`.\n * - Access follows the mail. Each row keeps a per-account breakdown, and every\n * view (`list`/`suggest`/`get`) is computed from the accounts the viewer can\n * read right now: counts, dates, name and `accountIds` never include an\n * account that was revoked, and a row with no readable account is hidden.\n * - `refresh()` only touches what it scanned. An empty readable set (no\n * policy, tenant mismatch, no `read` scope) changes nothing; otherwise only\n * the scanned accounts' entries are replaced, so a narrower principal can\n * never erase data from accounts outside its view.\n * - Delegated principals (a host scope or account ceiling, or a principal id\n * that is not the user id, as agent credentials are) get nothing and cannot\n * write unless the host passes `allowDelegated: true`, the explicit owner\n * consent to act on the owner's private rows.\n * - Linking is the owner's choice: `linkProfile()` stores a `Profile` id after\n * checking the profile exists in the tenant; `unlinkProfile()` clears it.\n *\n * @packageDocumentation\n */\n\nimport {\n isUniqueViolationError,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { runWithMailSystemAccess } from '../access.js';\nimport { CorrespondentCollection } from '../collections/CorrespondentCollection.js';\nimport { EmailCollection } from '../collections/EmailCollection.js';\nimport { readNotificationProfile, withTenant } from '../host.js';\nimport type { Correspondent } from '../models/Correspondent.js';\nimport type { Email } from '../models/Email.js';\nimport type { EmailAccount } from '../models/EmailAccount.js';\nimport type { MessagingPrincipal } from '../permissions.js';\nimport {\n type MailSearchServiceOptions,\n readableMailAccounts,\n} from './MailSearchService.js';\n\nexport interface CorrespondentServiceOptions {\n db: SmrtClassOptions['db'];\n tenantId: string;\n principal: MessagingPrincipal;\n /**\n * Let a delegated principal (agent credential with ceilings) use the\n * owner's private correspondents. Off by default; hosts turn it on only\n * with the owner's consent.\n */\n allowDelegated?: boolean;\n}\n\nexport interface CorrespondentView {\n id: string;\n address: string;\n displayName: string;\n messageCount: number;\n sentCount: number;\n receivedCount: number;\n firstContactAt: Date | null;\n lastContactAt: Date | null;\n accountIds: string[];\n profileId: string | null;\n}\n\nexport interface CorrespondentRefreshResult {\n /** Correspondents written (created or updated). */\n upserted: number;\n /** Rows removed because no readable mail mentions them any more. */\n removed: number;\n /** Mail rows examined. */\n scanned: number;\n}\n\nexport interface ListCorrespondentsOptions {\n /** Substring of address or display name (case-insensitive). */\n query?: string;\n /** Page size, 1 to 200. Default 50. */\n limit?: number;\n /** Previous page's `nextCursor`. */\n cursor?: string | null;\n}\n\nconst SCAN_BATCH = 500;\nconst DEFAULT_LIMIT = 50;\nconst MAX_LIMIT = 200;\nconst SUGGEST_MAX = 20;\nconst EMAIL_PATTERN = /^[^\\s@<>]+@[^\\s@<>]+$/;\n\ninterface Party {\n address: string;\n name: string;\n}\n\nfunction parseParties(json: string | null | undefined): Party[] {\n if (!json) return [];\n try {\n const parsed = JSON.parse(json);\n if (!Array.isArray(parsed)) return [];\n const out: Party[] = [];\n for (const p of parsed) {\n const address = normalizeCorrespondentAddress(\n typeof p === 'string' ? p : p?.address,\n );\n if (address) {\n out.push({\n address,\n name: typeof p === 'object' && p?.name ? String(p.name).trim() : '',\n });\n }\n }\n return out;\n } catch {\n return [];\n }\n}\n\n/** Lower-cased, trimmed address, or null when it is not an email address. */\nexport function normalizeCorrespondentAddress(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const address = value.trim().toLowerCase();\n return EMAIL_PATTERN.test(address) ? address : null;\n}\n\ninterface AccountEntry {\n sent: number;\n received: number;\n first: number | null;\n last: number | null;\n name: string;\n nameAt: number;\n}\n\ntype Breakdown = Record<string, AccountEntry>;\n\nfunction parseBreakdown(row: Correspondent): Breakdown {\n try {\n const parsed = JSON.parse(row.accountBreakdown || '{}');\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Breakdown)\n : {};\n } catch {\n return {};\n }\n}\n\n/** The row as the viewer may see it: readable accounts only, else null. */\nfunction viewOf(\n row: Correspondent,\n readable: ReadonlySet<string>,\n): CorrespondentView | null {\n const all = parseBreakdown(row);\n const ids = Object.keys(all).filter((id) => readable.has(id));\n // A linked row that was reset (no account contributes) stays reachable so\n // its owner can still unlink it.\n const reset = Object.keys(all).length === 0 && Boolean(row.profileId);\n if (!ids.length && !reset) return null;\n let sent = 0;\n let received = 0;\n let first: number | null = null;\n let last: number | null = null;\n let name = '';\n let nameAt = -1;\n for (const id of ids) {\n const e = all[id];\n sent += e.sent;\n received += e.received;\n if (e.first !== null)\n first = first === null ? e.first : Math.min(first, e.first);\n if (e.last !== null) last = last === null ? e.last : Math.max(last, e.last);\n if (e.name && e.nameAt >= nameAt) {\n name = e.name;\n nameAt = e.nameAt;\n }\n }\n return {\n id: row.id as string,\n address: row.address,\n displayName: name,\n messageCount: sent + received,\n sentCount: sent,\n receivedCount: received,\n firstContactAt: first === null ? null : new Date(first),\n lastContactAt: last === null ? null : new Date(last),\n accountIds: ids.sort(),\n profileId: row.profileId,\n };\n}\n\nexport class CorrespondentService {\n constructor(private readonly options: CorrespondentServiceOptions) {}\n\n private get ownerUserId(): string | null {\n const { principal } = this.options;\n return principal.userId ?? principal.id ?? null;\n }\n\n /** Agent-style principal acting under ceilings or a credential id. */\n private get delegated(): boolean {\n const { principal } = this.options;\n return Boolean(\n principal.scopes ||\n principal.accountIds ||\n (principal.id && principal.userId && principal.id !== principal.userId),\n );\n }\n\n /** The owner whose rows this principal may use, or null. */\n private get actingOwner(): string | null {\n if (this.delegated && !this.options.allowDelegated) return null;\n return this.ownerUserId;\n }\n\n private searchOptions(): MailSearchServiceOptions {\n return this.options;\n }\n\n private async rows(): Promise<CorrespondentCollection> {\n return CorrespondentCollection.create({ db: this.options.db });\n }\n\n private async readableIds(): Promise<Set<string>> {\n return new Set(\n (await readableMailAccounts(this.searchOptions())).map((a) => a.id),\n );\n }\n\n /**\n * Re-derive this owner's correspondents from readable mail. Idempotent.\n * Only the scanned (readable) accounts' entries are replaced; entries of\n * accounts outside the scan are kept as they are. Nothing changes when no\n * account is readable. Addresses of the scanned accounts are not\n * correspondents. A delegated principal is refused.\n */\n async refresh(): Promise<CorrespondentRefreshResult> {\n const result: CorrespondentRefreshResult = {\n upserted: 0,\n removed: 0,\n scanned: 0,\n };\n if (this.delegated && !this.options.allowDelegated) {\n throw new Error('Correspondents are private to their owner.');\n }\n const owner = this.actingOwner;\n const { tenantId, db } = this.options;\n if (!owner) return result;\n const accounts = await readableMailAccounts(this.searchOptions());\n const ids = accounts.map((a) => a.id);\n // No readable account (no policy, tenant mismatch, no read scope): there\n // is no evidence about any row, so none is changed.\n if (!ids.length) return result;\n const scanned = new Set(ids);\n\n const own = new Set<string>(await this.ownAddresses(ids));\n const aggs = new Map<string, Breakdown>();\n const touch = (\n party: Party,\n kind: 'sent' | 'received',\n at: number,\n accountId: string,\n ) => {\n if (own.has(party.address)) return;\n let perAccount = aggs.get(party.address);\n if (!perAccount) {\n perAccount = {};\n aggs.set(party.address, perAccount);\n }\n let e = perAccount[accountId];\n if (!e) {\n e = {\n sent: 0,\n received: 0,\n first: null,\n last: null,\n name: '',\n nameAt: -1,\n };\n perAccount[accountId] = e;\n }\n if (kind === 'sent') e.sent += 1;\n else e.received += 1;\n if (at) {\n e.first = e.first === null ? at : Math.min(e.first, at);\n e.last = e.last === null ? at : Math.max(e.last, at);\n }\n if (party.name && at >= e.nameAt) {\n e.name = party.name;\n e.nameAt = at;\n }\n };\n\n await withTenant({ tenantId }, () =>\n runWithMailSystemAccess(async () => {\n const emails = await EmailCollection.create({ db });\n for (let offset = 0; ; offset += SCAN_BATCH) {\n const batch = (await emails.list({\n where: { tenantId, 'accountId in': ids },\n orderBy: ['id ASC'],\n limit: SCAN_BATCH,\n offset,\n })) as Email[];\n for (const email of batch) {\n result.scanned += 1;\n const at = email.date?.getTime() ?? 0;\n const sender = normalizeCorrespondentAddress(email.fromAddress);\n if (sender) {\n touch(\n { address: sender, name: email.fromName?.trim() ?? '' },\n 'sent',\n at,\n email.accountId,\n );\n }\n for (const p of [\n ...parseParties(email.toAddresses),\n ...parseParties(email.ccAddresses),\n ]) {\n touch(p, 'received', at, email.accountId);\n }\n }\n if (batch.length < SCAN_BATCH) break;\n }\n }),\n );\n\n await withTenant({ tenantId }, async () => {\n const rows = await this.rows();\n const existing = (await rows.list({\n where: { tenantId, ownerUserId: owner },\n limit: 100000,\n })) as Correspondent[];\n const byAddress = new Map(existing.map((r) => [r.address, r]));\n const addresses = new Set([...aggs.keys(), ...byAddress.keys()]);\n for (const address of addresses) {\n let row = byAddress.get(address);\n // Keep entries of accounts outside the scan; replace scanned ones.\n const merged: Breakdown = {};\n if (row) {\n for (const [id, e] of Object.entries(parseBreakdown(row))) {\n if (!scanned.has(id)) merged[id] = e;\n }\n }\n Object.assign(merged, aggs.get(address) ?? {});\n if (!Object.keys(merged).length && row && !row.profileId) {\n await row.delete();\n result.removed += 1;\n continue;\n }\n if (!row) {\n try {\n row = await rows.create({\n _insertOnly: true,\n tenantId,\n ownerUserId: owner,\n address,\n });\n } catch (error) {\n // A concurrent refresh stored the row first: update that one.\n if (!isUniqueViolationError(error)) throw error;\n row = (\n (await rows.list({\n where: { tenantId, ownerUserId: owner, address },\n limit: 1,\n })) as Correspondent[]\n )[0];\n if (!row) throw error;\n }\n }\n let sent = 0;\n let received = 0;\n let first: number | null = null;\n let last: number | null = null;\n let name = '';\n let nameAt = -1;\n for (const e of Object.values(merged)) {\n sent += e.sent;\n received += e.received;\n if (e.first !== null)\n first = first === null ? e.first : Math.min(first, e.first);\n if (e.last !== null)\n last = last === null ? e.last : Math.max(last, e.last);\n if (e.name && e.nameAt >= nameAt) {\n name = e.name;\n nameAt = e.nameAt;\n }\n }\n row.accountBreakdown = JSON.stringify(merged);\n row.accountIds = JSON.stringify(Object.keys(merged).sort());\n row.sentCount = sent;\n row.receivedCount = received;\n row.messageCount = sent + received;\n row.firstContactAt = first === null ? null : new Date(first);\n row.lastContactAt = last === null ? null : new Date(last);\n row.displayName = name || row.displayName;\n await row.save();\n result.upserted += 1;\n }\n });\n return result;\n }\n\n private async ownAddresses(accountIds: string[]): Promise<string[]> {\n const { EmailAccountCollection } = await import(\n '../collections/EmailAccountCollection.js'\n );\n const accounts = await EmailAccountCollection.create({\n db: this.options.db,\n });\n const out: string[] = [];\n for (const id of accountIds) {\n const account = (await accounts.get({\n id,\n tenantId: this.options.tenantId,\n })) as EmailAccount | null;\n const addr = normalizeCorrespondentAddress(account?.email);\n if (addr) out.push(addr);\n }\n return out;\n }\n\n /** The owner's correspondents, as seen through the readable accounts. */\n private async visible(): Promise<CorrespondentView[]> {\n const owner = this.actingOwner;\n if (!owner) return [];\n const readable = await this.readableIds();\n if (!readable.size) return [];\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const rows = (await (\n await this.rows()\n ).list({\n where: { tenantId: this.options.tenantId, ownerUserId: owner },\n orderBy: ['lastContactAt DESC', 'id ASC'],\n limit: 100000,\n })) as Correspondent[];\n const views: CorrespondentView[] = [];\n for (const r of rows) {\n const v = viewOf(r, readable);\n if (v?.accountIds.length) views.push(v);\n }\n return views.sort(\n (a, b) =>\n (b.lastContactAt?.getTime() ?? 0) -\n (a.lastContactAt?.getTime() ?? 0) ||\n a.address.localeCompare(b.address),\n );\n });\n }\n\n async list(options: ListCorrespondentsOptions = {}): Promise<{\n correspondents: CorrespondentView[];\n nextCursor: string | null;\n }> {\n const requested = Number.isFinite(options.limit)\n ? Math.trunc(options.limit as number)\n : DEFAULT_LIMIT;\n const limit = Math.min(Math.max(requested, 1), MAX_LIMIT);\n const start = options.cursor ? Number(options.cursor) : 0;\n if (!Number.isInteger(start) || start < 0) {\n throw new Error('Invalid correspondent cursor.');\n }\n const q = options.query?.trim().toLowerCase();\n const all = (await this.visible()).filter(\n (r) =>\n !q || r.address.includes(q) || r.displayName.toLowerCase().includes(q),\n );\n return {\n correspondents: all.slice(start, start + limit),\n nextCursor: start + limit < all.length ? String(start + limit) : null,\n };\n }\n\n /**\n * Recipient autocomplete: correspondents whose address or name starts with\n * (or, for names, has a word starting with) `prefix`, best first.\n */\n async suggest(prefix: string, limit = 8): Promise<CorrespondentView[]> {\n const p = prefix.trim().toLowerCase();\n if (!p) return [];\n const cap = Math.min(Math.max(Math.trunc(limit) || 1, 1), SUGGEST_MAX);\n const scored: Array<{ view: CorrespondentView; rank: number }> = [];\n for (const view of await this.visible()) {\n const name = view.displayName.toLowerCase();\n let rank = -1;\n if (view.address.startsWith(p)) rank = 0;\n else if (name.startsWith(p)) rank = 1;\n else if (name.split(/\\s+/).some((w) => w.startsWith(p))) rank = 2;\n else if (view.address.includes(p)) rank = 3;\n if (rank >= 0) scored.push({ view, rank });\n }\n scored.sort(\n (a, b) =>\n a.rank - b.rank ||\n b.view.messageCount - a.view.messageCount ||\n a.view.address.localeCompare(b.view.address),\n );\n return scored.slice(0, cap).map((s) => s.view);\n }\n\n private async owned(\n id: string,\n ): Promise<{ row: Correspondent; view: CorrespondentView } | null> {\n const owner = this.actingOwner;\n if (!owner) return null;\n const readable = await this.readableIds();\n if (!readable.size) return null;\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const found = (\n (await (\n await this.rows()\n ).list({\n where: { tenantId: this.options.tenantId, ownerUserId: owner, id },\n limit: 1,\n })) as Correspondent[]\n )[0];\n if (!found) return null;\n const view = viewOf(found, readable);\n return view ? { row: found, view } : null;\n });\n }\n\n async get(id: string): Promise<CorrespondentView | null> {\n return (await this.owned(id))?.view ?? null;\n }\n\n private assertMayWrite(): void {\n if (this.delegated && !this.options.allowDelegated) {\n throw new Error('Correspondents are private to their owner.');\n }\n }\n\n /** Link a correspondent to a `Profile` of this tenant (owner's choice). */\n async linkProfile(id: string, profileId: string): Promise<CorrespondentView> {\n this.assertMayWrite();\n const hit = await this.owned(id);\n if (!hit) throw new Error('Correspondent not found.');\n const profile = await readNotificationProfile(\n this.options.db as never,\n this.options.tenantId,\n profileId,\n );\n if (\n !profile ||\n (profile.tenantId && profile.tenantId !== this.options.tenantId)\n ) {\n throw new Error('Profile not found.');\n }\n hit.row.profileId = profileId;\n await withTenant({ tenantId: this.options.tenantId }, () => hit.row.save());\n return { ...hit.view, profileId };\n }\n\n async unlinkProfile(id: string): Promise<CorrespondentView> {\n this.assertMayWrite();\n const hit = await this.owned(id);\n if (!hit) throw new Error('Correspondent not found.');\n hit.row.profileId = null;\n await withTenant({ tenantId: this.options.tenantId }, () => hit.row.save());\n return { ...hit.view, profileId: null };\n }\n}\n","import {\n isUniqueViolationError,\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { NotificationOptOutCollection } from '../collections/NotificationOptOutCollection.js';\nimport { withTenant } from '../host.js';\nimport {\n NOTIFICATION_DELIVERY_CHANNELS,\n type NotificationDeliveryChannel,\n} from '../models/NotificationDelivery.js';\nimport {\n isValidNotificationOptOutScope,\n NOTIFICATION_OPT_OUT_ALL_SCOPE,\n NotificationOptOut,\n} from '../models/NotificationOptOut.js';\nimport type { NotificationSuppressionRequest } from './NotificationOutboxService.js';\n\n/** The signed-in person making a request, as the host authenticated them. */\nexport interface NotificationOptOutPrincipal {\n userId: string;\n /**\n * The tenant the principal is authenticated in. Required and must equal the\n * request's tenant: a principal never acts in another tenant. A host whose\n * recipient is authenticated elsewhere (e.g. a member of a child tenant)\n * authorizes the recipient itself and makes a trusted call without a\n * principal instead.\n */\n tenantId: string;\n}\n\nexport interface NotificationOptOutKey {\n tenantId: string;\n recipientUserId: string;\n channel: NotificationDeliveryChannel;\n /** `*` or a host key such as `project:<uuid>`. */\n scope: string;\n}\n\nexport interface NotificationOptOutChange extends NotificationOptOutKey {\n /**\n * The signed-in person, authenticated in this tenant. When present only the\n * recipient themself may change the row, and only in the principal's own\n * tenant; when omitted the call is trusted host code that has already\n * authenticated the recipient (e.g. a signed unsubscribe link, or a host\n * route whose member belongs to a child tenant of the delivery tenant).\n */\n principal?: NotificationOptOutPrincipal;\n}\n\nexport interface NotificationOptOutListRequest {\n tenantId: string;\n recipientUserId: string;\n principal: NotificationOptOutPrincipal;\n}\n\nexport type NotificationOptOutDenialReason = 'principal' | 'tenant';\n\n/** Thrown when a principal tries to read or change another person's opt-out. */\nexport class NotificationOptOutDeniedError extends Error {\n constructor(\n readonly reason: NotificationOptOutDenialReason,\n message: string,\n ) {\n super(message);\n this.name = 'NotificationOptOutDeniedError';\n }\n}\n\nfunction requireText(value: string | undefined, name: string): string {\n const text = typeof value === 'string' ? value.trim() : '';\n if (!text) throw new Error(`A notification opt-out ${name} is required.`);\n return text;\n}\n\nfunction validate(key: NotificationOptOutKey): NotificationOptOutKey {\n const channel = key.channel;\n if (!NOTIFICATION_DELIVERY_CHANNELS.includes(channel)) {\n throw new Error(`Unknown notification channel '${String(channel)}'.`);\n }\n if (!isValidNotificationOptOutScope(key.scope)) {\n throw new Error(\n `Invalid notification opt-out scope '${String(key.scope)}': use '*' or a key like 'project:<id>'.`,\n );\n }\n return {\n tenantId: requireText(key.tenantId, 'tenant'),\n recipientUserId: requireText(key.recipientUserId, 'recipient'),\n channel,\n scope: key.scope,\n };\n}\n\nfunction authorize(\n principal: NotificationOptOutPrincipal | undefined,\n tenantId: string,\n recipientUserId: string,\n): string {\n if (!principal) return 'system';\n if (!principal.tenantId || principal.tenantId !== tenantId) {\n throw new NotificationOptOutDeniedError(\n 'tenant',\n 'Principal does not belong to this tenant.',\n );\n }\n if (!principal.userId || principal.userId !== recipientUserId) {\n throw new NotificationOptOutDeniedError(\n 'principal',\n 'Only the recipient may change or list their notification opt-outs.',\n );\n }\n return principal.userId;\n}\n\n/**\n * The per-recipient opt-out ledger behind the outbox's `isSuppressed` hook.\n *\n * Writes are idempotent and, with a `principal`, limited to the recipient's\n * own rows. {@link isOptedOut} is a trusted read for suppression: it runs\n * where the recipient is not the caller (a manager enqueues, a worker\n * dispatches) and is always scoped to the given tenant.\n */\nexport class NotificationOptOutService {\n constructor(private readonly options: { db: SmrtClassOptions['db'] }) {}\n\n private collection(): Promise<NotificationOptOutCollection> {\n return NotificationOptOutCollection.create({ db: this.options.db });\n }\n\n /** Opt the recipient out of `scope`; a repeat leaves the row untouched. */\n async optOut(change: NotificationOptOutChange): Promise<NotificationOptOut> {\n return this.change(change, true);\n }\n\n /** Clear an opt-out; a repeat, or no row at all, is a no-op. */\n async optIn(change: NotificationOptOutChange): Promise<NotificationOptOut> {\n return this.change(change, false);\n }\n\n /**\n * Whether the recipient has opted out of `scope` (a `*` row matches every\n * scope). Trusted read: no principal, always under the tenant's scope.\n */\n async isOptedOut(key: NotificationOptOutKey): Promise<boolean> {\n const { tenantId, recipientUserId, channel, scope } = validate(key);\n const scopes =\n scope === NOTIFICATION_OPT_OUT_ALL_SCOPE\n ? [scope]\n : [scope, NOTIFICATION_OPT_OUT_ALL_SCOPE];\n return withTenant({ tenantId }, async () => {\n const rows = await (await this.collection()).list({\n where: { tenantId, recipientUserId, channel, 'scope in': scopes },\n });\n return rows.some((row) => row.optedOutAt !== null);\n });\n }\n\n /** The recipient's own active opt-outs, in one tenant. */\n async listForRecipient(\n request: NotificationOptOutListRequest,\n ): Promise<NotificationOptOut[]> {\n const tenantId = requireText(request.tenantId, 'tenant');\n const recipientUserId = requireText(request.recipientUserId, 'recipient');\n if (!request.principal) {\n throw new NotificationOptOutDeniedError(\n 'principal',\n 'A principal is required to list opt-outs.',\n );\n }\n authorize(request.principal, tenantId, recipientUserId);\n return withTenant({ tenantId }, async () => {\n const rows = await (await this.collection()).list({\n where: { tenantId, recipientUserId },\n orderBy: 'scope ASC',\n });\n return rows.filter((row) => row.optedOutAt !== null);\n });\n }\n\n private async change(\n change: NotificationOptOutChange,\n optedOut: boolean,\n ): Promise<NotificationOptOut> {\n const key = validate(change);\n const updatedBy = authorize(\n change.principal,\n key.tenantId,\n key.recipientUserId,\n );\n const { tenantId, recipientUserId, channel, scope } = key;\n\n return withTenant({ tenantId }, async () => {\n const rows = await this.collection();\n const find = async () =>\n (\n await rows.list({\n where: { tenantId, recipientUserId, channel, scope },\n limit: 1,\n })\n )[0];\n\n const apply = async (row: NotificationOptOut) => {\n if (row.isOptedOut === optedOut) return row; // already in that state\n row.optedOutAt = optedOut ? new Date() : null;\n row.updatedBy = updatedBy;\n await row.save();\n return row;\n };\n\n const existing = await find();\n if (existing) return apply(existing);\n if (!optedOut) {\n // Nothing to clear; return an unsaved, opted-in view of the key.\n return new (ObjectRegistry.resolveEffectiveConstructor(\n NotificationOptOut,\n ))({\n tenantId,\n recipientUserId,\n channel,\n scope,\n optedOutAt: null,\n updatedBy,\n });\n }\n try {\n return await rows.create({\n _insertOnly: true,\n tenantId,\n recipientUserId,\n channel,\n scope,\n optedOutAt: new Date(),\n updatedBy,\n });\n } catch (error) {\n if (!isUniqueViolationError(error)) throw error;\n const winner = await find();\n if (!winner) throw error;\n return apply(winner);\n }\n });\n }\n}\n\n/**\n * Build an `isSuppressed` function for `NotificationOutboxOptions` from the\n * ledger. `scopeOf` maps a notification to the scope a recipient can opt out\n * of (e.g. `project:<uuid>` from its `sourceRef`), or null when the\n * notification is not opt-out-able. A `*` opt-out suppresses any notification\n * `scopeOf` maps to a scope; returning `'*'` checks only the tenant-wide row.\n */\nexport function optOutSuppression(\n service: Pick<NotificationOptOutService, 'isOptedOut'>,\n scopeOf: (\n request: NotificationSuppressionRequest,\n ) => string | null | Promise<string | null>,\n): (request: NotificationSuppressionRequest) => Promise<boolean> {\n return async (request) => {\n const scope = await scopeOf(request);\n if (scope === null || scope === undefined) return false;\n return service.isOptedOut({\n tenantId: request.tenantId,\n recipientUserId: request.recipientUserId,\n channel: request.channel,\n scope,\n });\n };\n}\n","import { detectEngine } from '@happyvertical/smrt-core';\n/** Explicit maintenance migration for typed email contact identities. No runtime DDL. */\nimport type { DatabaseInterface } from '@happyvertical/smrt-core/migrations';\nimport {\n assertNotificationMaintenanceHost,\n buildSqliteRebuildStatements,\n} from '../host.js';\n\nexport type NotificationProfileRecipientEngine = 'postgres' | 'sqlite';\nexport interface NotificationProfileRecipientPlan {\n engine: NotificationProfileRecipientEngine;\n ready: boolean;\n statements: string[];\n invalidRowIds: string[];\n obsoleteIndexes: string[];\n}\nconst table = 'notification_deliveries';\nconst checkName = 'notification_deliveries_recipient_identity_check';\nconst userIndex = 'notification_deliveries_user_identity';\nconst profileIndex = 'notification_deliveries_profile_identity';\nconst typedIndex = 'notification_deliveries_typed_identity';\nconst identityCheck = `(recipient_kind IS NOT NULL AND ((recipient_kind = 'user' AND recipient_user_id IS NOT NULL AND length(trim(CAST(recipient_user_id AS TEXT))) > 0 AND recipient_profile_id IS NULL AND (required_dispatch_policy IS NULL OR required_dispatch_policy NOT LIKE 'profile:%') AND kind NOT LIKE 'protected:profile:%') OR (recipient_kind = 'profile' AND recipient_user_id IS NULL AND recipient_profile_id IS NOT NULL AND length(trim(CAST(recipient_profile_id AS TEXT))) > 0 AND channel = 'email' AND required_dispatch_policy IS NOT NULL AND length(trim(required_dispatch_policy)) > 8 AND required_dispatch_policy LIKE 'profile:%' AND kind = 'protected:' || required_dispatch_policy)))`;\n/** Canonical Boolean tree ignores PG's redundant parentheses/casts, preserving AND/OR precedence. */\nfunction canonicalCheck(sql: string): string {\n const value = sql\n .trim()\n .replace(/^CHECK\\s*/i, '')\n .replace(/::text\\b/gi, '')\n .replace(/!~~/g, ' NOT LIKE ')\n .replace(/~~/g, ' LIKE ')\n .replace(/CAST\\(\\s*([a-z_]+)\\s+AS\\s+TEXT\\s*\\)/gi, '$1')\n .replace(/TRIM\\(\\s*BOTH\\s+FROM\\s+/gi, 'trim(');\n function outer(text: string): string {\n text = text.trim();\n while (text.startsWith('(') && text.endsWith(')')) {\n let depth = 0,\n quoted = false,\n complete = true;\n for (let i = 0; i < text.length - 1; i++) {\n if (text[i] === \"'\") quoted = !quoted;\n if (quoted) continue;\n if (text[i] === '(') depth++;\n if (text[i] === ')' && --depth === 0) {\n complete = false;\n break;\n }\n }\n if (!complete) break;\n text = text.slice(1, -1).trim();\n }\n return text;\n }\n function parse(text: string): unknown {\n text = outer(text);\n for (const op of ['OR', 'AND']) {\n let depth = 0,\n quoted = false,\n start = 0;\n const terms: string[] = [];\n for (let i = 0; i < text.length; i++) {\n if (text[i] === \"'\") quoted = !quoted;\n if (quoted) continue;\n if (text[i] === '(') depth++;\n if (text[i] === ')') depth--;\n if (\n !depth &&\n text.slice(i).match(new RegExp('^' + op + '\\\\b', 'i')) &&\n (i === 0 || /\\s/.test(text[i - 1]))\n ) {\n terms.push(text.slice(start, i));\n start = i + op.length;\n i += op.length - 1;\n }\n }\n if (terms.length)\n return [op, ...[...terms, text.slice(start)].map(parse)];\n }\n return text.toLowerCase().replace(/[\\s()\"]/g, '');\n }\n return JSON.stringify(parse(value));\n}\nconst quote = (name: string) => {\n if (!/^[a-z_][a-z0-9_]*$/i.test(name))\n throw new Error('Unsafe notification schema identifier.');\n return `\"${name}\"`;\n};\nfunction indexColumns(sql: string): string[] {\n const match = /\\(([^()]+)\\)\\s*(?:NULLS\\s+NOT\\s+DISTINCT)?\\s*$/i.exec(sql);\n return match\n ? match[1].split(',').map((s) => s.trim().replaceAll('\"', ''))\n : [];\n}\nfunction same(a: string[], b: string[]) {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\nconst userColumns = ['tenant_id', 'recipient_user_id', 'channel', 'source_ref'];\nconst profileColumns = [\n 'tenant_id',\n 'recipient_profile_id',\n 'channel',\n 'source_ref',\n];\nconst typedColumns = [\n 'tenant_id',\n 'recipient_kind',\n 'recipient_user_id',\n 'recipient_profile_id',\n 'channel',\n 'source_ref',\n];\nasync function inspect(\n db: Pick<DatabaseInterface, 'query'>,\n engine: NotificationProfileRecipientEngine,\n) {\n if (engine !== 'sqlite' && engine !== 'postgres')\n throw new Error(\n 'Profile recipients require SQLite or PostgreSQL maintenance.',\n );\n const columns =\n engine === 'sqlite'\n ? ((await db.query(`PRAGMA table_info(${quote(table)})`)).rows as {\n name: string;\n notnull: number;\n }[])\n : ((\n await db.query(\n \"SELECT column_name AS name, CASE WHEN is_nullable='NO' THEN 1 ELSE 0 END AS notnull FROM information_schema.columns WHERE table_schema=current_schema() AND table_name=?\",\n table,\n )\n ).rows as { name: string; notnull: number }[]);\n if (!columns.length)\n throw new Error(\n 'Migrate the notification outbox table before profile recipient maintenance.',\n );\n const indexes =\n engine === 'sqlite'\n ? ((\n await db.query(\n \"SELECT name, sql FROM sqlite_master WHERE type='index' AND tbl_name=? AND sql IS NOT NULL\",\n table,\n )\n ).rows as { name: string; sql: string }[])\n : ((\n await db.query(\n 'SELECT indexname AS name, indexdef AS sql FROM pg_indexes WHERE schemaname=current_schema() AND tablename=?',\n table,\n )\n ).rows as { name: string; sql: string }[]);\n const ddl =\n engine === 'sqlite'\n ? String(\n (\n await db.query(\n \"SELECT sql FROM sqlite_master WHERE type='table' AND name=?\",\n table,\n )\n ).rows[0]?.sql ?? '',\n )\n : String(\n (\n await db.query(\n 'SELECT pg_get_constraintdef(oid) AS sql FROM pg_constraint WHERE conrelid=?::regclass AND conname=?',\n table,\n checkName,\n )\n ).rows[0]?.sql ?? '',\n );\n const obsolete = indexes.filter(\n (i) =>\n /NULLS\\s+NOT\\s+DISTINCT/i.test(i.sql) &&\n same(indexColumns(i.sql), userColumns),\n );\n const validIndex = (name: string, expected: string[]) =>\n indexes.some(\n (i) =>\n i.name === name &&\n /CREATE\\s+UNIQUE\\s+INDEX/i.test(i.sql) &&\n same(indexColumns(i.sql), expected) &&\n !(/NULLS\\s+NOT\\s+DISTINCT/i.test(i.sql) && name !== typedIndex),\n );\n const hasColumns = ['recipient_kind', 'recipient_profile_id'].every((name) =>\n columns.some((c) => c.name === name),\n );\n const hasCheck =\n engine === 'sqlite'\n ? ddl.includes(checkName) && ddl.includes(identityCheck)\n : !ddl.includes('NOT VALID') &&\n canonicalCheck(ddl) === canonicalCheck(identityCheck);\n const ready =\n hasColumns &&\n !Number(columns.find((c) => c.name === 'recipient_user_id')?.notnull) &&\n hasCheck &&\n !obsolete.length &&\n validIndex(userIndex, userColumns) &&\n validIndex(profileIndex, profileColumns) &&\n validIndex(typedIndex, typedColumns);\n return {\n columns,\n indexes,\n ddl,\n obsolete,\n ready,\n hasColumns,\n hasCheck,\n validIndex,\n };\n}\n/** Read-only plan against the live schema. Refuses ambiguous drift and never changes rows. */\nexport async function planNotificationProfileRecipients(\n db: Pick<DatabaseInterface, 'query'>,\n engine: NotificationProfileRecipientEngine,\n): Promise<NotificationProfileRecipientPlan> {\n assertNotificationMaintenanceHost();\n const state = await inspect(db, engine);\n const result: NotificationProfileRecipientPlan = {\n engine,\n ready: state.ready,\n statements: [],\n invalidRowIds: [],\n obsoleteIndexes: state.obsolete.map((i) => i.name),\n };\n if (state.ready) return result;\n const kind = state.columns.some((c) => c.name === 'recipient_kind')\n ? 'recipient_kind'\n : \"'user'\";\n const profile = state.columns.some((c) => c.name === 'recipient_profile_id')\n ? 'recipient_profile_id'\n : 'NULL';\n const rows = (\n await db.query(\n `SELECT id, tenant_id, recipient_user_id, ${kind} AS recipient_kind, ${profile} AS recipient_profile_id, channel, source_ref, kind, required_dispatch_policy FROM ${quote(table)}`,\n )\n ).rows;\n const identities = new Set<string>();\n for (const row of rows) {\n const user =\n row.recipient_kind === 'user' &&\n row.recipient_user_id != null &&\n String(row.recipient_user_id).trim() !== '' &&\n row.recipient_profile_id == null;\n const contact =\n row.recipient_kind === 'profile' &&\n row.recipient_user_id == null &&\n row.recipient_profile_id != null &&\n String(row.recipient_profile_id).trim() !== '' &&\n row.channel === 'email' &&\n typeof row.required_dispatch_policy === 'string' &&\n Boolean(row.required_dispatch_policy.trim()) &&\n row.kind === `protected:${row.required_dispatch_policy}`;\n const key = JSON.stringify([\n row.tenant_id,\n row.recipient_kind,\n row.recipient_user_id,\n row.recipient_profile_id,\n row.channel,\n row.source_ref,\n ]);\n if (!(user || contact) || identities.has(key))\n result.invalidRowIds.push(String(row.id));\n identities.add(key);\n }\n if (result.invalidRowIds.length) return result;\n for (const [name, columns] of [\n [userIndex, userColumns],\n [profileIndex, profileColumns],\n [typedIndex, typedColumns],\n ] as const) {\n const found = state.indexes.find((i) => i.name === name);\n if (found && !state.validIndex(name, [...columns]))\n throw new Error(`Unexpected notification index drift: ${name}`);\n }\n if (engine === 'postgres') {\n if (!state.columns.some((c) => c.name === 'recipient_kind'))\n result.statements.push(\n `ALTER TABLE ${quote(table)} ADD COLUMN recipient_kind TEXT NOT NULL DEFAULT 'user'`,\n );\n if (!state.columns.some((c) => c.name === 'recipient_profile_id'))\n result.statements.push(\n `ALTER TABLE ${quote(table)} ADD COLUMN recipient_profile_id UUID REFERENCES profiles(id)`,\n );\n result.statements.push(\n `ALTER TABLE ${quote(table)} ALTER COLUMN recipient_user_id DROP NOT NULL`,\n );\n if (!state.hasCheck) {\n if (state.ddl)\n throw new Error('Unexpected notification identity CHECK drift.');\n result.statements.push(\n `ALTER TABLE ${quote(table)} ADD CONSTRAINT ${quote(checkName)} CHECK ${identityCheck}`,\n );\n }\n for (const index of state.obsolete)\n result.statements.push(`DROP INDEX ${quote(index.name)}`);\n } else if (\n !state.hasColumns ||\n Number(\n state.columns.find((c) => c.name === 'recipient_user_id')?.notnull,\n ) ||\n !state.hasCheck\n ) {\n // The core planner owns live-DDL preservation and rowid/index/trigger copying.\n const incoming = (\n await db.query(\n \"SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite\\\\_%' ESCAPE '\\\\' AND name<>?\",\n table,\n )\n ).rows;\n for (const row of incoming) {\n const refs = (\n await db.query(`PRAGMA foreign_key_list(${quote(String(row.name))})`)\n ).rows;\n if (refs.some((r) => r.table === table))\n throw new Error(\n 'SQLite profile maintenance requires an explicit inbound-FK-safe migration window.',\n );\n }\n if (!/\\)\\s*;?\\s*$/.test(state.ddl))\n throw new Error('Unsupported SQLite notification table shape.');\n if (state.ddl.includes(checkName) && !state.hasCheck)\n throw new Error('Unexpected notification identity CHECK drift.');\n const ddl = state.hasCheck\n ? state.ddl\n : state.ddl.replace(\n /\\)\\s*;?\\s*$/,\n `, CONSTRAINT ${quote(checkName)} CHECK ${identityCheck})`,\n );\n const triggers = (\n await db.query(\n \"SELECT name,sql FROM sqlite_master WHERE type='trigger' AND tbl_name=?\",\n table,\n )\n ).rows as { name: string; sql: string }[];\n const plan = buildSqliteRebuildStatements({\n tableName: table,\n createTableSql: ddl,\n columnTypes: new Map(),\n columns: state.columns.map((c) => c.name),\n objects: [...state.indexes, ...triggers],\n legacyAlterTable: Boolean(\n (await db.query('PRAGMA legacy_alter_table')).rows[0]\n ?.legacy_alter_table,\n ),\n // Checked above: no other table references this one, so the plan needs\n // no guard against a cascade (#4937).\n inboundReferences: [],\n nullableColumns: new Set(\n Number(\n state.columns.find((c) => c.name === 'recipient_user_id')?.notnull,\n )\n ? ['recipient_user_id']\n : [],\n ),\n appendColumns: [\n ...(!state.columns.some((c) => c.name === 'recipient_kind')\n ? [\n {\n name: 'recipient_kind',\n definition: \"recipient_kind TEXT NOT NULL DEFAULT 'user'\",\n copyExpression: \"'user'\",\n },\n ]\n : []),\n ...(!state.columns.some((c) => c.name === 'recipient_profile_id')\n ? [\n {\n name: 'recipient_profile_id',\n definition: 'recipient_profile_id UUID REFERENCES profiles(id)',\n copyExpression: 'NULL',\n },\n ]\n : []),\n ],\n });\n if (!plan)\n throw new Error(\n 'SQLite profile identity rebuild requires manual schema reconciliation.',\n );\n if (plan.statements.some((s) => /PRAGMA foreign_keys\\s*=\\s*OFF/i.test(s)))\n throw new Error(\n 'SQLite profile maintenance cannot disable foreign keys.',\n );\n result.statements.push(...plan.statements);\n }\n for (const [name, columns] of [\n [userIndex, userColumns],\n [profileIndex, profileColumns],\n [typedIndex, typedColumns],\n ] as const)\n if (!state.validIndex(name, [...columns]))\n result.statements.push(\n `CREATE UNIQUE INDEX ${quote(name)} ON ${quote(table)} (${columns.map(quote).join(', ')})${engine === 'postgres' && name === typedIndex ? ' NULLS NOT DISTINCT' : ''}`,\n );\n return result;\n}\n/** Apply/replay atomically using a root maintenance handle. No row IDs or evidence are rewritten. */\nexport async function migrateNotificationProfileRecipients(\n db: DatabaseInterface,\n engine: NotificationProfileRecipientEngine,\n): Promise<NotificationProfileRecipientPlan> {\n assertNotificationMaintenanceHost();\n if (!db.transaction)\n throw new Error('Notification profile migration requires transactions.');\n let result: NotificationProfileRecipientPlan | undefined;\n await db.transaction(async (tx) => {\n if (engine === 'postgres')\n await tx.query(`LOCK TABLE ${quote(table)} IN ACCESS EXCLUSIVE MODE`);\n const plan = await planNotificationProfileRecipients(tx, engine);\n if (plan.invalidRowIds.length)\n throw new Error(\n `Invalid notification recipient rows: ${plan.invalidRowIds.join(', ')}`,\n );\n for (const statement of plan.statements) await tx.query(statement);\n const verified = await planNotificationProfileRecipients(tx, engine);\n if (!verified.ready)\n throw new Error(\n 'Notification profile schema did not reach verified constraints.',\n );\n result = plan;\n });\n if (!result)\n throw new Error(\n 'Notification profile migration transaction did not execute.',\n );\n return result;\n}\n/** Profile-only runtime admission gate checks physical constraints/indexes, never a migration marker. */\nexport async function assertNotificationProfileRecipientSchema(\n db: Pick<DatabaseInterface, 'query' | 'url'>,\n): Promise<void> {\n const hint: unknown = Reflect.get(db, 'type');\n const engine = detectEngine(\n db.url,\n typeof hint === 'string' ? hint : undefined,\n );\n if (engine !== 'sqlite' && engine !== 'postgres')\n throw new Error(\n 'Profile recipients require explicit supported schema maintenance.',\n );\n if (!(await inspect(db, engine)).ready)\n throw new Error('Profile recipient schema maintenance is required.');\n}\n","import {\n isUniqueViolationError,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { decideMailAccess, runWithMailSystemAccess } from '../access.js';\nimport { AccountCollection } from '../collections/AccountCollection.js';\nimport { EmailCollection } from '../collections/EmailCollection.js';\nimport { MessageCollection } from '../collections/MessageCollection.js';\nimport { NotificationDeliveryCollection } from '../collections/NotificationDeliveryCollection.js';\nimport {\n normalizeIdentityEmail,\n readNotificationProfile,\n withSystemContext,\n withTenant,\n} from '../host.js';\nimport { assertNotificationProfileRecipientSchema } from '../migrations/profileRecipients.js';\nimport { EmailAccount } from '../models/EmailAccount.js';\nimport type { Message } from '../models/Message.js';\nimport type {\n NotificationDelivery,\n NotificationDeliveryChannel,\n NotificationDeliveryTransition,\n} from '../models/NotificationDelivery.js';\nimport { assertNotificationRecipientIdentity } from '../notification-recipient-identity.js';\nimport {\n assertMessagingPermission,\n type MessagingPrincipal,\n SEND_MESSAGES_PERMISSION,\n} from '../permissions.js';\nimport {\n ProtectedNotificationHandoffError,\n protectedNotificationMetadata,\n withProtectedNotificationHandoff,\n} from '../protected-notification-handoff.js';\nimport type { SendEmailAttachment, SendEmailOptions } from '../types.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Transport seam\n// ─────────────────────────────────────────────────────────────────────────\n\n/** What a transport knows about one provider handoff. */\nexport type NotificationTransportOutcome =\n | { status: 'accepted'; providerMessageId?: string }\n | { status: 'rejected'; error: string; retryable: boolean }\n | { status: 'unknown'; error: string };\n\n/** What a transport can say about an earlier handoff during recovery. */\nexport type NotificationTransportReconciliation =\n | NotificationTransportOutcome\n | { status: 'not-sent' };\n\nexport interface NotificationTransportRequest {\n delivery: NotificationDelivery;\n /** The delivery's single outbound message (an `Email` for `email`). */\n message: Message;\n /** Stable per delivery; pass it to providers that dedupe on a key. */\n idempotencyKey: string;\n /** Host-authorized send-time bytes; never file paths or remote URLs. */\n attachments?: SendEmailAttachment[];\n}\n\n/**\n * Hands one outbound message to a provider. The default\n * ({@link messageSendTransport}) delivers through `Message.send()` and the\n * message's account sender; tests and hosts with their own provider inject\n * another.\n */\nexport interface NotificationTransport {\n readonly name: string;\n /**\n * True only when the provider deduplicates on `idempotencyKey`, so sending\n * again after an unknown outcome cannot deliver twice. Then an unknown\n * outcome is retried; otherwise it becomes `uncertain`.\n */\n readonly idempotent?: boolean;\n send(\n request: NotificationTransportRequest,\n ): Promise<NotificationTransportOutcome>;\n /**\n * After a crash or lease loss following a handoff, report what is known\n * from durable state. Omit when nothing can be known (outcome: uncertain).\n */\n reconcile?(\n request: NotificationTransportRequest,\n ): Promise<NotificationTransportReconciliation>;\n}\n\n/**\n * Delivers through the canonical `Message.send()` (account → provider sender)\n * and reconciles from the message's own `sendStatus`.\n *\n * SMTP and the SDK email providers take no idempotency key, so this\n * transport is not idempotent: a handoff whose outcome is lost stays\n * `uncertain` instead of risking a second email.\n */\nexport const messageSendTransport: NotificationTransport = {\n name: 'message-send',\n idempotent: false,\n async send({ message, attachments }) {\n const options: SendEmailOptions | undefined = attachments\n ? { attachments }\n : undefined;\n const result = await message.send(options);\n if (result.success) {\n return {\n status: 'accepted',\n ...(result.providerMessageId\n ? { providerMessageId: result.providerMessageId }\n : {}),\n };\n }\n // The provider may have taken it (a dropped connection or a thrown\n // sender), or send() refused because its own claim on the message\n // failed and another sender may be mid-flight: never retry blindly.\n if (\n result.outcomeUnknown ||\n message.sendStatus === 'sending' ||\n message.sendStatus === 'sent'\n ) {\n return {\n status: 'unknown',\n error: result.error ?? 'The provider did not confirm the outcome.',\n };\n }\n return {\n status: 'rejected',\n error: result.error ?? 'Send failed',\n retryable: true,\n };\n },\n async reconcile({ message }) {\n const messages = await MessageCollection.create({ db: message.db });\n const stored = message.id ? await messages.get({ id: message.id }) : null;\n switch (stored?.sendStatus) {\n case 'sent':\n return { status: 'accepted' };\n case 'failed':\n if (stored.isSendOutcomeUnknown()) {\n return {\n status: 'unknown',\n error:\n stored.sendError || 'The provider did not confirm the outcome.',\n };\n }\n return {\n status: 'rejected',\n error: stored.sendError || 'Send failed',\n retryable: true,\n };\n case 'draft':\n case 'pending':\n case 'scheduled':\n return { status: 'not-sent' };\n default:\n return {\n status: 'unknown',\n error: 'The provider handoff did not record an outcome.',\n };\n }\n },\n};\n\n// ─────────────────────────────────────────────────────────────────────────\n// Service contract\n// ─────────────────────────────────────────────────────────────────────────\n\nexport type NotificationOutboxDenialReason =\n | 'permission'\n | 'recipient'\n | 'sender'\n | 'link';\n\n/** Thrown when the host's policy refuses an enqueue; nothing is stored. */\nexport class NotificationOutboxDeniedError extends Error {\n constructor(\n readonly reason: NotificationOutboxDenialReason,\n message: string,\n ) {\n super(message);\n this.name = 'NotificationOutboxDeniedError';\n }\n}\n\nexport interface NotificationRecipientRequest {\n tenantId: string;\n recipientUserId: string;\n channel: NotificationDeliveryChannel;\n}\n\nexport interface NotificationProfileRecipientRequest {\n tenantId: string;\n recipientProfileId: string;\n channel: 'email';\n}\n\nexport interface NotificationRecipient {\n address: string;\n name?: string;\n}\n\nexport interface NotificationSuppressionRequest\n extends NotificationRecipientRequest {\n kind: string;\n sourceRef: string;\n}\nexport interface NotificationProfileSuppressionRequest\n extends NotificationProfileRecipientRequest {\n kind: string;\n sourceRef: string;\n}\n\nexport interface NotificationOutboxOptions {\n db: SmrtClassOptions['db'];\n /**\n * Host authorization for recipients: the address of `recipientUserId` when\n * the host allows notifying them in `tenantId` (e.g. a member of that\n * tenant), otherwise null, which denies the enqueue. Callers never supply\n * an address.\n */\n resolveRecipient(\n request: NotificationRecipientRequest,\n ): Promise<NotificationRecipient | null> | NotificationRecipient | null;\n /** Resource-aware authorization for a current tenant-owned external contact. No address input. */\n resolveProfileRecipient?(\n request: NotificationProfileRecipientRequest,\n ): Promise<NotificationRecipient | null> | NotificationRecipient | null;\n /** The sending `EmailAccount` id for a tenant (deployment setup). */\n resolveSenderAccountId(request: {\n tenantId: string;\n }): Promise<string | null> | string | null;\n /** Absolute http(s) URL deep links are built on, e.g. `https://app.example.com`. */\n linkBaseUrl: string;\n /** Optional opt-out hook, checked at enqueue and again before handoff. */\n isSuppressed?(\n request: NotificationSuppressionRequest,\n ): Promise<boolean> | boolean;\n /** External contacts have their own opt-out policy; never infer a User preference or fabricate a User ID. */\n isProfileSuppressed?(\n request: NotificationProfileSuppressionRequest,\n ): Promise<boolean> | boolean;\n /** Provider seam; defaults to {@link messageSendTransport}. */\n transport?: NotificationTransport;\n /**\n * Resolve and authorize current immutable document bytes before each fresh\n * provider handoff. A failure is a pre-handoff rejection, never a silent\n * attachment omission. Reconciliation does not need document access.\n */\n resolveAttachments?(\n request: NotificationTransportRequest,\n ): Promise<SendEmailAttachment[]> | SendEmailAttachment[];\n /** Trusted server map. Protected rows cannot be dispatched without their exact policy. */\n dispatchPolicies?: Readonly<\n Record<\n string,\n {\n resolveAttachments(\n request: NotificationTransportRequest,\n ): Promise<SendEmailAttachment[]> | SendEmailAttachment[];\n }\n >\n >;\n /**\n * When set, enqueue, dispatch and reconcile require `messages.send` in the tenant.\n * Omit only for trusted system code that performs its own authorization.\n */\n principal?: MessagingPrincipal;\n /** Lease length; must exceed the slowest provider handoff (default 5 min). */\n leaseMs?: number;\n /** Lease budget per delivery (default 5). */\n maxAttempts?: number;\n /** Delay before attempt `n + 1` after `n` failed (default 1 min · 2ⁿ⁻¹, ≤ 1 h). */\n retryDelayMs?(attempts: number): number;\n /** Clock (tests). */\n now?(): Date;\n}\n\nexport interface NotificationEmailInput {\n tenantId: string;\n /** Exactly one recipient reference is required. Existing User calls remain unchanged. */\n recipientUserId?: string;\n /** External contact; requires email, a trusted protected policy and explicit schema maintenance. */\n recipientProfileId?: string;\n /** Idempotency key for the event, e.g. `project-question:<id>:asked`. */\n sourceRef: string;\n /** Host-defined type, e.g. `project-question.asked`. */\n kind: string;\n /** One line; CR/LF are rejected. */\n subject: string;\n /** Plain-text body; the deep link is appended on its own line. */\n text: string;\n /** Host-relative path of the deep link (`/portal/...`). */\n path: string;\n /** Do not send before this time (default: now). */\n notBefore?: Date;\n /** Required trusted server policy; cannot be downgraded after enqueue. */\n requiredDispatchPolicy?: string;\n /** Host-approved immutable resource/version/digest and destination binding. */\n dispatchPolicyBinding?: Record<string, unknown>;\n}\n\nexport interface NotificationEnqueueResult {\n delivery: NotificationDelivery;\n /** False when `sourceRef` matched an existing delivery (returned untouched). */\n created: boolean;\n}\n\nexport type NotificationDispatchOutcome =\n | 'sent'\n | 'retry-scheduled'\n | 'failed'\n | 'uncertain'\n | 'cancelled'\n | 'blocked'\n | 'lease-lost';\n\nexport interface NotificationDispatchReport {\n /** Rows this call won a lease on. */\n leased: number;\n outcomes: Array<{\n deliveryId: string;\n tenantId: string;\n outcome: NotificationDispatchOutcome;\n }>;\n}\n\nexport interface NotificationDispatchOptions {\n /** Tenants to dispatch; omit to discover due rows across all tenants. */\n tenantIds?: readonly string[];\n /** Exact delivery selection, applied before query limits and lease acquisition. Empty selects none. */\n deliveryIds?: readonly string[];\n /** Maximum rows to lease in this call (default 25, max 200). */\n limit?: number;\n}\n\nexport type NotificationReconcileOutcome = 'sent' | 'retry' | 'failed';\n\n/** Delivery ids are uuids; anything else can match no row. */\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst DEFAULT_LEASE_MS = 5 * 60_000;\nconst DEFAULT_MAX_ATTEMPTS = 5;\nconst DEFAULT_LIMIT = 25;\nconst MAX_LIMIT = 200;\n\nfunction defaultRetryDelayMs(attempts: number): number {\n return Math.min(60_000 * 2 ** Math.max(0, attempts - 1), 60 * 60_000);\n}\n\nfunction requireText(value: string | undefined, name: string): string {\n const text = value?.trim();\n if (!text) throw new Error(`A notification ${name} is required.`);\n return text;\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * The id of a delivery's one outbound message: a name-based uuid derived from\n * the delivery id, so every dispatcher computes the same identity.\n */\nexport async function notificationDeliveryMessageId(\n deliveryId: string,\n): Promise<string> {\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(\n `smrt-messages:notification-delivery:${deliveryId}`,\n ),\n );\n const bytes = new Uint8Array(digest).slice(0, 16);\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50; // version 5 (name-based)\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; // RFC 4122 variant\n const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map((group) => group.join(''))\n .join('-');\n}\n\n/** The correlation id that ties a delivery to its one outbound message. */\nexport function notificationDeliveryCorrelationId(deliveryId: string): string {\n return `notification-delivery:${deliveryId}`;\n}\n\n/**\n * Build an absolute deep link from a host-relative `path` on `baseUrl`.\n *\n * The link always stays on the configured origin (no `//host`, backslash, or\n * scheme tricks) and never carries credentials: the destination is an\n * ordinary authenticated route, so the recipient signs in as themselves.\n */\nexport function buildNotificationLink(baseUrl: string, path: string): string {\n let base: URL;\n try {\n base = new URL(baseUrl);\n } catch {\n throw new Error('Notification link base URL must be an absolute URL.');\n }\n if (base.protocol !== 'https:' && base.protocol !== 'http:') {\n throw new Error('Notification link base URL must use http or https.');\n }\n if (base.username || base.password || base.search || base.hash) {\n throw new Error(\n 'Notification link base URL must not carry credentials, a query, or a fragment.',\n );\n }\n if (\n typeof path !== 'string' ||\n !path.startsWith('/') ||\n path.startsWith('//') ||\n /[\\\\\\s]/u.test(path) ||\n // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting them is the point\n /[\\u0000-\\u001f\\u007f]/u.test(path)\n ) {\n throw new NotificationOutboxDeniedError(\n 'link',\n 'Notification links must be a host-relative path such as /inbox/123.',\n );\n }\n const prefix = base.pathname.replace(/\\/+$/u, '');\n const link = new URL(`${prefix}${path}`, base.origin);\n if (link.origin !== base.origin) {\n throw new NotificationOutboxDeniedError(\n 'link',\n 'Notification links must stay on the configured origin.',\n );\n }\n return link.toString();\n}\n\n/**\n * Source-keyed, durable notification email outbox.\n *\n * `enqueueEmail()` stores one `NotificationDelivery` per\n * `(tenant, recipient, email, sourceRef)` — a repeated event returns the\n * existing row — after the host has authorized the recipient and sender.\n * `dispatchDue()` leases due rows with a compare-and-set, creates the single\n * outbound `Email` under the lease, hands it to the transport, and records\n * the outcome; it is safe to run from several workers at once and to crash\n * at any point. See `packages/messages/agents/notification-outbox.md`.\n */\nexport class NotificationOutboxService {\n /** Additive dispatch contracts hosts can require before activating a sender. */\n static readonly capabilities = Object.freeze({\n deliverySelection: true,\n attachments: true,\n requiredPolicy: true,\n protectedCanonicalSend: true,\n profileRecipients: true,\n } as const);\n private readonly transport: NotificationTransport;\n private readonly leaseMs: number;\n private readonly maxAttempts: number;\n private readonly retryDelayMs: (attempts: number) => number;\n private readonly now: () => Date;\n\n constructor(private readonly options: NotificationOutboxOptions) {\n // Validate the configured origin eagerly so a bad deployment fails at boot.\n buildNotificationLink(options.linkBaseUrl, '/');\n this.transport = options.transport ?? messageSendTransport;\n this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;\n this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n this.retryDelayMs = options.retryDelayMs ?? defaultRetryDelayMs;\n this.now = options.now ?? (() => new Date());\n if (!Number.isInteger(this.leaseMs) || this.leaseMs < 1_000) {\n throw new Error('Notification lease must be at least 1000 ms.');\n }\n if (!Number.isInteger(this.maxAttempts) || this.maxAttempts < 1) {\n throw new Error('Notification maxAttempts must be a positive integer.');\n }\n }\n\n private collection(): Promise<NotificationDeliveryCollection> {\n return NotificationDeliveryCollection.create({ db: this.options.db });\n }\n\n private authorize(tenantId: string): void {\n if (!this.options.principal) return;\n try {\n assertMessagingPermission(\n this.options.principal,\n tenantId,\n SEND_MESSAGES_PERMISSION,\n );\n } catch (error) {\n throw new NotificationOutboxDeniedError('permission', errorText(error));\n }\n }\n\n /** Store one email delivery for the event unless `sourceRef` already has one. */\n async enqueueEmail(\n input: NotificationEmailInput,\n ): Promise<NotificationEnqueueResult> {\n const tenantId = requireText(input.tenantId, 'tenant');\n if (\n input.kind?.startsWith('protected:') &&\n input.kind !== `protected:${input.requiredDispatchPolicy}`\n )\n throw new Error(\n 'Protected notification kinds require their exact dispatch policy.',\n );\n const requiredDispatchPolicy =\n input.requiredDispatchPolicy === undefined\n ? ''\n : requireText(input.requiredDispatchPolicy, 'dispatch policy');\n if (\n requiredDispatchPolicy &&\n !this.dispatchPolicy(requiredDispatchPolicy)\n ) {\n throw new NotificationOutboxDeniedError(\n 'permission',\n 'Required notification dispatch policy is unavailable.',\n );\n }\n if (\n requiredDispatchPolicy &&\n (!input.dispatchPolicyBinding ||\n typeof input.dispatchPolicyBinding !== 'object' ||\n Array.isArray(input.dispatchPolicyBinding) ||\n !Object.keys(input.dispatchPolicyBinding).length)\n ) {\n throw new Error(\n 'Protected notification requires an approved dispatch policy binding.',\n );\n }\n const dispatchPolicyBinding = JSON.stringify(\n input.dispatchPolicyBinding ?? {},\n );\n const profilePath = input.recipientProfileId !== undefined;\n if (profilePath === (input.recipientUserId !== undefined))\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'Choose exactly one typed recipient.',\n );\n const recipientUserId = profilePath\n ? null\n : requireText(input.recipientUserId, 'recipient');\n const recipientProfileId = profilePath\n ? requireText(input.recipientProfileId, 'profile recipient')\n : null;\n const recipientKind = profilePath ? 'profile' : 'user';\n assertNotificationRecipientIdentity({\n recipientKind,\n recipientUserId,\n recipientProfileId,\n channel: 'email',\n kind: input.kind,\n requiredDispatchPolicy,\n });\n\n const sourceRef = requireText(input.sourceRef, 'sourceRef');\n const kind = requireText(input.kind, 'kind');\n const subject = requireText(input.subject, 'subject');\n const text = requireText(input.text, 'text');\n if (/[\\r\\n]/u.test(subject)) {\n throw new Error('A notification subject must be a single line.');\n }\n const channel: NotificationDeliveryChannel = 'email';\n this.authorize(tenantId);\n if (profilePath)\n await assertNotificationProfileRecipientSchema(\n (await this.collection()).db,\n );\n const href = buildNotificationLink(this.options.linkBaseUrl, input.path);\n\n return withTenant({ tenantId }, async () => {\n const deliveries = await this.collection();\n const findExisting = async () =>\n (\n await deliveries.list({\n where: {\n tenantId,\n recipientKind,\n recipientUserId,\n recipientProfileId,\n channel,\n sourceRef,\n },\n limit: 1,\n })\n )[0];\n const existing = await findExisting();\n if (existing) {\n if (recipientProfileId) await this.validateProfileDelivery(existing);\n return { delivery: existing, created: false };\n }\n\n const recipient = recipientProfileId\n ? await this.resolveProfile({ tenantId, recipientProfileId, channel })\n : await this.options.resolveRecipient({\n tenantId,\n recipientUserId: recipientUserId as string,\n channel,\n });\n const address = recipient?.address?.trim();\n if (!address || /[\\s,;<>]/u.test(address) || !address.includes('@')) {\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'The host did not authorize an email recipient for this user.',\n );\n }\n const accountId = await this.requireSenderAccount(tenantId);\n if (!(await this.principalMaySend({ tenantId, accountId }))) {\n throw new NotificationOutboxDeniedError(\n 'permission',\n 'The principal lacks send access on the sender account.',\n );\n }\n const suppressed = await this.isSuppressed({\n tenantId,\n ...(recipientUserId ? { recipientUserId } : {}),\n ...(recipientProfileId\n ? { recipientProfileId, recipientKind: 'profile' as const }\n : {}),\n channel,\n kind,\n sourceRef,\n });\n\n try {\n const delivery = await deliveries.create({\n _insertOnly: true,\n tenantId,\n recipientUserId,\n recipientProfileId,\n recipientKind,\n channel,\n sourceRef,\n kind,\n requiredDispatchPolicy,\n dispatchPolicyBinding,\n subject,\n textBody: text,\n href,\n recipientAddress: address,\n recipientName: recipient?.name?.trim() ?? '',\n accountId,\n messageId: null,\n status: suppressed ? 'cancelled' : 'pending',\n stateVersion: 0,\n transitionId: '',\n attempts: 0,\n maxAttempts: this.maxAttempts,\n nextAttemptAt: input.notBefore ?? this.now(),\n leaseToken: null,\n leaseExpiresAt: null,\n handedOffAt: null,\n deliveredAt: null,\n providerMessageId: '',\n lastError: suppressed ? 'Suppressed by recipient preference.' : '',\n });\n return { delivery, created: true };\n } catch (error) {\n if (!isUniqueViolationError(error)) throw error;\n const winner = await findExisting();\n if (!winner) throw error;\n return { delivery: winner, created: false };\n }\n });\n }\n\n /** Lease and deliver due rows; returns what happened to each leased row. */\n async dispatchDue(\n options: NotificationDispatchOptions = {},\n ): Promise<NotificationDispatchReport> {\n const limit = Math.min(options.limit ?? DEFAULT_LIMIT, MAX_LIMIT);\n if (!Number.isInteger(limit) || limit < 1) {\n throw new Error(\n 'Notification dispatch limit must be a positive integer.',\n );\n }\n let tenantIds = options.tenantIds;\n if (this.options.principal && tenantIds === undefined) {\n const tenantId = this.options.principal.tenantId;\n if (!tenantId) {\n throw new NotificationOutboxDeniedError(\n 'permission',\n 'A messaging principal must select explicit dispatch tenants.',\n );\n }\n tenantIds = [tenantId];\n }\n if (tenantIds !== undefined) {\n tenantIds = [\n ...new Set(tenantIds.map((id) => requireText(id, 'tenant'))),\n ];\n // Authorize every requested scope before discovering or leasing any row.\n for (const tenantId of tenantIds) this.authorize(tenantId);\n }\n const deliveryIds =\n options.deliveryIds === undefined\n ? undefined\n : [...new Set(options.deliveryIds)];\n if (\n deliveryIds?.some(\n (id) => typeof id !== 'string' || !UUID_PATTERN.test(id),\n )\n ) {\n throw new Error('Notification dispatch delivery ids must be UUIDs.');\n }\n const report: NotificationDispatchReport = { leased: 0, outcomes: [] };\n if (tenantIds?.length === 0 || deliveryIds?.length === 0) return report;\n for await (const candidate of this.findDue(tenantIds, limit, deliveryIds)) {\n if (report.leased >= limit) break;\n this.authorize(candidate.tenantId);\n if (\n (candidate.kind.startsWith('protected:') &&\n candidate.kind !== `protected:${candidate.requiredDispatchPolicy}`) ||\n (candidate.requiredDispatchPolicy &&\n !this.dispatchPolicy(candidate.requiredDispatchPolicy))\n ) {\n const lastError =\n 'Blocked: required notification dispatch policy is unavailable.';\n if (candidate.lastError !== lastError)\n await withTenant({ tenantId: candidate.tenantId }, () =>\n candidate.transition({ lastError }),\n );\n report.outcomes.push({\n deliveryId: candidate.id as string,\n tenantId: candidate.tenantId,\n outcome: 'blocked',\n });\n continue;\n }\n try {\n await withTenant({ tenantId: candidate.tenantId }, () =>\n this.validateProfileDelivery(candidate),\n );\n } catch (cause) {\n const lastError = `Blocked: ${errorText(cause)}`;\n if (candidate.lastError !== lastError)\n await withTenant({ tenantId: candidate.tenantId }, () =>\n candidate.transition({ lastError }),\n );\n report.outcomes.push({\n deliveryId: candidate.id as string,\n tenantId: candidate.tenantId,\n outcome: 'blocked',\n });\n continue;\n }\n // Without a principal this is trusted worker code and the per-account\n // policy is lifted. With a principal, the tenant permission is only a\n // ceiling: the principal must also hold `send` on the sender account.\n if (!(await this.principalMaySend(candidate))) {\n const lastError = 'Blocked: mail access denied for scope send';\n if (candidate.lastError !== lastError)\n await withTenant({ tenantId: candidate.tenantId }, () =>\n candidate.transition({ lastError }),\n );\n report.outcomes.push({\n deliveryId: candidate.id as string,\n tenantId: candidate.tenantId,\n outcome: 'blocked',\n });\n continue;\n }\n const outcome = await withTenant({ tenantId: candidate.tenantId }, () =>\n runWithMailSystemAccess(() => this.dispatchOne(candidate)),\n );\n if (!outcome) continue;\n report.leased += 1;\n report.outcomes.push({\n deliveryId: candidate.id as string,\n tenantId: candidate.tenantId,\n outcome,\n });\n }\n return report;\n }\n\n /** Deliveries waiting for a reconciliation decision, oldest first. */\n async listUncertain(options: {\n tenantId: string;\n limit?: number;\n }): Promise<NotificationDelivery[]> {\n const tenantId = requireText(options.tenantId, 'tenant');\n this.authorize(tenantId);\n return withTenant({ tenantId }, async () =>\n (await this.collection()).list({\n where: { tenantId, status: 'uncertain' },\n orderBy: 'handedOffAt ASC',\n limit: Math.min(options.limit ?? DEFAULT_LIMIT, MAX_LIMIT),\n }),\n );\n }\n\n /**\n * Settle an `uncertain` delivery after checking the provider out of band:\n * `sent` (it arrived), `failed` (give up), or `retry` (send again,\n * accepting the risk of a duplicate; a message left claimed by a dead\n * sender is released first). Returns false when the row is not uncertain\n * any more, or for `retry` when the message is recorded as sent.\n */\n async reconcile(input: {\n tenantId: string;\n deliveryId: string;\n outcome: NotificationReconcileOutcome;\n note?: string;\n }): Promise<boolean> {\n const tenantId = requireText(input.tenantId, 'tenant');\n this.authorize(tenantId);\n // Ids may come from requests; on a native uuid column (PostgreSQL) a\n // malformed one would fail the query (22P02) instead of matching nothing.\n if (!UUID_PATTERN.test(input.deliveryId ?? '')) return false;\n return withTenant({ tenantId }, async () => {\n if (this.options.principal) {\n const delivery = (\n await (\n await this.collection()\n ).list({ where: { tenantId, id: input.deliveryId }, limit: 1 })\n )[0];\n if (!delivery || !(await this.principalMaySend(delivery))) return false;\n }\n return runWithMailSystemAccess(() => this.reconcileImpl(tenantId, input));\n });\n }\n\n /** True without a principal (trusted worker); else needs `send` on the account. */\n private async principalMaySend(delivery: {\n tenantId: string;\n accountId?: string;\n }): Promise<boolean> {\n const principal = this.options.principal;\n if (!principal) return true;\n const tenantId = delivery.tenantId;\n const userId = principal.userId ?? principal.id;\n if (!delivery.accountId) return false;\n const account = await withTenant({ tenantId }, () =>\n runWithMailSystemAccess(async () =>\n (await AccountCollection.create({ db: this.options.db })).get({\n id: delivery.accountId,\n }),\n ),\n );\n if (!account || account.tenantId !== tenantId) return false;\n // No user identity: only unowned (tenant-wide) accounts pass.\n const decision = await withTenant({ tenantId }, () =>\n decideMailAccess(\n account,\n 'send',\n userId ? { id: principal.id ?? userId, tenantId, userId } : null,\n ),\n );\n return decision.allowed;\n }\n\n private async reconcileImpl(\n tenantId: string,\n input: {\n deliveryId: string;\n outcome: NotificationReconcileOutcome;\n note?: string;\n },\n ): Promise<boolean> {\n {\n const delivery = (\n await (\n await this.collection()\n ).list({\n where: { tenantId, id: input.deliveryId },\n limit: 1,\n })\n )[0];\n if (delivery?.status !== 'uncertain') return false;\n const note = input.note?.trim();\n const now = this.now();\n switch (input.outcome) {\n case 'sent':\n return delivery.transition({\n status: 'sent',\n deliveredAt: now,\n ...(note ? { lastError: note } : {}),\n });\n case 'failed':\n return delivery.transition({\n status: 'failed',\n lastError: note || delivery.lastError,\n });\n case 'retry': {\n // The canonical message must be sendable again: a crash can leave\n // it claimed ('sending') by a sender that no longer exists. The\n // delivery is uncertain, so no dispatcher holds it.\n const message = delivery.messageId\n ? await this.loadMessage(delivery.messageId)\n : null;\n if (message?.sendStatus === 'sent') return false;\n if (\n message?.sendStatus === 'sending' &&\n !(await message.abandonSendAttempt(\n note || 'Released for an operator-approved retry.',\n ))\n ) {\n return false;\n }\n return delivery.transition({\n status: 'pending',\n nextAttemptAt: now,\n handedOffAt: null,\n // One more lease, so a delivery already at its budget can retry.\n attempts: Math.min(delivery.attempts, delivery.maxAttempts - 1),\n ...(note ? { lastError: note } : {}),\n });\n }\n default:\n throw new Error(`Unknown reconcile outcome '${input.outcome}'.`);\n }\n }\n }\n\n // ───────────────────────────────────────────────────────────────────────\n\n private async requireSenderAccount(tenantId: string): Promise<string> {\n const accountId = (\n await this.options.resolveSenderAccountId({ tenantId })\n )?.trim();\n const account = accountId\n ? await (await AccountCollection.create({ db: this.options.db })).get({\n id: accountId,\n })\n : null;\n if (\n !account ||\n !(account instanceof EmailAccount) ||\n account.tenantId !== tenantId ||\n !account.isActive\n ) {\n throw new NotificationOutboxDeniedError(\n 'sender',\n 'No active email sender account is configured for this tenant.',\n );\n }\n return account.id as string;\n }\n\n private async isSuppressed(request: {\n tenantId: string;\n channel: NotificationDeliveryChannel;\n kind: string;\n sourceRef: string;\n recipientUserId?: string;\n recipientProfileId?: string;\n recipientKind?: 'profile';\n }): Promise<boolean> {\n if (request.recipientProfileId)\n return Boolean(\n await this.options.isProfileSuppressed?.({\n tenantId: request.tenantId,\n recipientProfileId: request.recipientProfileId,\n channel: 'email',\n kind: request.kind,\n sourceRef: request.sourceRef,\n }),\n );\n if (!request.recipientUserId)\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'Missing typed suppression recipient.',\n );\n return Boolean(\n await this.options.isSuppressed?.({\n tenantId: request.tenantId,\n recipientUserId: request.recipientUserId,\n channel: request.channel,\n kind: request.kind,\n sourceRef: request.sourceRef,\n }),\n );\n }\n\n private async resolveProfile(\n request: NotificationProfileRecipientRequest,\n ): Promise<NotificationRecipient> {\n const db = (await this.collection()).db;\n const profile = await readNotificationProfile(\n db,\n request.tenantId,\n request.recipientProfileId,\n );\n const resolved = await this.options.resolveProfileRecipient?.(request);\n const address = profile?.email ? normalizeIdentityEmail(profile.email) : '';\n if (\n !profile ||\n profile.tenantId !== request.tenantId ||\n !address ||\n containsControlCharacter(address) ||\n !/^[^\\s@,;<>]+@[^\\s@,;<>]+\\.[^\\s@,;<>]+$/u.test(address) ||\n !resolved?.address ||\n normalizeIdentityEmail(resolved.address) !== address\n )\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'Current tenant-owned profile email is not authorized.',\n );\n if (resolved.name && containsControlCharacter(resolved.name))\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'Malformed profile recipient display name.',\n );\n return { address, name: resolved.name?.trim() ?? '' };\n }\n private async validateProfileDelivery(\n delivery: NotificationDelivery,\n ): Promise<void> {\n assertNotificationRecipientIdentity(delivery);\n if (delivery.recipientKind !== 'profile') return;\n await assertNotificationProfileRecipientSchema(\n (await this.collection()).db,\n );\n const current = await this.resolveProfile({\n tenantId: delivery.tenantId,\n recipientProfileId: delivery.recipientProfileId as string,\n channel: 'email',\n });\n if (\n current.address !== delivery.recipientAddress ||\n (current.name ?? '') !== delivery.recipientName\n )\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'Approved profile recipient changed; review again.',\n );\n }\n private dispatchPolicy(id: string) {\n const policies = this.options.dispatchPolicies;\n if (!policies || !Object.hasOwn(policies, id)) return undefined;\n const policy = policies[id];\n return typeof policy?.resolveAttachments === 'function'\n ? policy\n : undefined;\n }\n\n private async *findDue(\n tenantIds: readonly string[] | undefined,\n limit: number,\n deliveryIds?: readonly string[],\n ): AsyncGenerator<NotificationDelivery> {\n const now = this.now();\n const visited = new Set<string>();\n // Each page is bounded; a blocked prefix cannot consume the lease budget.\n // Expired leases precede pending rows, including across explicit scopes.\n for (const phase of [\n { status: 'sending', column: 'lease_expires_at' },\n { status: 'pending', column: 'next_attempt_at' },\n ] as const) {\n for (const tenantId of tenantIds ?? [undefined]) {\n let cursor: { id: string; cursor_at: string } | undefined;\n for (;;) {\n const read = async () => {\n const deliveries = await this.collection();\n const table = `\"${deliveries.tableName.replaceAll('\"', '\"\"')}\"`;\n const conditions = ['status = ?', `${phase.column} <= ?`];\n const values: unknown[] = [phase.status, now.toISOString()];\n if (tenantId !== undefined) {\n conditions.push('tenant_id = ?');\n values.push(tenantId);\n }\n if (deliveryIds) {\n conditions.push(\n `id IN (${deliveryIds.map(() => '?').join(',')})`,\n );\n values.push(...deliveryIds);\n }\n if (cursor) {\n conditions.push(\n `(${phase.column} > ? OR (${phase.column} = ? AND id > ?))`,\n );\n values.push(cursor.cursor_at, cursor.cursor_at, cursor.id);\n }\n // Capture the cursor in this same query, before hydration or writes.\n // PostgreSQL Date hydration loses microseconds; CAST preserves the\n // physical timestamp so equal/sub-ms rows cannot repeat forever.\n const result = await deliveries.db.query(\n `SELECT id, CAST(${phase.column} AS TEXT) AS cursor_at FROM ${table}\n WHERE ${conditions.join(' AND ')}\n ORDER BY ${phase.column} ASC, id ASC LIMIT ?`,\n ...values,\n limit,\n );\n const positions = result.rows as Array<{\n id: string;\n cursor_at: string;\n }>;\n if (\n positions.some(\n (row) =>\n typeof row.id !== 'string' ||\n !UUID_PATTERN.test(row.id) ||\n typeof row.cursor_at !== 'string' ||\n !row.cursor_at,\n )\n )\n throw new Error('Invalid notification dispatch cursor.');\n if (!positions.length) return { positions, rows: [] };\n const rows = await deliveries.list({\n where: {\n ...(tenantId === undefined ? {} : { tenantId }),\n id: positions.map((row) => row.id),\n },\n limit: positions.length,\n });\n const byId = new Map(rows.map((row) => [row.id, row]));\n return {\n positions,\n rows: positions.flatMap((row) => {\n const delivery = byId.get(row.id);\n return delivery ? [delivery] : [];\n }),\n };\n };\n const page =\n tenantId === undefined\n ? await withSystemContext(read)\n : await withTenant({ tenantId }, read);\n if (!page.positions.length) break;\n cursor = page.positions[page.positions.length - 1];\n for (const row of page.rows) {\n if (!row.id || visited.has(row.id)) continue;\n visited.add(row.id);\n yield row;\n }\n if (page.positions.length < limit) break;\n }\n }\n }\n }\n\n /** Lease one candidate and carry it to an outcome; null when not leased. */\n private async dispatchOne(\n candidate: NotificationDelivery,\n ): Promise<NotificationDispatchOutcome | null> {\n // Re-read under the tenant scope; the candidate may be stale.\n const delivery = (\n await (\n await this.collection()\n ).list({\n where: { tenantId: candidate.tenantId, id: candidate.id },\n limit: 1,\n })\n )[0];\n if (!delivery) return null;\n const now = this.now();\n\n const recovering =\n delivery.status === 'sending' &&\n delivery.leaseExpiresAt !== null &&\n delivery.leaseExpiresAt.getTime() <= now.getTime();\n const due =\n delivery.status === 'pending' &&\n delivery.nextAttemptAt.getTime() <= now.getTime();\n if (!recovering && !due) return null;\n\n const leaseToken = crypto.randomUUID();\n const leaseExpiresAt = new Date(now.getTime() + this.leaseMs);\n // A lapsed lease whose attempt already reached the provider is a crash or\n // lease loss mid-handoff: learn what we can before anything is resent.\n const priorHandoff = recovering && delivery.handedOffAt !== null;\n const won = await delivery.transition({\n status: 'sending',\n leaseToken,\n leaseExpiresAt,\n attempts: priorHandoff ? delivery.attempts : delivery.attempts + 1,\n ...(priorHandoff ? {} : { handedOffAt: null }),\n });\n if (!won) return null;\n\n try {\n if (priorHandoff) {\n const resolved = await this.recoverHandoff(delivery, leaseToken);\n if (resolved) return resolved;\n }\n\n if (\n await this.isSuppressed({\n tenantId: delivery.tenantId,\n ...(delivery.recipientUserId\n ? { recipientUserId: delivery.recipientUserId }\n : {}),\n ...(delivery.recipientProfileId\n ? {\n recipientProfileId: delivery.recipientProfileId,\n recipientKind: 'profile' as const,\n }\n : {}),\n channel: delivery.channel,\n kind: delivery.kind,\n sourceRef: delivery.sourceRef,\n })\n ) {\n return this.settle(delivery, leaseToken, {\n status: 'cancelled',\n lastError: 'Suppressed by recipient preference.',\n });\n }\n\n await this.validateProfileDelivery(delivery);\n const message = await this.ensureMessage(delivery, leaseToken);\n if (!message) return 'lease-lost';\n const request: NotificationTransportRequest = {\n delivery,\n message,\n idempotencyKey: notificationDeliveryCorrelationId(\n delivery.id as string,\n ),\n };\n const resolver = delivery.requiredDispatchPolicy\n ? this.dispatchPolicy(delivery.requiredDispatchPolicy)\n ?.resolveAttachments\n : this.options.resolveAttachments;\n if (delivery.requiredDispatchPolicy && !resolver)\n throw new Error(\n 'Required notification dispatch policy is unavailable.',\n );\n if (resolver) {\n const attachments = await resolver(request);\n if (\n !Array.isArray(attachments) ||\n (delivery.requiredDispatchPolicy && attachments.length === 0) ||\n attachments.some(\n (attachment) =>\n !attachment ||\n typeof attachment.filename !== 'string' ||\n !attachment.filename.trim() ||\n /[\\r\\n\\0]/.test(attachment.filename) ||\n !(attachment.content instanceof Uint8Array) ||\n (attachment.contentType !== undefined &&\n (typeof attachment.contentType !== 'string' ||\n !attachment.contentType.trim() ||\n /[\\r\\n\\0]/.test(attachment.contentType))) ||\n (attachment.contentId !== undefined &&\n (typeof attachment.contentId !== 'string' ||\n /[\\r\\n\\0]/.test(attachment.contentId))) ||\n (attachment.contentDisposition !== undefined &&\n !['attachment', 'inline'].includes(\n attachment.contentDisposition,\n )),\n )\n )\n throw new Error(\n 'Notification attachment resolver returned malformed bytes or metadata.',\n );\n request.attachments = attachments.map((attachment) => ({\n ...attachment,\n content: Uint8Array.from(attachment.content),\n }));\n }\n if (\n !(await delivery.transition(\n { handedOffAt: this.now() },\n { leaseToken },\n ))\n ) {\n return 'lease-lost';\n }\n\n let outcome: NotificationTransportOutcome;\n try {\n outcome = await withProtectedNotificationHandoff(\n request,\n this.now,\n async () => {\n await this.validateProfileDelivery(delivery);\n return this.transport.send(request);\n },\n );\n } catch (error) {\n // A throw after handoff says nothing about whether the provider\n // accepted the message.\n outcome =\n error instanceof ProtectedNotificationHandoffError\n ? { status: 'rejected', retryable: true, error: errorText(error) }\n : { status: 'unknown', error: errorText(error) };\n }\n return this.applyOutcome(delivery, leaseToken, outcome);\n } catch (error) {\n // A failure before handoff (message creation, suppression hook) is safe\n // to retry; one after handoff has already been mapped to an outcome.\n if (delivery.handedOffAt !== null) throw error;\n return this.applyOutcome(delivery, leaseToken, {\n status: 'rejected',\n error: errorText(error),\n retryable: true,\n });\n }\n }\n\n private async recoverHandoff(\n delivery: NotificationDelivery,\n leaseToken: string,\n ): Promise<NotificationDispatchOutcome | null> {\n const message = delivery.messageId\n ? await this.loadMessage(delivery.messageId)\n : null;\n let known: NotificationTransportReconciliation = {\n status: 'unknown',\n error: 'Lease lapsed after the provider handoff; outcome unknown.',\n };\n if (message && this.transport.reconcile) {\n try {\n known = await this.transport.reconcile({\n delivery,\n message,\n idempotencyKey: notificationDeliveryCorrelationId(\n delivery.id as string,\n ),\n });\n } catch (error) {\n known = { status: 'unknown', error: errorText(error) };\n }\n }\n if (known.status === 'not-sent') {\n // Nothing reached the provider; this lease becomes a fresh attempt.\n if (\n !(await delivery.transition(\n { handedOffAt: null, attempts: delivery.attempts + 1 },\n { leaseToken },\n ))\n ) {\n return 'lease-lost';\n }\n return null;\n }\n if (known.status === 'unknown' && this.transport.idempotent) {\n // The provider dedupes on the key: resending is the reconciliation.\n if (\n !(await delivery.transition(\n { handedOffAt: null, attempts: delivery.attempts + 1 },\n { leaseToken },\n ))\n ) {\n return 'lease-lost';\n }\n return null;\n }\n return this.applyOutcome(delivery, leaseToken, known);\n }\n\n private async applyOutcome(\n delivery: NotificationDelivery,\n leaseToken: string,\n outcome: NotificationTransportOutcome,\n ): Promise<NotificationDispatchOutcome> {\n if (outcome.status === 'accepted') {\n return this.settle(delivery, leaseToken, {\n status: 'sent',\n deliveredAt: this.now(),\n providerMessageId: outcome.providerMessageId ?? '',\n lastError: '',\n });\n }\n if (outcome.status === 'unknown') {\n if (\n this.transport.idempotent &&\n delivery.attempts < delivery.maxAttempts\n ) {\n return this.scheduleRetry(delivery, leaseToken, outcome.error);\n }\n return this.settle(delivery, leaseToken, {\n status: 'uncertain',\n lastError: outcome.error,\n });\n }\n if (outcome.retryable && delivery.attempts < delivery.maxAttempts) {\n return this.scheduleRetry(delivery, leaseToken, outcome.error);\n }\n return this.settle(delivery, leaseToken, {\n status: 'failed',\n lastError: outcome.error,\n });\n }\n\n private async scheduleRetry(\n delivery: NotificationDelivery,\n leaseToken: string,\n error: string,\n ): Promise<NotificationDispatchOutcome> {\n const delay = this.retryDelayMs(delivery.attempts);\n const won = await this.endLease(delivery, leaseToken, {\n status: 'pending',\n nextAttemptAt: new Date(this.now().getTime() + Math.max(0, delay)),\n handedOffAt: null,\n lastError: error,\n });\n return won ? 'retry-scheduled' : 'lease-lost';\n }\n\n /** End the lease in a terminal status; reports lease loss instead of overwriting. */\n private async settle(\n delivery: NotificationDelivery,\n leaseToken: string,\n changes: NotificationDeliveryTransition & {\n status: 'sent' | 'failed' | 'uncertain' | 'cancelled';\n },\n ): Promise<NotificationDispatchOutcome> {\n const won = await this.endLease(delivery, leaseToken, changes);\n return won ? changes.status : 'lease-lost';\n }\n\n private endLease(\n delivery: NotificationDelivery,\n leaseToken: string,\n changes: NotificationDeliveryTransition,\n ): Promise<boolean> {\n return delivery.transition(\n { ...changes, leaseToken: null, leaseExpiresAt: null },\n { leaseToken },\n );\n }\n\n private async loadMessage(messageId: string): Promise<Message | null> {\n const messages = await MessageCollection.create({ db: this.options.db });\n return (await messages.get({ id: messageId })) ?? null;\n }\n\n /**\n * The delivery's single outbound `Email`, created under the lease. Its id\n * is derived from the delivery id and inserted insert-only, so a stale\n * dispatcher that resumes after its lease was taken over hits the stored\n * row (a unique violation) instead of creating a second email.\n */\n private async ensureMessage(\n delivery: NotificationDelivery,\n leaseToken: string,\n ): Promise<Message | null> {\n if (delivery.messageId) {\n const message = await this.loadMessage(delivery.messageId);\n if (message) return this.protectCanonicalMessage(delivery, message);\n }\n const messageId = await notificationDeliveryMessageId(\n delivery.id as string,\n );\n let message = await this.loadMessage(messageId);\n if (!message) {\n const body = `${delivery.textBody}\\n\\n${delivery.href}\\n`;\n const emails = await EmailCollection.create({ db: this.options.db });\n try {\n await emails.create({\n _insertOnly: true,\n id: messageId,\n tenantId: delivery.tenantId,\n accountId: delivery.accountId,\n correlationId: notificationDeliveryCorrelationId(\n delivery.id as string,\n ),\n subject: delivery.subject,\n body,\n textBody: body,\n toAddresses: JSON.stringify([\n {\n address: delivery.recipientAddress,\n ...(delivery.recipientName\n ? { name: delivery.recipientName }\n : {}),\n },\n ]),\n ...(delivery.requiredDispatchPolicy\n ? {\n metadata: protectedNotificationMetadata(\n delivery.id!,\n delivery.requiredDispatchPolicy,\n ),\n }\n : {}),\n sendStatus: 'pending',\n // Delivery is owned by the outbox's attempt budget, not the message's.\n maxRetries: 0,\n });\n } catch (error) {\n if (!isUniqueViolationError(error)) throw error;\n }\n // Reload so send()'s compare-and-set sees the stored revision.\n message = await this.loadMessage(messageId);\n if (!message) throw new Error('The outbound email could not be stored.');\n }\n if (delivery.messageId !== message.id) {\n if (\n !(await delivery.transition(\n { messageId: message.id as string },\n { leaseToken },\n ))\n ) {\n return null;\n }\n }\n return this.protectCanonicalMessage(delivery, message);\n }\n\n /** Backfill the non-authorizing durable marker on an existing protected canonical row. */\n private async protectCanonicalMessage(\n delivery: NotificationDelivery,\n message: Message,\n ): Promise<Message> {\n if (delivery.requiredDispatchPolicy) {\n const existing = message.getMetadata();\n const protectedMarker = JSON.parse(\n protectedNotificationMetadata(\n delivery.id!,\n delivery.requiredDispatchPolicy,\n ),\n );\n if (!existing.__smrtProtectedOutbox) {\n message.setMetadata({ ...existing, ...protectedMarker });\n await message.save();\n }\n }\n return message;\n }\n}\n\nfunction containsControlCharacter(value: string): boolean {\n return [...value].some((char) => {\n const code = char.codePointAt(0) as number;\n return code < 32 || code === 127;\n });\n}\n","import {\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { AccountCollection } from '../collections/AccountCollection.js';\nimport { MessagingEndpointCollection } from '../collections/MessagingEndpointCollection.js';\nimport { PersonaMessageRouteCollection } from '../collections/PersonaMessageRouteCollection.js';\nimport { withTenant } from '../host.js';\nimport { Email } from '../models/Email.js';\nimport { EmailAccount } from '../models/EmailAccount.js';\nimport { Message } from '../models/Message.js';\nimport type { PersonaMessageRoute } from '../models/PersonaMessageRoute.js';\nimport {\n assertMessagingPermission,\n type MessagingPrincipal,\n SEND_MESSAGES_PERMISSION,\n} from '../permissions.js';\nimport type {\n MessageSendResult,\n SendEmailOptions,\n SendPersonaMessageOptions,\n} from '../types.js';\n\nexport interface PersonaMessageSendResult {\n routeId: string;\n messageId: string;\n delivery: MessageSendResult;\n}\n\n/** Resolves a persona-owned route and delivers a persisted outbound message. */\nexport class PersonaMessagingService {\n constructor(\n private readonly options: {\n db: SmrtClassOptions['db'];\n tenantId: string;\n /** Omit only for trusted system code that performs its own authorization. */\n principal?: MessagingPrincipal;\n },\n ) {}\n\n async send(\n input: SendPersonaMessageOptions,\n ): Promise<PersonaMessageSendResult> {\n if (this.options.principal) {\n assertMessagingPermission(\n this.options.principal,\n this.options.tenantId,\n SEND_MESSAGES_PERMISSION,\n );\n }\n if (!input.personaId)\n throw new Error('A persona is required to send a message.');\n if (!input.body.trim()) throw new Error('Message body cannot be empty.');\n\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const route = await this.resolveRoute(input);\n const accounts = await AccountCollection.create({ db: this.options.db });\n const endpoints = await MessagingEndpointCollection.create({\n db: this.options.db,\n });\n const [account, endpoint] = await Promise.all([\n accounts.get({ id: route.accountId }),\n endpoints.get({ id: route.endpointId }),\n ]);\n if (\n !account ||\n account.tenantId !== this.options.tenantId ||\n !account.isActive\n ) {\n throw new Error('The selected messaging account is unavailable.');\n }\n if (\n !endpoint ||\n endpoint.tenantId !== this.options.tenantId ||\n !endpoint.isActive\n ) {\n throw new Error('The selected messaging endpoint is unavailable.');\n }\n if (account.channelType !== endpoint.channel) {\n throw new Error(\n 'The selected messaging route has mismatched channels.',\n );\n }\n\n if (input.attachments?.length && endpoint.channel !== 'email') {\n throw new Error('Attachments are only supported on email routes.');\n }\n\n let message: Message;\n const base = {\n db: this.options.db,\n tenantId: this.options.tenantId,\n accountId: route.accountId,\n endpointId: route.endpointId,\n personaId: input.personaId,\n correlationId: input.correlationId ?? '',\n subject: input.subject ?? '',\n body: input.body.trim(),\n sendStatus: 'pending' as const,\n };\n if (endpoint.channel === 'email') {\n if (!(account instanceof EmailAccount)) {\n throw new Error('Email routes require an EmailAccount.');\n }\n const address = endpoint.getAddress<{ email?: string }>();\n if (!address.email) throw new Error('Email endpoint has no address.');\n const email = new (ObjectRegistry.resolveEffectiveConstructor(Email))({\n ...base,\n textBody: base.body,\n hasAttachments: Boolean(input.attachments?.length),\n });\n email.setToAddresses([{ address: address.email }]);\n message = email;\n } else {\n message = new (ObjectRegistry.resolveEffectiveConstructor(Message))(\n base,\n );\n }\n await message.initialize();\n await message.save();\n const sendOptions: SendEmailOptions | undefined = input.attachments\n ?.length\n ? { attachments: input.attachments }\n : undefined;\n const delivery = await message.send(sendOptions);\n return {\n routeId: route.id ?? '',\n messageId: message.id ?? '',\n delivery,\n };\n });\n }\n\n private async resolveRoute(\n input: SendPersonaMessageOptions,\n ): Promise<PersonaMessageRoute> {\n const routes = await PersonaMessageRouteCollection.create({\n db: this.options.db,\n });\n if (input.routeId) {\n const route = await routes.get({ id: input.routeId });\n if (\n !route ||\n route.tenantId !== this.options.tenantId ||\n route.personaId !== input.personaId ||\n !route.enabled\n ) {\n throw new Error(\n 'The requested persona messaging route is unavailable.',\n );\n }\n return route;\n }\n\n let candidates = await routes.forPersona(input.personaId);\n if (input.purpose) {\n candidates = candidates.filter(\n (route) => route.purpose === input.purpose,\n );\n } else {\n const defaults = candidates.filter(\n (route) => route.purpose === 'default',\n );\n if (defaults.length > 0) candidates = defaults;\n }\n candidates.sort((left, right) => right.priority - left.priority);\n\n if (input.channel) {\n const endpoints = await MessagingEndpointCollection.create({\n db: this.options.db,\n });\n for (const route of candidates) {\n const endpoint = await endpoints.get({ id: route.endpointId });\n if (endpoint?.channel === input.channel) return route;\n }\n throw new Error(\n `No ${input.channel} route is configured for this persona.`,\n );\n }\n\n const route = candidates[0];\n if (!route)\n throw new Error('No messaging route is configured for this persona.');\n return route;\n }\n}\n","import {\n isUniqueViolationError,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { UserNotificationCollection } from '../collections/UserNotificationCollection.js';\nimport { withTenant } from '../host.js';\nimport {\n USER_NOTIFICATION_SEVERITIES,\n type UserNotification,\n type UserNotificationSeverity,\n} from '../models/UserNotification.js';\n\n/** What to tell one person. */\nexport interface UserNotificationInput {\n tenantId: string;\n recipientUserId: string;\n /** Host-defined type, e.g. `social-post.failed`. */\n kind: string;\n title: string;\n body?: string;\n href?: string | null;\n severity?: UserNotificationSeverity;\n /**\n * Dedupe key for the underlying event (e.g. `social-post:<id>:failed`). A\n * second `notify()` with the same `(tenantId, recipientUserId, sourceRef)`\n * returns the existing row untouched, read state included. Omit for\n * one-off notifications; a unique ref is generated.\n */\n sourceRef?: string;\n /** When the event happened (default: now). */\n occurredAt?: Date;\n}\n\nexport interface UserNotificationNotifyResult {\n notification: UserNotification;\n /** False when `sourceRef` matched an existing notification. */\n created: boolean;\n}\n\nexport interface UserNotificationListOptions {\n /** Tenants to read (at least one). Each is read under its own tenant scope. */\n tenantIds: readonly string[];\n /** Only rows not yet read. */\n unreadOnly?: boolean;\n /** Include dismissed rows (default false). */\n includeDismissed?: boolean;\n /** Only rows that happened at or after this time. */\n since?: Date;\n /** Newest-first cap across all tenants (default 50, max 200). */\n limit?: number;\n}\n\nexport interface UserNotificationScope {\n tenantId: string;\n}\n\n/** Notification ids are uuids; anything else can match no row. */\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst DEFAULT_LIMIT = 50;\nconst MAX_LIMIT = 200;\n\nfunction requireText(value: string | undefined, name: string): string {\n const text = value?.trim();\n if (!text) throw new Error(`A notification ${name} is required.`);\n return text;\n}\n\nfunction clampLimit(limit: number | undefined): number {\n if (limit === undefined) return DEFAULT_LIMIT;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new Error('Notification list limit must be a positive integer.');\n }\n return Math.min(limit, MAX_LIMIT);\n}\n\n/**\n * Creates, lists, and updates per-user notifications (`UserNotification`).\n *\n * The service is the authorization boundary for the model: every read and\n * write is filtered to one recipient and runs under an explicit tenant\n * scope. The host decides who may be notified (e.g. the poster of a failed\n * social post) and passes the signed-in user's id for reads; it never lets\n * a request choose another user's id.\n */\nexport class UserNotificationService {\n constructor(private readonly options: { db: SmrtClassOptions['db'] }) {}\n\n private collection(): Promise<UserNotificationCollection> {\n return UserNotificationCollection.create({ db: this.options.db });\n }\n\n /** Store a notification unless its `sourceRef` already exists. */\n async notify(\n input: UserNotificationInput,\n ): Promise<UserNotificationNotifyResult> {\n const tenantId = requireText(input.tenantId, 'tenant');\n const recipientUserId = requireText(input.recipientUserId, 'recipient');\n const kind = requireText(input.kind, 'kind');\n const title = requireText(input.title, 'title');\n const severity = input.severity ?? 'info';\n if (!USER_NOTIFICATION_SEVERITIES.includes(severity)) {\n throw new Error(`Unknown notification severity '${severity}'.`);\n }\n const sourceRef =\n input.sourceRef?.trim() || `notification:${crypto.randomUUID()}`;\n\n return withTenant({ tenantId }, async () => {\n const notifications = await this.collection();\n const findExisting = async () =>\n (\n await notifications.list({\n where: { tenantId, recipientUserId, sourceRef },\n limit: 1,\n })\n )[0];\n const existing = await findExisting();\n if (existing) return { notification: existing, created: false };\n\n // Insert-only: a concurrent notify() for the same event may have stored\n // the row since the lookup above. An upsert would then overwrite it —\n // title, and read/dismissed state reset to null — so a collision is\n // resolved by returning the stored row untouched instead.\n let notification: UserNotification;\n try {\n notification = await notifications.create({\n _insertOnly: true,\n tenantId,\n recipientUserId,\n kind,\n title,\n body: input.body?.trim() ?? '',\n href: input.href ?? null,\n severity,\n sourceRef,\n occurredAt: input.occurredAt ?? new Date(),\n readAt: null,\n dismissedAt: null,\n });\n } catch (error) {\n if (!isUniqueViolationError(error)) throw error;\n const winner = await findExisting();\n if (!winner) throw error;\n return { notification: winner, created: false };\n }\n return { notification, created: true };\n });\n }\n\n /** `notify()` for each recipient (duplicates in the list are ignored). */\n async notifyMany(\n recipientUserIds: readonly string[],\n input: Omit<UserNotificationInput, 'recipientUserId'>,\n ): Promise<UserNotificationNotifyResult[]> {\n const results: UserNotificationNotifyResult[] = [];\n for (const recipientUserId of new Set(recipientUserIds)) {\n results.push(await this.notify({ ...input, recipientUserId }));\n }\n return results;\n }\n\n /** A user's notifications across the given tenants, newest first. */\n async listForUser(\n userId: string,\n options: UserNotificationListOptions,\n ): Promise<UserNotification[]> {\n const recipientUserId = requireText(userId, 'recipient');\n const limit = clampLimit(options.limit);\n const tenantIds = [...new Set(options.tenantIds.filter(Boolean))];\n const notifications = await this.collection();\n\n const perTenant = await Promise.all(\n tenantIds.map((tenantId) =>\n withTenant({ tenantId }, () =>\n notifications.list({\n where: {\n tenantId,\n recipientUserId,\n ...(options.includeDismissed ? {} : { dismissedAt: null }),\n ...(options.unreadOnly ? { readAt: null } : {}),\n ...(options.since ? { 'occurredAt >=': options.since } : {}),\n },\n orderBy: 'occurredAt DESC',\n limit,\n }),\n ),\n ),\n );\n\n return perTenant\n .flat()\n .sort((a, b) => b.occurredAt.getTime() - a.occurredAt.getTime())\n .slice(0, limit);\n }\n\n /** Unread, undismissed count across the given tenants. */\n async countUnread(\n userId: string,\n options: Pick<UserNotificationListOptions, 'tenantIds' | 'since'>,\n ): Promise<number> {\n const recipientUserId = requireText(userId, 'recipient');\n const notifications = await this.collection();\n const counts = await Promise.all(\n [...new Set(options.tenantIds.filter(Boolean))].map((tenantId) =>\n withTenant({ tenantId }, () =>\n notifications.count({\n where: {\n tenantId,\n recipientUserId,\n readAt: null,\n dismissedAt: null,\n ...(options.since ? { 'occurredAt >=': options.since } : {}),\n },\n }),\n ),\n ),\n );\n return counts.reduce((sum, count) => sum + Number(count), 0);\n }\n\n /** Mark the user's own notifications read; returns how many changed. */\n async markRead(\n userId: string,\n ids: readonly string[],\n scope: UserNotificationScope,\n ): Promise<number> {\n return this.stamp(userId, ids, scope, 'readAt');\n }\n\n /** Dismiss (and mark read) the user's own notifications. */\n async dismiss(\n userId: string,\n ids: readonly string[],\n scope: UserNotificationScope,\n ): Promise<number> {\n return this.stamp(userId, ids, scope, 'dismissedAt');\n }\n\n /** Mark every unread notification of the user in these tenants read. */\n async markAllRead(\n userId: string,\n options: Pick<UserNotificationListOptions, 'tenantIds'>,\n ): Promise<number> {\n const recipientUserId = requireText(userId, 'recipient');\n const notifications = await this.collection();\n const now = new Date();\n let changed = 0;\n for (const tenantId of new Set(options.tenantIds.filter(Boolean))) {\n changed += await withTenant({ tenantId }, async () => {\n const unread = await notifications.list({\n where: { tenantId, recipientUserId, readAt: null },\n });\n for (const notification of unread) {\n notification.readAt = now;\n await notification.save();\n }\n return unread.length;\n });\n }\n return changed;\n }\n\n private async stamp(\n userId: string,\n ids: readonly string[],\n scope: UserNotificationScope,\n column: 'readAt' | 'dismissedAt',\n ): Promise<number> {\n const recipientUserId = requireText(userId, 'recipient');\n const tenantId = requireText(scope.tenantId, 'tenant');\n // Ids come from requests. A malformed one can match no row, and on a\n // native uuid column (PostgreSQL) it would fail the whole query (22P02)\n // instead, so drop it before querying.\n const wanted = [\n ...new Set(\n ids.filter(\n (id): id is string => typeof id === 'string' && UUID_PATTERN.test(id),\n ),\n ),\n ];\n if (wanted.length === 0) return 0;\n\n return withTenant({ tenantId }, async () => {\n const notifications = await this.collection();\n // The recipient filter is the authorization check: another user's id\n // simply matches nothing.\n const rows = await notifications.list({\n where: { tenantId, recipientUserId, 'id in': wanted },\n });\n const now = new Date();\n let changed = 0;\n for (const notification of rows) {\n if (notification[column] !== null) continue;\n notification[column] = now;\n if (column === 'dismissedAt' && notification.readAt === null) {\n notification.readAt = now;\n }\n await notification.save();\n changed += 1;\n }\n return changed;\n });\n }\n}\n","import { SmrtRecipe } from '@happyvertical/smrt-core';\nimport { Email } from './models/Email.js';\nimport { EmailAccount } from './models/EmailAccount.js';\nimport { SlackAccount } from './models/SlackAccount.js';\nimport { SlackMessage } from './models/SlackMessage.js';\nimport { UserNotification } from './models/UserNotification.js';\n\n/** Email reading and composing with application-owned transport. */\nexport class MailboxRecipe extends SmrtRecipe {\n static id = 'messages.mailbox';\n static label = 'Mailbox';\n static summary = 'Read and compose email from your connected accounts.';\n static synonyms = ['email', 'inbox', 'mail'];\n static group = {\n id: 'messages',\n label: 'Messaging',\n summary: 'Choose email and personal updates independently.',\n };\n static section = {\n id: 'messages',\n label: 'Messaging',\n icon: 'folder',\n description: 'Read email and keep up with updates addressed to you.',\n };\n static models = [Email, EmailAccount];\n static runtime = 'both' as const;\n static surfaces = [\n {\n kind: 'route',\n path: '/messages/mailbox',\n export: '@happyvertical/smrt-messages/svelte#MessageList',\n label: 'Mailbox',\n },\n {\n kind: 'playground',\n export: '@happyvertical/smrt-messages/svelte#MailboxDemo',\n label: 'Mailbox with mocked sending',\n },\n ] as const;\n static providers = [\n {\n id: 'email-inbox',\n kind: 'email',\n options: ['imap', 'pop3', 'gmail', 'jmap'],\n required: true,\n },\n {\n id: 'email-send',\n kind: 'email',\n options: ['smtp', 'gmail'],\n required: false,\n },\n ];\n static demoSeed = {\n data: {\n accounts: [\n {\n id: 'demo-account',\n name: 'Demo Inbox',\n providerType: 'email',\n email: 'you@example.com',\n isActive: true,\n },\n ],\n messages: [\n {\n id: 'demo-welcome',\n type: 'email',\n accountId: 'demo-account',\n subject: 'Welcome to your mailbox',\n body: 'Fictional mail. Sending is mocked; nothing leaves this browser.',\n senderName: 'Demo colleague',\n senderAddress: 'colleague@example.com',\n recipientAddresses: [{ address: 'you@example.com' }],\n date: '2026-01-01T12:00:00Z',\n isRead: false,\n isFlagged: false,\n hasAttachments: false,\n },\n ],\n },\n };\n static nav = [\n {\n label: 'Mailbox',\n model: Email,\n key: 'mailbox',\n icon: 'folder',\n noun: 'email',\n description: 'Read email from your connected accounts.',\n },\n {\n label: 'Failed sends',\n model: Email,\n key: 'failed-sends',\n icon: 'fileText',\n noun: 'email',\n description: 'Review email whose last send attempt failed.',\n filter: { field: 'sendStatus', value: 'failed' },\n },\n ];\n static help = './help/mailbox.md';\n static options = {\n Email: {\n fields: {\n created_at: { help: 'When this email was first recorded.' },\n updated_at: { help: 'When this email record was last changed.' },\n },\n },\n EmailAccount: {\n fields: {\n created_at: {\n help: 'When this mailbox connection was first recorded.',\n },\n updated_at: { help: 'When this mailbox connection was last changed.' },\n },\n },\n } as const;\n}\n\n/** Recipient-scoped in-app notification bell. */\nexport class NotificationsRecipe extends SmrtRecipe {\n static id = 'messages.notifications';\n static label = 'Notifications';\n static summary = 'See updates addressed to you and mark them read.';\n static synonyms = ['alerts', 'notification bell'];\n static group = {\n id: 'messages',\n label: 'Messaging',\n summary: 'Choose email and personal updates independently.',\n };\n static section = {\n id: 'messages',\n label: 'Messaging',\n icon: 'folder',\n description: 'Read email and keep up with updates addressed to you.',\n };\n static models = [UserNotification];\n static runtime = 'both' as const;\n static surfaces = [\n {\n kind: 'shell-widget',\n slot: 'header.end',\n export: '@happyvertical/smrt-svelte/notifications#NotificationBell',\n label: 'Notifications',\n },\n ] as const;\n static providers = [\n {\n id: 'notifications',\n kind: 'notifications',\n options: ['user-notification-service'],\n required: true,\n },\n ];\n static demoSeed = {\n data: {\n items: [\n {\n id: 'demo-notification',\n title: 'You were mentioned',\n body: 'A fictional update for the demo user.',\n occurredAt: '2026-01-01T12:00:00Z',\n severity: 'info',\n readAt: null,\n },\n ],\n },\n };\n // Recipient-scoped reads use the bell provider, never generated model routes.\n static nav = [];\n static help = './help/notifications.md';\n}\n\n/** Slack messages from connected workspaces, read by channel and thread. */\nexport class SlackRecipe extends SmrtRecipe {\n static id = 'messages.slack';\n static label = 'Slack';\n static summary = 'Read Slack messages from your connected workspaces.';\n static synonyms = [\n 'slack',\n 'slack messages',\n 'slack channels',\n 'workspace chat',\n 'team chat',\n ];\n static group = {\n id: 'messages',\n label: 'Messaging',\n summary: 'Choose email and personal updates independently.',\n };\n static section = {\n id: 'messages',\n label: 'Messaging',\n icon: 'folder',\n description: 'Read email and keep up with updates addressed to you.',\n };\n static models = [SlackMessage, SlackAccount];\n static nav = [\n {\n label: 'Slack messages',\n model: SlackMessage,\n key: 'slack-messages',\n icon: 'folder',\n noun: 'message',\n description: 'Read messages from your connected workspaces by channel.',\n },\n {\n label: 'Slack workspaces',\n model: SlackAccount,\n icon: 'users',\n noun: 'workspace',\n description: 'The workspaces your application is connected to.',\n },\n ];\n static help = './help/slack.md';\n static options = {\n SlackMessage: {\n fields: {\n channelName: { label: 'Channel', order: 1 },\n body: { label: 'Message', order: 2 },\n threadId: { label: 'Thread', order: 3 },\n sendStatus: { label: 'Sent status', order: 4 },\n accountId: { label: 'Workspace', order: 5 },\n fromName: { label: 'From', visibility: 'advanced' },\n fromAddress: { visibility: 'advanced' },\n toAddresses: { visibility: 'advanced' },\n subject: { visibility: 'advanced' },\n date: { visibility: 'advanced' },\n isRead: { visibility: 'advanced' },\n isFlagged: { visibility: 'advanced' },\n isEdited: { label: 'Edited', visibility: 'advanced' },\n messageType: { label: 'Message kind', visibility: 'advanced' },\n reactions: { visibility: 'advanced' },\n hasAttachments: { visibility: 'advanced' },\n channelId: { visibility: 'advanced' },\n sentAt: { visibility: 'advanced' },\n sendError: { visibility: 'advanced' },\n scheduledSendAt: { visibility: 'advanced' },\n inReplyToMessageId: { label: 'Replying to', visibility: 'advanced' },\n personaId: { visibility: 'advanced' },\n endpointId: { visibility: 'advanced' },\n retryCount: { visibility: 'hidden' },\n maxRetries: { visibility: 'hidden' },\n size: { visibility: 'hidden' },\n correlationId: { visibility: 'hidden' },\n slackTs: { visibility: 'hidden' },\n slackThreadTs: { visibility: 'hidden' },\n blocks: { visibility: 'hidden' },\n metadata: { visibility: 'hidden' },\n tenantId: { visibility: 'hidden' },\n created_at: { help: 'When this message was first recorded.' },\n updated_at: { help: 'When this message record was last changed.' },\n },\n },\n SlackAccount: {\n fields: {\n name: { order: 1 },\n workspaceName: { label: 'Workspace', order: 2 },\n isActive: { label: 'Enabled', order: 3 },\n lastSyncAt: { label: 'Last checked', order: 4 },\n workspaceId: { visibility: 'advanced' },\n credentialSecretId: { visibility: 'hidden' },\n settings: { visibility: 'hidden' },\n botUserId: { label: 'Bot user', visibility: 'advanced' },\n providerType: { visibility: 'advanced' },\n channelType: { visibility: 'advanced' },\n configuration: { visibility: 'advanced' },\n tenantId: { visibility: 'hidden' },\n created_at: {\n help: 'When this workspace connection was first recorded.',\n },\n updated_at: {\n help: 'When this workspace connection was last changed.',\n },\n },\n },\n } as const;\n}\n","/**\n * @happyvertical/smrt-messages\n *\n * Unified multi-channel messaging with STI-based hierarchies\n *\n * @packageDocumentation\n */\n\n// Self-register this package's manifest before any @smrt() decorator fires\n// downstream. Must come first so the side effect runs ahead of the class\n// module loads below. See __smrt-register__.ts for issue #1132 context.\nimport './__smrt-register__.js';\n\nimport { ensureMailAccessEnforcementRegistered } from './access-enforcement.js';\nimport { ensureMessagingPermissionsRegistered } from './permissions.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Per-account mail access (owner + grants; see access.ts)\n// ─────────────────────────────────────────────────────────────────────────\nexport {\n assertMailAccess,\n canAccessMailAccount,\n configureMailAccess,\n decideMailAccess,\n deniedMailAccountIds,\n type GrantMailAccessInput,\n isMailScope,\n isPersonMailPrincipal,\n MAIL_ACCOUNT_RESOURCE_TYPE,\n MAIL_SCOPES,\n type MailAccessAdmin,\n type MailAccessConfig,\n type MailAccessDecision,\n MailAccessError,\n type MailAccessReason,\n type MailAccessResolver,\n type MailAccessResolverContext,\n MailAccessService,\n type MailAccessSubject,\n type MailPrincipal,\n type MailScope,\n mailScopePermission,\n resetMailAccess,\n resolveMailPrincipal,\n runWithMailSystemAccess,\n} from './access.js';\nexport {\n MailDraftError,\n type MailDraftInput,\n MailDraftService,\n} from './mail-drafts.js';\nexport type {\n MailSyncOptions,\n MailSyncResult,\n MailSyncSkipReason,\n} from './mail-sync.js';\nexport {\n CHANGE_FEED_PROVIDERS,\n type EnqueueMailSyncOptions,\n enqueueDueMailSyncs,\n enqueueMailSync,\n MAIL_SYNC_QUEUE,\n mailSyncDedupeKey,\n} from './mail-sync-jobs.js';\nexport {\n type MailTriageAction,\n type MailTriageActionKind,\n type MailTriageFailure,\n type MailTriageResult,\n type MailWriteBackCapability,\n MailWriteBackUnsupportedError,\n} from './mail-triage.js';\n\nexport {\n type AgentSendPolicyContext,\n APPROVE_HELD_SEND_PERMISSION,\n auditMailAction,\n configureMailSendApprovals,\n effectiveAgentSendPolicy,\n type HeldSendDecisionResult,\n type HeldSendEdits,\n HeldSendError,\n type MailSendApprovalActor,\n type MailSendApprovalCheckResult,\n type MailSendApprovalConfig,\n type MailSendApprovalGate,\n type MailSendApprovalOutcome,\n MailSendApprovalService,\n type MailSendApprovalView,\n mailSendBindingHash,\n resetMailSendApprovals,\n stampHandledBy,\n threadHandledBy,\n} from './send-approval.js';\n\nimport { ensureBuiltinMessagingProvidersRegistered } from './providers.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Base classes (new)\n// ─────────────────────────────────────────────────────────────────────────\n\nexport { AccountCollection } from './collections/AccountCollection';\nexport { AttachmentCollection } from './collections/AttachmentCollection';\nexport { CorrespondentCollection } from './collections/CorrespondentCollection.js';\n// Base collections\nexport { MessageCollection } from './collections/MessageCollection';\nexport { MessagingEndpointCollection } from './collections/MessagingEndpointCollection.js';\nexport { NotificationDeliveryCollection } from './collections/NotificationDeliveryCollection.js';\nexport { NotificationOptOutCollection } from './collections/NotificationOptOutCollection.js';\nexport { PersonaMessageRouteCollection } from './collections/PersonaMessageRouteCollection.js';\nexport { UserNotificationCollection } from './collections/UserNotificationCollection.js';\nexport { Account } from './models/Account';\nexport { Attachment } from './models/Attachment';\nexport {\n Correspondent,\n type CorrespondentOptions,\n} from './models/Correspondent.js';\n// Base models\nexport { Message } from './models/Message';\nexport { MessagingEndpoint } from './models/MessagingEndpoint.js';\nexport {\n NOTIFICATION_DELIVERY_CHANNELS,\n NotificationDelivery,\n type NotificationDeliveryChannel,\n type NotificationDeliveryOptions,\n type NotificationDeliveryStatus,\n type NotificationDeliveryTransition,\n} from './models/NotificationDelivery.js';\nexport {\n isValidNotificationOptOutScope,\n NOTIFICATION_OPT_OUT_ALL_SCOPE,\n NOTIFICATION_OPT_OUT_SCOPE_PATTERN,\n NotificationOptOut,\n type NotificationOptOutOptions,\n} from './models/NotificationOptOut.js';\nexport { PersonaMessageRoute } from './models/PersonaMessageRoute.js';\nexport {\n USER_NOTIFICATION_SEVERITIES,\n UserNotification,\n type UserNotificationOptions,\n type UserNotificationSeverity,\n} from './models/UserNotification.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Email (backward-compatible)\n// ─────────────────────────────────────────────────────────────────────────\n\nexport { EmailAccountCollection } from './collections/EmailAccountCollection';\nexport { EmailAttachmentCollection } from './collections/EmailAttachmentCollection';\n// Email collections\nexport { EmailCollection } from './collections/EmailCollection';\nexport { EmailFolderCollection } from './collections/EmailFolderCollection';\n// Email models\nexport { Email } from './models/Email';\nexport { EmailAccount } from './models/EmailAccount';\nexport { EmailAttachment } from './models/EmailAttachment';\nexport { EmailFolder } from './models/EmailFolder';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Email filtering (whitelist/blacklist)\n// ─────────────────────────────────────────────────────────────────────────\n\nexport { BlacklistCollection } from './collections/BlacklistCollection';\nexport { WhitelistCollection } from './collections/WhitelistCollection';\nexport { Blacklist } from './models/Blacklist';\nexport { Whitelist } from './models/Whitelist';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Provider stubs\n// ─────────────────────────────────────────────────────────────────────────\n\n// Account types\nexport { SlackAccount } from './models/SlackAccount';\nexport { SlackMessage } from './models/SlackMessage';\nexport { TelegramAccount } from './models/TelegramAccount.js';\n// Message types\nexport { Tweet } from './models/Tweet';\nexport { TwitterAccount } from './models/TwitterAccount';\nexport { ZulipAccount } from './models/ZulipAccount.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Senders\n// ─────────────────────────────────────────────────────────────────────────\n\nexport {\n assertMessagingPermission,\n ensureMessagingPermissionsRegistered,\n MANAGE_MESSAGE_CREDENTIALS_PERMISSION,\n MANAGE_MESSAGE_ROUTES_PERMISSION,\n MESSAGES_ROLE_PERMISSION_MATRIX,\n MESSAGING_PERMISSION_DEFINITIONS,\n type MessagingPrincipal,\n messagingPrincipalFromPermissions,\n SEND_MESSAGES_PERMISSION,\n type SeedMessagesRolePermissionsResult,\n seedMessagesRolePermissions,\n} from './permissions.js';\nexport {\n ensureBuiltinMessagingProvidersRegistered,\n getMessagingProvider,\n listMessagingProviders,\n type MessagingProviderDefinition,\n type MessagingProviderField,\n type MessagingProviderFieldType,\n registerMessagingProvider,\n} from './providers.js';\nexport { EmailSender } from './senders/EmailSender';\nexport { SlackSender } from './senders/SlackSender';\nexport { TelegramSender } from './senders/TelegramSender.js';\nexport { TweetSender } from './senders/TweetSender';\nexport { ZulipSender } from './senders/ZulipSender.js';\nexport {\n type CorrespondentRefreshResult,\n CorrespondentService,\n type CorrespondentServiceOptions,\n type CorrespondentView,\n type ListCorrespondentsOptions,\n normalizeCorrespondentAddress,\n} from './services/CorrespondentService.js';\nexport {\n type MailProviderSearchResult,\n type MailSearchHit,\n type MailSearchPage,\n type MailSearchQuery,\n MailSearchService,\n type MailSearchServiceOptions,\n readableMailAccounts,\n} from './services/MailSearchService.js';\nexport {\n type ListAccountsOptions,\n type ListAccountsResult,\n type MessagingAccountInput,\n type MessagingAccountListing,\n type MessagingAccountView,\n type MessagingEndpointInput,\n type MessagingEndpointView,\n MessagingSettingsService,\n type PersonaMessageRouteInput,\n} from './services/MessagingSettingsService.js';\nexport {\n type NotificationOptOutChange,\n type NotificationOptOutDenialReason,\n NotificationOptOutDeniedError,\n type NotificationOptOutKey,\n type NotificationOptOutListRequest,\n type NotificationOptOutPrincipal,\n NotificationOptOutService,\n optOutSuppression,\n} from './services/NotificationOptOutService.js';\nexport {\n buildNotificationLink,\n messageSendTransport,\n type NotificationDispatchOptions,\n type NotificationDispatchOutcome,\n type NotificationDispatchReport,\n type NotificationEmailInput,\n type NotificationEnqueueResult,\n type NotificationOutboxDenialReason,\n NotificationOutboxDeniedError,\n type NotificationOutboxOptions,\n NotificationOutboxService,\n type NotificationProfileRecipientRequest,\n type NotificationProfileSuppressionRequest,\n type NotificationRecipient,\n type NotificationRecipientRequest,\n type NotificationReconcileOutcome,\n type NotificationSuppressionRequest,\n type NotificationTransport,\n type NotificationTransportOutcome,\n type NotificationTransportReconciliation,\n type NotificationTransportRequest,\n notificationDeliveryCorrelationId,\n notificationDeliveryMessageId,\n} from './services/NotificationOutboxService.js';\nexport {\n type PersonaMessageSendResult,\n PersonaMessagingService,\n} from './services/PersonaMessagingService.js';\nexport {\n type UserNotificationInput,\n type UserNotificationListOptions,\n type UserNotificationNotifyResult,\n type UserNotificationScope,\n UserNotificationService,\n} from './services/UserNotificationService.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────\n\nexport type {\n AccountOptions,\n AccountSearchFilters,\n AccountType,\n AgentSendPolicy,\n AttachmentOptions,\n // Email options (backward compat)\n EmailAccountOptions,\n EmailAccountSearchFilters,\n EmailAttachmentOptions,\n EmailFolderOptions,\n EmailFolderSearchFilters,\n EmailOptions,\n EmailSearchFilters,\n KnownMessagingChannel,\n // Base options\n MessageOptions,\n // Search filters\n MessageSearchFilters,\n MessageSenderInterface,\n // Send types\n MessageSendResult,\n // Discriminator types\n MessageType,\n MessagingChannel,\n MessagingEndpointOptions,\n PersonaMessageRouteOptions,\n ProviderType,\n SendEmailAttachment,\n SendEmailOptions,\n SendMessageOptions,\n SendPersonaMessageOptions,\n SendSlackOptions,\n SendStatus,\n SendTweetOptions,\n SlackAccountOptions,\n SlackMessageOptions,\n // Sync types\n SyncOptions,\n SyncProgress,\n SyncResult,\n // Provider options\n TweetOptions,\n TwitterAccountOptions,\n} from './types';\n\nensureBuiltinMessagingProvidersRegistered();\nensureMessagingPermissionsRegistered();\nensureMailAccessEnforcementRegistered();\n\nexport {\n assertNotificationProfileRecipientSchema,\n migrateNotificationProfileRecipients,\n type NotificationProfileRecipientEngine,\n type NotificationProfileRecipientPlan,\n planNotificationProfileRecipients,\n} from './migrations/profileRecipients.js';\nexport {\n type NotificationRecipientIdentity,\n PROFILE_NOTIFICATION_POLICY_PREFIX,\n profileNotificationPolicy,\n} from './notification-recipient-identity.js';\nexport { MailboxRecipe, NotificationsRecipe, SlackRecipe } from './recipes.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyCA,IAAM,gBAAsC;CAC1C,SAAS;CACT,OAAO;CACP,aAAa;CACb,YAAY;CACZ,SAAS;CACT,cAAc;CACd,iBAAiB;AACnB;AAEA,SAAS,SAAS,MAAe,MAAwB;CACvD,IAAI,OAAO,SAAS,YAAY,OAAO;CACvC,OACE,SAAS,QACR,KAA+B,qBAC7B;AAEP;AAEA,SAAS,OAAO,WAAmB,SAA0C;CAI3E,MAAM,QAFJ,eAAe,SAAS,QAAQ,sBAAsB,SAAS,KAC/D,eAAe,SAAS,SAAS,EAAA,EACV;CACzB,IAAI,MAAM;EACR,IAAI,SAAS,MAAM,OAAO,GAAG,OAAO;EACpC,IAAI,SAAS,MAAM,WAAW,GAAG,OAAO;EACxC,IAAI,SAAS,MAAM,UAAU,GAAG,OAAO;EACvC,IAAI,SAAS,MAAM,OAAO,GAAG,OAAO;EACpC,OAAO;CACT;CACA,OAAO,cAAc,cAAc;AACrC;AAGA,IAAM,mBAAmB;AAEzB,SAAS,SACP,OACA,QACA,aACsB;CAMtB,QAL4C,MAAM,QAAQ,KAAK,IAC3D,QACA,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,EAAA,CAGJ,SAAS,UAAU,CAC/B,CAAC,GAAG,OAAO,EAAE,oBAAoB,OAAO,CAAC,GACzC,GAAG,YAAY,KAAK,UAAU,CAAC,GAAG,OAAO,KAAK,CAAC,CACjD,CAAC;AACH;AAQA,eAAe,gBACb,MACA,UACkB;CAClB,MAAM,MAAM;CACZ,IAAI;EACF,MAAM,y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SAAS;GACtC,QAAQ,EAAE,YAAY,SAAS;GAC/B,UAAU,EAAE,YAAY,SAAS;GACjC,UAAU,EAAE,YAAY,SAAS;GACjC,YAAY,EAAE,MAAM,wCAAwC;GAC5D,YAAY,EAAE,MAAM,6CAA6C;EACnE,EACF;EACA,cAAc,EACZ,QAAQ;GACN,MAAM,EAAE,OAAO,EAAE;GACjB,eAAe;IAAE,OAAO;IAAa,OAAO;GAAE;GAC9C,UAAU;IAAE,OAAO;IAAW,OAAO;GAAE;GACvC,YAAY;IAAE,OAAO;IAAgB,OAAO;GAAE;GAC9C,aAAa,EAAE,YAAY,WAAW;GACtC,oBAAoB,EAAE,YAAY,SAAS;GAC3C,UAAU,EAAE,YAAY,SAAS;GACjC,WAAW;IAAE,OAAO;IAAY,YAAY;GAAW;GACvD,cAAc,EAAE,YAAY,WAAW;GACvC,aAAa,EAAE,YAAY,WAAW;GACtC,eAAe,EAAE,YAAY,WAAW;GACxC,UAAU,EAAE,YAAY,SAAS;GACjC,YAAY,EACV,MAAM,qDACR;GACA,YAAY,EACV,MAAM,mDACR;EACF,EACF;CACF;AACF;;;AC0DA,0CAA0C;AAC1C,qCAAqC;AACrC,sCAAsC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["registered","username","password","rest","hits","message","route"],"sources":["../src/access-enforcement.ts","../src/mail-drafts.ts","../src/mail-sync-jobs.ts","../src/models/Correspondent.ts","../src/collections/CorrespondentCollection.ts","../src/models/NotificationDelivery.ts","../src/collections/NotificationDeliveryCollection.ts","../src/models/NotificationOptOut.ts","../src/collections/NotificationOptOutCollection.ts","../src/models/PersonaMessageRoute.ts","../src/collections/PersonaMessageRouteCollection.ts","../src/models/UserNotification.ts","../src/collections/UserNotificationCollection.ts","../src/models/EmailAttachment.ts","../src/collections/EmailAttachmentCollection.ts","../src/models/Blacklist.ts","../src/collections/BlacklistCollection.ts","../src/models/Whitelist.ts","../src/collections/WhitelistCollection.ts","../src/models/SlackAccount.ts","../src/models/SlackMessage.ts","../src/models/TelegramAccount.ts","../src/models/Tweet.ts","../src/models/TwitterAccount.ts","../src/models/ZulipAccount.ts","../src/services/MessagingSettingsService.ts","../src/services/MailSearchService.ts","../src/services/CorrespondentService.ts","../src/services/NotificationOptOutService.ts","../src/migrations/profileRecipients.ts","../src/services/NotificationOutboxService.ts","../src/services/PersonaMessagingService.ts","../src/services/UserNotificationService.ts","../src/recipes.ts","../src/index.ts"],"sourcesContent":["/**\n * Collection-layer enforcement of per-account mail access (see `access.ts`).\n *\n * Registered once at package load as a `GlobalInterceptors` entry, so every\n * list/get/count/raw read of an owned account's emails, folders and\n * attachments is filtered in the collection, not in a component. Matching is\n * by STI ancestry, so an app subclass of `Email` is governed too.\n *\n * Account rows themselves are not filtered here: senders, routes and the\n * outbox read them without a principal, and the content (emails, folders,\n * attachments) is what an account grant protects.\n *\n * @packageDocumentation\n */\n\nimport {\n type CollectionInterceptor,\n GlobalInterceptors,\n type InterceptorContext,\n type ListOptions,\n ObjectRegistry,\n type QueryInterceptResult,\n type QueryOptions,\n type SmrtObject,\n} from '@happyvertical/smrt-core';\nimport {\n assertHydratedMailAccess,\n deniedMailAccountIds,\n getEffectiveMailAccessConfigs,\n inMailSystemAccess,\n learnMailAccessOptions,\n MailAccessError,\n runWithMailSystemAccess,\n} from './access.js';\nimport { Account } from './models/Account.js';\nimport { Attachment } from './models/Attachment.js';\nimport { EmailFolder } from './models/EmailFolder.js';\nimport { Message } from './models/Message.js';\n\ntype Kind = 'message' | 'folder' | 'attachment' | 'account';\n\nconst NAME_FALLBACK: Record<string, Kind> = {\n Message: 'message',\n Email: 'message',\n EmailFolder: 'folder',\n Attachment: 'attachment',\n Account: 'account',\n EmailAccount: 'account',\n EmailAttachment: 'attachment',\n};\n\nfunction descends(ctor: unknown, base: unknown): boolean {\n if (typeof ctor !== 'function') return false;\n return (\n ctor === base ||\n (ctor as { prototype: object }).prototype instanceof\n (base as new () => object)\n );\n}\n\nfunction kindOf(className: string, context: InterceptorContext): Kind | null {\n const registered =\n ObjectRegistry.getClass(context.qualifiedClassName ?? className) ??\n ObjectRegistry.getClass(className);\n const ctor = registered?.constructor;\n if (ctor) {\n if (descends(ctor, Message)) return 'message';\n if (descends(ctor, EmailFolder)) return 'folder';\n if (descends(ctor, Attachment)) return 'attachment';\n if (descends(ctor, Account)) return 'account';\n return null;\n }\n return NAME_FALLBACK[className] ?? null;\n}\n\n/** SQL parameter budget for one exclusion list; beyond it, fail closed. */\nconst MAX_EXCLUDED_IDS = 900;\n\nfunction restrict(\n where: ListOptions['where'],\n denied: string[],\n unaccounted: Record<string, unknown>[],\n): ListOptions['where'] {\n const groups: Record<string, unknown>[][] = Array.isArray(where)\n ? where\n : [[where ?? {}]];\n // NOT IN drops NULL accountIds, so rows with no account are added back\n // explicitly, and only the shapes that are provably not a mailbox's.\n return groups.flatMap((group) => [\n [...group, { 'accountId not in': denied }],\n ...unaccounted.map((extra) => [...group, extra]),\n ]);\n}\n\ntype Row = {\n accountId?: string | null;\n messageId?: string | null;\n options?: unknown;\n};\n\nasync function allowedInstance(\n kind: Kind,\n instance: SmrtObject,\n): Promise<boolean> {\n const row = instance as unknown as Row;\n try {\n await assertHydratedMailAccess(\n kind === 'attachment'\n ? row\n : { accountId: row.accountId, options: row.options },\n );\n return true;\n } catch (error) {\n if (error instanceof MailAccessError) return false;\n throw error;\n }\n}\n\nexport const MAIL_ACCESS_INTERCEPTOR_NAME = 'smrt-messages-account-access';\n\nexport function createMailAccessInterceptor(): CollectionInterceptor {\n return {\n name: MAIL_ACCESS_INTERCEPTOR_NAME,\n // After tenancy (100) so tenant scoping has already narrowed the read.\n priority: 50,\n\n onCollectionReady(className, collection, context) {\n // Every read path starts here, whichever collection class serves the\n // item (a default collection for an app subclass or Tweet included), so\n // the database is registered before any filtering decision.\n if (!kindOf(className, context)) return;\n learnMailAccessOptions({\n ...(collection.options as object),\n db: collection.db,\n } as never);\n },\n\n async beforeList(className, options, context) {\n if (!getEffectiveMailAccessConfigs().length || inMailSystemAccess()) {\n return options;\n }\n const kind = kindOf(className, context);\n if (!kind || kind === 'account') return options;\n const denied = await deniedMailAccountIds('read');\n if (!denied.length) return options;\n if (denied.length > MAX_EXCLUDED_IDS) {\n throw new MailAccessError('read', 'denied');\n }\n const unaccounted =\n kind === 'attachment'\n ? [\n { accountId: null, messageId: null },\n { accountId: null, messageId: '' },\n ]\n : [{ accountId: null }];\n return {\n ...options,\n where: restrict(options.where, denied, unaccounted),\n };\n },\n\n async beforeSave(instance, context) {\n const kind = kindOf(instance.constructor.name, context);\n if (kind === 'account') {\n learnMailAccessOptions((instance as unknown as Row).options as never);\n return;\n }\n if (kind !== 'attachment') return;\n const row = instance as unknown as Row;\n // Always derive the account from the message: a caller-supplied\n // accountId (for instance through a generated create) is never trusted.\n row.accountId = null;\n if (!row.messageId || !row.options) return;\n const { MessageCollection } = await import(\n './collections/MessageCollection.js'\n );\n const message = await runWithMailSystemAccess(async () =>\n (await MessageCollection.create(row.options as never)).get({\n id: row.messageId as string,\n }),\n );\n row.accountId = message?.accountId || null;\n },\n\n async afterList(className, results, context) {\n if (inMailSystemAccess()) return results;\n const kind = kindOf(className, context);\n if (!kind) return results;\n if (kind === 'account') {\n for (const item of results) {\n learnMailAccessOptions((item as unknown as Row).options as never);\n }\n return results;\n }\n // Filters hydrated rows (the only filter for legacy attachments) and\n // defends rows that reached here by another path.\n const kept: typeof results = [];\n const cache = new Map<string, boolean>();\n for (const item of results) {\n const row = item as unknown as Row;\n const key = `${kind}:${row.accountId ?? ''}:${row.messageId ?? ''}`;\n let ok = cache.get(key);\n if (ok === undefined) {\n ok = await allowedInstance(kind, item);\n cache.set(key, ok);\n }\n if (ok) kept.push(item);\n }\n return kept;\n },\n\n async afterGet(className, instance, context) {\n if (!instance || inMailSystemAccess()) return instance;\n const kind = kindOf(className, context);\n if (!kind) return instance;\n if (kind === 'account') {\n learnMailAccessOptions((instance as unknown as Row).options as never);\n return instance;\n }\n return (await allowedInstance(kind, instance)) ? instance : null;\n },\n\n async beforeQuery(\n className,\n options: QueryOptions,\n context,\n ): Promise<QueryInterceptResult> {\n const unchanged = { sql: options.sql, params: options.params };\n if (!getEffectiveMailAccessConfigs().length || inMailSystemAccess()) {\n return unchanged;\n }\n const kind = kindOf(className, context);\n if (!kind || kind === 'account') return unchanged;\n // Raw SQL cannot be narrowed to granted accounts. When any account is\n // closed to the principal, refuse rather than leak its rows.\n if ((await deniedMailAccountIds('read')).length) {\n throw new MailAccessError('read', 'denied');\n }\n return unchanged;\n },\n };\n}\n\nlet registered = false;\n\n/** Idempotent; called at package load. */\nexport function ensureMailAccessEnforcementRegistered(): void {\n if (registered) return;\n registered = true;\n GlobalInterceptors.register(createMailAccessInterceptor());\n}\n","/**\n * Mail drafts for people and agents (smrt#5141, Epic I).\n *\n * `MailDraftService.save()` creates or updates a local draft `Email` on one\n * mail account, under the host-supplied acting principal:\n *\n * - The principal needs the `draft` scope on the account (and `read` to reply\n * to a message there). Fail closed, like every mail access decision.\n * - The draft is always from the account's own address: sending as another\n * person is not possible through this service.\n * - Only an unsent draft (`isDraft`, `sendStatus` `draft`) of the same\n * account can be updated. Updating a draft that waits for approval changes\n * its content, so the waiting approval no longer applies to it.\n * - The acting principal is recorded as \"handled by\".\n *\n * `submit()` sends the draft through `Message.send()`, so the account's agent\n * send policy decides whether an agent's draft leaves or waits for a person.\n * Drafts are local rows; writing them to the mail server is a later step.\n *\n * @packageDocumentation\n */\n\nimport {\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport {\n assertMailAccess,\n MailAccessError,\n resolveMailPrincipal,\n runWithMailSystemAccess,\n withoutListBounds,\n} from './access.js';\nimport type { Email } from './models/Email.js';\nimport type { EmailAccount } from './models/EmailAccount.js';\nimport { auditMailAction, stampHandledBy } from './send-approval.js';\nimport type { MessageSendResult, SendEmailOptions } from './types.js';\n\ntype Recipient = { address: string; name?: string };\n\nexport interface MailDraftInput {\n /** The mail account the draft is sent from. */\n accountId: string;\n /** Update this draft instead of creating one. */\n draftId?: string;\n /** Create a reply to this message (new drafts only). */\n inReplyToMessageId?: string;\n /** With `inReplyToMessageId`: copy the original To and Cc. */\n replyAll?: boolean;\n subject?: string;\n textBody?: string;\n htmlBody?: string;\n toAddresses?: Recipient[];\n ccAddresses?: Recipient[];\n bccAddresses?: Recipient[];\n}\n\nexport class MailDraftError extends Error {\n readonly status: number;\n constructor(message: string, status = 400) {\n super(message);\n this.name = 'MailDraftError';\n this.status = status;\n }\n}\n\nfunction assertRecipients(value: unknown, label: string): void {\n if (value === undefined) return;\n if (\n !Array.isArray(value) ||\n value.some(\n (entry) =>\n !entry ||\n typeof entry.address !== 'string' ||\n !entry.address.includes('@') ||\n (entry.name !== undefined && typeof entry.name !== 'string'),\n )\n ) {\n throw new MailDraftError(`${label} must be a list of { address, name? }.`);\n }\n}\n\nexport class MailDraftService {\n constructor(private readonly options: SmrtClassOptions) {}\n\n private async account(accountId: string): Promise<EmailAccount> {\n const { EmailAccountCollection } = await import(\n './collections/EmailAccountCollection.js'\n );\n const account = (await runWithMailSystemAccess(async () =>\n (\n await EmailAccountCollection.create(withoutListBounds(this.options))\n ).get({ id: accountId }),\n )) as EmailAccount | null;\n if (!account?.id) {\n throw new MailDraftError('Mail account not found.', 404);\n }\n return account;\n }\n\n private async stored(id: string): Promise<Email | null> {\n const { EmailCollection } = await import(\n './collections/EmailCollection.js'\n );\n return (await runWithMailSystemAccess(async () =>\n (await EmailCollection.create(this.options as never)).get({ id }),\n )) as Email | null;\n }\n\n /** Create or update a draft. Returns the saved draft. */\n async save(input: MailDraftInput): Promise<Email> {\n assertRecipients(input.toAddresses, 'toAddresses');\n assertRecipients(input.ccAddresses, 'ccAddresses');\n assertRecipients(input.bccAddresses, 'bccAddresses');\n const account = await this.account(input.accountId);\n const principal = await resolveMailPrincipal();\n if (\n principal &&\n account.tenantId &&\n principal.tenantId !== account.tenantId\n ) {\n throw new MailAccessError('draft', 'tenant_mismatch');\n }\n await assertMailAccess(account, 'draft');\n\n let draft: Email;\n if (input.draftId) {\n const existing = await this.stored(input.draftId);\n if (!existing || existing.accountId !== account.id) {\n throw new MailDraftError('Draft not found.', 404);\n }\n if (!existing.isDraft || existing.sendStatus !== 'draft') {\n throw new MailDraftError('Only an unsent draft can be changed.', 409);\n }\n draft = existing;\n } else if (input.inReplyToMessageId) {\n await assertMailAccess(account, 'read');\n const original = await this.stored(input.inReplyToMessageId);\n if (!original || original.accountId !== account.id) {\n throw new MailDraftError('Message not found.', 404);\n }\n draft = original.createReply({ replyAll: input.replyAll === true });\n await draft.initialize();\n } else {\n const { Email: EmailClass } = await import('./models/Email.js');\n const Draft = ObjectRegistry.resolveEffectiveConstructor(EmailClass);\n draft = new Draft({\n ...(this.options as Record<string, unknown>),\n tenantId: account.tenantId,\n accountId: account.id as string,\n isDraft: true,\n sendStatus: 'draft',\n isRead: true,\n toAddresses: '[]',\n ccAddresses: '[]',\n bccAddresses: '[]',\n });\n await draft.initialize();\n }\n\n if (input.subject !== undefined) draft.subject = input.subject;\n if (input.textBody !== undefined) {\n draft.textBody = input.textBody;\n draft.body = input.textBody;\n }\n if (input.htmlBody !== undefined) draft.htmlBody = input.htmlBody;\n if (input.toAddresses !== undefined)\n draft.toAddresses = JSON.stringify(input.toAddresses);\n if (input.ccAddresses !== undefined)\n draft.ccAddresses = JSON.stringify(input.ccAddresses);\n if (input.bccAddresses !== undefined)\n draft.bccAddresses = JSON.stringify(input.bccAddresses);\n // Always from the account's own address (no sending as someone else).\n draft.fromAddress = account.email;\n draft.tenantId = account.tenantId;\n draft.accountId = account.id as string;\n draft.isDraft = true;\n draft.sendStatus = 'draft';\n draft.updatedAt = new Date();\n stampHandledBy(draft, principal);\n await draft.save();\n await auditMailAction('messages.draft.save', draft);\n return draft;\n }\n\n /**\n * Send a draft. The account's agent send policy applies: an agent's draft\n * normally comes back with `pendingApproval` and waits for a person.\n */\n async submit(\n draftId: string,\n options?: SendEmailOptions,\n ): Promise<MessageSendResult> {\n const draft = await this.stored(draftId);\n if (!draft?.accountId || !draft.isDraft) {\n throw new MailDraftError('Draft not found.', 404);\n }\n const account = await this.account(draft.accountId);\n await assertMailAccess(account, 'draft');\n return await draft.send(options);\n }\n}\n","/**\n * Mail sync as an idempotent background job (Epic I, #5130).\n *\n * The job is `EmailAccount.syncChanges()` on one account, run by the\n * `@happyvertical/smrt-jobs` TaskRunner. One account has one lane: the job is\n * deduplicated per tenant and account, so asking twice while a run is pending\n * or running returns the same job. Runs are at-least-once and safe to repeat:\n * the change-feed cursor only moves after a batch is applied.\n *\n * `@happyvertical/smrt-jobs` is a regular dependency, loaded lazily on first use. A host\n * that schedules mail sync installs it and runs a TaskRunner on the\n * {@link MAIL_SYNC_QUEUE} queue (and calls these helpers from its scheduler).\n *\n * @packageDocumentation\n */\n\nimport { ObjectRegistry } from '@happyvertical/smrt-core';\nimport type { DatabaseInterface } from '@happyvertical/sql';\nimport type { MailSyncOptions } from './mail-sync.js';\nimport type { EmailAccount } from './models/EmailAccount';\n\n/** Queue the mail sync jobs run on. */\nexport const MAIL_SYNC_QUEUE = 'mail-sync';\n\n/** Providers whose server offers the change feed. */\nexport const CHANGE_FEED_PROVIDERS: readonly string[] = ['jmap'];\n\nexport interface EnqueueMailSyncOptions extends MailSyncOptions {\n /** When to run. Default: now. */\n runAt?: Date;\n /** Job priority (higher runs sooner). */\n priority?: number;\n /** Attempts before the job fails for good. Default 3. */\n maxAttempts?: number;\n /** Job timeout in milliseconds. Default 15 minutes. */\n timeout?: number;\n}\n\n/** The dedupe key that makes one account one lane. */\nexport function mailSyncDedupeKey(accountId: string): string {\n return `mail-sync:${accountId}`;\n}\n\nfunction accountClassName(): string {\n const registered =\n ObjectRegistry.getClass('EmailAccount') ??\n ObjectRegistry.getClassByQualifiedName(\n '@happyvertical/smrt-messages:EmailAccount',\n );\n return registered?.qualifiedName ?? registered?.name ?? 'EmailAccount';\n}\n\n/**\n * Queue a sync of one account. Returns the queued (or already pending/running)\n * job, or null when the account is closed to sync (inactive, needing\n * reconnection, no change feed): nothing is queued for it.\n */\nexport async function enqueueMailSync(\n account: EmailAccount,\n options: EnqueueMailSyncOptions = {},\n) {\n if (!account.id) throw new Error('enqueueMailSync needs a persisted account');\n if (!account.isActive || account.needsReconnect) return null;\n if (!CHANGE_FEED_PROVIDERS.includes(account.providerType)) return null;\n const { SmrtJobCollection } = await import('@happyvertical/smrt-jobs');\n const db = account.db as DatabaseInterface;\n const jobs = await SmrtJobCollection.create({ db });\n const args: Record<string, unknown> = {};\n if (options.limit !== undefined) args.limit = options.limit;\n if (options.maxBatches !== undefined) args.maxBatches = options.maxBatches;\n if (options.since !== undefined) {\n args.since = options.since ? new Date(options.since).toISOString() : null;\n }\n return jobs.enqueueJob({\n dedupeKey: mailSyncDedupeKey(account.id),\n tenantId: account.tenantId ?? null,\n queue: MAIL_SYNC_QUEUE,\n objectType: accountClassName(),\n objectId: account.id,\n method: 'syncChanges',\n // The runner calls the method with this object as its one argument.\n args,\n runAt: options.runAt,\n priority: options.priority,\n maxAttempts: options.maxAttempts ?? 3,\n timeout: options.timeout ?? 15 * 60 * 1000,\n });\n}\n\n/**\n * Queue a sync for every active account that is due (never synced, or last\n * synced at least its `syncIntervalMinutes` ago). Safe to call on every\n * scheduler tick: accounts that already have a job queued are not duplicated.\n */\nexport async function enqueueDueMailSyncs(\n accounts: EmailAccount[],\n options: EnqueueMailSyncOptions & { now?: Date } = {},\n): Promise<string[]> {\n const now = (options.now ?? new Date()).getTime();\n const queued: string[] = [];\n for (const account of accounts) {\n const due =\n !account.lastSyncAt ||\n now - account.lastSyncAt.getTime() >=\n (account.syncIntervalMinutes || 0) * 60_000;\n if (!due) continue;\n const job = await enqueueMailSync(account, options);\n if (job?.id) queued.push(String(job.id));\n }\n return queued;\n}\n","import type { SmrtObjectOptions } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n crossPackageRef,\n field,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\n\nexport interface CorrespondentOptions extends SmrtObjectOptions {\n tenantId?: string;\n ownerUserId?: string;\n address?: string;\n displayName?: string;\n messageCount?: number;\n sentCount?: number;\n receivedCount?: number;\n firstContactAt?: Date | null;\n lastContactAt?: Date | null;\n accountIds?: string;\n accountBreakdown?: string;\n profileId?: string | null;\n}\n\n/**\n * Someone one person writes to or hears from, derived from that person's\n * synced mail (#5132). Private to its owner: every row belongs to one\n * `ownerUserId`, is never shared across the tenant, and is read and changed\n * only through `CorrespondentService`, which filters on the acting user. The\n * generated REST/MCP/CLI surfaces are off for that reason.\n *\n * Everything but the address is optional: a correspondent has no name until\n * mail carries one, and no `profileId` until the owner links a smrt-profiles\n * `Profile` on purpose. Deriving never creates or links a `Profile`.\n * `accountIds` (JSON array) records which of the owner's readable mail\n * accounts the address was seen in, so the service can hide a correspondent\n * once the owner loses read access to every one of them.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'correspondents',\n api: false,\n mcp: false,\n cli: false,\n conflictColumns: ['tenant_id', 'owner_user_id', 'address'],\n indexes: [\n {\n name: 'correspondents_owner_last_contact_idx',\n columns: ['tenantId', 'ownerUserId', 'lastContactAt'],\n },\n ],\n})\nexport class Correspondent extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n /** The one person this row is private to (`smrt-users:User`, uuid). */\n @crossPackageRef('@happyvertical/smrt-users:User', {\n required: true,\n requiredFor: 'identity',\n })\n ownerUserId = '';\n\n /** Lower-cased email address. */\n @field({ required: true, requiredFor: 'identity' })\n address = '';\n\n /** The most recent name mail used for this address; may be empty. */\n displayName = '';\n\n /** Messages the owner can read that mention this address. */\n messageCount = 0;\n /** Of those, messages sent by this address. */\n sentCount = 0;\n /** Of those, messages sent to or copied to this address. */\n receivedCount = 0;\n\n firstContactAt: Date | null = null;\n lastContactAt: Date | null = null;\n\n /** JSON array of mail account ids the address was seen in. */\n accountIds = '[]';\n\n /**\n * JSON object keyed by mail account id with that account's own sent and\n * received counts, first/last contact, and latest name. The service builds\n * every view from the accounts the viewer can read only; the top-level\n * counts above are totals kept for storage and are never shown on their own.\n */\n accountBreakdown = '{}';\n\n /** Optional link to a smrt-profiles `Profile`, set only by the owner. */\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', { nullable: true })\n profileId: string | null = null;\n\n constructor(options: CorrespondentOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.ownerUserId !== undefined)\n this.ownerUserId = options.ownerUserId;\n if (options.address !== undefined) this.address = options.address;\n if (options.displayName !== undefined)\n this.displayName = options.displayName;\n if (options.messageCount !== undefined)\n this.messageCount = options.messageCount;\n if (options.sentCount !== undefined) this.sentCount = options.sentCount;\n if (options.receivedCount !== undefined)\n this.receivedCount = options.receivedCount;\n if (options.firstContactAt !== undefined)\n this.firstContactAt = options.firstContactAt;\n if (options.lastContactAt !== undefined)\n this.lastContactAt = options.lastContactAt;\n if (options.accountIds !== undefined) this.accountIds = options.accountIds;\n if (options.accountBreakdown !== undefined)\n this.accountBreakdown = options.accountBreakdown;\n if (options.profileId !== undefined) this.profileId = options.profileId;\n }\n\n /** Account ids this address was seen in (empty on unreadable JSON). */\n get seenInAccountIds(): string[] {\n try {\n const parsed = JSON.parse(this.accountIds || '[]');\n return Array.isArray(parsed)\n ? parsed.filter((id): id is string => typeof id === 'string')\n : [];\n } catch {\n return [];\n }\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { Correspondent } from '../models/Correspondent.js';\n\nexport class CorrespondentCollection extends SmrtCollection<Correspondent> {\n static readonly _itemClass = Correspondent;\n}\n","import type {\n SmrtObjectOptions,\n SmrtSaveOptions,\n} from '@happyvertical/smrt-core';\nimport { isDeepStrictEqual } from '../host.js';\nimport { assertNotificationRecipientIdentity } from '../notification-recipient-identity.js';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n type CollectionInterceptor,\n crossPackageRef,\n field,\n foreignKey,\n GlobalInterceptors,\n SmrtObject,\n smrt,\n usesEmbeddedRevisionFallback,\n withEmbeddedWriteQueue,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\n\n/** Channels the notification outbox can deliver through. */\nexport type NotificationDeliveryChannel = 'email';\n\nexport const NOTIFICATION_DELIVERY_CHANNELS: readonly NotificationDeliveryChannel[] =\n ['email'];\n\n/**\n * Where a delivery is in its lifecycle.\n *\n * - `pending`: waiting for `nextAttemptAt`.\n * - `sending`: leased by one dispatcher until `leaseExpiresAt`.\n * - `sent`: the provider accepted it (terminal).\n * - `failed`: rejected for good or out of attempts (terminal).\n * - `uncertain`: handed to a provider whose outcome is unknown; waits for\n * reconciliation and is never resent automatically.\n * - `cancelled`: suppressed by the host before handoff (terminal).\n */\nexport type NotificationDeliveryStatus =\n | 'pending'\n | 'sending'\n | 'sent'\n | 'failed'\n | 'uncertain'\n | 'cancelled';\n\nexport interface NotificationDeliveryOptions extends SmrtObjectOptions {\n tenantId?: string;\n recipientUserId?: string | null;\n recipientProfileId?: string | null;\n recipientKind?: 'user' | 'profile';\n channel?: NotificationDeliveryChannel;\n sourceRef?: string;\n kind?: string;\n requiredDispatchPolicy?: string;\n dispatchPolicyBinding?: string;\n subject?: string;\n textBody?: string;\n href?: string;\n recipientAddress?: string;\n recipientName?: string;\n accountId?: string;\n messageId?: string | null;\n status?: NotificationDeliveryStatus;\n stateVersion?: number;\n transitionId?: string;\n attempts?: number;\n maxAttempts?: number;\n nextAttemptAt?: Date;\n leaseToken?: string | null;\n leaseExpiresAt?: Date | null;\n handedOffAt?: Date | null;\n deliveredAt?: Date | null;\n providerMessageId?: string;\n lastError?: string;\n}\n\n/** Column values a lease transition may change (camelCase field names). */\nexport type NotificationDeliveryTransition = Partial<\n Pick<\n NotificationDelivery,\n | 'messageId'\n | 'status'\n | 'attempts'\n | 'nextAttemptAt'\n | 'leaseToken'\n | 'leaseExpiresAt'\n | 'handedOffAt'\n | 'deliveredAt'\n | 'providerMessageId'\n | 'lastError'\n >\n>;\n\nconst TRANSITION_COLUMNS: Record<keyof NotificationDeliveryTransition, string> =\n {\n messageId: 'message_id',\n status: 'status',\n attempts: 'attempts',\n nextAttemptAt: 'next_attempt_at',\n leaseToken: 'lease_token',\n leaseExpiresAt: 'lease_expires_at',\n handedOffAt: 'handed_off_at',\n deliveredAt: 'delivered_at',\n providerMessageId: 'provider_message_id',\n lastError: 'last_error',\n };\n\n// Private owning-policy snapshots reach Core's final INSERT/UPDATE predicate.\n// An unnamed interceptor is retained by reference: reloaded module instances\n// cannot replace another active save's lexical WeakMap with a fresh empty map.\nconst saveGuards = new WeakMap<SmrtObject, Record<string, unknown>>();\nconst activeSaves = new WeakSet<SmrtObject>();\nconst saveGuardInterceptor: CollectionInterceptor = {\n writeGuard: (instance) => saveGuards.get(instance),\n bulkMutation: {\n compatible: (className) =>\n className !== 'NotificationDelivery' &&\n className !== '@happyvertical/smrt-messages:NotificationDelivery',\n },\n};\n\n/**\n * One durable, source-keyed notification delivery to one person over one\n * external channel (the outbox row behind `NotificationOutboxService`).\n *\n * `sourceRef` is the idempotency key: one row per\n * `(tenant, recipient, channel, sourceRef)` (the conflict identity), and that\n * row produces at most one outbound `Message`. The recipient address is a\n * snapshot taken from the host's recipient resolver at enqueue time, never a\n * caller-chosen address.\n *\n * Every state change after creation goes through {@link transition}, a\n * compare-and-set on `stateVersion`, so concurrent dispatchers cannot both\n * hold the lease or overwrite each other's outcome. Generated REST/MCP/CLI\n * are off: rows carry recipient addresses and are reached only through the\n * service.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'notification_deliveries',\n api: false,\n mcp: false,\n cli: false,\n conflictColumns: [\n 'tenant_id',\n 'recipient_kind',\n 'recipient_user_id',\n 'recipient_profile_id',\n 'channel',\n 'source_ref',\n ],\n indexes: [\n {\n name: 'notification_deliveries_user_identity',\n columns: ['tenantId', 'recipientUserId', 'channel', 'sourceRef'],\n unique: true,\n },\n {\n name: 'notification_deliveries_profile_identity',\n columns: ['tenantId', 'recipientProfileId', 'channel', 'sourceRef'],\n unique: true,\n },\n {\n name: 'notification_deliveries_due_idx',\n columns: ['status', 'nextAttemptAt'],\n },\n {\n name: 'notification_deliveries_lease_idx',\n columns: ['status', 'leaseExpiresAt'],\n },\n ],\n})\nexport class NotificationDelivery extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n /** The person being told (`smrt-users:User`, uuid). */\n @crossPackageRef('@happyvertical/smrt-users:User', { nullable: true })\n recipientUserId: string | null = null;\n\n /** Stable external contact identity; never a fabricated auth account. */\n @crossPackageRef('@happyvertical/smrt-profiles:Profile', { nullable: true })\n recipientProfileId: string | null = null;\n\n /**\n * Exactly one of `recipientUserId` and `recipientProfileId` is set, and this\n * says which. Neither column is required alone: the either/or rule is a\n * cross-field check (`assertNotificationRecipientIdentity`, run on every\n * save). Legacy rows remain users.\n */\n @field({ required: true, requiredFor: 'identity' })\n recipientKind: 'user' | 'profile' = 'user';\n\n /** Delivery channel; only `email` today. */\n @field({ required: true, requiredFor: 'identity' })\n channel: NotificationDeliveryChannel = 'email';\n\n /** Idempotency key for the underlying event (see class docs). */\n @field({ required: true, requiredFor: 'idempotency' })\n sourceRef = '';\n\n /** Host-defined type, e.g. `project-question.asked`. */\n @field({ required: true, requiredFor: 'identity' })\n kind = '';\n\n /** Trusted host policy required at every provider handoff; empty is legacy ordinary mail. */\n requiredDispatchPolicy = '';\n\n /** Immutable host-approved resource/version/digest binding, serialized JSON. */\n @field({ type: 'json' })\n dispatchPolicyBinding = '{}';\n\n /** Email subject line. */\n @field()\n subject = '';\n\n /** Plain-text body; the deep link is appended on its own line. */\n @field()\n textBody = '';\n\n /** Absolute deep link on the host's configured origin (no credentials). */\n @field()\n href = '';\n\n /** Address snapshot from the host recipient resolver. */\n @field({ required: true, requiredFor: 'identity' })\n recipientAddress = '';\n\n /** Display name snapshot from the host recipient resolver. */\n recipientName = '';\n\n /** Sender `EmailAccount` in the same tenant. */\n @foreignKey('Account')\n accountId = '';\n\n /** The single outbound `Message` (created under the first lease). */\n @foreignKey('Message')\n messageId: string | null = null;\n\n status: NotificationDeliveryStatus = 'pending';\n\n /** Compare-and-set counter; bumped by every transition. */\n stateVersion = 0;\n\n /** Unique id of the transition that wrote the current state. */\n transitionId = '';\n\n /** Leases acquired so far (provider handoffs are a subset). */\n attempts = 0;\n\n /** Lease budget before the delivery fails for good. */\n maxAttempts = 5;\n\n /** Earliest time a dispatcher may lease a `pending` row. */\n nextAttemptAt = new Date();\n\n /** Proof of the current lease holder; cleared when the lease ends. */\n leaseToken: string | null = null;\n\n /** When the current lease lapses and the row becomes recoverable. */\n leaseExpiresAt: Date | null = null;\n\n /** Set just before the current attempt reaches the provider. */\n handedOffAt: Date | null = null;\n\n /** When the provider accepted the message. */\n deliveredAt: Date | null = null;\n\n /** Provider message id, when the provider returns one. */\n providerMessageId = '';\n\n /** The latest failure or uncertainty reason. */\n lastError = '';\n\n constructor(options: NotificationDeliveryOptions = {}) {\n super(options);\n const assign = <K extends keyof NotificationDeliveryOptions>(key: K) => {\n if (options[key] !== undefined) {\n (this as unknown as Record<string, unknown>)[key as string] =\n options[key];\n }\n };\n for (const key of [\n 'tenantId',\n 'recipientUserId',\n 'recipientProfileId',\n 'recipientKind',\n 'channel',\n 'sourceRef',\n 'kind',\n 'requiredDispatchPolicy',\n 'dispatchPolicyBinding',\n 'subject',\n 'textBody',\n 'href',\n 'recipientAddress',\n 'recipientName',\n 'accountId',\n 'messageId',\n 'status',\n 'stateVersion',\n 'transitionId',\n 'attempts',\n 'maxAttempts',\n 'nextAttemptAt',\n 'leaseToken',\n 'leaseExpiresAt',\n 'handedOffAt',\n 'deliveredAt',\n 'providerMessageId',\n 'lastError',\n ] as const) {\n assign(key);\n }\n }\n\n /** Protected consent and document bindings cannot be downgraded by ordinary saves. */\n override async save(options?: SmrtSaveOptions): Promise<this> {\n if (activeSaves.has(this))\n throw new Error(\n 'Concurrent saves of one notification delivery are not supported.',\n );\n activeSaves.add(this);\n try {\n return await this.saveWithGuard(options);\n } finally {\n saveGuards.delete(this);\n activeSaves.delete(this);\n }\n }\n\n private async saveWithGuard(options?: SmrtSaveOptions): Promise<this> {\n assertNotificationRecipientIdentity(this);\n\n if (\n this.kind.startsWith('protected:') &&\n (!this.requiredDispatchPolicy ||\n this.kind !== `protected:${this.requiredDispatchPolicy}`)\n ) {\n throw new Error(\n 'Protected notification kinds require their exact dispatch policy.',\n );\n }\n // Use Core's existing missing-schema contract before any protection query.\n // Initialization defers table verification and must not load over patches.\n await this.verifyStorageReady();\n let stored: Record<string, unknown> | undefined;\n if (this.id) {\n const { rows } = await this.db.query(\n 'SELECT tenant_id, required_dispatch_policy, dispatch_policy_binding, source_ref, recipient_user_id, recipient_profile_id, recipient_kind, recipient_address, account_id, kind, subject, text_body, href, recipient_name, channel, status, state_version, transition_id, attempts, max_attempts, next_attempt_at, lease_token, lease_expires_at, handed_off_at, delivered_at, provider_message_id, last_error, message_id FROM notification_deliveries WHERE id = ?',\n this.id,\n );\n stored = rows[0] as Record<string, unknown> | undefined;\n }\n if (!stored) {\n // A new-ID clone can still upsert the same natural identity. Authorize against that row too.\n const existing = await this.db.query(\n 'SELECT * FROM notification_deliveries WHERE tenant_id=? AND recipient_kind=? AND recipient_user_id IS NOT DISTINCT FROM ? AND recipient_profile_id IS NOT DISTINCT FROM ? AND channel=? AND source_ref=?',\n this.tenantId,\n this.recipientKind,\n this.recipientUserId,\n this.recipientProfileId,\n this.channel,\n this.sourceRef,\n );\n stored = existing.rows[0] as Record<string, unknown> | undefined;\n }\n if (\n stored &&\n (stored.required_dispatch_policy || this.requiredDispatchPolicy)\n ) {\n const binding = (value: unknown) =>\n typeof value === 'string' ? JSON.parse(value) : value;\n const instant = (value: unknown) =>\n value == null ? null : new Date(value as string | Date).getTime();\n if (\n stored.status !== this.status ||\n Number(stored.state_version) !== this.stateVersion ||\n stored.transition_id !== this.transitionId ||\n Number(stored.attempts) !== this.attempts ||\n Number(stored.max_attempts) !== this.maxAttempts ||\n stored.lease_token !== this.leaseToken ||\n stored.message_id !== this.messageId ||\n stored.provider_message_id !== this.providerMessageId ||\n stored.last_error !== this.lastError ||\n instant(stored.next_attempt_at) !== instant(this.nextAttemptAt) ||\n instant(stored.lease_expires_at) !== instant(this.leaseExpiresAt) ||\n instant(stored.handed_off_at) !== instant(this.handedOffAt) ||\n instant(stored.delivered_at) !== instant(this.deliveredAt)\n ) {\n throw new Error(\n 'Protected notification lifecycle changes require a guarded transition.',\n );\n }\n\n if (\n stored.tenant_id !== this.tenantId ||\n stored.required_dispatch_policy !== this.requiredDispatchPolicy ||\n !isDeepStrictEqual(\n binding(stored.dispatch_policy_binding),\n binding(this.dispatchPolicyBinding),\n ) ||\n stored.source_ref !== this.sourceRef ||\n stored.recipient_user_id !== this.recipientUserId ||\n stored.recipient_profile_id !== this.recipientProfileId ||\n stored.recipient_kind !== this.recipientKind ||\n stored.recipient_address !== this.recipientAddress ||\n stored.account_id !== this.accountId ||\n stored.channel !== this.channel ||\n stored.recipient_name !== this.recipientName ||\n stored.kind !== this.kind ||\n stored.subject !== this.subject ||\n stored.text_body !== this.textBody ||\n stored.href !== this.href\n ) {\n throw new Error(\n 'Protected notification consent and dispatch policy are immutable.',\n );\n }\n }\n const guard =\n stored?.required_dispatch_policy || this.requiredDispatchPolicy\n ? Object.fromEntries(\n [\n 'tenant_id',\n 'required_dispatch_policy',\n 'dispatch_policy_binding',\n 'source_ref',\n 'recipient_user_id',\n 'recipient_profile_id',\n 'recipient_kind',\n 'recipient_address',\n 'recipient_name',\n 'account_id',\n 'kind',\n 'channel',\n 'subject',\n 'text_body',\n 'href',\n 'status',\n 'state_version',\n 'transition_id',\n 'attempts',\n 'max_attempts',\n 'lease_token',\n 'message_id',\n 'provider_message_id',\n 'last_error',\n ].map((column) => [\n column,\n stored\n ? stored[column]\n : (this as unknown as Record<string, unknown>)[\n column.replace(/_([a-z])/g, (_, letter: string) =>\n letter.toUpperCase(),\n )\n ],\n ]),\n )\n : {\n // Bind the observed legacy NULL exactly; a new ordinary row uses ''.\n required_dispatch_policy: stored\n ? stored.required_dispatch_policy\n : '',\n kind: stored ? stored.kind : this.kind,\n };\n if (!stored && this.requiredDispatchPolicy) this.requireInsertOnSave();\n saveGuards.set(this, guard);\n if (!GlobalInterceptors.getAll().includes(saveGuardInterceptor))\n GlobalInterceptors.register(saveGuardInterceptor);\n // Core preserves supplied options/revision guards and applies this mandatory\n // predicate at the final write. State/version covers lifecycle dates without\n // comparing lossy hydrated PostgreSQL timestamps.\n return super.save(options);\n }\n\n /** Protected history must survive mutable caller flags and uncertain outcomes. */\n override async delete(): Promise<void> {\n const stored = this.id\n ? await this.db.get(this.tableName, { id: this.id })\n : null;\n if (\n stored?.required_dispatch_policy ||\n String(stored?.kind ?? '').startsWith('protected:')\n )\n throw new Error(\n 'Protected notification delivery history cannot be deleted.',\n );\n return super.delete();\n }\n\n /** Whether no further automatic work will happen on this row. */\n get isSettled(): boolean {\n return (\n this.status === 'sent' ||\n this.status === 'failed' ||\n this.status === 'cancelled' ||\n this.status === 'uncertain'\n );\n }\n\n /**\n * Apply `changes` only if the stored row is still at `stateVersion` (and,\n * when `leaseToken` is given, still held by that lease). Returns whether\n * this caller won; on success the instance reflects the stored row.\n *\n * PostgreSQL and remote LibSQL evaluate the guard in one conditional\n * UPDATE; local embedded engines use the process write queue, matching\n * `Message.send()`'s claim. The durable row is re-read either way, and the\n * write is recognised by its unique `transitionId`, because DuckDB's update\n * result over-reports affected rows.\n */\n async transition(\n changes: NotificationDeliveryTransition,\n expected: { leaseToken?: string } = {},\n ): Promise<boolean> {\n if (!this.id) throw new Error('Cannot transition an unsaved delivery.');\n const fromVersion = this.stateVersion;\n const nextVersion = fromVersion + 1;\n const transitionId = crypto.randomUUID();\n const values: Record<string, unknown> = {\n state_version: nextVersion,\n transition_id: transitionId,\n updated_at: new Date(),\n };\n for (const [key, value] of Object.entries(changes)) {\n const column =\n TRANSITION_COLUMNS[key as keyof NotificationDeliveryTransition];\n if (!column) throw new Error(`'${key}' is not a transition field.`);\n values[column] = value;\n }\n\n const matches = (row: Record<string, unknown> | null) =>\n row !== null &&\n Number(row.state_version) === fromVersion &&\n (expected.leaseToken === undefined ||\n row.lease_token === expected.leaseToken);\n\n const useEmbeddedFallback = usesEmbeddedRevisionFallback(this.db);\n await withEmbeddedWriteQueue(this.db, useEmbeddedFallback, async () => {\n if (useEmbeddedFallback) {\n const current = await this.getCanonicalPersistedRow({ id: this.id });\n if (!matches(current)) return;\n await this.db.upsert(this.tableName, ['id'], {\n ...current,\n ...values,\n });\n return;\n }\n await this.db.update(\n this.tableName,\n {\n id: this.id,\n tenant_id: this.tenantId,\n state_version: fromVersion,\n ...(expected.leaseToken === undefined\n ? {}\n : { lease_token: expected.leaseToken }),\n },\n values,\n );\n });\n\n const verified = await this.getCanonicalPersistedRow({ id: this.id });\n // The transition id, not the version, proves this caller's write won:\n // a losing caller would see the winner's identical next version.\n if (!verified || verified.transition_id !== transitionId) return false;\n await this.completePersistedUpdate(verified);\n return true;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { NotificationDelivery } from '../models/NotificationDelivery.js';\n\nexport class NotificationDeliveryCollection extends SmrtCollection<NotificationDelivery> {\n static readonly _itemClass = NotificationDelivery;\n}\n","import type { SmrtObjectOptions } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n crossPackageRef,\n field,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport type { NotificationDeliveryChannel } from './NotificationDelivery.js';\n\n/** `*` (everything in the tenant) or a host key such as `project:<uuid>`. */\nexport const NOTIFICATION_OPT_OUT_SCOPE_PATTERN =\n /^(?:\\*|[a-z][a-z0-9-]*:[A-Za-z0-9._:-]{1,200})$/;\n\n/** The scope that matches every notification of the channel in the tenant. */\nexport const NOTIFICATION_OPT_OUT_ALL_SCOPE = '*';\n\nexport function isValidNotificationOptOutScope(\n scope: unknown,\n): scope is string {\n return (\n typeof scope === 'string' && NOTIFICATION_OPT_OUT_SCOPE_PATTERN.test(scope)\n );\n}\n\nexport interface NotificationOptOutOptions extends SmrtObjectOptions {\n tenantId?: string;\n recipientUserId?: string;\n channel?: NotificationDeliveryChannel;\n scope?: string;\n optedOutAt?: Date | null;\n updatedBy?: string;\n}\n\n/**\n * One person's opt-out of one notification channel for one scope, in one\n * tenant: the preference store behind the outbox's `isSuppressed` hook.\n *\n * Identity is `(tenant, recipient, channel, scope)` (the conflict identity).\n * `optedOutAt` is set while the person is opted out and cleared by an opt-in,\n * so the row keeps its history. `scope` is a host-defined key validated by\n * {@link NOTIFICATION_OPT_OUT_SCOPE_PATTERN}. Read and change rows through\n * `NotificationOptOutService`; the generated REST/MCP/CLI are off because the\n * service is the authorization boundary.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'notification_opt_outs',\n api: false,\n mcp: false,\n cli: false,\n conflictColumns: ['tenant_id', 'recipient_user_id', 'channel', 'scope'],\n})\nexport class NotificationOptOut extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n /** The person who opted out (`smrt-users:User`, uuid). */\n @crossPackageRef('@happyvertical/smrt-users:User', {\n required: true,\n requiredFor: 'identity',\n })\n recipientUserId = '';\n\n /** Channel opted out of; only `email` today. */\n @field({ required: true })\n channel: NotificationDeliveryChannel = 'email';\n\n /** `*` or a host key such as `project:<uuid>`. */\n @field({ required: true, requiredFor: 'identity' })\n scope = '';\n\n /** When the opt-out took effect; null once the person opted back in. */\n optedOutAt: Date | null = null;\n\n /** Who last changed the row: the person's user id, or `system` for host code. */\n updatedBy = '';\n\n constructor(options: NotificationOptOutOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.recipientUserId !== undefined)\n this.recipientUserId = options.recipientUserId;\n if (options.channel !== undefined) this.channel = options.channel;\n if (options.scope !== undefined) this.scope = options.scope;\n if (options.optedOutAt !== undefined) this.optedOutAt = options.optedOutAt;\n if (options.updatedBy !== undefined) this.updatedBy = options.updatedBy;\n }\n\n get isOptedOut(): boolean {\n return this.optedOutAt !== null;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { NotificationOptOut } from '../models/NotificationOptOut.js';\n\nexport class NotificationOptOutCollection extends SmrtCollection<NotificationOptOut> {\n static readonly _itemClass = NotificationOptOut;\n}\n","import {\n crossPackageRef,\n field,\n foreignKey,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport type { PersonaMessageRouteOptions } from '../types.js';\n\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'persona_message_routes',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n conflictColumns: [\n 'tenant_id',\n 'persona_id',\n 'account_id',\n 'endpoint_id',\n 'purpose',\n ],\n})\nexport class PersonaMessageRoute extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n @crossPackageRef('@happyvertical/smrt-personas:AgentPersona', {\n required: true,\n requiredFor: 'identity',\n })\n personaId = '';\n\n @foreignKey('Account', { required: true, requiredFor: 'identity' })\n accountId = '';\n\n @foreignKey('MessagingEndpoint', { required: true, requiredFor: 'identity' })\n endpointId = '';\n\n @field({ required: true })\n purpose = 'default';\n\n priority = 0;\n enabled = true;\n createdAt = new Date();\n updatedAt = new Date();\n\n constructor(options: PersonaMessageRouteOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.personaId !== undefined) this.personaId = options.personaId;\n if (options.accountId !== undefined) this.accountId = options.accountId;\n if (options.endpointId !== undefined) this.endpointId = options.endpointId;\n if (options.purpose !== undefined) this.purpose = options.purpose;\n if (options.priority !== undefined) this.priority = options.priority;\n if (options.enabled !== undefined) this.enabled = options.enabled;\n if (options.createdAt !== undefined) this.createdAt = options.createdAt;\n if (options.updatedAt !== undefined) this.updatedAt = options.updatedAt;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { PersonaMessageRoute } from '../models/PersonaMessageRoute.js';\n\nexport class PersonaMessageRouteCollection extends SmrtCollection<PersonaMessageRoute> {\n static readonly _itemClass = PersonaMessageRoute;\n\n async forPersona(personaId: string): Promise<PersonaMessageRoute[]> {\n return this.list({ where: { personaId, enabled: true } });\n }\n}\n","import type { SmrtObjectOptions } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport {\n crossPackageRef,\n field,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\n\n/** How much a notification matters to its recipient. */\nexport type UserNotificationSeverity = 'info' | 'success' | 'warning' | 'error';\n\nexport const USER_NOTIFICATION_SEVERITIES: readonly UserNotificationSeverity[] =\n ['info', 'success', 'warning', 'error'];\n\nexport interface UserNotificationOptions extends SmrtObjectOptions {\n tenantId?: string;\n recipientUserId?: string;\n kind?: string;\n title?: string;\n body?: string;\n href?: string | null;\n severity?: UserNotificationSeverity;\n sourceRef?: string;\n occurredAt?: Date;\n readAt?: Date | null;\n dismissedAt?: Date | null;\n}\n\n/**\n * One in-app notification for one person, with its own read state.\n *\n * The in-app channel of smrt-messages: where `Message` is delivered through\n * an external provider, a `UserNotification` is stored for a user and shown\n * by the host (a bell, a notifications page). Create, list, and change read\n * state through `UserNotificationService`, which checks the recipient on\n * every write; the generated REST/MCP/CLI surfaces are off because a plain\n * tenant-scoped list would show every member's notifications.\n *\n * `sourceRef` is the dedupe key: one row per `(tenant, recipient, sourceRef)`\n * (the conflict identity), so re-deriving the same event (a failed social\n * post, a failed render) never notifies twice. The service generates a unique\n * ref when the caller has none.\n */\n@TenantScoped({ mode: 'required' })\n@smrt({\n tableName: 'user_notifications',\n api: false,\n mcp: false,\n cli: false,\n conflictColumns: ['tenant_id', 'recipient_user_id', 'source_ref'],\n // The bell reads a recipient's newest rows in one tenant.\n indexes: [\n {\n name: 'user_notifications_recipient_occurred_idx',\n columns: ['tenantId', 'recipientUserId', 'occurredAt'],\n },\n ],\n})\nexport class UserNotification extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId()\n tenantId = '';\n\n /** The person this notification is for (`smrt-users:User`, uuid). */\n @crossPackageRef('@happyvertical/smrt-users:User', {\n required: true,\n requiredFor: 'identity',\n })\n recipientUserId = '';\n\n /** Host-defined type, e.g. `social-post.failed` (used for icons/filters). */\n @field()\n kind = '';\n\n /** One short plain sentence. */\n @field()\n title = '';\n\n /** Optional detail line. */\n body = '';\n\n /** Where the notification leads (host-relative path or URL). */\n href: string | null = null;\n\n severity: UserNotificationSeverity = 'info';\n\n /** Dedupe key, unique per tenant and recipient (see class docs). */\n @field({ required: true, requiredFor: 'idempotency' })\n sourceRef = '';\n\n /** When the underlying event happened (sort key). */\n occurredAt = new Date();\n\n /** Set when the recipient has seen it. */\n readAt: Date | null = null;\n\n /** Set when the recipient has cleared it; dismissed rows are hidden. */\n dismissedAt: Date | null = null;\n\n constructor(options: UserNotificationOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.recipientUserId !== undefined)\n this.recipientUserId = options.recipientUserId;\n if (options.kind !== undefined) this.kind = options.kind;\n if (options.title !== undefined) this.title = options.title;\n if (options.body !== undefined) this.body = options.body;\n if (options.href !== undefined) this.href = options.href;\n if (options.severity !== undefined) this.severity = options.severity;\n if (options.sourceRef !== undefined) this.sourceRef = options.sourceRef;\n if (options.occurredAt !== undefined) this.occurredAt = options.occurredAt;\n if (options.readAt !== undefined) this.readAt = options.readAt;\n if (options.dismissedAt !== undefined)\n this.dismissedAt = options.dismissedAt;\n }\n\n get isRead(): boolean {\n return this.readAt !== null;\n }\n\n get isDismissed(): boolean {\n return this.dismissedAt !== null;\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { UserNotification } from '../models/UserNotification.js';\n\nexport class UserNotificationCollection extends SmrtCollection<UserNotification> {\n static readonly _itemClass = UserNotification;\n}\n","/**\n * EmailAttachment - Backward-compatible alias for Attachment\n *\n * @deprecated Use Attachment instead. EmailAttachment is preserved for backward compatibility.\n */\n\nimport type { EmailAttachmentOptions } from '../types';\nimport { Attachment } from './Attachment';\n\n/**\n * @deprecated Use Attachment instead\n */\nexport class EmailAttachment extends Attachment {\n /**\n * Legacy emailId field — maps to messageId\n */\n get emailId(): string {\n return this.messageId;\n }\n\n set emailId(value: string) {\n this.messageId = value;\n }\n\n constructor(options: EmailAttachmentOptions = {}) {\n // Map emailId to messageId for backward compat\n const mappedOptions = {\n ...options,\n messageId: options.emailId || options.messageId || '',\n };\n super(mappedOptions);\n }\n\n /**\n * Get the email this attachment belongs to\n * @deprecated Use getMessage() instead\n */\n async getEmail() {\n if (!this.messageId) return null;\n\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n return await collection.get({ id: this.messageId });\n }\n}\n","/**\n * EmailAttachmentCollection - Backward-compatible collection for EmailAttachment\n *\n * @deprecated Use AttachmentCollection instead\n */\n\nimport { queryGlobal, queryWithGlobals } from '../host.js';\nimport { EmailAttachment } from '../models/EmailAttachment';\nimport { AttachmentCollection } from './AttachmentCollection';\n\n/**\n * @deprecated Use AttachmentCollection instead\n */\nexport class EmailAttachmentCollection extends AttachmentCollection {\n static override readonly _itemClass = EmailAttachment;\n\n /**\n * Get attachments for an email\n * @deprecated Use getByMessage() instead\n */\n async getByEmail(emailId: string): Promise<EmailAttachment[]> {\n return (await this.getByMessage(emailId)) as EmailAttachment[];\n }\n\n /**\n * Get image attachments\n */\n override async getImages(emailId?: string): Promise<EmailAttachment[]> {\n return (await super.getImages(emailId)) as EmailAttachment[];\n }\n\n /**\n * Get PDF attachments\n */\n override async getPdfs(emailId?: string): Promise<EmailAttachment[]> {\n return (await super.getPdfs(emailId)) as EmailAttachment[];\n }\n\n /**\n * Get inline attachments\n */\n override async getInline(emailId: string): Promise<EmailAttachment[]> {\n return (await super.getInline(emailId)) as EmailAttachment[];\n }\n\n /**\n * Get regular attachments\n */\n override async getRegular(emailId: string): Promise<EmailAttachment[]> {\n return (await super.getRegular(emailId)) as EmailAttachment[];\n }\n\n /**\n * Delete all attachments for an email\n * @deprecated Use deleteByMessage() instead\n */\n async deleteByEmail(emailId: string): Promise<number> {\n return await this.deleteByMessage(emailId);\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n override async findByTenant(tenantId: string): Promise<EmailAttachment[]> {\n return this.list({ where: { tenantId } }) as Promise<EmailAttachment[]>;\n }\n\n // EmailAttachment is a CTI subclass of the @TenantScoped Attachment (own\n // `email_attachments` table, no `_meta_type`) and inherits its recognition\n // (#1596); route global / cross-global lookups through the raw helpers.\n override async findGlobal(): Promise<EmailAttachment[]> {\n return queryGlobal<EmailAttachment>(this);\n }\n\n override async findWithGlobals(tenantId: string): Promise<EmailAttachment[]> {\n return queryWithGlobals<EmailAttachment>(\n this,\n tenantId,\n 'EmailAttachment.findWithGlobals',\n );\n }\n}\n","import { SmrtObject, smrt } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport type { BlacklistOptions } from '../types';\n\n/**\n * Blacklist - Block entries for email filtering\n *\n * Supports three pattern types:\n * - email: Exact email address (spam@example.com)\n * - domain: Entire domain (*@spam.com)\n * - regex: Custom regex pattern\n */\n@smrt({\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n cli: { skipApiCheck: true },\n tenantScoped: true,\n})\nexport class Blacklist extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n pattern: string = '';\n type: 'email' | 'domain' | 'regex' = 'email';\n reason: string = '';\n autoArchive: boolean = true;\n\n constructor(options: BlacklistOptions = {}) {\n super(options);\n\n if (options.pattern !== undefined) {\n this.pattern = options.pattern;\n }\n if (options.type !== undefined) {\n this.type = options.type;\n }\n }\n\n /**\n * Check if an email address matches this blacklist entry\n */\n matches(email: string): boolean {\n const normalizedEmail = email.toLowerCase().trim();\n\n switch (this.type) {\n case 'email':\n return normalizedEmail === this.pattern.toLowerCase().trim();\n\n case 'domain': {\n const domain = normalizedEmail.split('@')[1];\n return domain === this.pattern.toLowerCase().trim();\n }\n\n case 'regex': {\n const pattern = this.pattern.trim();\n if (!pattern) {\n return false;\n }\n try {\n const regex = new RegExp(pattern, 'i');\n return regex.test(normalizedEmail);\n } catch {\n return false;\n }\n }\n\n default:\n return false;\n }\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { Blacklist } from '../models/Blacklist.js';\n\nexport class BlacklistCollection extends SmrtCollection<Blacklist> {\n static readonly _itemClass = Blacklist;\n\n /**\n * Check if an email is blacklisted\n */\n async isBlacklisted(email: string): Promise<boolean> {\n const entries = await this.list({});\n\n for (const entry of entries) {\n if (entry.matches(email)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Get the matching blacklist entry for an email\n */\n async getMatchingEntry(email: string): Promise<Blacklist | null> {\n const entries = await this.list({});\n\n for (const entry of entries) {\n if (entry.matches(email)) {\n return entry;\n }\n }\n\n return null;\n }\n}\n","import { SmrtObject, smrt } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport type { WhitelistOptions } from '../types';\n\n/**\n * Whitelist - Allow-only entries for email filtering\n *\n * Supports three pattern types:\n * - email: Exact email address (user@example.com)\n * - domain: Entire domain (*@example.com)\n * - regex: Custom regex pattern\n */\n@smrt({\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n cli: { skipApiCheck: true },\n tenantScoped: true,\n})\nexport class Whitelist extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n pattern: string = '';\n type: 'email' | 'domain' | 'regex' = 'email';\n category: string | null = null;\n description: string = '';\n\n constructor(options: WhitelistOptions = {}) {\n super(options);\n\n if (options.pattern !== undefined) {\n this.pattern = options.pattern;\n }\n if (options.type !== undefined) {\n this.type = options.type;\n }\n }\n\n /**\n * Check if an email address matches this whitelist entry\n */\n matches(email: string): boolean {\n const normalizedEmail = email.toLowerCase().trim();\n\n switch (this.type) {\n case 'email':\n return normalizedEmail === this.pattern.toLowerCase().trim();\n\n case 'domain': {\n const domain = normalizedEmail.split('@')[1];\n return domain === this.pattern.toLowerCase().trim();\n }\n\n case 'regex': {\n const pattern = this.pattern.trim();\n if (!pattern) {\n return false;\n }\n try {\n const regex = new RegExp(pattern, 'i');\n return regex.test(normalizedEmail);\n } catch {\n return false;\n }\n }\n\n default:\n return false;\n }\n }\n}\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { Whitelist } from '../models/Whitelist.js';\n\nexport class WhitelistCollection extends SmrtCollection<Whitelist> {\n static readonly _itemClass = Whitelist;\n\n /**\n * Check if an email is whitelisted for a specific category\n */\n async isWhitelisted(email: string, category?: string): Promise<boolean> {\n const entries = await this.list({});\n\n for (const entry of entries) {\n if (!entry.matches(email)) {\n continue;\n }\n\n if (!category) {\n return true;\n }\n\n if (entry.category === category || entry.category === null) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Get the matching whitelist entry for an email\n */\n async getMatchingEntry(email: string): Promise<Whitelist | null> {\n const entries = await this.list({});\n\n for (const entry of entries) {\n if (entry.matches(email)) {\n return entry;\n }\n }\n\n return null;\n }\n\n /**\n * Get whitelist entries by category\n */\n async getByCategory(category: string): Promise<Whitelist[]> {\n return await this.list({\n where: { category },\n });\n }\n}\n","/**\n * SlackAccount model - Slack workspace account extending the Account STI base\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { field, smrt } from '@happyvertical/smrt-core';\nimport type { MessageSenderInterface, SlackAccountOptions } from '../types';\nimport { Account } from './Account';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n})\nexport class SlackAccount extends Account { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @field({ description: 'The identifier of the connected workspace.' })\n workspaceId = '';\n @field({ description: 'The name of the connected workspace.' })\n workspaceName = '';\n @field({\n description: 'The bot user your application posts as in this workspace.',\n })\n botUserId = '';\n\n constructor(options: SlackAccountOptions = {}) {\n super(options);\n\n if (options.workspaceId !== undefined)\n this.workspaceId = options.workspaceId;\n if (options.workspaceName !== undefined)\n this.workspaceName = options.workspaceName;\n if (options.botUserId !== undefined) this.botUserId = options.botUserId;\n\n // Default provider type\n if (!this.providerType) this.providerType = 'slack';\n this.channelType = 'slack';\n }\n\n /**\n * Create a sender for this Slack account\n */\n override async createSender(): Promise<MessageSenderInterface> {\n const { SlackSender } = await import('../senders/SlackSender');\n return new SlackSender(this);\n }\n}\n","/**\n * SlackMessage model - Slack message extending the Message STI base\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { field, smrt } from '@happyvertical/smrt-core';\nimport type { SlackMessageOptions } from '../types';\nimport { Message } from './Message';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get', 'create'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n // Message is read-only over REST; this provider type is writable there.\n widenParentExposure: { api: ['create'] },\n})\nexport class SlackMessage extends Message { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @field({ description: 'The identifier of the channel this message is in.' })\n channelId = '';\n @field({ description: 'The name of the channel this message was posted in.' })\n channelName = '';\n @field({ description: \"The workspace's own reference for this message.\" })\n slackTs = ''; // Slack message timestamp (unique ID)\n @field({\n description:\n \"The workspace's own reference for the thread this message belongs to.\",\n })\n slackThreadTs = ''; // Thread parent timestamp\n @field({ description: 'The reactions people added to this message.' })\n reactions = ''; // JSON array of {name, count, users[]}\n @field({ description: 'Whether this message was edited after posting.' })\n isEdited = false;\n @field({\n description: 'The kind of message, such as one from a person or a bot.',\n })\n messageType = ''; // 'message', 'bot_message', etc.\n @field({\n description: 'The rich layout of the message as the workspace stores it.',\n })\n blocks = ''; // JSON - Slack Block Kit blocks\n\n constructor(options: SlackMessageOptions = {}) {\n super(options);\n\n if (options.channelId !== undefined) this.channelId = options.channelId;\n if (options.channelName !== undefined)\n this.channelName = options.channelName;\n if (options.slackTs !== undefined) this.slackTs = options.slackTs;\n if (options.slackThreadTs !== undefined)\n this.slackThreadTs = options.slackThreadTs;\n if (options.reactions !== undefined) this.reactions = options.reactions;\n if (options.isEdited !== undefined) this.isEdited = options.isEdited;\n if (options.messageType !== undefined)\n this.messageType = options.messageType;\n if (options.blocks !== undefined) this.blocks = options.blocks;\n }\n\n /**\n * Reply in the same channel and thread. `channelId` is routing identity\n * (SlackSender posts to it), so it is restored after the base draft reset;\n * a reply to a top-level message starts that message's thread.\n */\n override createReply(options?: { replyAll?: boolean }): SlackMessage {\n const reply = super.createReply(options) as SlackMessage;\n reply.channelId = this.channelId;\n reply.channelName = this.channelName;\n reply.slackThreadTs = this.slackThreadTs || this.slackTs;\n return reply;\n }\n\n /** Forward into the same channel, outside the original's thread. */\n override createForward(): SlackMessage {\n const forward = super.createForward() as SlackMessage;\n forward.channelId = this.channelId;\n forward.channelName = this.channelName;\n return forward;\n }\n\n /**\n * Get reactions as parsed array\n */\n getReactions(): Array<{ name: string; count: number; users?: string[] }> {\n if (!this.reactions) return [];\n try {\n return JSON.parse(this.reactions);\n } catch {\n return [];\n }\n }\n\n /**\n * Get blocks as parsed array\n */\n getBlocks(): Record<string, unknown>[] {\n if (!this.blocks) return [];\n try {\n return JSON.parse(this.blocks);\n } catch {\n return [];\n }\n }\n\n /**\n * Check if message is in a thread\n */\n isInThread(): boolean {\n return !!this.slackThreadTs && this.slackThreadTs !== this.slackTs;\n }\n\n /**\n * Get total reaction count\n */\n getTotalReactions(): number {\n return this.getReactions().reduce((sum, r) => sum + r.count, 0);\n }\n}\n","import { smrt } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport type { AccountOptions } from '../types.js';\nimport { Account } from './Account.js';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n})\nexport class TelegramAccount extends Account { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n constructor(options: AccountOptions = {}) {\n super(options);\n this.providerType = 'telegram';\n this.channelType = 'telegram';\n }\n}\n","/**\n * Tweet model - Twitter/X message extending the Message STI base\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { smrt } from '@happyvertical/smrt-core';\nimport type { TweetOptions } from '../types';\nimport { Message } from './Message';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get', 'create'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n // Message is read-only over REST; this provider type is writable there.\n widenParentExposure: { api: ['create'] },\n})\nexport class Tweet extends Message { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n tweetId = '';\n retweetCount = 0;\n likeCount = 0;\n replyCount = 0;\n isRetweet = false;\n isReply = false;\n mediaUrls = ''; // JSON array\n hashtags = ''; // JSON array\n mentions = ''; // JSON array\n\n constructor(options: TweetOptions = {}) {\n super(options);\n\n if (options.tweetId !== undefined) this.tweetId = options.tweetId;\n if (options.retweetCount !== undefined)\n this.retweetCount = options.retweetCount;\n if (options.likeCount !== undefined) this.likeCount = options.likeCount;\n if (options.replyCount !== undefined) this.replyCount = options.replyCount;\n if (options.isRetweet !== undefined) this.isRetweet = options.isRetweet;\n if (options.isReply !== undefined) this.isReply = options.isReply;\n if (options.mediaUrls !== undefined) this.mediaUrls = options.mediaUrls;\n if (options.hashtags !== undefined) this.hashtags = options.hashtags;\n if (options.mentions !== undefined) this.mentions = options.mentions;\n }\n\n /**\n * Get media URLs as parsed array\n */\n getMediaUrls(): string[] {\n if (!this.mediaUrls) return [];\n try {\n return JSON.parse(this.mediaUrls);\n } catch {\n return [];\n }\n }\n\n /**\n * Get hashtags as parsed array\n */\n getHashtags(): string[] {\n if (!this.hashtags) return [];\n try {\n return JSON.parse(this.hashtags);\n } catch {\n return [];\n }\n }\n\n /**\n * Get mentions as parsed array\n */\n getMentions(): string[] {\n if (!this.mentions) return [];\n try {\n return JSON.parse(this.mentions);\n } catch {\n return [];\n }\n }\n\n /**\n * Get total engagement count\n */\n getEngagement(): number {\n return this.retweetCount + this.likeCount + this.replyCount;\n }\n}\n","/**\n * TwitterAccount model - Twitter/X account extending the Account STI base\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { smrt } from '@happyvertical/smrt-core';\nimport type { MessageSenderInterface, TwitterAccountOptions } from '../types';\nimport { Account } from './Account';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n})\nexport class TwitterAccount extends Account { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n handle = '';\n twitterUserId = '';\n\n constructor(options: TwitterAccountOptions = {}) {\n super(options);\n\n if (options.handle !== undefined) this.handle = options.handle;\n if (options.twitterUserId !== undefined)\n this.twitterUserId = options.twitterUserId;\n\n // Default provider type\n if (!this.providerType) this.providerType = 'twitter';\n this.channelType = 'twitter';\n }\n\n /**\n * Create a sender for this Twitter account\n */\n override async createSender(): Promise<MessageSenderInterface> {\n const { TweetSender } = await import('../senders/TweetSender');\n return new TweetSender(this);\n }\n}\n","import { smrt } from '@happyvertical/smrt-core';\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport type { AccountOptions } from '../types.js';\nimport { Account } from './Account.js';\n\n@smrt({\n tableStrategy: 'sti',\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: { include: ['list', 'get'] },\n})\nexport class ZulipAccount extends Account { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n constructor(options: AccountOptions = {}) {\n super(options);\n this.providerType = 'zulip';\n this.channelType = 'zulip';\n }\n}\n","import {\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport {\n decideMailAccess,\n getMailAccessConfig,\n MAIL_ACCOUNT_RESOURCE_TYPE,\n MAIL_SCOPES,\n type MailPrincipal,\n type MailScope,\n runWithMailSystemAccess,\n withoutListBounds,\n} from '../access.js';\nimport { AccountCollection } from '../collections/AccountCollection.js';\nimport { AttachmentCollection } from '../collections/AttachmentCollection.js';\nimport { EmailFolderCollection } from '../collections/EmailFolderCollection.js';\nimport { MessageCollection } from '../collections/MessageCollection.js';\nimport { MessagingEndpointCollection } from '../collections/MessagingEndpointCollection.js';\nimport { PersonaMessageRouteCollection } from '../collections/PersonaMessageRouteCollection.js';\nimport { withTenant } from '../host.js';\nimport { Account } from '../models/Account.js';\nimport { EmailAccount } from '../models/EmailAccount.js';\nimport { MessagingEndpoint } from '../models/MessagingEndpoint.js';\nimport { PersonaMessageRoute } from '../models/PersonaMessageRoute.js';\nimport { TelegramAccount } from '../models/TelegramAccount.js';\nimport { ZulipAccount } from '../models/ZulipAccount.js';\nimport {\n assertMessagingPermission,\n MANAGE_MESSAGE_CREDENTIALS_PERMISSION,\n MANAGE_MESSAGE_ROUTES_PERMISSION,\n type MessagingPrincipal,\n} from '../permissions.js';\nimport {\n getMessagingProvider,\n listMessagingProviders,\n type MessagingProviderDefinition,\n type MessagingProviderField,\n type MessagingProviderFunctionKey,\n} from '../providers.js';\nimport type { MessagingChannel } from '../types.js';\n\nexport interface MessagingAccountInput {\n id?: string;\n name: string;\n providerId: string;\n configuration: Record<string, unknown>;\n /** Omit on update to leave the stored secret unchanged. */\n credentials?: Record<string, unknown>;\n active?: boolean;\n /**\n * The new account's owner (create only; must be the acting principal).\n * Ownership changes later go through `MailAccessService.setOwner`.\n */\n ownerUserId?: string | null;\n /** A short name shown beside the account, such as Support. */\n label?: string | null;\n}\n\n/** A mailbox connected with a write-only secret such as an app password. */\nexport interface MailboxConnectInput {\n /** Reconnect an existing mailbox: replaces its credential. */\n id?: string;\n name: string;\n label?: string | null;\n providerId: string;\n /** Non-secret connection settings, including this account's own endpoint. */\n configuration: Record<string, unknown>;\n /** Write-only: validated, stored in smrt-secrets, never returned. */\n credentials: Record<string, unknown>;\n}\n\n/** What `connectMailbox` hands to the validator before anything is stored. */\nexport interface MailboxValidationRequest {\n provider: MessagingProviderDefinition;\n configuration: Record<string, unknown>;\n /** The normalized secret payload exactly as it would be stored. */\n credentials: Record<string, unknown>;\n}\n\nexport interface MessagingEndpointInput {\n id?: string;\n label: string;\n providerId: string;\n profileId?: string | null;\n address: Record<string, unknown>;\n active?: boolean;\n}\n\nexport interface PersonaMessageRouteInput {\n id?: string;\n personaId: string;\n accountId: string;\n endpointId: string;\n purpose?: string;\n priority?: number;\n enabled?: boolean;\n}\n\nexport interface MessagingAccountView {\n id: string;\n name: string;\n providerId: string;\n channel: MessagingChannel;\n configuration: Record<string, unknown>;\n hasCredentials: boolean;\n active: boolean;\n ownerUserId: string | null;\n label: string | null;\n connectionStatus: string | null;\n statusMessage: string | null;\n}\n\n/** An account the acting principal owns or holds a grant on. */\nexport interface MessagingAccountListing extends MessagingAccountView {\n /** `owner` administers the account; `shared` holds only grants. */\n relation: 'owner' | 'shared';\n /** Effective scopes: the owner holds all four, a grantee what grants allow. */\n scopes: MailScope[];\n}\n\nexport interface ListAccountsOptions {\n /** Page size, 1 to 200. Default 50. */\n limit?: number;\n /** The `nextCursor` of the previous page. */\n cursor?: string | null;\n}\n\nexport interface ListAccountsResult {\n accounts: MessagingAccountListing[];\n /** Pass as `cursor` for the next page; null when there are no more. */\n nextCursor: string | null;\n}\n\nconst LIST_ACCOUNTS_DEFAULT_LIMIT = 50;\nconst LIST_ACCOUNTS_MAX_LIMIT = 200;\nconst CANDIDATE_PAGE = 500;\n\nexport interface MessagingEndpointView {\n id: string;\n label: string;\n channel: MessagingChannel;\n profileId: string | null;\n maskedAddress: string;\n active: boolean;\n verified: boolean;\n}\n\n/** Permission-gated server API for a schema-driven messaging settings page. */\nexport class MessagingSettingsService {\n constructor(\n private readonly options: {\n db: SmrtClassOptions['db'];\n tenantId: string;\n principal: MessagingPrincipal;\n /** Cross-package ownership check supplied by the host/personas layer. */\n resolvePersonaTenantId: (personaId: string) => Promise<string | null>;\n /**\n * Opens a session with the candidate credential before `connectMailbox`\n * stores anything. Defaults to the provider's email client; reject to\n * refuse the connection.\n */\n validateMailbox?: (request: MailboxValidationRequest) => Promise<void>;\n /**\n * Hostnames the built-in validator may connect to: exact names or\n * `*.suffix`. Without this list (and without a custom `validateMailbox`)\n * connecting a mailbox is refused, so a permission holder cannot make\n * the server probe arbitrary hosts. Private, loopback and link-local\n * addresses are refused even when listed.\n */\n allowedMailHosts?: readonly string[];\n /** Ports the built-in validator may use. Default: standard mail ports. */\n allowedMailPorts?: readonly number[];\n },\n ) {}\n\n getProviderDefinitions(options: { includeUnavailable?: boolean } = {}) {\n return listMessagingProviders(options).map(\n ({\n createSender: _createSender,\n createEmailClient: _createEmailClient,\n createMessageClient: _createMessageClient,\n ...provider\n }) => provider,\n );\n }\n\n async list(personaId: string): Promise<{\n providers: Array<\n Omit<MessagingProviderDefinition, MessagingProviderFunctionKey>\n >;\n accounts: MessagingAccountView[];\n endpoints: MessagingEndpointView[];\n routes: PersonaMessageRoute[];\n }> {\n this.assert(MANAGE_MESSAGE_ROUTES_PERMISSION);\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const accounts = await AccountCollection.create({ db: this.options.db });\n const endpoints = await MessagingEndpointCollection.create({\n db: this.options.db,\n });\n const routes = await PersonaMessageRouteCollection.create({\n db: this.options.db,\n });\n const [accountRows, endpointRows, routeRows] = await Promise.all([\n accounts.list({}),\n endpoints.list({}),\n routes.list({ where: { personaId } }),\n ]);\n return {\n providers: this.getProviderDefinitions({ includeUnavailable: true }),\n accounts: accountRows.map((account) => this.accountView(account)),\n endpoints: endpointRows.map((endpoint) => this.endpointView(endpoint)),\n routes: routeRows,\n };\n });\n }\n\n /**\n * Stores account settings only: it never opens a connection, so it is not an\n * SSRF vector by itself (connecting goes through `connectMailbox`, which is\n * allowlisted). The SMTP host/port it stores predate this change and are\n * used later by the sender; hosts that need an outbound allowlist apply it\n * there.\n */\n async saveAccount(\n input: MessagingAccountInput,\n ): Promise<MessagingAccountView> {\n return this.persistAccount(input, false);\n }\n\n /**\n * `receiveOnly` admits providers that are not outbound transports (IMAP,\n * POP3): a mailbox can be connected for reading without being a sender.\n */\n private async persistAccount(\n input: MessagingAccountInput,\n receiveOnly: boolean,\n ): Promise<MessagingAccountView> {\n this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);\n const provider = this.requireProvider(input.providerId);\n if (!provider.available && !(receiveOnly && provider.channel === 'email'))\n throw new Error(`Provider '${provider.id}' is not available.`);\n this.validateFields(\n input.configuration,\n provider.configurationFields,\n 'configuration',\n );\n if (input.credentials) {\n this.validateFields(\n input.credentials,\n provider.credentialFields,\n 'credentials',\n );\n }\n\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const collection = await AccountCollection.create({\n db: this.options.db,\n });\n let account = input.id ? await collection.get({ id: input.id }) : null;\n const isNew = !account;\n if (account && account.tenantId !== this.options.tenantId) {\n throw new Error('Messaging account belongs to another tenant.');\n }\n if (account && account.providerType !== provider.id) {\n throw new Error(\n 'A messaging account provider cannot be changed in place.',\n );\n }\n if (account) this.assertMayManage(account);\n if (account && input.ownerUserId !== undefined) {\n if ((input.ownerUserId ?? null) !== (account.ownerUserId ?? null)) {\n throw new Error(\n 'Change a mail account owner with MailAccessService.setOwner.',\n );\n }\n }\n if (\n !account &&\n input.ownerUserId &&\n input.ownerUserId !== this.actingUserId\n ) {\n throw new Error('A new mail account can only be owned by its creator.');\n }\n if (\n isNew &&\n !input.credentials &&\n provider.credentialFields.some((field) => field.required)\n ) {\n throw new Error(\n `Credentials are required for new ${provider.label} accounts.`,\n );\n }\n\n if (!account) {\n account = this.newAccount(provider, input);\n await account.initialize();\n }\n\n account.name = input.name.trim();\n if (isNew && input.ownerUserId) account.ownerUserId = input.ownerUserId;\n if (input.label !== undefined)\n account.label = input.label?.trim() || null;\n account.isActive = input.active ?? account.isActive;\n account.channelType = provider.channel;\n const configuration = this.normalizeConfiguration(\n provider,\n input.configuration,\n );\n account.setConfiguration(configuration);\n if (account instanceof EmailAccount) {\n account.email = String(configuration.email ?? '');\n }\n account.updatedAt = new Date();\n await account.save();\n\n if (input.credentials) {\n await account.setCredentials(\n this.normalizeCredentials(provider, input.credentials),\n );\n }\n\n return this.accountView(account);\n });\n }\n\n /**\n * Connect a mailbox with a write-only secret (an app password). The\n * credential is validated by opening a session first; a refusal leaves no\n * account and no secret behind. The connecting user becomes the owner.\n */\n async connectMailbox(\n input: MailboxConnectInput,\n ): Promise<MessagingAccountView> {\n this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);\n // A connected mailbox always has an owner: without a user to own it the\n // account would silently be readable tenant-wide.\n if (!this.actingUserId) {\n throw new Error('Connecting a mailbox needs a signed-in user.');\n }\n if (input.id) {\n // Reconnect, never create-by-id: fails before any server is contacted.\n await withTenant({ tenantId: this.options.tenantId }, async () => {\n this.assertMayManage(await this.loadAccount(input.id as string));\n });\n }\n const provider = this.requireProvider(input.providerId);\n if (provider.channel !== 'email') {\n throw new Error(`Provider '${provider.id}' cannot connect a mailbox.`);\n }\n this.validateFields(\n input.configuration,\n provider.configurationFields,\n 'configuration',\n );\n this.validateFields(\n input.credentials,\n provider.credentialFields,\n 'credentials',\n );\n const configuration = this.normalizeConfiguration(\n provider,\n input.configuration,\n );\n const credentials = this.normalizeCredentials(provider, input.credentials);\n await this.validateConnection({ provider, configuration, credentials });\n const view = await this.persistAccount(\n {\n id: input.id,\n name: input.name,\n label: input.label,\n providerId: input.providerId,\n configuration: input.configuration,\n credentials: input.credentials,\n active: true,\n ownerUserId: input.id ? undefined : (this.actingUserId ?? null),\n },\n true,\n );\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const account = await this.loadAccount(view.id);\n await account.markConnected();\n return this.accountView(account);\n });\n }\n\n /** Pause or resume a mailbox without touching its credential. */\n async setAccountActive(\n accountId: string,\n active: boolean,\n ): Promise<MessagingAccountView> {\n this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const account = await this.loadAccount(accountId);\n this.assertMayManage(account);\n account.isActive = active;\n account.updatedAt = new Date();\n await account.save();\n return this.accountView(account);\n });\n }\n\n /**\n * Remove a mailbox: its stored credential, its synced emails, folders and\n * attachments, and the account itself.\n */\n async removeAccount(accountId: string): Promise<void> {\n this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);\n await withTenant({ tenantId: this.options.tenantId }, async () => {\n const account = await this.loadAccount(accountId);\n this.assertMayManage(account);\n await runWithMailSystemAccess(async () => {\n const db = this.options.db;\n const messages = await MessageCollection.create({ db });\n const attachments = await AttachmentCollection.create({ db });\n const folders = await EmailFolderCollection.create({ db });\n for (const message of await messages.list({ where: { accountId } })) {\n if (message.id) {\n for (const attachment of await attachments.list({\n where: { messageId: message.id },\n })) {\n await attachment.delete();\n }\n }\n await message.delete();\n }\n for (const folder of await folders.list({ where: { accountId } })) {\n await folder.delete();\n }\n });\n await account.removeCredentials();\n await account.delete();\n });\n }\n\n async saveEndpoint(\n input: MessagingEndpointInput,\n ): Promise<MessagingEndpointView> {\n this.assert(MANAGE_MESSAGE_ROUTES_PERMISSION);\n const provider = this.requireProvider(input.providerId);\n if (!provider.available)\n throw new Error(`Provider '${provider.id}' is not available.`);\n this.validateFields(input.address, provider.endpointFields, 'endpoint');\n\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const collection = await MessagingEndpointCollection.create({\n db: this.options.db,\n });\n let endpoint = input.id ? await collection.get({ id: input.id }) : null;\n if (endpoint && endpoint.tenantId !== this.options.tenantId) {\n throw new Error('Messaging endpoint belongs to another tenant.');\n }\n if (!endpoint) {\n endpoint = new (ObjectRegistry.resolveEffectiveConstructor(\n MessagingEndpoint,\n ))({\n db: this.options.db,\n tenantId: this.options.tenantId,\n });\n await endpoint.initialize();\n }\n endpoint.label = input.label.trim();\n if (input.profileId !== undefined) {\n endpoint.profileId = input.profileId;\n }\n endpoint.channel = provider.channel;\n endpoint.isActive = input.active ?? endpoint.isActive;\n endpoint.setAddress(input.address);\n endpoint.updatedAt = new Date();\n await endpoint.save();\n return this.endpointView(endpoint);\n });\n }\n\n async saveRoute(\n input: PersonaMessageRouteInput,\n ): Promise<PersonaMessageRoute> {\n this.assert(MANAGE_MESSAGE_ROUTES_PERMISSION);\n const personaTenantId = await this.options.resolvePersonaTenantId(\n input.personaId,\n );\n if (personaTenantId !== this.options.tenantId) {\n throw new Error('Messaging persona was not found in this tenant.');\n }\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const accounts = await AccountCollection.create({ db: this.options.db });\n const endpoints = await MessagingEndpointCollection.create({\n db: this.options.db,\n });\n const routes = await PersonaMessageRouteCollection.create({\n db: this.options.db,\n });\n const [account, endpoint] = await Promise.all([\n accounts.get({ id: input.accountId }),\n endpoints.get({ id: input.endpointId }),\n ]);\n if (!account || account.tenantId !== this.options.tenantId) {\n throw new Error('Messaging account was not found in this tenant.');\n }\n if (!endpoint || endpoint.tenantId !== this.options.tenantId) {\n throw new Error('Messaging endpoint was not found in this tenant.');\n }\n const accountProvider = getMessagingProvider(account.providerType);\n if (\n !accountProvider?.available ||\n accountProvider.channel !== account.channelType\n ) {\n throw new Error(\n 'Messaging account provider is not available for outbound delivery.',\n );\n }\n if (account.channelType !== endpoint.channel) {\n throw new Error(\n 'Messaging account and endpoint channels do not match.',\n );\n }\n\n let route = input.id ? await routes.get({ id: input.id }) : null;\n if (route && route.tenantId !== this.options.tenantId) {\n throw new Error('Messaging route belongs to another tenant.');\n }\n if (!route) {\n route = new (ObjectRegistry.resolveEffectiveConstructor(\n PersonaMessageRoute,\n ))({\n db: this.options.db,\n tenantId: this.options.tenantId,\n });\n await route.initialize();\n }\n route.personaId = input.personaId;\n route.accountId = input.accountId;\n route.endpointId = input.endpointId;\n route.purpose = input.purpose?.trim() || 'default';\n route.priority = input.priority ?? 0;\n route.enabled = input.enabled ?? route.enabled;\n route.updatedAt = new Date();\n await route.save();\n return route;\n });\n }\n\n /**\n * Accounts the acting principal owns or holds an active grant on, in this\n * service's tenant, with the effective scopes per account. It never lists\n * unowned (tenant-wide) accounts or accounts of other users. Every decision\n * goes through `decideMailAccess`, so ownership, grants, the tenant\n * `messages.<scope>` ceiling and tenant isolation are the same as for mail\n * reads; no separate authorization path exists here. Fail closed: no\n * principal user, a principal of another tenant, or an unconfigured mail\n * access policy (`configureMailAccess`, which owned accounts need to be\n * decided at all) yields an empty list. Paged by account id.\n */\n async listAccounts(\n options: ListAccountsOptions = {},\n ): Promise<ListAccountsResult> {\n const empty: ListAccountsResult = { accounts: [], nextCursor: null };\n const userId = this.actingUserId;\n const { tenantId, principal } = this.options;\n if (!userId || !tenantId) return empty;\n if (principal.tenantId && principal.tenantId !== tenantId) return empty;\n // Owned accounts are only decidable under an explicit policy; a database\n // merely learned from mail rows must not open them up.\n if (!getMailAccessConfig()) return empty;\n const requested = Number.isFinite(options.limit)\n ? Math.trunc(options.limit as number)\n : LIST_ACCOUNTS_DEFAULT_LIMIT;\n const limit = Math.min(Math.max(requested, 1), LIST_ACCOUNTS_MAX_LIMIT);\n const subject: MailPrincipal = {\n id: principal.id ?? userId,\n userId,\n tenantId,\n // The host's limits (an agent credential's allow-list and scopes) ride\n // on the principal and are applied by decideMailAccess below.\n ...(principal.scopes ? { scopes: principal.scopes } : {}),\n ...(principal.accountIds ? { accountIds: principal.accountIds } : {}),\n };\n return withTenant({ tenantId }, async () => {\n const candidates = await this.accountCandidateIds(userId);\n if (subject.accountIds) {\n for (const id of [...candidates]) {\n if (!subject.accountIds.includes(id)) candidates.delete(id);\n }\n }\n const accounts = await AccountCollection.create(\n withoutListBounds({ db: this.options.db }),\n );\n const sorted = [...candidates].sort();\n const start = options.cursor\n ? sorted.findIndex((id) => id > (options.cursor as string))\n : 0;\n const out: MessagingAccountListing[] = [];\n let lastId: string | null = null;\n let more = false;\n for (const id of start < 0 ? [] : sorted.slice(start)) {\n if (out.length >= limit) {\n more = true;\n break;\n }\n const account = await accounts.get({ id });\n if (!account || account.tenantId !== tenantId) continue;\n lastId = id;\n const scopes: MailScope[] = [];\n let owner = false;\n for (const scope of MAIL_SCOPES) {\n const decision = await decideMailAccess(\n {\n id: account.id,\n tenantId: account.tenantId,\n ownerUserId: account.ownerUserId,\n },\n scope,\n subject,\n );\n if (decision.reason === 'owner' && decision.allowed) owner = true;\n if (\n decision.allowed &&\n (decision.reason === 'owner' || decision.reason === 'grant')\n ) {\n scopes.push(scope);\n }\n }\n if (!scopes.length) continue;\n out.push({\n ...this.accountView(account),\n relation: owner ? 'owner' : 'shared',\n scopes,\n });\n }\n return { accounts: out, nextCursor: more ? lastId : null };\n });\n }\n\n /** Ids of accounts the user owns or holds a grant row on (tenant scoped). */\n private async accountCandidateIds(userId: string): Promise<Set<string>> {\n const { tenantId, db } = this.options;\n const ids = new Set<string>();\n const accounts = await AccountCollection.create(withoutListBounds({ db }));\n const { ResourceGrantCollection } = await import(\n '@happyvertical/smrt-users'\n );\n const grants = await ResourceGrantCollection.create(\n withoutListBounds({ db }),\n );\n for (let offset = 0; ; offset += CANDIDATE_PAGE) {\n const rows = await accounts.list({\n where: { tenantId, ownerUserId: userId },\n limit: CANDIDATE_PAGE,\n offset,\n orderBy: 'id ASC',\n });\n for (const row of rows) if (row.id) ids.add(row.id);\n if (rows.length < CANDIDATE_PAGE) break;\n }\n for (let offset = 0; ; offset += CANDIDATE_PAGE) {\n const rows = await grants.list({\n where: { tenantId, userId, resourceType: MAIL_ACCOUNT_RESOURCE_TYPE },\n limit: CANDIDATE_PAGE,\n offset,\n orderBy: 'id ASC',\n });\n for (const row of rows) {\n if (row.isActive() && row.effect === 'grant') ids.add(row.resourceId);\n }\n if (rows.length < CANDIDATE_PAGE) break;\n }\n return ids;\n }\n\n /** The user who owns accounts this principal creates; null when unknown. */\n private get actingUserId(): string | null {\n return this.options.principal.userId ?? this.options.principal.id ?? null;\n }\n\n private async loadAccount(accountId: string): Promise<Account> {\n const accounts = await AccountCollection.create({ db: this.options.db });\n const account = await accounts.get({ id: accountId });\n if (!account || account.tenantId !== this.options.tenantId) {\n throw new Error('Messaging account was not found in this tenant.');\n }\n return account;\n }\n\n /** An owned mailbox is managed by its owner only; unowned ones by admins. */\n private assertMayManage(account: Account): void {\n if (account.ownerUserId && account.ownerUserId !== this.actingUserId) {\n throw new Error('Only the mail account owner can change this account.');\n }\n }\n\n private async validateConnection(\n request: MailboxValidationRequest,\n ): Promise<void> {\n try {\n if (this.options.validateMailbox) {\n await this.options.validateMailbox(request);\n return;\n }\n this.assertAllowedTarget(request.configuration);\n const create = request.provider.createEmailClient;\n if (!create) {\n throw new Error('this provider cannot check a mailbox sign-in');\n }\n const settings: Record<string, unknown> = {\n ...request.configuration,\n ...request.credentials,\n };\n delete settings.email;\n const client = await create({\n type: request.provider.id,\n ...settings,\n } as Parameters<typeof create>[0]);\n try {\n await client.connect();\n } finally {\n await client.disconnect().catch(() => undefined);\n }\n } catch {\n // Never echo server or network detail: it would let a permission\n // holder map internal hosts, and it can carry the secret.\n throw new Error('The mail server did not accept this connection.');\n }\n }\n\n /**\n * Host and port allowlist for the built-in validator (SSRF guard).\n *\n * Names are checked, not resolved: an allowlisted name that resolves (or is\n * rebound) to a private address is the host's allowlist responsibility, so\n * list only names you control, or pass a `validateMailbox` that resolves and\n * pins the address it connects to.\n */\n private assertAllowedTarget(configuration: Record<string, unknown>): void {\n // Every target-bearing field present is checked, so a permitted `host`\n // cannot shelter a different `url` or `endpoint` (the JMAP provider's\n // session URL is `url`).\n const targets: Array<{ host: string; port: number | undefined }> = [];\n if (typeof configuration.host === 'string' && configuration.host) {\n targets.push({\n host: configuration.host,\n port:\n typeof configuration.port === 'number'\n ? configuration.port\n : undefined,\n });\n }\n for (const key of ['endpoint', 'url'] as const) {\n const value = configuration[key];\n if (value === undefined || value === null || value === '') continue;\n if (typeof value !== 'string') throw new Error('refused');\n const url = new URL(value);\n // https only, and never credentials in the URL.\n if (url.protocol !== 'https:' || url.username || url.password) {\n throw new Error('refused');\n }\n targets.push({\n host: url.hostname,\n port: url.port ? Number(url.port) : 443,\n });\n }\n if (!targets.length) throw new Error('refused');\n const allowed = this.options.allowedMailHosts ?? [];\n const ports = this.options.allowedMailPorts ?? [\n 143, 443, 465, 587, 993, 995,\n ];\n for (const target of targets) {\n const host = target.host.toLowerCase().replace(/^\\[|\\]$/g, '');\n const listed = allowed.some((entry) => {\n const pattern = entry.toLowerCase();\n return pattern.startsWith('*.')\n ? host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1\n : host === pattern;\n });\n if (!host || !listed || isPrivateMailHost(host)) {\n throw new Error('refused');\n }\n if (target.port !== undefined && !ports.includes(target.port)) {\n throw new Error('refused');\n }\n }\n }\n\n private assert(permission: string): void {\n assertMessagingPermission(\n this.options.principal,\n this.options.tenantId,\n permission,\n );\n }\n\n private requireProvider(providerId: string): MessagingProviderDefinition {\n const provider = getMessagingProvider(providerId);\n if (!provider)\n throw new Error(`Unknown messaging provider '${providerId}'.`);\n return provider;\n }\n\n private validateFields(\n values: Record<string, unknown>,\n fields: MessagingProviderField[],\n kind: string,\n ): void {\n const allowed = new Set(fields.map((field) => field.id));\n for (const key of Object.keys(values)) {\n if (!allowed.has(key)) {\n throw new Error(`Unknown ${kind} field '${key}'.`);\n }\n }\n for (const field of fields) {\n const value = values[field.id];\n const missing = value === undefined || value === '';\n if (field.required && (missing || value === null)) {\n throw new Error(`${field.label} is required in ${kind}.`);\n }\n if (missing) continue;\n\n if (\n field.type === 'number' &&\n (typeof value !== 'number' || !Number.isFinite(value))\n ) {\n throw new Error(`${field.label} must be a finite number in ${kind}.`);\n }\n if (field.type === 'boolean' && typeof value !== 'boolean') {\n throw new Error(`${field.label} must be a boolean in ${kind}.`);\n }\n if (\n field.type !== 'number' &&\n field.type !== 'boolean' &&\n typeof value !== 'string'\n ) {\n throw new Error(`${field.label} must be a string in ${kind}.`);\n }\n if (\n field.type === 'select' &&\n field.options?.length &&\n !field.options.some((option) => option.value === value)\n ) {\n throw new Error(`${field.label} has an invalid option in ${kind}.`);\n }\n }\n }\n\n private newAccount(\n provider: MessagingProviderDefinition,\n input: MessagingAccountInput,\n ): Account {\n const options = {\n db: this.options.db,\n tenantId: this.options.tenantId,\n name: input.name.trim(),\n providerType: provider.id,\n channelType: provider.channel,\n };\n if (provider.id === 'zulip')\n return new (ObjectRegistry.resolveEffectiveConstructor(ZulipAccount))(\n options,\n );\n if (provider.id === 'telegram')\n return new (ObjectRegistry.resolveEffectiveConstructor(TelegramAccount))(\n options,\n );\n if (provider.channel === 'email') {\n return new (ObjectRegistry.resolveEffectiveConstructor(EmailAccount))({\n ...options,\n providerType: provider.id as 'smtp' | 'imap' | 'pop3' | 'gmail',\n });\n }\n return new (ObjectRegistry.resolveEffectiveConstructor(Account))(options);\n }\n\n private normalizeCredentials(\n provider: MessagingProviderDefinition,\n credentials: Record<string, unknown>,\n ): Record<string, unknown> {\n if (provider.channel !== 'email') return credentials;\n if (provider.id === 'gmail') {\n return { auth: credentials };\n }\n if (provider.id === 'jmap') {\n // JMAP signs in with a bearer token or a user and password, as one\n // `auth` value; a token must not be shadowed by an empty user/pass.\n const { username, password, token, ...rest } = credentials;\n if (typeof token === 'string' && token) {\n return { ...rest, auth: { type: 'bearer', token } };\n }\n return { ...rest, auth: { user: username, pass: password } };\n }\n const { username, password, ...rest } = credentials;\n return {\n ...rest,\n auth: { user: username, pass: password },\n };\n }\n\n private normalizeConfiguration(\n provider: MessagingProviderDefinition,\n configuration: Record<string, unknown>,\n ): Record<string, unknown> {\n if (provider.channel !== 'email' || configuration.secure === undefined) {\n return configuration;\n }\n return {\n ...configuration,\n secure: configuration.secure === true || configuration.secure === 'true',\n };\n }\n\n private accountView(account: Account): MessagingAccountView {\n return {\n id: account.id ?? '',\n name: account.name,\n providerId: account.providerType,\n channel: account.channelType,\n configuration: account.getConfiguration(),\n hasCredentials: account.hasCredentials,\n active: account.isActive,\n ownerUserId: account.ownerUserId,\n label: account.label,\n connectionStatus: account.connectionStatus,\n statusMessage: account.statusMessage,\n };\n }\n\n private endpointView(endpoint: MessagingEndpoint): MessagingEndpointView {\n return {\n id: endpoint.id ?? '',\n label: endpoint.label,\n channel: endpoint.channel,\n profileId: endpoint.profileId,\n maskedAddress: endpoint.getMaskedAddress(),\n active: endpoint.isActive,\n verified: endpoint.verifiedAt !== null,\n };\n }\n}\n\n/** Loopback, private, link-local and unspecified addresses and names. */\nfunction isPrivateMailHost(host: string): boolean {\n if (host === 'localhost' || host.endsWith('.localhost')) return true;\n const v4 = host.match(/^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/);\n if (v4) {\n const [a, b] = [Number(v4[1]), Number(v4[2])];\n return (\n a === 0 ||\n a === 10 ||\n a === 127 ||\n (a === 100 && b >= 64 && b <= 127) ||\n (a === 169 && b === 254) ||\n (a === 172 && b >= 16 && b <= 31) ||\n (a === 192 && b === 168)\n );\n }\n if (host.includes(':')) {\n return (\n host === '::' ||\n host === '::1' ||\n /^f[cd]/.test(host) ||\n /^fe[89ab]/.test(host) ||\n host.startsWith('::ffff:')\n );\n }\n return false;\n}\n","/**\n * Per-account mail search (Epic I, I6, #5132).\n *\n * `MailSearchService` searches the mail a principal may read and nothing else:\n *\n * - The searchable accounts are exactly `MessagingSettingsService.listAccounts`\n * with the `read` scope, so the decision is `decideMailAccess` (owner, grant,\n * tenant ceiling, the host's scope and account ceilings) and fails closed\n * without a principal, on a tenant mismatch or without `configureMailAccess`.\n * An `accountIds` filter can only narrow that set; unreadable ids are dropped.\n * - Every local read is constrained to those account ids in the query itself\n * and then runs as trusted code (`runWithMailSystemAccess`), because the\n * decision was already made here with the explicit principal.\n * - Local search is a keyword scan over a bounded, newest-first candidate\n * window (case-insensitive on every database), with optional semantic\n * ranking through core `semanticSearchIds()` when `Email` embeddings are\n * available. Provider search asks each account's own server through the\n * SDK's `search()` and falls back to the local index, per account, when the\n * provider cannot or does not answer.\n *\n * @packageDocumentation\n */\n\nimport type { SearchCriteria } from '@happyvertical/email';\nimport type { SmrtClassOptions } from '@happyvertical/smrt-core';\nimport { runWithMailSystemAccess } from '../access.js';\nimport { EmailAccountCollection } from '../collections/EmailAccountCollection.js';\nimport { EmailCollection } from '../collections/EmailCollection.js';\nimport { withTenant } from '../host.js';\nimport type { Email } from '../models/Email.js';\nimport type { EmailAccount } from '../models/EmailAccount.js';\nimport type { MessagingPrincipal } from '../permissions.js';\nimport {\n type MessagingAccountListing,\n MessagingSettingsService,\n} from './MessagingSettingsService.js';\n\nexport interface MailSearchServiceOptions {\n db: SmrtClassOptions['db'];\n tenantId: string;\n /** The acting principal, as for `MessagingSettingsService`. */\n principal: MessagingPrincipal;\n}\n\n/** Filters shared by local and provider search. */\nexport interface MailSearchQuery {\n /** Free text matched against subject, body, sender name and address. */\n text?: string;\n /** Narrow to these accounts; ids the principal cannot read are ignored. */\n accountIds?: readonly string[];\n /** Sender address or name contains. */\n from?: string;\n /** A recipient (to or cc) address or name contains. */\n to?: string;\n subject?: string;\n /** Mailbox label or folder name or path (exact, case-insensitive). */\n label?: string;\n hasAttachment?: boolean;\n isRead?: boolean;\n isFlagged?: boolean;\n /** Sent on or after. */\n since?: Date;\n /** Sent before. */\n before?: Date;\n /** Page size, 1 to 100. Default 25. */\n limit?: number;\n /** The previous page's `nextCursor`. */\n cursor?: string | null;\n /**\n * `keyword` (default) never calls an embedding model. `semantic` ranks by\n * meaning and falls back to keyword when embeddings are unavailable;\n * `semanticUsed` on the result says which happened.\n */\n mode?: 'keyword' | 'semantic';\n}\n\nexport interface MailSearchHit {\n accountId: string;\n /** Local `Email` row id; null for a provider hit not yet synced. */\n emailId: string | null;\n providerMessageId: string;\n threadId: string;\n subject: string;\n fromAddress: string;\n fromName: string;\n date: Date | null;\n snippet: string;\n isRead: boolean;\n isFlagged: boolean;\n hasAttachments: boolean;\n labels: string[];\n /** Where the hit came from. */\n source: 'local' | 'provider';\n /** Similarity in 0..1 when ranked semantically. */\n similarity?: number;\n}\n\nexport interface MailSearchPage {\n hits: MailSearchHit[];\n nextCursor: string | null;\n /** Accounts that were searched (readable and, if given, requested). */\n accountIds: string[];\n /** True when the scan window ended before every candidate was examined. */\n truncated: boolean;\n semanticUsed: boolean;\n}\n\nexport interface MailProviderSearchResult {\n hits: MailSearchHit[];\n /** Accounts answered by the provider. */\n providerAccountIds: string[];\n /** Accounts answered from the local index instead, with the reason. */\n fallbackAccounts: Array<{ accountId: string; reason: string }>;\n accountIds: string[];\n truncated: boolean;\n}\n\nconst DEFAULT_LIMIT = 25;\nconst MAX_LIMIT = 100;\nconst SCAN_BATCH = 200;\n/** Upper bound on rows examined by one local search call. */\nconst SCAN_LIMIT = 5000;\nconst SNIPPET_LENGTH = 200;\n\nfunction clampLimit(limit: number | undefined): number {\n if (limit === undefined) return DEFAULT_LIMIT;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new Error('Mail search limit must be a positive integer.');\n }\n return Math.min(limit, MAX_LIMIT);\n}\n\nfunction parseCursor(cursor: string | null | undefined): number {\n if (!cursor) return 0;\n const n = Number(cursor);\n if (!Number.isInteger(n) || n < 0) {\n throw new Error('Invalid mail search cursor.');\n }\n return n;\n}\n\nconst lower = (v: string | null | undefined) => (v ?? '').toLowerCase();\n\n/** Addresses of a JSON `[{address, name}]` column as lower-cased haystacks. */\nexport function recipientHaystack(json: string | null | undefined): string {\n if (!json) return '';\n try {\n const parsed = JSON.parse(json);\n if (!Array.isArray(parsed)) return lower(json);\n return parsed\n .map((p) =>\n typeof p === 'string' ? p : `${p?.address ?? ''} ${p?.name ?? ''}`,\n )\n .join(' ')\n .toLowerCase();\n } catch {\n return lower(json);\n }\n}\n\nfunction labelsOf(email: Email): string[] {\n const out = new Set<string>();\n for (const raw of [email.labels]) {\n try {\n const parsed = JSON.parse(raw || '[]');\n if (Array.isArray(parsed))\n for (const l of parsed) if (typeof l === 'string') out.add(l);\n } catch {\n // unreadable labels are treated as none\n }\n }\n if (email.folderPath) out.add(email.folderPath);\n return [...out];\n}\n\nfunction toHit(email: Email, similarity?: number): MailSearchHit {\n const body = (email.textBody || email.body || '').replace(/\\s+/g, ' ');\n return {\n accountId: email.accountId,\n emailId: email.id ?? null,\n providerMessageId: email.providerMessageId,\n threadId: email.threadId,\n subject: email.subject,\n fromAddress: email.fromAddress,\n fromName: email.fromName,\n date: email.date ?? null,\n snippet: body.slice(0, SNIPPET_LENGTH),\n isRead: email.isRead,\n isFlagged: email.isFlagged,\n hasAttachments: email.hasAttachments,\n labels: labelsOf(email),\n source: 'local',\n ...(similarity === undefined ? {} : { similarity }),\n };\n}\n\nfunction matches(email: Email, q: MailSearchQuery): boolean {\n if (q.from) {\n const f = q.from.toLowerCase();\n if (!`${lower(email.fromAddress)} ${lower(email.fromName)}`.includes(f))\n return false;\n }\n if (q.to) {\n const t = q.to.toLowerCase();\n if (\n !`${recipientHaystack(email.toAddresses)} ${recipientHaystack(email.ccAddresses)}`.includes(\n t,\n )\n )\n return false;\n }\n if (q.subject && !lower(email.subject).includes(q.subject.toLowerCase()))\n return false;\n if (q.label) {\n const wanted = q.label.toLowerCase();\n if (!labelsOf(email).some((l) => l.toLowerCase() === wanted)) return false;\n }\n if (q.text) {\n const t = q.text.toLowerCase();\n const hay = `${lower(email.subject)} ${lower(email.textBody)} ${lower(\n email.body,\n )} ${lower(email.fromAddress)} ${lower(email.fromName)}`;\n // Every word must appear somewhere (order-free).\n for (const word of t.split(/\\s+/).filter(Boolean)) {\n if (!hay.includes(word)) return false;\n }\n }\n return true;\n}\n\n/** SQL-expressible part of the query, always bound to the readable accounts. */\nfunction structuredWhere(\n q: MailSearchQuery,\n tenantId: string,\n accountIds: string[],\n): Record<string, unknown> {\n const where: Record<string, unknown> = {\n tenantId,\n 'accountId in': accountIds,\n };\n if (q.hasAttachment !== undefined) where.hasAttachments = q.hasAttachment;\n if (q.isRead !== undefined) where.isRead = q.isRead;\n if (q.isFlagged !== undefined) where.isFlagged = q.isFlagged;\n if (q.since) where['date >='] = q.since;\n if (q.before) where['date <'] = q.before;\n return where;\n}\n\nexport class MailSearchService {\n constructor(private readonly options: MailSearchServiceOptions) {}\n\n /** Accounts the principal may search: owner or `read` grant, nothing else. */\n async searchableAccounts(): Promise<MessagingAccountListing[]> {\n return readableMailAccounts(this.options);\n }\n\n private async scope(\n requested: readonly string[] | undefined,\n ): Promise<{ ids: string[]; accounts: MessagingAccountListing[] }> {\n const accounts = await this.searchableAccounts();\n const wanted = requested ? new Set(requested) : null;\n const chosen = accounts.filter((a) => !wanted || wanted.has(a.id));\n return { ids: chosen.map((a) => a.id), accounts: chosen };\n }\n\n /** Search the local index across every readable account. */\n async search(query: MailSearchQuery = {}): Promise<MailSearchPage> {\n const limit = clampLimit(query.limit);\n const start = parseCursor(query.cursor);\n const { ids } = await this.scope(query.accountIds);\n const empty: MailSearchPage = {\n hits: [],\n nextCursor: null,\n accountIds: ids,\n truncated: false,\n semanticUsed: false,\n };\n if (!ids.length) return empty;\n const { tenantId, db } = this.options;\n\n return withTenant({ tenantId }, () =>\n runWithMailSystemAccess(async () => {\n const emails = await EmailCollection.create({ db });\n const where = structuredWhere(query, tenantId, ids);\n\n if (query.mode === 'semantic' && query.text) {\n const ranked = await emails.semanticMatches(query.text, where);\n if (ranked?.length) {\n const hits: MailSearchHit[] = [];\n for (const match of ranked) {\n const email = (\n (await emails.list({\n where: { ...where, id: match.id },\n limit: 1,\n })) as Email[]\n )[0];\n if (email && matches(email, { ...query, text: undefined })) {\n hits.push(toHit(email, match.similarity));\n }\n }\n const page = hits.slice(start, start + limit);\n return {\n hits: page,\n nextCursor:\n start + limit < hits.length ? String(start + limit) : null,\n accountIds: ids,\n truncated: false,\n semanticUsed: true,\n };\n }\n }\n\n const hits: MailSearchHit[] = [];\n let scanned = start;\n let exhausted = false;\n while (hits.length < limit + 1 && scanned - start < SCAN_LIMIT) {\n const batch = (await emails.list({\n where,\n orderBy: ['date DESC', 'id ASC'],\n limit: SCAN_BATCH,\n offset: scanned,\n })) as Email[];\n for (const email of batch) {\n scanned += 1;\n if (matches(email, query)) hits.push(toHit(email));\n if (hits.length > limit) break;\n }\n if (batch.length < SCAN_BATCH) {\n exhausted = true;\n break;\n }\n if (hits.length > limit) break;\n }\n const more = hits.length > limit;\n const pageHits = hits.slice(0, limit);\n // Resume exactly after the last returned hit: re-scan is cheaper than\n // skipping results, so the cursor is the position of the first\n // unreturned candidate.\n let nextCursor: string | null = null;\n let truncated = false;\n if (more) {\n nextCursor = String(scanned - 1);\n } else if (!exhausted) {\n truncated = true;\n nextCursor = String(scanned);\n }\n return {\n hits: pageHits,\n nextCursor,\n accountIds: ids,\n truncated,\n semanticUsed: false,\n };\n }),\n );\n }\n\n /**\n * Ask each readable account's own server (SDK `search()`), falling back to\n * the local index for accounts whose provider cannot search or fails. One\n * account's failure never blocks the others. Provider hits that are already\n * synced carry their local `emailId`.\n */\n async searchProvider(\n query: MailSearchQuery = {},\n ): Promise<MailProviderSearchResult> {\n const limit = clampLimit(query.limit);\n const { ids, accounts } = await this.scope(query.accountIds);\n const result: MailProviderSearchResult = {\n hits: [],\n providerAccountIds: [],\n fallbackAccounts: [],\n accountIds: ids,\n truncated: false,\n };\n if (!ids.length) return result;\n const { tenantId, db } = this.options;\n const criteria = toSearchCriteria(query);\n\n for (const listing of accounts) {\n let answered = false;\n let reason = 'provider search unavailable';\n try {\n const hits = await withTenant({ tenantId }, () =>\n runWithMailSystemAccess(async () => {\n const emailAccounts = await EmailAccountCollection.create({ db });\n const account = (await emailAccounts.get({\n id: listing.id,\n tenantId,\n })) as EmailAccount | null;\n if (!account) throw new Error('account not found');\n const client = await account.createClient();\n try {\n await client.connect();\n const caps = await client.getCapabilities();\n if (!caps.search) {\n reason = 'provider does not support search';\n return null;\n }\n // IMAP searches only the selected mailbox and a fresh client\n // has none, so it answers [] for everything: never report that\n // as a successful provider search; use the local index.\n if (client.getAdapter() === 'imap') {\n reason = 'provider search needs a selected mailbox';\n return null;\n }\n const found = await client.search(criteria);\n const emails = await EmailCollection.create({ db });\n const out: MailSearchHit[] = [];\n for (const msg of found) {\n if (!matchesFlags(msg, query)) continue;\n if (out.length >= limit) {\n result.truncated = true;\n break;\n }\n const local = msg.id\n ? ((\n await emails.list({\n where: {\n tenantId,\n accountId: listing.id,\n providerMessageId: msg.id,\n },\n limit: 1,\n })\n )[0] as Email | undefined)\n : undefined;\n out.push(\n local\n ? { ...toHit(local), source: 'provider' as const }\n : {\n accountId: listing.id,\n emailId: null,\n providerMessageId: msg.id ?? '',\n threadId: msg.threadId ?? '',\n subject: msg.subject ?? '',\n fromAddress: msg.from?.address ?? '',\n fromName: msg.from?.name ?? '',\n date: msg.date ?? null,\n snippet: (msg.text ?? '')\n .replace(/\\s+/g, ' ')\n .slice(0, SNIPPET_LENGTH),\n isRead: (msg.flags ?? []).includes('\\\\Seen' as never),\n isFlagged: (msg.flags ?? []).includes(\n '\\\\Flagged' as never,\n ),\n hasAttachments: (msg.attachments?.length ?? 0) > 0,\n labels: msg.labels ?? [],\n source: 'provider' as const,\n },\n );\n }\n return out;\n } finally {\n await client.disconnect().catch(() => undefined);\n }\n }),\n );\n if (hits) {\n result.hits.push(...hits);\n result.providerAccountIds.push(listing.id);\n answered = true;\n }\n } catch (error) {\n // Provider text can carry account details; report a fixed reason.\n reason = 'provider search failed';\n }\n if (!answered) {\n result.fallbackAccounts.push({ accountId: listing.id, reason });\n const local = await this.search({\n ...query,\n accountIds: [listing.id],\n cursor: null,\n mode: 'keyword',\n });\n result.hits.push(...local.hits);\n if (local.truncated) result.truncated = true;\n }\n }\n result.hits.sort(\n (a, b) => (b.date?.getTime() ?? 0) - (a.date?.getTime() ?? 0),\n );\n if (result.hits.length > limit) {\n result.hits = result.hits.slice(0, limit);\n result.truncated = true;\n }\n return result;\n }\n}\n\nfunction toSearchCriteria(q: MailSearchQuery): SearchCriteria {\n return {\n ...(q.text ? { q: q.text } : {}),\n ...(q.from ? { from: q.from } : {}),\n ...(q.to ? { to: q.to } : {}),\n ...(q.subject ? { subject: q.subject } : {}),\n ...(q.since ? { since: q.since } : {}),\n ...(q.before ? { before: q.before } : {}),\n ...(q.isRead === false ? { unread: true } : {}),\n ...(q.isFlagged ? { flagged: true } : {}),\n };\n}\n\n/**\n * Filters the SDK criteria cannot express (label, attachments, read and\n * flagged state in both directions) applied to provider hits.\n */\nfunction matchesFlags(\n msg: {\n flags?: readonly string[];\n attachments?: unknown[];\n labels?: string[];\n folder?: string;\n folders?: string[];\n },\n q: MailSearchQuery,\n): boolean {\n const flags = new Set((msg.flags ?? []).map((f) => String(f).toLowerCase()));\n if (q.hasAttachment !== undefined) {\n if ((msg.attachments?.length ?? 0) > 0 !== q.hasAttachment) return false;\n }\n if (q.isRead !== undefined && flags.has('\\\\seen') !== q.isRead) return false;\n if (q.isFlagged !== undefined && flags.has('\\\\flagged') !== q.isFlagged)\n return false;\n if (q.label) {\n const wanted = q.label.toLowerCase();\n const names = [\n ...(msg.labels ?? []),\n ...(msg.folders ?? []),\n ...(msg.folder ? [msg.folder] : []),\n ];\n if (!names.some((n) => n.toLowerCase() === wanted)) return false;\n }\n return true;\n}\n\n/**\n * Accounts on which the principal holds `read`, paged out of\n * `listAccounts()` (the one account-discovery decision).\n */\nexport async function readableMailAccounts(\n options: MailSearchServiceOptions,\n): Promise<MessagingAccountListing[]> {\n const settings = new MessagingSettingsService({\n db: options.db,\n tenantId: options.tenantId,\n principal: options.principal,\n resolvePersonaTenantId: async () => null,\n });\n const out: MessagingAccountListing[] = [];\n let cursor: string | null = null;\n do {\n const page = await settings.listAccounts({ limit: 200, cursor });\n for (const account of page.accounts) {\n if (account.scopes.includes('read')) out.push(account);\n }\n cursor = page.nextCursor;\n } while (cursor);\n return out;\n}\n","/**\n * Private correspondents (Epic I, I6, #5132).\n *\n * `CorrespondentService` derives and serves one person's correspondents from\n * the mail that person can read:\n *\n * - Private by construction. Every read and write filters on the acting\n * user's id and the explicit tenant; there is no tenant-wide listing and no\n * way to name another owner. A principal with no user id gets nothing.\n * - Derived, never invented. `refresh()` scans the readable accounts' mail\n * (the same decision as search: `listAccounts` with `read`) and stores\n * address, latest display name, counts, first and last contact and the\n * accounts the address was seen in. It never creates or links a\n * smrt-profiles `Profile`.\n * - Access follows the mail. Each row keeps a per-account breakdown, and every\n * view (`list`/`suggest`/`get`) is computed from the accounts the viewer can\n * read right now: counts, dates, name and `accountIds` never include an\n * account that was revoked, and a row with no readable account is hidden.\n * - `refresh()` only touches what it scanned. An empty readable set (no\n * policy, tenant mismatch, no `read` scope) changes nothing; otherwise only\n * the scanned accounts' entries are replaced, so a narrower principal can\n * never erase data from accounts outside its view.\n * - Delegated principals (a host scope or account ceiling, or a principal id\n * that is not the user id, as agent credentials are) get nothing and cannot\n * write unless the host passes `allowDelegated: true`, the explicit owner\n * consent to act on the owner's private rows.\n * - Linking is the owner's choice: `linkProfile()` stores a `Profile` id after\n * checking the profile exists in the tenant; `unlinkProfile()` clears it.\n *\n * @packageDocumentation\n */\n\nimport {\n isUniqueViolationError,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { runWithMailSystemAccess } from '../access.js';\nimport { CorrespondentCollection } from '../collections/CorrespondentCollection.js';\nimport { EmailCollection } from '../collections/EmailCollection.js';\nimport { readNotificationProfile, withTenant } from '../host.js';\nimport type { Correspondent } from '../models/Correspondent.js';\nimport type { Email } from '../models/Email.js';\nimport type { EmailAccount } from '../models/EmailAccount.js';\nimport type { MessagingPrincipal } from '../permissions.js';\nimport {\n type MailSearchServiceOptions,\n readableMailAccounts,\n} from './MailSearchService.js';\n\nexport interface CorrespondentServiceOptions {\n db: SmrtClassOptions['db'];\n tenantId: string;\n principal: MessagingPrincipal;\n /**\n * Let a delegated principal (agent credential with ceilings) use the\n * owner's private correspondents. Off by default; hosts turn it on only\n * with the owner's consent.\n */\n allowDelegated?: boolean;\n}\n\nexport interface CorrespondentView {\n id: string;\n address: string;\n displayName: string;\n messageCount: number;\n sentCount: number;\n receivedCount: number;\n firstContactAt: Date | null;\n lastContactAt: Date | null;\n accountIds: string[];\n profileId: string | null;\n}\n\nexport interface CorrespondentRefreshResult {\n /** Correspondents written (created or updated). */\n upserted: number;\n /** Rows removed because no readable mail mentions them any more. */\n removed: number;\n /** Mail rows examined. */\n scanned: number;\n}\n\nexport interface ListCorrespondentsOptions {\n /** Substring of address or display name (case-insensitive). */\n query?: string;\n /** Page size, 1 to 200. Default 50. */\n limit?: number;\n /** Previous page's `nextCursor`. */\n cursor?: string | null;\n}\n\nconst SCAN_BATCH = 500;\nconst DEFAULT_LIMIT = 50;\nconst MAX_LIMIT = 200;\nconst SUGGEST_MAX = 20;\nconst EMAIL_PATTERN = /^[^\\s@<>]+@[^\\s@<>]+$/;\n\ninterface Party {\n address: string;\n name: string;\n}\n\nfunction parseParties(json: string | null | undefined): Party[] {\n if (!json) return [];\n try {\n const parsed = JSON.parse(json);\n if (!Array.isArray(parsed)) return [];\n const out: Party[] = [];\n for (const p of parsed) {\n const address = normalizeCorrespondentAddress(\n typeof p === 'string' ? p : p?.address,\n );\n if (address) {\n out.push({\n address,\n name: typeof p === 'object' && p?.name ? String(p.name).trim() : '',\n });\n }\n }\n return out;\n } catch {\n return [];\n }\n}\n\n/** Lower-cased, trimmed address, or null when it is not an email address. */\nexport function normalizeCorrespondentAddress(value: unknown): string | null {\n if (typeof value !== 'string') return null;\n const address = value.trim().toLowerCase();\n return EMAIL_PATTERN.test(address) ? address : null;\n}\n\ninterface AccountEntry {\n sent: number;\n received: number;\n first: number | null;\n last: number | null;\n name: string;\n nameAt: number;\n}\n\ntype Breakdown = Record<string, AccountEntry>;\n\nfunction parseBreakdown(row: Correspondent): Breakdown {\n try {\n const parsed = JSON.parse(row.accountBreakdown || '{}');\n return parsed && typeof parsed === 'object' && !Array.isArray(parsed)\n ? (parsed as Breakdown)\n : {};\n } catch {\n return {};\n }\n}\n\n/** The row as the viewer may see it: readable accounts only, else null. */\nfunction viewOf(\n row: Correspondent,\n readable: ReadonlySet<string>,\n): CorrespondentView | null {\n const all = parseBreakdown(row);\n const ids = Object.keys(all).filter((id) => readable.has(id));\n // A linked row that was reset (no account contributes) stays reachable so\n // its owner can still unlink it.\n const reset = Object.keys(all).length === 0 && Boolean(row.profileId);\n if (!ids.length && !reset) return null;\n let sent = 0;\n let received = 0;\n let first: number | null = null;\n let last: number | null = null;\n let name = '';\n let nameAt = -1;\n for (const id of ids) {\n const e = all[id];\n sent += e.sent;\n received += e.received;\n if (e.first !== null)\n first = first === null ? e.first : Math.min(first, e.first);\n if (e.last !== null) last = last === null ? e.last : Math.max(last, e.last);\n if (e.name && e.nameAt >= nameAt) {\n name = e.name;\n nameAt = e.nameAt;\n }\n }\n return {\n id: row.id as string,\n address: row.address,\n displayName: name,\n messageCount: sent + received,\n sentCount: sent,\n receivedCount: received,\n firstContactAt: first === null ? null : new Date(first),\n lastContactAt: last === null ? null : new Date(last),\n accountIds: ids.sort(),\n profileId: row.profileId,\n };\n}\n\nexport class CorrespondentService {\n constructor(private readonly options: CorrespondentServiceOptions) {}\n\n private get ownerUserId(): string | null {\n const { principal } = this.options;\n return principal.userId ?? principal.id ?? null;\n }\n\n /** Agent-style principal acting under ceilings or a credential id. */\n private get delegated(): boolean {\n const { principal } = this.options;\n return Boolean(\n principal.scopes ||\n principal.accountIds ||\n (principal.id && principal.userId && principal.id !== principal.userId),\n );\n }\n\n /** The owner whose rows this principal may use, or null. */\n private get actingOwner(): string | null {\n if (this.delegated && !this.options.allowDelegated) return null;\n return this.ownerUserId;\n }\n\n private searchOptions(): MailSearchServiceOptions {\n return this.options;\n }\n\n private async rows(): Promise<CorrespondentCollection> {\n return CorrespondentCollection.create({ db: this.options.db });\n }\n\n private async readableIds(): Promise<Set<string>> {\n return new Set(\n (await readableMailAccounts(this.searchOptions())).map((a) => a.id),\n );\n }\n\n /**\n * Re-derive this owner's correspondents from readable mail. Idempotent.\n * Only the scanned (readable) accounts' entries are replaced; entries of\n * accounts outside the scan are kept as they are. Nothing changes when no\n * account is readable. Addresses of the scanned accounts are not\n * correspondents. A delegated principal is refused.\n */\n async refresh(): Promise<CorrespondentRefreshResult> {\n const result: CorrespondentRefreshResult = {\n upserted: 0,\n removed: 0,\n scanned: 0,\n };\n if (this.delegated && !this.options.allowDelegated) {\n throw new Error('Correspondents are private to their owner.');\n }\n const owner = this.actingOwner;\n const { tenantId, db } = this.options;\n if (!owner) return result;\n const accounts = await readableMailAccounts(this.searchOptions());\n const ids = accounts.map((a) => a.id);\n // No readable account (no policy, tenant mismatch, no read scope): there\n // is no evidence about any row, so none is changed.\n if (!ids.length) return result;\n const scanned = new Set(ids);\n\n const own = new Set<string>(await this.ownAddresses(ids));\n const aggs = new Map<string, Breakdown>();\n const touch = (\n party: Party,\n kind: 'sent' | 'received',\n at: number,\n accountId: string,\n ) => {\n if (own.has(party.address)) return;\n let perAccount = aggs.get(party.address);\n if (!perAccount) {\n perAccount = {};\n aggs.set(party.address, perAccount);\n }\n let e = perAccount[accountId];\n if (!e) {\n e = {\n sent: 0,\n received: 0,\n first: null,\n last: null,\n name: '',\n nameAt: -1,\n };\n perAccount[accountId] = e;\n }\n if (kind === 'sent') e.sent += 1;\n else e.received += 1;\n if (at) {\n e.first = e.first === null ? at : Math.min(e.first, at);\n e.last = e.last === null ? at : Math.max(e.last, at);\n }\n if (party.name && at >= e.nameAt) {\n e.name = party.name;\n e.nameAt = at;\n }\n };\n\n await withTenant({ tenantId }, () =>\n runWithMailSystemAccess(async () => {\n const emails = await EmailCollection.create({ db });\n for (let offset = 0; ; offset += SCAN_BATCH) {\n const batch = (await emails.list({\n where: { tenantId, 'accountId in': ids },\n orderBy: ['id ASC'],\n limit: SCAN_BATCH,\n offset,\n })) as Email[];\n for (const email of batch) {\n result.scanned += 1;\n const at = email.date?.getTime() ?? 0;\n const sender = normalizeCorrespondentAddress(email.fromAddress);\n if (sender) {\n touch(\n { address: sender, name: email.fromName?.trim() ?? '' },\n 'sent',\n at,\n email.accountId,\n );\n }\n for (const p of [\n ...parseParties(email.toAddresses),\n ...parseParties(email.ccAddresses),\n ]) {\n touch(p, 'received', at, email.accountId);\n }\n }\n if (batch.length < SCAN_BATCH) break;\n }\n }),\n );\n\n await withTenant({ tenantId }, async () => {\n const rows = await this.rows();\n const existing = (await rows.list({\n where: { tenantId, ownerUserId: owner },\n limit: 100000,\n })) as Correspondent[];\n const byAddress = new Map(existing.map((r) => [r.address, r]));\n const addresses = new Set([...aggs.keys(), ...byAddress.keys()]);\n for (const address of addresses) {\n let row = byAddress.get(address);\n // Keep entries of accounts outside the scan; replace scanned ones.\n const merged: Breakdown = {};\n if (row) {\n for (const [id, e] of Object.entries(parseBreakdown(row))) {\n if (!scanned.has(id)) merged[id] = e;\n }\n }\n Object.assign(merged, aggs.get(address) ?? {});\n if (!Object.keys(merged).length && row && !row.profileId) {\n await row.delete();\n result.removed += 1;\n continue;\n }\n if (!row) {\n try {\n row = await rows.create({\n _insertOnly: true,\n tenantId,\n ownerUserId: owner,\n address,\n });\n } catch (error) {\n // A concurrent refresh stored the row first: update that one.\n if (!isUniqueViolationError(error)) throw error;\n row = (\n (await rows.list({\n where: { tenantId, ownerUserId: owner, address },\n limit: 1,\n })) as Correspondent[]\n )[0];\n if (!row) throw error;\n }\n }\n let sent = 0;\n let received = 0;\n let first: number | null = null;\n let last: number | null = null;\n let name = '';\n let nameAt = -1;\n for (const e of Object.values(merged)) {\n sent += e.sent;\n received += e.received;\n if (e.first !== null)\n first = first === null ? e.first : Math.min(first, e.first);\n if (e.last !== null)\n last = last === null ? e.last : Math.max(last, e.last);\n if (e.name && e.nameAt >= nameAt) {\n name = e.name;\n nameAt = e.nameAt;\n }\n }\n row.accountBreakdown = JSON.stringify(merged);\n row.accountIds = JSON.stringify(Object.keys(merged).sort());\n row.sentCount = sent;\n row.receivedCount = received;\n row.messageCount = sent + received;\n row.firstContactAt = first === null ? null : new Date(first);\n row.lastContactAt = last === null ? null : new Date(last);\n row.displayName = name || row.displayName;\n await row.save();\n result.upserted += 1;\n }\n });\n return result;\n }\n\n private async ownAddresses(accountIds: string[]): Promise<string[]> {\n const { EmailAccountCollection } = await import(\n '../collections/EmailAccountCollection.js'\n );\n const accounts = await EmailAccountCollection.create({\n db: this.options.db,\n });\n const out: string[] = [];\n for (const id of accountIds) {\n const account = (await accounts.get({\n id,\n tenantId: this.options.tenantId,\n })) as EmailAccount | null;\n const addr = normalizeCorrespondentAddress(account?.email);\n if (addr) out.push(addr);\n }\n return out;\n }\n\n /** The owner's correspondents, as seen through the readable accounts. */\n private async visible(): Promise<CorrespondentView[]> {\n const owner = this.actingOwner;\n if (!owner) return [];\n const readable = await this.readableIds();\n if (!readable.size) return [];\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const rows = (await (\n await this.rows()\n ).list({\n where: { tenantId: this.options.tenantId, ownerUserId: owner },\n orderBy: ['lastContactAt DESC', 'id ASC'],\n limit: 100000,\n })) as Correspondent[];\n const views: CorrespondentView[] = [];\n for (const r of rows) {\n const v = viewOf(r, readable);\n if (v?.accountIds.length) views.push(v);\n }\n return views.sort(\n (a, b) =>\n (b.lastContactAt?.getTime() ?? 0) -\n (a.lastContactAt?.getTime() ?? 0) ||\n a.address.localeCompare(b.address),\n );\n });\n }\n\n async list(options: ListCorrespondentsOptions = {}): Promise<{\n correspondents: CorrespondentView[];\n nextCursor: string | null;\n }> {\n const requested = Number.isFinite(options.limit)\n ? Math.trunc(options.limit as number)\n : DEFAULT_LIMIT;\n const limit = Math.min(Math.max(requested, 1), MAX_LIMIT);\n const start = options.cursor ? Number(options.cursor) : 0;\n if (!Number.isInteger(start) || start < 0) {\n throw new Error('Invalid correspondent cursor.');\n }\n const q = options.query?.trim().toLowerCase();\n const all = (await this.visible()).filter(\n (r) =>\n !q || r.address.includes(q) || r.displayName.toLowerCase().includes(q),\n );\n return {\n correspondents: all.slice(start, start + limit),\n nextCursor: start + limit < all.length ? String(start + limit) : null,\n };\n }\n\n /**\n * Recipient autocomplete: correspondents whose address or name starts with\n * (or, for names, has a word starting with) `prefix`, best first.\n */\n async suggest(prefix: string, limit = 8): Promise<CorrespondentView[]> {\n const p = prefix.trim().toLowerCase();\n if (!p) return [];\n const cap = Math.min(Math.max(Math.trunc(limit) || 1, 1), SUGGEST_MAX);\n const scored: Array<{ view: CorrespondentView; rank: number }> = [];\n for (const view of await this.visible()) {\n const name = view.displayName.toLowerCase();\n let rank = -1;\n if (view.address.startsWith(p)) rank = 0;\n else if (name.startsWith(p)) rank = 1;\n else if (name.split(/\\s+/).some((w) => w.startsWith(p))) rank = 2;\n else if (view.address.includes(p)) rank = 3;\n if (rank >= 0) scored.push({ view, rank });\n }\n scored.sort(\n (a, b) =>\n a.rank - b.rank ||\n b.view.messageCount - a.view.messageCount ||\n a.view.address.localeCompare(b.view.address),\n );\n return scored.slice(0, cap).map((s) => s.view);\n }\n\n private async owned(\n id: string,\n ): Promise<{ row: Correspondent; view: CorrespondentView } | null> {\n const owner = this.actingOwner;\n if (!owner) return null;\n const readable = await this.readableIds();\n if (!readable.size) return null;\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const found = (\n (await (\n await this.rows()\n ).list({\n where: { tenantId: this.options.tenantId, ownerUserId: owner, id },\n limit: 1,\n })) as Correspondent[]\n )[0];\n if (!found) return null;\n const view = viewOf(found, readable);\n return view ? { row: found, view } : null;\n });\n }\n\n async get(id: string): Promise<CorrespondentView | null> {\n return (await this.owned(id))?.view ?? null;\n }\n\n private assertMayWrite(): void {\n if (this.delegated && !this.options.allowDelegated) {\n throw new Error('Correspondents are private to their owner.');\n }\n }\n\n /** Link a correspondent to a `Profile` of this tenant (owner's choice). */\n async linkProfile(id: string, profileId: string): Promise<CorrespondentView> {\n this.assertMayWrite();\n const hit = await this.owned(id);\n if (!hit) throw new Error('Correspondent not found.');\n const profile = await readNotificationProfile(\n this.options.db as never,\n this.options.tenantId,\n profileId,\n );\n if (\n !profile ||\n (profile.tenantId && profile.tenantId !== this.options.tenantId)\n ) {\n throw new Error('Profile not found.');\n }\n hit.row.profileId = profileId;\n await withTenant({ tenantId: this.options.tenantId }, () => hit.row.save());\n return { ...hit.view, profileId };\n }\n\n async unlinkProfile(id: string): Promise<CorrespondentView> {\n this.assertMayWrite();\n const hit = await this.owned(id);\n if (!hit) throw new Error('Correspondent not found.');\n hit.row.profileId = null;\n await withTenant({ tenantId: this.options.tenantId }, () => hit.row.save());\n return { ...hit.view, profileId: null };\n }\n}\n","import {\n isUniqueViolationError,\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { NotificationOptOutCollection } from '../collections/NotificationOptOutCollection.js';\nimport { withTenant } from '../host.js';\nimport {\n NOTIFICATION_DELIVERY_CHANNELS,\n type NotificationDeliveryChannel,\n} from '../models/NotificationDelivery.js';\nimport {\n isValidNotificationOptOutScope,\n NOTIFICATION_OPT_OUT_ALL_SCOPE,\n NotificationOptOut,\n} from '../models/NotificationOptOut.js';\nimport type { NotificationSuppressionRequest } from './NotificationOutboxService.js';\n\n/** The signed-in person making a request, as the host authenticated them. */\nexport interface NotificationOptOutPrincipal {\n userId: string;\n /**\n * The tenant the principal is authenticated in. Required and must equal the\n * request's tenant: a principal never acts in another tenant. A host whose\n * recipient is authenticated elsewhere (e.g. a member of a child tenant)\n * authorizes the recipient itself and makes a trusted call without a\n * principal instead.\n */\n tenantId: string;\n}\n\nexport interface NotificationOptOutKey {\n tenantId: string;\n recipientUserId: string;\n channel: NotificationDeliveryChannel;\n /** `*` or a host key such as `project:<uuid>`. */\n scope: string;\n}\n\nexport interface NotificationOptOutChange extends NotificationOptOutKey {\n /**\n * The signed-in person, authenticated in this tenant. When present only the\n * recipient themself may change the row, and only in the principal's own\n * tenant; when omitted the call is trusted host code that has already\n * authenticated the recipient (e.g. a signed unsubscribe link, or a host\n * route whose member belongs to a child tenant of the delivery tenant).\n */\n principal?: NotificationOptOutPrincipal;\n}\n\nexport interface NotificationOptOutListRequest {\n tenantId: string;\n recipientUserId: string;\n principal: NotificationOptOutPrincipal;\n}\n\nexport type NotificationOptOutDenialReason = 'principal' | 'tenant';\n\n/** Thrown when a principal tries to read or change another person's opt-out. */\nexport class NotificationOptOutDeniedError extends Error {\n constructor(\n readonly reason: NotificationOptOutDenialReason,\n message: string,\n ) {\n super(message);\n this.name = 'NotificationOptOutDeniedError';\n }\n}\n\nfunction requireText(value: string | undefined, name: string): string {\n const text = typeof value === 'string' ? value.trim() : '';\n if (!text) throw new Error(`A notification opt-out ${name} is required.`);\n return text;\n}\n\nfunction validate(key: NotificationOptOutKey): NotificationOptOutKey {\n const channel = key.channel;\n if (!NOTIFICATION_DELIVERY_CHANNELS.includes(channel)) {\n throw new Error(`Unknown notification channel '${String(channel)}'.`);\n }\n if (!isValidNotificationOptOutScope(key.scope)) {\n throw new Error(\n `Invalid notification opt-out scope '${String(key.scope)}': use '*' or a key like 'project:<id>'.`,\n );\n }\n return {\n tenantId: requireText(key.tenantId, 'tenant'),\n recipientUserId: requireText(key.recipientUserId, 'recipient'),\n channel,\n scope: key.scope,\n };\n}\n\nfunction authorize(\n principal: NotificationOptOutPrincipal | undefined,\n tenantId: string,\n recipientUserId: string,\n): string {\n if (!principal) return 'system';\n if (!principal.tenantId || principal.tenantId !== tenantId) {\n throw new NotificationOptOutDeniedError(\n 'tenant',\n 'Principal does not belong to this tenant.',\n );\n }\n if (!principal.userId || principal.userId !== recipientUserId) {\n throw new NotificationOptOutDeniedError(\n 'principal',\n 'Only the recipient may change or list their notification opt-outs.',\n );\n }\n return principal.userId;\n}\n\n/**\n * The per-recipient opt-out ledger behind the outbox's `isSuppressed` hook.\n *\n * Writes are idempotent and, with a `principal`, limited to the recipient's\n * own rows. {@link isOptedOut} is a trusted read for suppression: it runs\n * where the recipient is not the caller (a manager enqueues, a worker\n * dispatches) and is always scoped to the given tenant.\n */\nexport class NotificationOptOutService {\n constructor(private readonly options: { db: SmrtClassOptions['db'] }) {}\n\n private collection(): Promise<NotificationOptOutCollection> {\n return NotificationOptOutCollection.create({ db: this.options.db });\n }\n\n /** Opt the recipient out of `scope`; a repeat leaves the row untouched. */\n async optOut(change: NotificationOptOutChange): Promise<NotificationOptOut> {\n return this.change(change, true);\n }\n\n /** Clear an opt-out; a repeat, or no row at all, is a no-op. */\n async optIn(change: NotificationOptOutChange): Promise<NotificationOptOut> {\n return this.change(change, false);\n }\n\n /**\n * Whether the recipient has opted out of `scope` (a `*` row matches every\n * scope). Trusted read: no principal, always under the tenant's scope.\n */\n async isOptedOut(key: NotificationOptOutKey): Promise<boolean> {\n const { tenantId, recipientUserId, channel, scope } = validate(key);\n const scopes =\n scope === NOTIFICATION_OPT_OUT_ALL_SCOPE\n ? [scope]\n : [scope, NOTIFICATION_OPT_OUT_ALL_SCOPE];\n return withTenant({ tenantId }, async () => {\n const rows = await (await this.collection()).list({\n where: { tenantId, recipientUserId, channel, 'scope in': scopes },\n });\n return rows.some((row) => row.optedOutAt !== null);\n });\n }\n\n /** The recipient's own active opt-outs, in one tenant. */\n async listForRecipient(\n request: NotificationOptOutListRequest,\n ): Promise<NotificationOptOut[]> {\n const tenantId = requireText(request.tenantId, 'tenant');\n const recipientUserId = requireText(request.recipientUserId, 'recipient');\n if (!request.principal) {\n throw new NotificationOptOutDeniedError(\n 'principal',\n 'A principal is required to list opt-outs.',\n );\n }\n authorize(request.principal, tenantId, recipientUserId);\n return withTenant({ tenantId }, async () => {\n const rows = await (await this.collection()).list({\n where: { tenantId, recipientUserId },\n orderBy: 'scope ASC',\n });\n return rows.filter((row) => row.optedOutAt !== null);\n });\n }\n\n private async change(\n change: NotificationOptOutChange,\n optedOut: boolean,\n ): Promise<NotificationOptOut> {\n const key = validate(change);\n const updatedBy = authorize(\n change.principal,\n key.tenantId,\n key.recipientUserId,\n );\n const { tenantId, recipientUserId, channel, scope } = key;\n\n return withTenant({ tenantId }, async () => {\n const rows = await this.collection();\n const find = async () =>\n (\n await rows.list({\n where: { tenantId, recipientUserId, channel, scope },\n limit: 1,\n })\n )[0];\n\n const apply = async (row: NotificationOptOut) => {\n if (row.isOptedOut === optedOut) return row; // already in that state\n row.optedOutAt = optedOut ? new Date() : null;\n row.updatedBy = updatedBy;\n await row.save();\n return row;\n };\n\n const existing = await find();\n if (existing) return apply(existing);\n if (!optedOut) {\n // Nothing to clear; return an unsaved, opted-in view of the key.\n return new (ObjectRegistry.resolveEffectiveConstructor(\n NotificationOptOut,\n ))({\n tenantId,\n recipientUserId,\n channel,\n scope,\n optedOutAt: null,\n updatedBy,\n });\n }\n try {\n return await rows.create({\n _insertOnly: true,\n tenantId,\n recipientUserId,\n channel,\n scope,\n optedOutAt: new Date(),\n updatedBy,\n });\n } catch (error) {\n if (!isUniqueViolationError(error)) throw error;\n const winner = await find();\n if (!winner) throw error;\n return apply(winner);\n }\n });\n }\n}\n\n/**\n * Build an `isSuppressed` function for `NotificationOutboxOptions` from the\n * ledger. `scopeOf` maps a notification to the scope a recipient can opt out\n * of (e.g. `project:<uuid>` from its `sourceRef`), or null when the\n * notification is not opt-out-able. A `*` opt-out suppresses any notification\n * `scopeOf` maps to a scope; returning `'*'` checks only the tenant-wide row.\n */\nexport function optOutSuppression(\n service: Pick<NotificationOptOutService, 'isOptedOut'>,\n scopeOf: (\n request: NotificationSuppressionRequest,\n ) => string | null | Promise<string | null>,\n): (request: NotificationSuppressionRequest) => Promise<boolean> {\n return async (request) => {\n const scope = await scopeOf(request);\n if (scope === null || scope === undefined) return false;\n return service.isOptedOut({\n tenantId: request.tenantId,\n recipientUserId: request.recipientUserId,\n channel: request.channel,\n scope,\n });\n };\n}\n","import { detectEngine } from '@happyvertical/smrt-core';\n/** Explicit maintenance migration for typed email contact identities. No runtime DDL. */\nimport type { DatabaseInterface } from '@happyvertical/smrt-core/migrations';\nimport {\n assertNotificationMaintenanceHost,\n buildSqliteRebuildStatements,\n} from '../host.js';\n\nexport type NotificationProfileRecipientEngine = 'postgres' | 'sqlite';\nexport interface NotificationProfileRecipientPlan {\n engine: NotificationProfileRecipientEngine;\n ready: boolean;\n statements: string[];\n invalidRowIds: string[];\n obsoleteIndexes: string[];\n}\nconst table = 'notification_deliveries';\nconst checkName = 'notification_deliveries_recipient_identity_check';\nconst userIndex = 'notification_deliveries_user_identity';\nconst profileIndex = 'notification_deliveries_profile_identity';\nconst typedIndex = 'notification_deliveries_typed_identity';\nconst identityCheck = `(recipient_kind IS NOT NULL AND ((recipient_kind = 'user' AND recipient_user_id IS NOT NULL AND length(trim(CAST(recipient_user_id AS TEXT))) > 0 AND recipient_profile_id IS NULL AND (required_dispatch_policy IS NULL OR required_dispatch_policy NOT LIKE 'profile:%') AND kind NOT LIKE 'protected:profile:%') OR (recipient_kind = 'profile' AND recipient_user_id IS NULL AND recipient_profile_id IS NOT NULL AND length(trim(CAST(recipient_profile_id AS TEXT))) > 0 AND channel = 'email' AND required_dispatch_policy IS NOT NULL AND length(trim(required_dispatch_policy)) > 8 AND required_dispatch_policy LIKE 'profile:%' AND kind = 'protected:' || required_dispatch_policy)))`;\n/** Canonical Boolean tree ignores PG's redundant parentheses/casts, preserving AND/OR precedence. */\nfunction canonicalCheck(sql: string): string {\n const value = sql\n .trim()\n .replace(/^CHECK\\s*/i, '')\n .replace(/::text\\b/gi, '')\n .replace(/!~~/g, ' NOT LIKE ')\n .replace(/~~/g, ' LIKE ')\n .replace(/CAST\\(\\s*([a-z_]+)\\s+AS\\s+TEXT\\s*\\)/gi, '$1')\n .replace(/TRIM\\(\\s*BOTH\\s+FROM\\s+/gi, 'trim(');\n function outer(text: string): string {\n text = text.trim();\n while (text.startsWith('(') && text.endsWith(')')) {\n let depth = 0,\n quoted = false,\n complete = true;\n for (let i = 0; i < text.length - 1; i++) {\n if (text[i] === \"'\") quoted = !quoted;\n if (quoted) continue;\n if (text[i] === '(') depth++;\n if (text[i] === ')' && --depth === 0) {\n complete = false;\n break;\n }\n }\n if (!complete) break;\n text = text.slice(1, -1).trim();\n }\n return text;\n }\n function parse(text: string): unknown {\n text = outer(text);\n for (const op of ['OR', 'AND']) {\n let depth = 0,\n quoted = false,\n start = 0;\n const terms: string[] = [];\n for (let i = 0; i < text.length; i++) {\n if (text[i] === \"'\") quoted = !quoted;\n if (quoted) continue;\n if (text[i] === '(') depth++;\n if (text[i] === ')') depth--;\n if (\n !depth &&\n text.slice(i).match(new RegExp('^' + op + '\\\\b', 'i')) &&\n (i === 0 || /\\s/.test(text[i - 1]))\n ) {\n terms.push(text.slice(start, i));\n start = i + op.length;\n i += op.length - 1;\n }\n }\n if (terms.length)\n return [op, ...[...terms, text.slice(start)].map(parse)];\n }\n return text.toLowerCase().replace(/[\\s()\"]/g, '');\n }\n return JSON.stringify(parse(value));\n}\nconst quote = (name: string) => {\n if (!/^[a-z_][a-z0-9_]*$/i.test(name))\n throw new Error('Unsafe notification schema identifier.');\n return `\"${name}\"`;\n};\nfunction indexColumns(sql: string): string[] {\n const match = /\\(([^()]+)\\)\\s*(?:NULLS\\s+NOT\\s+DISTINCT)?\\s*$/i.exec(sql);\n return match\n ? match[1].split(',').map((s) => s.trim().replaceAll('\"', ''))\n : [];\n}\nfunction same(a: string[], b: string[]) {\n return a.length === b.length && a.every((v, i) => v === b[i]);\n}\nconst userColumns = ['tenant_id', 'recipient_user_id', 'channel', 'source_ref'];\nconst profileColumns = [\n 'tenant_id',\n 'recipient_profile_id',\n 'channel',\n 'source_ref',\n];\nconst typedColumns = [\n 'tenant_id',\n 'recipient_kind',\n 'recipient_user_id',\n 'recipient_profile_id',\n 'channel',\n 'source_ref',\n];\nasync function inspect(\n db: Pick<DatabaseInterface, 'query'>,\n engine: NotificationProfileRecipientEngine,\n) {\n if (engine !== 'sqlite' && engine !== 'postgres')\n throw new Error(\n 'Profile recipients require SQLite or PostgreSQL maintenance.',\n );\n const columns =\n engine === 'sqlite'\n ? ((await db.query(`PRAGMA table_info(${quote(table)})`)).rows as {\n name: string;\n notnull: number;\n }[])\n : ((\n await db.query(\n \"SELECT column_name AS name, CASE WHEN is_nullable='NO' THEN 1 ELSE 0 END AS notnull FROM information_schema.columns WHERE table_schema=current_schema() AND table_name=?\",\n table,\n )\n ).rows as { name: string; notnull: number }[]);\n if (!columns.length)\n throw new Error(\n 'Migrate the notification outbox table before profile recipient maintenance.',\n );\n const indexes =\n engine === 'sqlite'\n ? ((\n await db.query(\n \"SELECT name, sql FROM sqlite_master WHERE type='index' AND tbl_name=? AND sql IS NOT NULL\",\n table,\n )\n ).rows as { name: string; sql: string }[])\n : ((\n await db.query(\n 'SELECT indexname AS name, indexdef AS sql FROM pg_indexes WHERE schemaname=current_schema() AND tablename=?',\n table,\n )\n ).rows as { name: string; sql: string }[]);\n const ddl =\n engine === 'sqlite'\n ? String(\n (\n await db.query(\n \"SELECT sql FROM sqlite_master WHERE type='table' AND name=?\",\n table,\n )\n ).rows[0]?.sql ?? '',\n )\n : String(\n (\n await db.query(\n 'SELECT pg_get_constraintdef(oid) AS sql FROM pg_constraint WHERE conrelid=?::regclass AND conname=?',\n table,\n checkName,\n )\n ).rows[0]?.sql ?? '',\n );\n const obsolete = indexes.filter(\n (i) =>\n /NULLS\\s+NOT\\s+DISTINCT/i.test(i.sql) &&\n same(indexColumns(i.sql), userColumns),\n );\n const validIndex = (name: string, expected: string[]) =>\n indexes.some(\n (i) =>\n i.name === name &&\n /CREATE\\s+UNIQUE\\s+INDEX/i.test(i.sql) &&\n same(indexColumns(i.sql), expected) &&\n !(/NULLS\\s+NOT\\s+DISTINCT/i.test(i.sql) && name !== typedIndex),\n );\n const hasColumns = ['recipient_kind', 'recipient_profile_id'].every((name) =>\n columns.some((c) => c.name === name),\n );\n const hasCheck =\n engine === 'sqlite'\n ? ddl.includes(checkName) && ddl.includes(identityCheck)\n : !ddl.includes('NOT VALID') &&\n canonicalCheck(ddl) === canonicalCheck(identityCheck);\n const ready =\n hasColumns &&\n !Number(columns.find((c) => c.name === 'recipient_user_id')?.notnull) &&\n hasCheck &&\n !obsolete.length &&\n validIndex(userIndex, userColumns) &&\n validIndex(profileIndex, profileColumns) &&\n validIndex(typedIndex, typedColumns);\n return {\n columns,\n indexes,\n ddl,\n obsolete,\n ready,\n hasColumns,\n hasCheck,\n validIndex,\n };\n}\n/** Read-only plan against the live schema. Refuses ambiguous drift and never changes rows. */\nexport async function planNotificationProfileRecipients(\n db: Pick<DatabaseInterface, 'query'>,\n engine: NotificationProfileRecipientEngine,\n): Promise<NotificationProfileRecipientPlan> {\n assertNotificationMaintenanceHost();\n const state = await inspect(db, engine);\n const result: NotificationProfileRecipientPlan = {\n engine,\n ready: state.ready,\n statements: [],\n invalidRowIds: [],\n obsoleteIndexes: state.obsolete.map((i) => i.name),\n };\n if (state.ready) return result;\n const kind = state.columns.some((c) => c.name === 'recipient_kind')\n ? 'recipient_kind'\n : \"'user'\";\n const profile = state.columns.some((c) => c.name === 'recipient_profile_id')\n ? 'recipient_profile_id'\n : 'NULL';\n const rows = (\n await db.query(\n `SELECT id, tenant_id, recipient_user_id, ${kind} AS recipient_kind, ${profile} AS recipient_profile_id, channel, source_ref, kind, required_dispatch_policy FROM ${quote(table)}`,\n )\n ).rows;\n const identities = new Set<string>();\n for (const row of rows) {\n const user =\n row.recipient_kind === 'user' &&\n row.recipient_user_id != null &&\n String(row.recipient_user_id).trim() !== '' &&\n row.recipient_profile_id == null;\n const contact =\n row.recipient_kind === 'profile' &&\n row.recipient_user_id == null &&\n row.recipient_profile_id != null &&\n String(row.recipient_profile_id).trim() !== '' &&\n row.channel === 'email' &&\n typeof row.required_dispatch_policy === 'string' &&\n Boolean(row.required_dispatch_policy.trim()) &&\n row.kind === `protected:${row.required_dispatch_policy}`;\n const key = JSON.stringify([\n row.tenant_id,\n row.recipient_kind,\n row.recipient_user_id,\n row.recipient_profile_id,\n row.channel,\n row.source_ref,\n ]);\n if (!(user || contact) || identities.has(key))\n result.invalidRowIds.push(String(row.id));\n identities.add(key);\n }\n if (result.invalidRowIds.length) return result;\n for (const [name, columns] of [\n [userIndex, userColumns],\n [profileIndex, profileColumns],\n [typedIndex, typedColumns],\n ] as const) {\n const found = state.indexes.find((i) => i.name === name);\n if (found && !state.validIndex(name, [...columns]))\n throw new Error(`Unexpected notification index drift: ${name}`);\n }\n if (engine === 'postgres') {\n if (!state.columns.some((c) => c.name === 'recipient_kind'))\n result.statements.push(\n `ALTER TABLE ${quote(table)} ADD COLUMN recipient_kind TEXT NOT NULL DEFAULT 'user'`,\n );\n if (!state.columns.some((c) => c.name === 'recipient_profile_id'))\n result.statements.push(\n `ALTER TABLE ${quote(table)} ADD COLUMN recipient_profile_id UUID REFERENCES profiles(id)`,\n );\n result.statements.push(\n `ALTER TABLE ${quote(table)} ALTER COLUMN recipient_user_id DROP NOT NULL`,\n );\n if (!state.hasCheck) {\n if (state.ddl)\n throw new Error('Unexpected notification identity CHECK drift.');\n result.statements.push(\n `ALTER TABLE ${quote(table)} ADD CONSTRAINT ${quote(checkName)} CHECK ${identityCheck}`,\n );\n }\n for (const index of state.obsolete)\n result.statements.push(`DROP INDEX ${quote(index.name)}`);\n } else if (\n !state.hasColumns ||\n Number(\n state.columns.find((c) => c.name === 'recipient_user_id')?.notnull,\n ) ||\n !state.hasCheck\n ) {\n // The core planner owns live-DDL preservation and rowid/index/trigger copying.\n const incoming = (\n await db.query(\n \"SELECT name, sql FROM main.sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite\\\\_%' ESCAPE '\\\\'\",\n )\n ).rows;\n for (const row of incoming) {\n const refs =\n // Read in `main`, where the table was listed: a temporary table of\n // the same name would otherwise answer for a real child.\n (\n await db.query(\n `PRAGMA main.foreign_key_list(${quote(String(row.name))})`,\n )\n ).rows;\n // SQLite resolves a referenced table name case-insensitively, and the\n // table's own self-reference counts: the staging copy would be its child.\n if (\n refs.some((r) => String(r.table).toLowerCase() === table.toLowerCase())\n )\n throw new Error(\n 'SQLite profile maintenance requires an explicit inbound-FK-safe migration window.',\n );\n }\n if (!/\\)\\s*;?\\s*$/.test(state.ddl))\n throw new Error('Unsupported SQLite notification table shape.');\n if (state.ddl.includes(checkName) && !state.hasCheck)\n throw new Error('Unexpected notification identity CHECK drift.');\n const ddl = state.hasCheck\n ? state.ddl\n : state.ddl.replace(\n /\\)\\s*;?\\s*$/,\n `, CONSTRAINT ${quote(checkName)} CHECK ${identityCheck})`,\n );\n const triggers = (\n await db.query(\n \"SELECT name,sql FROM sqlite_master WHERE type='trigger' AND tbl_name=?\",\n table,\n )\n ).rows as { name: string; sql: string }[];\n const plan = buildSqliteRebuildStatements({\n tableName: table,\n createTableSql: ddl,\n columnTypes: new Map(),\n columns: state.columns.map((c) => c.name),\n objects: [...state.indexes, ...triggers],\n legacyAlterTable: Boolean(\n (await db.query('PRAGMA legacy_alter_table')).rows[0]\n ?.legacy_alter_table,\n ),\n // Checked above: no other table references this one, so the plan needs\n // no guard against a cascade (#4937).\n inboundReferences: [],\n nullableColumns: new Set(\n Number(\n state.columns.find((c) => c.name === 'recipient_user_id')?.notnull,\n )\n ? ['recipient_user_id']\n : [],\n ),\n appendColumns: [\n ...(!state.columns.some((c) => c.name === 'recipient_kind')\n ? [\n {\n name: 'recipient_kind',\n definition: \"recipient_kind TEXT NOT NULL DEFAULT 'user'\",\n copyExpression: \"'user'\",\n },\n ]\n : []),\n ...(!state.columns.some((c) => c.name === 'recipient_profile_id')\n ? [\n {\n name: 'recipient_profile_id',\n definition: 'recipient_profile_id UUID REFERENCES profiles(id)',\n copyExpression: 'NULL',\n },\n ]\n : []),\n ],\n });\n if (!plan)\n throw new Error(\n 'SQLite profile identity rebuild requires manual schema reconciliation.',\n );\n if (plan.statements.some((s) => /PRAGMA foreign_keys\\s*=\\s*OFF/i.test(s)))\n throw new Error(\n 'SQLite profile maintenance cannot disable foreign keys.',\n );\n result.statements.push(...plan.statements);\n }\n for (const [name, columns] of [\n [userIndex, userColumns],\n [profileIndex, profileColumns],\n [typedIndex, typedColumns],\n ] as const)\n if (!state.validIndex(name, [...columns]))\n result.statements.push(\n `CREATE UNIQUE INDEX ${quote(name)} ON ${quote(table)} (${columns.map(quote).join(', ')})${engine === 'postgres' && name === typedIndex ? ' NULLS NOT DISTINCT' : ''}`,\n );\n return result;\n}\n/** Apply/replay atomically using a root maintenance handle. No row IDs or evidence are rewritten. */\nexport async function migrateNotificationProfileRecipients(\n db: DatabaseInterface,\n engine: NotificationProfileRecipientEngine,\n): Promise<NotificationProfileRecipientPlan> {\n assertNotificationMaintenanceHost();\n if (!db.transaction)\n throw new Error('Notification profile migration requires transactions.');\n let result: NotificationProfileRecipientPlan | undefined;\n await db.transaction(async (tx) => {\n if (engine === 'postgres')\n await tx.query(`LOCK TABLE ${quote(table)} IN ACCESS EXCLUSIVE MODE`);\n const plan = await planNotificationProfileRecipients(tx, engine);\n if (plan.invalidRowIds.length)\n throw new Error(\n `Invalid notification recipient rows: ${plan.invalidRowIds.join(', ')}`,\n );\n for (const statement of plan.statements) await tx.query(statement);\n const verified = await planNotificationProfileRecipients(tx, engine);\n if (!verified.ready)\n throw new Error(\n 'Notification profile schema did not reach verified constraints.',\n );\n result = plan;\n });\n if (!result)\n throw new Error(\n 'Notification profile migration transaction did not execute.',\n );\n return result;\n}\n/** Profile-only runtime admission gate checks physical constraints/indexes, never a migration marker. */\nexport async function assertNotificationProfileRecipientSchema(\n db: Pick<DatabaseInterface, 'query' | 'url'>,\n): Promise<void> {\n const hint: unknown = Reflect.get(db, 'type');\n const engine = detectEngine(\n db.url,\n typeof hint === 'string' ? hint : undefined,\n );\n if (engine !== 'sqlite' && engine !== 'postgres')\n throw new Error(\n 'Profile recipients require explicit supported schema maintenance.',\n );\n if (!(await inspect(db, engine)).ready)\n throw new Error('Profile recipient schema maintenance is required.');\n}\n","import {\n isUniqueViolationError,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { decideMailAccess, runWithMailSystemAccess } from '../access.js';\nimport { AccountCollection } from '../collections/AccountCollection.js';\nimport { EmailCollection } from '../collections/EmailCollection.js';\nimport { MessageCollection } from '../collections/MessageCollection.js';\nimport { NotificationDeliveryCollection } from '../collections/NotificationDeliveryCollection.js';\nimport {\n normalizeIdentityEmail,\n readNotificationProfile,\n withSystemContext,\n withTenant,\n} from '../host.js';\nimport { assertNotificationProfileRecipientSchema } from '../migrations/profileRecipients.js';\nimport { EmailAccount } from '../models/EmailAccount.js';\nimport type { Message } from '../models/Message.js';\nimport type {\n NotificationDelivery,\n NotificationDeliveryChannel,\n NotificationDeliveryTransition,\n} from '../models/NotificationDelivery.js';\nimport { assertNotificationRecipientIdentity } from '../notification-recipient-identity.js';\nimport {\n assertMessagingPermission,\n type MessagingPrincipal,\n SEND_MESSAGES_PERMISSION,\n} from '../permissions.js';\nimport {\n ProtectedNotificationHandoffError,\n protectedNotificationMetadata,\n withProtectedNotificationHandoff,\n} from '../protected-notification-handoff.js';\nimport type { SendEmailAttachment, SendEmailOptions } from '../types.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Transport seam\n// ─────────────────────────────────────────────────────────────────────────\n\n/** What a transport knows about one provider handoff. */\nexport type NotificationTransportOutcome =\n | { status: 'accepted'; providerMessageId?: string }\n | { status: 'rejected'; error: string; retryable: boolean }\n | { status: 'unknown'; error: string };\n\n/** What a transport can say about an earlier handoff during recovery. */\nexport type NotificationTransportReconciliation =\n | NotificationTransportOutcome\n | { status: 'not-sent' };\n\nexport interface NotificationTransportRequest {\n delivery: NotificationDelivery;\n /** The delivery's single outbound message (an `Email` for `email`). */\n message: Message;\n /** Stable per delivery; pass it to providers that dedupe on a key. */\n idempotencyKey: string;\n /** Host-authorized send-time bytes; never file paths or remote URLs. */\n attachments?: SendEmailAttachment[];\n}\n\n/**\n * Hands one outbound message to a provider. The default\n * ({@link messageSendTransport}) delivers through `Message.send()` and the\n * message's account sender; tests and hosts with their own provider inject\n * another.\n */\nexport interface NotificationTransport {\n readonly name: string;\n /**\n * True only when the provider deduplicates on `idempotencyKey`, so sending\n * again after an unknown outcome cannot deliver twice. Then an unknown\n * outcome is retried; otherwise it becomes `uncertain`.\n */\n readonly idempotent?: boolean;\n send(\n request: NotificationTransportRequest,\n ): Promise<NotificationTransportOutcome>;\n /**\n * After a crash or lease loss following a handoff, report what is known\n * from durable state. Omit when nothing can be known (outcome: uncertain).\n */\n reconcile?(\n request: NotificationTransportRequest,\n ): Promise<NotificationTransportReconciliation>;\n}\n\n/**\n * Delivers through the canonical `Message.send()` (account → provider sender)\n * and reconciles from the message's own `sendStatus`.\n *\n * SMTP and the SDK email providers take no idempotency key, so this\n * transport is not idempotent: a handoff whose outcome is lost stays\n * `uncertain` instead of risking a second email.\n */\nexport const messageSendTransport: NotificationTransport = {\n name: 'message-send',\n idempotent: false,\n async send({ message, attachments }) {\n const options: SendEmailOptions | undefined = attachments\n ? { attachments }\n : undefined;\n const result = await message.send(options);\n if (result.success) {\n return {\n status: 'accepted',\n ...(result.providerMessageId\n ? { providerMessageId: result.providerMessageId }\n : {}),\n };\n }\n // The provider may have taken it (a dropped connection or a thrown\n // sender), or send() refused because its own claim on the message\n // failed and another sender may be mid-flight: never retry blindly.\n if (\n result.outcomeUnknown ||\n message.sendStatus === 'sending' ||\n message.sendStatus === 'sent'\n ) {\n return {\n status: 'unknown',\n error: result.error ?? 'The provider did not confirm the outcome.',\n };\n }\n return {\n status: 'rejected',\n error: result.error ?? 'Send failed',\n retryable: true,\n };\n },\n async reconcile({ message }) {\n const messages = await MessageCollection.create({ db: message.db });\n const stored = message.id ? await messages.get({ id: message.id }) : null;\n switch (stored?.sendStatus) {\n case 'sent':\n return { status: 'accepted' };\n case 'failed':\n if (stored.isSendOutcomeUnknown()) {\n return {\n status: 'unknown',\n error:\n stored.sendError || 'The provider did not confirm the outcome.',\n };\n }\n return {\n status: 'rejected',\n error: stored.sendError || 'Send failed',\n retryable: true,\n };\n case 'draft':\n case 'pending':\n case 'scheduled':\n return { status: 'not-sent' };\n default:\n return {\n status: 'unknown',\n error: 'The provider handoff did not record an outcome.',\n };\n }\n },\n};\n\n// ─────────────────────────────────────────────────────────────────────────\n// Service contract\n// ─────────────────────────────────────────────────────────────────────────\n\nexport type NotificationOutboxDenialReason =\n | 'permission'\n | 'recipient'\n | 'sender'\n | 'link';\n\n/** Thrown when the host's policy refuses an enqueue; nothing is stored. */\nexport class NotificationOutboxDeniedError extends Error {\n constructor(\n readonly reason: NotificationOutboxDenialReason,\n message: string,\n ) {\n super(message);\n this.name = 'NotificationOutboxDeniedError';\n }\n}\n\nexport interface NotificationRecipientRequest {\n tenantId: string;\n recipientUserId: string;\n channel: NotificationDeliveryChannel;\n}\n\nexport interface NotificationProfileRecipientRequest {\n tenantId: string;\n recipientProfileId: string;\n channel: 'email';\n}\n\nexport interface NotificationRecipient {\n address: string;\n name?: string;\n}\n\nexport interface NotificationSuppressionRequest\n extends NotificationRecipientRequest {\n kind: string;\n sourceRef: string;\n}\nexport interface NotificationProfileSuppressionRequest\n extends NotificationProfileRecipientRequest {\n kind: string;\n sourceRef: string;\n}\n\nexport interface NotificationOutboxOptions {\n db: SmrtClassOptions['db'];\n /**\n * Host authorization for recipients: the address of `recipientUserId` when\n * the host allows notifying them in `tenantId` (e.g. a member of that\n * tenant), otherwise null, which denies the enqueue. Callers never supply\n * an address.\n */\n resolveRecipient(\n request: NotificationRecipientRequest,\n ): Promise<NotificationRecipient | null> | NotificationRecipient | null;\n /** Resource-aware authorization for a current tenant-owned external contact. No address input. */\n resolveProfileRecipient?(\n request: NotificationProfileRecipientRequest,\n ): Promise<NotificationRecipient | null> | NotificationRecipient | null;\n /** The sending `EmailAccount` id for a tenant (deployment setup). */\n resolveSenderAccountId(request: {\n tenantId: string;\n }): Promise<string | null> | string | null;\n /** Absolute http(s) URL deep links are built on, e.g. `https://app.example.com`. */\n linkBaseUrl: string;\n /** Optional opt-out hook, checked at enqueue and again before handoff. */\n isSuppressed?(\n request: NotificationSuppressionRequest,\n ): Promise<boolean> | boolean;\n /** External contacts have their own opt-out policy; never infer a User preference or fabricate a User ID. */\n isProfileSuppressed?(\n request: NotificationProfileSuppressionRequest,\n ): Promise<boolean> | boolean;\n /** Provider seam; defaults to {@link messageSendTransport}. */\n transport?: NotificationTransport;\n /**\n * Resolve and authorize current immutable document bytes before each fresh\n * provider handoff. A failure is a pre-handoff rejection, never a silent\n * attachment omission. Reconciliation does not need document access.\n */\n resolveAttachments?(\n request: NotificationTransportRequest,\n ): Promise<SendEmailAttachment[]> | SendEmailAttachment[];\n /** Trusted server map. Protected rows cannot be dispatched without their exact policy. */\n dispatchPolicies?: Readonly<\n Record<\n string,\n {\n resolveAttachments(\n request: NotificationTransportRequest,\n ): Promise<SendEmailAttachment[]> | SendEmailAttachment[];\n }\n >\n >;\n /**\n * When set, enqueue, dispatch and reconcile require `messages.send` in the tenant.\n * Omit only for trusted system code that performs its own authorization.\n */\n principal?: MessagingPrincipal;\n /** Lease length; must exceed the slowest provider handoff (default 5 min). */\n leaseMs?: number;\n /** Lease budget per delivery (default 5). */\n maxAttempts?: number;\n /** Delay before attempt `n + 1` after `n` failed (default 1 min · 2ⁿ⁻¹, ≤ 1 h). */\n retryDelayMs?(attempts: number): number;\n /** Clock (tests). */\n now?(): Date;\n}\n\nexport interface NotificationEmailInput {\n tenantId: string;\n /** Exactly one recipient reference is required. Existing User calls remain unchanged. */\n recipientUserId?: string;\n /** External contact; requires email, a trusted protected policy and explicit schema maintenance. */\n recipientProfileId?: string;\n /** Idempotency key for the event, e.g. `project-question:<id>:asked`. */\n sourceRef: string;\n /** Host-defined type, e.g. `project-question.asked`. */\n kind: string;\n /** One line; CR/LF are rejected. */\n subject: string;\n /** Plain-text body; the deep link is appended on its own line. */\n text: string;\n /** Host-relative path of the deep link (`/portal/...`). */\n path: string;\n /** Do not send before this time (default: now). */\n notBefore?: Date;\n /** Required trusted server policy; cannot be downgraded after enqueue. */\n requiredDispatchPolicy?: string;\n /** Host-approved immutable resource/version/digest and destination binding. */\n dispatchPolicyBinding?: Record<string, unknown>;\n}\n\nexport interface NotificationEnqueueResult {\n delivery: NotificationDelivery;\n /** False when `sourceRef` matched an existing delivery (returned untouched). */\n created: boolean;\n}\n\nexport type NotificationDispatchOutcome =\n | 'sent'\n | 'retry-scheduled'\n | 'failed'\n | 'uncertain'\n | 'cancelled'\n | 'blocked'\n | 'lease-lost';\n\nexport interface NotificationDispatchReport {\n /** Rows this call won a lease on. */\n leased: number;\n outcomes: Array<{\n deliveryId: string;\n tenantId: string;\n outcome: NotificationDispatchOutcome;\n }>;\n}\n\nexport interface NotificationDispatchOptions {\n /** Tenants to dispatch; omit to discover due rows across all tenants. */\n tenantIds?: readonly string[];\n /** Exact delivery selection, applied before query limits and lease acquisition. Empty selects none. */\n deliveryIds?: readonly string[];\n /** Maximum rows to lease in this call (default 25, max 200). */\n limit?: number;\n}\n\nexport type NotificationReconcileOutcome = 'sent' | 'retry' | 'failed';\n\n/** Delivery ids are uuids; anything else can match no row. */\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst DEFAULT_LEASE_MS = 5 * 60_000;\nconst DEFAULT_MAX_ATTEMPTS = 5;\nconst DEFAULT_LIMIT = 25;\nconst MAX_LIMIT = 200;\n\nfunction defaultRetryDelayMs(attempts: number): number {\n return Math.min(60_000 * 2 ** Math.max(0, attempts - 1), 60 * 60_000);\n}\n\nfunction requireText(value: string | undefined, name: string): string {\n const text = value?.trim();\n if (!text) throw new Error(`A notification ${name} is required.`);\n return text;\n}\n\nfunction errorText(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * The id of a delivery's one outbound message: a name-based uuid derived from\n * the delivery id, so every dispatcher computes the same identity.\n */\nexport async function notificationDeliveryMessageId(\n deliveryId: string,\n): Promise<string> {\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n new TextEncoder().encode(\n `smrt-messages:notification-delivery:${deliveryId}`,\n ),\n );\n const bytes = new Uint8Array(digest).slice(0, 16);\n bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50; // version 5 (name-based)\n bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; // RFC 4122 variant\n const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, '0'));\n return [\n hex.slice(0, 4),\n hex.slice(4, 6),\n hex.slice(6, 8),\n hex.slice(8, 10),\n hex.slice(10, 16),\n ]\n .map((group) => group.join(''))\n .join('-');\n}\n\n/** The correlation id that ties a delivery to its one outbound message. */\nexport function notificationDeliveryCorrelationId(deliveryId: string): string {\n return `notification-delivery:${deliveryId}`;\n}\n\n/**\n * Build an absolute deep link from a host-relative `path` on `baseUrl`.\n *\n * The link always stays on the configured origin (no `//host`, backslash, or\n * scheme tricks) and never carries credentials: the destination is an\n * ordinary authenticated route, so the recipient signs in as themselves.\n */\nexport function buildNotificationLink(baseUrl: string, path: string): string {\n let base: URL;\n try {\n base = new URL(baseUrl);\n } catch {\n throw new Error('Notification link base URL must be an absolute URL.');\n }\n if (base.protocol !== 'https:' && base.protocol !== 'http:') {\n throw new Error('Notification link base URL must use http or https.');\n }\n if (base.username || base.password || base.search || base.hash) {\n throw new Error(\n 'Notification link base URL must not carry credentials, a query, or a fragment.',\n );\n }\n if (\n typeof path !== 'string' ||\n !path.startsWith('/') ||\n path.startsWith('//') ||\n /[\\\\\\s]/u.test(path) ||\n // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting them is the point\n /[\\u0000-\\u001f\\u007f]/u.test(path)\n ) {\n throw new NotificationOutboxDeniedError(\n 'link',\n 'Notification links must be a host-relative path such as /inbox/123.',\n );\n }\n const prefix = base.pathname.replace(/\\/+$/u, '');\n const link = new URL(`${prefix}${path}`, base.origin);\n if (link.origin !== base.origin) {\n throw new NotificationOutboxDeniedError(\n 'link',\n 'Notification links must stay on the configured origin.',\n );\n }\n return link.toString();\n}\n\n/**\n * Source-keyed, durable notification email outbox.\n *\n * `enqueueEmail()` stores one `NotificationDelivery` per\n * `(tenant, recipient, email, sourceRef)` — a repeated event returns the\n * existing row — after the host has authorized the recipient and sender.\n * `dispatchDue()` leases due rows with a compare-and-set, creates the single\n * outbound `Email` under the lease, hands it to the transport, and records\n * the outcome; it is safe to run from several workers at once and to crash\n * at any point. See `packages/messages/agents/notification-outbox.md`.\n */\nexport class NotificationOutboxService {\n /** Additive dispatch contracts hosts can require before activating a sender. */\n static readonly capabilities = Object.freeze({\n deliverySelection: true,\n attachments: true,\n requiredPolicy: true,\n protectedCanonicalSend: true,\n profileRecipients: true,\n } as const);\n private readonly transport: NotificationTransport;\n private readonly leaseMs: number;\n private readonly maxAttempts: number;\n private readonly retryDelayMs: (attempts: number) => number;\n private readonly now: () => Date;\n\n constructor(private readonly options: NotificationOutboxOptions) {\n // Validate the configured origin eagerly so a bad deployment fails at boot.\n buildNotificationLink(options.linkBaseUrl, '/');\n this.transport = options.transport ?? messageSendTransport;\n this.leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS;\n this.maxAttempts = options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n this.retryDelayMs = options.retryDelayMs ?? defaultRetryDelayMs;\n this.now = options.now ?? (() => new Date());\n if (!Number.isInteger(this.leaseMs) || this.leaseMs < 1_000) {\n throw new Error('Notification lease must be at least 1000 ms.');\n }\n if (!Number.isInteger(this.maxAttempts) || this.maxAttempts < 1) {\n throw new Error('Notification maxAttempts must be a positive integer.');\n }\n }\n\n private collection(): Promise<NotificationDeliveryCollection> {\n return NotificationDeliveryCollection.create({ db: this.options.db });\n }\n\n private authorize(tenantId: string): void {\n if (!this.options.principal) return;\n try {\n assertMessagingPermission(\n this.options.principal,\n tenantId,\n SEND_MESSAGES_PERMISSION,\n );\n } catch (error) {\n throw new NotificationOutboxDeniedError('permission', errorText(error));\n }\n }\n\n /** Store one email delivery for the event unless `sourceRef` already has one. */\n async enqueueEmail(\n input: NotificationEmailInput,\n ): Promise<NotificationEnqueueResult> {\n const tenantId = requireText(input.tenantId, 'tenant');\n if (\n input.kind?.startsWith('protected:') &&\n input.kind !== `protected:${input.requiredDispatchPolicy}`\n )\n throw new Error(\n 'Protected notification kinds require their exact dispatch policy.',\n );\n const requiredDispatchPolicy =\n input.requiredDispatchPolicy === undefined\n ? ''\n : requireText(input.requiredDispatchPolicy, 'dispatch policy');\n if (\n requiredDispatchPolicy &&\n !this.dispatchPolicy(requiredDispatchPolicy)\n ) {\n throw new NotificationOutboxDeniedError(\n 'permission',\n 'Required notification dispatch policy is unavailable.',\n );\n }\n if (\n requiredDispatchPolicy &&\n (!input.dispatchPolicyBinding ||\n typeof input.dispatchPolicyBinding !== 'object' ||\n Array.isArray(input.dispatchPolicyBinding) ||\n !Object.keys(input.dispatchPolicyBinding).length)\n ) {\n throw new Error(\n 'Protected notification requires an approved dispatch policy binding.',\n );\n }\n const dispatchPolicyBinding = JSON.stringify(\n input.dispatchPolicyBinding ?? {},\n );\n const profilePath = input.recipientProfileId !== undefined;\n if (profilePath === (input.recipientUserId !== undefined))\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'Choose exactly one typed recipient.',\n );\n const recipientUserId = profilePath\n ? null\n : requireText(input.recipientUserId, 'recipient');\n const recipientProfileId = profilePath\n ? requireText(input.recipientProfileId, 'profile recipient')\n : null;\n const recipientKind = profilePath ? 'profile' : 'user';\n assertNotificationRecipientIdentity({\n recipientKind,\n recipientUserId,\n recipientProfileId,\n channel: 'email',\n kind: input.kind,\n requiredDispatchPolicy,\n });\n\n const sourceRef = requireText(input.sourceRef, 'sourceRef');\n const kind = requireText(input.kind, 'kind');\n const subject = requireText(input.subject, 'subject');\n const text = requireText(input.text, 'text');\n if (/[\\r\\n]/u.test(subject)) {\n throw new Error('A notification subject must be a single line.');\n }\n const channel: NotificationDeliveryChannel = 'email';\n this.authorize(tenantId);\n if (profilePath)\n await assertNotificationProfileRecipientSchema(\n (await this.collection()).db,\n );\n const href = buildNotificationLink(this.options.linkBaseUrl, input.path);\n\n return withTenant({ tenantId }, async () => {\n const deliveries = await this.collection();\n const findExisting = async () =>\n (\n await deliveries.list({\n where: {\n tenantId,\n recipientKind,\n recipientUserId,\n recipientProfileId,\n channel,\n sourceRef,\n },\n limit: 1,\n })\n )[0];\n const existing = await findExisting();\n if (existing) {\n if (recipientProfileId) await this.validateProfileDelivery(existing);\n return { delivery: existing, created: false };\n }\n\n const recipient = recipientProfileId\n ? await this.resolveProfile({ tenantId, recipientProfileId, channel })\n : await this.options.resolveRecipient({\n tenantId,\n recipientUserId: recipientUserId as string,\n channel,\n });\n const address = recipient?.address?.trim();\n if (!address || /[\\s,;<>]/u.test(address) || !address.includes('@')) {\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'The host did not authorize an email recipient for this user.',\n );\n }\n const accountId = await this.requireSenderAccount(tenantId);\n if (!(await this.principalMaySend({ tenantId, accountId }))) {\n throw new NotificationOutboxDeniedError(\n 'permission',\n 'The principal lacks send access on the sender account.',\n );\n }\n const suppressed = await this.isSuppressed({\n tenantId,\n ...(recipientUserId ? { recipientUserId } : {}),\n ...(recipientProfileId\n ? { recipientProfileId, recipientKind: 'profile' as const }\n : {}),\n channel,\n kind,\n sourceRef,\n });\n\n try {\n const delivery = await deliveries.create({\n _insertOnly: true,\n tenantId,\n recipientUserId,\n recipientProfileId,\n recipientKind,\n channel,\n sourceRef,\n kind,\n requiredDispatchPolicy,\n dispatchPolicyBinding,\n subject,\n textBody: text,\n href,\n recipientAddress: address,\n recipientName: recipient?.name?.trim() ?? '',\n accountId,\n messageId: null,\n status: suppressed ? 'cancelled' : 'pending',\n stateVersion: 0,\n transitionId: '',\n attempts: 0,\n maxAttempts: this.maxAttempts,\n nextAttemptAt: input.notBefore ?? this.now(),\n leaseToken: null,\n leaseExpiresAt: null,\n handedOffAt: null,\n deliveredAt: null,\n providerMessageId: '',\n lastError: suppressed ? 'Suppressed by recipient preference.' : '',\n });\n return { delivery, created: true };\n } catch (error) {\n if (!isUniqueViolationError(error)) throw error;\n const winner = await findExisting();\n if (!winner) throw error;\n return { delivery: winner, created: false };\n }\n });\n }\n\n /** Lease and deliver due rows; returns what happened to each leased row. */\n async dispatchDue(\n options: NotificationDispatchOptions = {},\n ): Promise<NotificationDispatchReport> {\n const limit = Math.min(options.limit ?? DEFAULT_LIMIT, MAX_LIMIT);\n if (!Number.isInteger(limit) || limit < 1) {\n throw new Error(\n 'Notification dispatch limit must be a positive integer.',\n );\n }\n let tenantIds = options.tenantIds;\n if (this.options.principal && tenantIds === undefined) {\n const tenantId = this.options.principal.tenantId;\n if (!tenantId) {\n throw new NotificationOutboxDeniedError(\n 'permission',\n 'A messaging principal must select explicit dispatch tenants.',\n );\n }\n tenantIds = [tenantId];\n }\n if (tenantIds !== undefined) {\n tenantIds = [\n ...new Set(tenantIds.map((id) => requireText(id, 'tenant'))),\n ];\n // Authorize every requested scope before discovering or leasing any row.\n for (const tenantId of tenantIds) this.authorize(tenantId);\n }\n const deliveryIds =\n options.deliveryIds === undefined\n ? undefined\n : [...new Set(options.deliveryIds)];\n if (\n deliveryIds?.some(\n (id) => typeof id !== 'string' || !UUID_PATTERN.test(id),\n )\n ) {\n throw new Error('Notification dispatch delivery ids must be UUIDs.');\n }\n const report: NotificationDispatchReport = { leased: 0, outcomes: [] };\n if (tenantIds?.length === 0 || deliveryIds?.length === 0) return report;\n for await (const candidate of this.findDue(tenantIds, limit, deliveryIds)) {\n if (report.leased >= limit) break;\n this.authorize(candidate.tenantId);\n if (\n (candidate.kind.startsWith('protected:') &&\n candidate.kind !== `protected:${candidate.requiredDispatchPolicy}`) ||\n (candidate.requiredDispatchPolicy &&\n !this.dispatchPolicy(candidate.requiredDispatchPolicy))\n ) {\n const lastError =\n 'Blocked: required notification dispatch policy is unavailable.';\n if (candidate.lastError !== lastError)\n await withTenant({ tenantId: candidate.tenantId }, () =>\n candidate.transition({ lastError }),\n );\n report.outcomes.push({\n deliveryId: candidate.id as string,\n tenantId: candidate.tenantId,\n outcome: 'blocked',\n });\n continue;\n }\n try {\n await withTenant({ tenantId: candidate.tenantId }, () =>\n this.validateProfileDelivery(candidate),\n );\n } catch (cause) {\n const lastError = `Blocked: ${errorText(cause)}`;\n if (candidate.lastError !== lastError)\n await withTenant({ tenantId: candidate.tenantId }, () =>\n candidate.transition({ lastError }),\n );\n report.outcomes.push({\n deliveryId: candidate.id as string,\n tenantId: candidate.tenantId,\n outcome: 'blocked',\n });\n continue;\n }\n // Without a principal this is trusted worker code and the per-account\n // policy is lifted. With a principal, the tenant permission is only a\n // ceiling: the principal must also hold `send` on the sender account.\n if (!(await this.principalMaySend(candidate))) {\n const lastError = 'Blocked: mail access denied for scope send';\n if (candidate.lastError !== lastError)\n await withTenant({ tenantId: candidate.tenantId }, () =>\n candidate.transition({ lastError }),\n );\n report.outcomes.push({\n deliveryId: candidate.id as string,\n tenantId: candidate.tenantId,\n outcome: 'blocked',\n });\n continue;\n }\n const outcome = await withTenant({ tenantId: candidate.tenantId }, () =>\n runWithMailSystemAccess(() => this.dispatchOne(candidate)),\n );\n if (!outcome) continue;\n report.leased += 1;\n report.outcomes.push({\n deliveryId: candidate.id as string,\n tenantId: candidate.tenantId,\n outcome,\n });\n }\n return report;\n }\n\n /** Deliveries waiting for a reconciliation decision, oldest first. */\n async listUncertain(options: {\n tenantId: string;\n limit?: number;\n }): Promise<NotificationDelivery[]> {\n const tenantId = requireText(options.tenantId, 'tenant');\n this.authorize(tenantId);\n return withTenant({ tenantId }, async () =>\n (await this.collection()).list({\n where: { tenantId, status: 'uncertain' },\n orderBy: 'handedOffAt ASC',\n limit: Math.min(options.limit ?? DEFAULT_LIMIT, MAX_LIMIT),\n }),\n );\n }\n\n /**\n * Settle an `uncertain` delivery after checking the provider out of band:\n * `sent` (it arrived), `failed` (give up), or `retry` (send again,\n * accepting the risk of a duplicate; a message left claimed by a dead\n * sender is released first). Returns false when the row is not uncertain\n * any more, or for `retry` when the message is recorded as sent.\n */\n async reconcile(input: {\n tenantId: string;\n deliveryId: string;\n outcome: NotificationReconcileOutcome;\n note?: string;\n }): Promise<boolean> {\n const tenantId = requireText(input.tenantId, 'tenant');\n this.authorize(tenantId);\n // Ids may come from requests; on a native uuid column (PostgreSQL) a\n // malformed one would fail the query (22P02) instead of matching nothing.\n if (!UUID_PATTERN.test(input.deliveryId ?? '')) return false;\n return withTenant({ tenantId }, async () => {\n if (this.options.principal) {\n const delivery = (\n await (\n await this.collection()\n ).list({ where: { tenantId, id: input.deliveryId }, limit: 1 })\n )[0];\n if (!delivery || !(await this.principalMaySend(delivery))) return false;\n }\n return runWithMailSystemAccess(() => this.reconcileImpl(tenantId, input));\n });\n }\n\n /** True without a principal (trusted worker); else needs `send` on the account. */\n private async principalMaySend(delivery: {\n tenantId: string;\n accountId?: string;\n }): Promise<boolean> {\n const principal = this.options.principal;\n if (!principal) return true;\n const tenantId = delivery.tenantId;\n const userId = principal.userId ?? principal.id;\n if (!delivery.accountId) return false;\n const account = await withTenant({ tenantId }, () =>\n runWithMailSystemAccess(async () =>\n (await AccountCollection.create({ db: this.options.db })).get({\n id: delivery.accountId,\n }),\n ),\n );\n if (!account || account.tenantId !== tenantId) return false;\n // No user identity: only unowned (tenant-wide) accounts pass.\n const decision = await withTenant({ tenantId }, () =>\n decideMailAccess(\n account,\n 'send',\n userId ? { id: principal.id ?? userId, tenantId, userId } : null,\n ),\n );\n return decision.allowed;\n }\n\n private async reconcileImpl(\n tenantId: string,\n input: {\n deliveryId: string;\n outcome: NotificationReconcileOutcome;\n note?: string;\n },\n ): Promise<boolean> {\n {\n const delivery = (\n await (\n await this.collection()\n ).list({\n where: { tenantId, id: input.deliveryId },\n limit: 1,\n })\n )[0];\n if (delivery?.status !== 'uncertain') return false;\n const note = input.note?.trim();\n const now = this.now();\n switch (input.outcome) {\n case 'sent':\n return delivery.transition({\n status: 'sent',\n deliveredAt: now,\n ...(note ? { lastError: note } : {}),\n });\n case 'failed':\n return delivery.transition({\n status: 'failed',\n lastError: note || delivery.lastError,\n });\n case 'retry': {\n // The canonical message must be sendable again: a crash can leave\n // it claimed ('sending') by a sender that no longer exists. The\n // delivery is uncertain, so no dispatcher holds it.\n const message = delivery.messageId\n ? await this.loadMessage(delivery.messageId)\n : null;\n if (message?.sendStatus === 'sent') return false;\n if (\n message?.sendStatus === 'sending' &&\n !(await message.abandonSendAttempt(\n note || 'Released for an operator-approved retry.',\n ))\n ) {\n return false;\n }\n return delivery.transition({\n status: 'pending',\n nextAttemptAt: now,\n handedOffAt: null,\n // One more lease, so a delivery already at its budget can retry.\n attempts: Math.min(delivery.attempts, delivery.maxAttempts - 1),\n ...(note ? { lastError: note } : {}),\n });\n }\n default:\n throw new Error(`Unknown reconcile outcome '${input.outcome}'.`);\n }\n }\n }\n\n // ───────────────────────────────────────────────────────────────────────\n\n private async requireSenderAccount(tenantId: string): Promise<string> {\n const accountId = (\n await this.options.resolveSenderAccountId({ tenantId })\n )?.trim();\n const account = accountId\n ? await (await AccountCollection.create({ db: this.options.db })).get({\n id: accountId,\n })\n : null;\n if (\n !account ||\n !(account instanceof EmailAccount) ||\n account.tenantId !== tenantId ||\n !account.isActive\n ) {\n throw new NotificationOutboxDeniedError(\n 'sender',\n 'No active email sender account is configured for this tenant.',\n );\n }\n return account.id as string;\n }\n\n private async isSuppressed(request: {\n tenantId: string;\n channel: NotificationDeliveryChannel;\n kind: string;\n sourceRef: string;\n recipientUserId?: string;\n recipientProfileId?: string;\n recipientKind?: 'profile';\n }): Promise<boolean> {\n if (request.recipientProfileId)\n return Boolean(\n await this.options.isProfileSuppressed?.({\n tenantId: request.tenantId,\n recipientProfileId: request.recipientProfileId,\n channel: 'email',\n kind: request.kind,\n sourceRef: request.sourceRef,\n }),\n );\n if (!request.recipientUserId)\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'Missing typed suppression recipient.',\n );\n return Boolean(\n await this.options.isSuppressed?.({\n tenantId: request.tenantId,\n recipientUserId: request.recipientUserId,\n channel: request.channel,\n kind: request.kind,\n sourceRef: request.sourceRef,\n }),\n );\n }\n\n private async resolveProfile(\n request: NotificationProfileRecipientRequest,\n ): Promise<NotificationRecipient> {\n const db = (await this.collection()).db;\n const profile = await readNotificationProfile(\n db,\n request.tenantId,\n request.recipientProfileId,\n );\n const resolved = await this.options.resolveProfileRecipient?.(request);\n const address = profile?.email ? normalizeIdentityEmail(profile.email) : '';\n if (\n !profile ||\n profile.tenantId !== request.tenantId ||\n !address ||\n containsControlCharacter(address) ||\n !/^[^\\s@,;<>]+@[^\\s@,;<>]+\\.[^\\s@,;<>]+$/u.test(address) ||\n !resolved?.address ||\n normalizeIdentityEmail(resolved.address) !== address\n )\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'Current tenant-owned profile email is not authorized.',\n );\n if (resolved.name && containsControlCharacter(resolved.name))\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'Malformed profile recipient display name.',\n );\n return { address, name: resolved.name?.trim() ?? '' };\n }\n private async validateProfileDelivery(\n delivery: NotificationDelivery,\n ): Promise<void> {\n assertNotificationRecipientIdentity(delivery);\n if (delivery.recipientKind !== 'profile') return;\n await assertNotificationProfileRecipientSchema(\n (await this.collection()).db,\n );\n const current = await this.resolveProfile({\n tenantId: delivery.tenantId,\n recipientProfileId: delivery.recipientProfileId as string,\n channel: 'email',\n });\n if (\n current.address !== delivery.recipientAddress ||\n (current.name ?? '') !== delivery.recipientName\n )\n throw new NotificationOutboxDeniedError(\n 'recipient',\n 'Approved profile recipient changed; review again.',\n );\n }\n private dispatchPolicy(id: string) {\n const policies = this.options.dispatchPolicies;\n if (!policies || !Object.hasOwn(policies, id)) return undefined;\n const policy = policies[id];\n return typeof policy?.resolveAttachments === 'function'\n ? policy\n : undefined;\n }\n\n private async *findDue(\n tenantIds: readonly string[] | undefined,\n limit: number,\n deliveryIds?: readonly string[],\n ): AsyncGenerator<NotificationDelivery> {\n const now = this.now();\n const visited = new Set<string>();\n // Each page is bounded; a blocked prefix cannot consume the lease budget.\n // Expired leases precede pending rows, including across explicit scopes.\n for (const phase of [\n { status: 'sending', column: 'lease_expires_at' },\n { status: 'pending', column: 'next_attempt_at' },\n ] as const) {\n for (const tenantId of tenantIds ?? [undefined]) {\n let cursor: { id: string; cursor_at: string } | undefined;\n for (;;) {\n const read = async () => {\n const deliveries = await this.collection();\n const table = `\"${deliveries.tableName.replaceAll('\"', '\"\"')}\"`;\n const conditions = ['status = ?', `${phase.column} <= ?`];\n const values: unknown[] = [phase.status, now.toISOString()];\n if (tenantId !== undefined) {\n conditions.push('tenant_id = ?');\n values.push(tenantId);\n }\n if (deliveryIds) {\n conditions.push(\n `id IN (${deliveryIds.map(() => '?').join(',')})`,\n );\n values.push(...deliveryIds);\n }\n if (cursor) {\n conditions.push(\n `(${phase.column} > ? OR (${phase.column} = ? AND id > ?))`,\n );\n values.push(cursor.cursor_at, cursor.cursor_at, cursor.id);\n }\n // Capture the cursor in this same query, before hydration or writes.\n // PostgreSQL Date hydration loses microseconds; CAST preserves the\n // physical timestamp so equal/sub-ms rows cannot repeat forever.\n const result = await deliveries.db.query(\n `SELECT id, CAST(${phase.column} AS TEXT) AS cursor_at FROM ${table}\n WHERE ${conditions.join(' AND ')}\n ORDER BY ${phase.column} ASC, id ASC LIMIT ?`,\n ...values,\n limit,\n );\n const positions = result.rows as Array<{\n id: string;\n cursor_at: string;\n }>;\n if (\n positions.some(\n (row) =>\n typeof row.id !== 'string' ||\n !UUID_PATTERN.test(row.id) ||\n typeof row.cursor_at !== 'string' ||\n !row.cursor_at,\n )\n )\n throw new Error('Invalid notification dispatch cursor.');\n if (!positions.length) return { positions, rows: [] };\n const rows = await deliveries.list({\n where: {\n ...(tenantId === undefined ? {} : { tenantId }),\n id: positions.map((row) => row.id),\n },\n limit: positions.length,\n });\n const byId = new Map(rows.map((row) => [row.id, row]));\n return {\n positions,\n rows: positions.flatMap((row) => {\n const delivery = byId.get(row.id);\n return delivery ? [delivery] : [];\n }),\n };\n };\n const page =\n tenantId === undefined\n ? await withSystemContext(read)\n : await withTenant({ tenantId }, read);\n if (!page.positions.length) break;\n cursor = page.positions[page.positions.length - 1];\n for (const row of page.rows) {\n if (!row.id || visited.has(row.id)) continue;\n visited.add(row.id);\n yield row;\n }\n if (page.positions.length < limit) break;\n }\n }\n }\n }\n\n /** Lease one candidate and carry it to an outcome; null when not leased. */\n private async dispatchOne(\n candidate: NotificationDelivery,\n ): Promise<NotificationDispatchOutcome | null> {\n // Re-read under the tenant scope; the candidate may be stale.\n const delivery = (\n await (\n await this.collection()\n ).list({\n where: { tenantId: candidate.tenantId, id: candidate.id },\n limit: 1,\n })\n )[0];\n if (!delivery) return null;\n const now = this.now();\n\n const recovering =\n delivery.status === 'sending' &&\n delivery.leaseExpiresAt !== null &&\n delivery.leaseExpiresAt.getTime() <= now.getTime();\n const due =\n delivery.status === 'pending' &&\n delivery.nextAttemptAt.getTime() <= now.getTime();\n if (!recovering && !due) return null;\n\n const leaseToken = crypto.randomUUID();\n const leaseExpiresAt = new Date(now.getTime() + this.leaseMs);\n // A lapsed lease whose attempt already reached the provider is a crash or\n // lease loss mid-handoff: learn what we can before anything is resent.\n const priorHandoff = recovering && delivery.handedOffAt !== null;\n const won = await delivery.transition({\n status: 'sending',\n leaseToken,\n leaseExpiresAt,\n attempts: priorHandoff ? delivery.attempts : delivery.attempts + 1,\n ...(priorHandoff ? {} : { handedOffAt: null }),\n });\n if (!won) return null;\n\n try {\n if (priorHandoff) {\n const resolved = await this.recoverHandoff(delivery, leaseToken);\n if (resolved) return resolved;\n }\n\n if (\n await this.isSuppressed({\n tenantId: delivery.tenantId,\n ...(delivery.recipientUserId\n ? { recipientUserId: delivery.recipientUserId }\n : {}),\n ...(delivery.recipientProfileId\n ? {\n recipientProfileId: delivery.recipientProfileId,\n recipientKind: 'profile' as const,\n }\n : {}),\n channel: delivery.channel,\n kind: delivery.kind,\n sourceRef: delivery.sourceRef,\n })\n ) {\n return this.settle(delivery, leaseToken, {\n status: 'cancelled',\n lastError: 'Suppressed by recipient preference.',\n });\n }\n\n await this.validateProfileDelivery(delivery);\n const message = await this.ensureMessage(delivery, leaseToken);\n if (!message) return 'lease-lost';\n const request: NotificationTransportRequest = {\n delivery,\n message,\n idempotencyKey: notificationDeliveryCorrelationId(\n delivery.id as string,\n ),\n };\n const resolver = delivery.requiredDispatchPolicy\n ? this.dispatchPolicy(delivery.requiredDispatchPolicy)\n ?.resolveAttachments\n : this.options.resolveAttachments;\n if (delivery.requiredDispatchPolicy && !resolver)\n throw new Error(\n 'Required notification dispatch policy is unavailable.',\n );\n if (resolver) {\n const attachments = await resolver(request);\n if (\n !Array.isArray(attachments) ||\n (delivery.requiredDispatchPolicy && attachments.length === 0) ||\n attachments.some(\n (attachment) =>\n !attachment ||\n typeof attachment.filename !== 'string' ||\n !attachment.filename.trim() ||\n /[\\r\\n\\0]/.test(attachment.filename) ||\n !(attachment.content instanceof Uint8Array) ||\n (attachment.contentType !== undefined &&\n (typeof attachment.contentType !== 'string' ||\n !attachment.contentType.trim() ||\n /[\\r\\n\\0]/.test(attachment.contentType))) ||\n (attachment.contentId !== undefined &&\n (typeof attachment.contentId !== 'string' ||\n /[\\r\\n\\0]/.test(attachment.contentId))) ||\n (attachment.contentDisposition !== undefined &&\n !['attachment', 'inline'].includes(\n attachment.contentDisposition,\n )),\n )\n )\n throw new Error(\n 'Notification attachment resolver returned malformed bytes or metadata.',\n );\n request.attachments = attachments.map((attachment) => ({\n ...attachment,\n content: Uint8Array.from(attachment.content),\n }));\n }\n if (\n !(await delivery.transition(\n { handedOffAt: this.now() },\n { leaseToken },\n ))\n ) {\n return 'lease-lost';\n }\n\n let outcome: NotificationTransportOutcome;\n try {\n outcome = await withProtectedNotificationHandoff(\n request,\n this.now,\n async () => {\n await this.validateProfileDelivery(delivery);\n return this.transport.send(request);\n },\n );\n } catch (error) {\n // A throw after handoff says nothing about whether the provider\n // accepted the message.\n outcome =\n error instanceof ProtectedNotificationHandoffError\n ? { status: 'rejected', retryable: true, error: errorText(error) }\n : { status: 'unknown', error: errorText(error) };\n }\n return this.applyOutcome(delivery, leaseToken, outcome);\n } catch (error) {\n // A failure before handoff (message creation, suppression hook) is safe\n // to retry; one after handoff has already been mapped to an outcome.\n if (delivery.handedOffAt !== null) throw error;\n return this.applyOutcome(delivery, leaseToken, {\n status: 'rejected',\n error: errorText(error),\n retryable: true,\n });\n }\n }\n\n private async recoverHandoff(\n delivery: NotificationDelivery,\n leaseToken: string,\n ): Promise<NotificationDispatchOutcome | null> {\n const message = delivery.messageId\n ? await this.loadMessage(delivery.messageId)\n : null;\n let known: NotificationTransportReconciliation = {\n status: 'unknown',\n error: 'Lease lapsed after the provider handoff; outcome unknown.',\n };\n if (message && this.transport.reconcile) {\n try {\n known = await this.transport.reconcile({\n delivery,\n message,\n idempotencyKey: notificationDeliveryCorrelationId(\n delivery.id as string,\n ),\n });\n } catch (error) {\n known = { status: 'unknown', error: errorText(error) };\n }\n }\n if (known.status === 'not-sent') {\n // Nothing reached the provider; this lease becomes a fresh attempt.\n if (\n !(await delivery.transition(\n { handedOffAt: null, attempts: delivery.attempts + 1 },\n { leaseToken },\n ))\n ) {\n return 'lease-lost';\n }\n return null;\n }\n if (known.status === 'unknown' && this.transport.idempotent) {\n // The provider dedupes on the key: resending is the reconciliation.\n if (\n !(await delivery.transition(\n { handedOffAt: null, attempts: delivery.attempts + 1 },\n { leaseToken },\n ))\n ) {\n return 'lease-lost';\n }\n return null;\n }\n return this.applyOutcome(delivery, leaseToken, known);\n }\n\n private async applyOutcome(\n delivery: NotificationDelivery,\n leaseToken: string,\n outcome: NotificationTransportOutcome,\n ): Promise<NotificationDispatchOutcome> {\n if (outcome.status === 'accepted') {\n return this.settle(delivery, leaseToken, {\n status: 'sent',\n deliveredAt: this.now(),\n providerMessageId: outcome.providerMessageId ?? '',\n lastError: '',\n });\n }\n if (outcome.status === 'unknown') {\n if (\n this.transport.idempotent &&\n delivery.attempts < delivery.maxAttempts\n ) {\n return this.scheduleRetry(delivery, leaseToken, outcome.error);\n }\n return this.settle(delivery, leaseToken, {\n status: 'uncertain',\n lastError: outcome.error,\n });\n }\n if (outcome.retryable && delivery.attempts < delivery.maxAttempts) {\n return this.scheduleRetry(delivery, leaseToken, outcome.error);\n }\n return this.settle(delivery, leaseToken, {\n status: 'failed',\n lastError: outcome.error,\n });\n }\n\n private async scheduleRetry(\n delivery: NotificationDelivery,\n leaseToken: string,\n error: string,\n ): Promise<NotificationDispatchOutcome> {\n const delay = this.retryDelayMs(delivery.attempts);\n const won = await this.endLease(delivery, leaseToken, {\n status: 'pending',\n nextAttemptAt: new Date(this.now().getTime() + Math.max(0, delay)),\n handedOffAt: null,\n lastError: error,\n });\n return won ? 'retry-scheduled' : 'lease-lost';\n }\n\n /** End the lease in a terminal status; reports lease loss instead of overwriting. */\n private async settle(\n delivery: NotificationDelivery,\n leaseToken: string,\n changes: NotificationDeliveryTransition & {\n status: 'sent' | 'failed' | 'uncertain' | 'cancelled';\n },\n ): Promise<NotificationDispatchOutcome> {\n const won = await this.endLease(delivery, leaseToken, changes);\n return won ? changes.status : 'lease-lost';\n }\n\n private endLease(\n delivery: NotificationDelivery,\n leaseToken: string,\n changes: NotificationDeliveryTransition,\n ): Promise<boolean> {\n return delivery.transition(\n { ...changes, leaseToken: null, leaseExpiresAt: null },\n { leaseToken },\n );\n }\n\n private async loadMessage(messageId: string): Promise<Message | null> {\n const messages = await MessageCollection.create({ db: this.options.db });\n return (await messages.get({ id: messageId })) ?? null;\n }\n\n /**\n * The delivery's single outbound `Email`, created under the lease. Its id\n * is derived from the delivery id and inserted insert-only, so a stale\n * dispatcher that resumes after its lease was taken over hits the stored\n * row (a unique violation) instead of creating a second email.\n */\n private async ensureMessage(\n delivery: NotificationDelivery,\n leaseToken: string,\n ): Promise<Message | null> {\n if (delivery.messageId) {\n const message = await this.loadMessage(delivery.messageId);\n if (message) return this.protectCanonicalMessage(delivery, message);\n }\n const messageId = await notificationDeliveryMessageId(\n delivery.id as string,\n );\n let message = await this.loadMessage(messageId);\n if (!message) {\n const body = `${delivery.textBody}\\n\\n${delivery.href}\\n`;\n const emails = await EmailCollection.create({ db: this.options.db });\n try {\n await emails.create({\n _insertOnly: true,\n id: messageId,\n tenantId: delivery.tenantId,\n accountId: delivery.accountId,\n correlationId: notificationDeliveryCorrelationId(\n delivery.id as string,\n ),\n subject: delivery.subject,\n body,\n textBody: body,\n toAddresses: JSON.stringify([\n {\n address: delivery.recipientAddress,\n ...(delivery.recipientName\n ? { name: delivery.recipientName }\n : {}),\n },\n ]),\n ...(delivery.requiredDispatchPolicy\n ? {\n metadata: protectedNotificationMetadata(\n delivery.id!,\n delivery.requiredDispatchPolicy,\n ),\n }\n : {}),\n sendStatus: 'pending',\n // Delivery is owned by the outbox's attempt budget, not the message's.\n maxRetries: 0,\n });\n } catch (error) {\n if (!isUniqueViolationError(error)) throw error;\n }\n // Reload so send()'s compare-and-set sees the stored revision.\n message = await this.loadMessage(messageId);\n if (!message) throw new Error('The outbound email could not be stored.');\n }\n if (delivery.messageId !== message.id) {\n if (\n !(await delivery.transition(\n { messageId: message.id as string },\n { leaseToken },\n ))\n ) {\n return null;\n }\n }\n return this.protectCanonicalMessage(delivery, message);\n }\n\n /** Backfill the non-authorizing durable marker on an existing protected canonical row. */\n private async protectCanonicalMessage(\n delivery: NotificationDelivery,\n message: Message,\n ): Promise<Message> {\n if (delivery.requiredDispatchPolicy) {\n const existing = message.getMetadata();\n const protectedMarker = JSON.parse(\n protectedNotificationMetadata(\n delivery.id!,\n delivery.requiredDispatchPolicy,\n ),\n );\n if (!existing.__smrtProtectedOutbox) {\n message.setMetadata({ ...existing, ...protectedMarker });\n await message.save();\n }\n }\n return message;\n }\n}\n\nfunction containsControlCharacter(value: string): boolean {\n return [...value].some((char) => {\n const code = char.codePointAt(0) as number;\n return code < 32 || code === 127;\n });\n}\n","import {\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { AccountCollection } from '../collections/AccountCollection.js';\nimport { MessagingEndpointCollection } from '../collections/MessagingEndpointCollection.js';\nimport { PersonaMessageRouteCollection } from '../collections/PersonaMessageRouteCollection.js';\nimport { withTenant } from '../host.js';\nimport { Email } from '../models/Email.js';\nimport { EmailAccount } from '../models/EmailAccount.js';\nimport { Message } from '../models/Message.js';\nimport type { PersonaMessageRoute } from '../models/PersonaMessageRoute.js';\nimport {\n assertMessagingPermission,\n type MessagingPrincipal,\n SEND_MESSAGES_PERMISSION,\n} from '../permissions.js';\nimport type {\n MessageSendResult,\n SendEmailOptions,\n SendPersonaMessageOptions,\n} from '../types.js';\n\nexport interface PersonaMessageSendResult {\n routeId: string;\n messageId: string;\n delivery: MessageSendResult;\n}\n\n/** Resolves a persona-owned route and delivers a persisted outbound message. */\nexport class PersonaMessagingService {\n constructor(\n private readonly options: {\n db: SmrtClassOptions['db'];\n tenantId: string;\n /** Omit only for trusted system code that performs its own authorization. */\n principal?: MessagingPrincipal;\n },\n ) {}\n\n async send(\n input: SendPersonaMessageOptions,\n ): Promise<PersonaMessageSendResult> {\n if (this.options.principal) {\n assertMessagingPermission(\n this.options.principal,\n this.options.tenantId,\n SEND_MESSAGES_PERMISSION,\n );\n }\n if (!input.personaId)\n throw new Error('A persona is required to send a message.');\n if (!input.body.trim()) throw new Error('Message body cannot be empty.');\n\n return withTenant({ tenantId: this.options.tenantId }, async () => {\n const route = await this.resolveRoute(input);\n const accounts = await AccountCollection.create({ db: this.options.db });\n const endpoints = await MessagingEndpointCollection.create({\n db: this.options.db,\n });\n const [account, endpoint] = await Promise.all([\n accounts.get({ id: route.accountId }),\n endpoints.get({ id: route.endpointId }),\n ]);\n if (\n !account ||\n account.tenantId !== this.options.tenantId ||\n !account.isActive\n ) {\n throw new Error('The selected messaging account is unavailable.');\n }\n if (\n !endpoint ||\n endpoint.tenantId !== this.options.tenantId ||\n !endpoint.isActive\n ) {\n throw new Error('The selected messaging endpoint is unavailable.');\n }\n if (account.channelType !== endpoint.channel) {\n throw new Error(\n 'The selected messaging route has mismatched channels.',\n );\n }\n\n if (input.attachments?.length && endpoint.channel !== 'email') {\n throw new Error('Attachments are only supported on email routes.');\n }\n\n let message: Message;\n const base = {\n db: this.options.db,\n tenantId: this.options.tenantId,\n accountId: route.accountId,\n endpointId: route.endpointId,\n personaId: input.personaId,\n correlationId: input.correlationId ?? '',\n subject: input.subject ?? '',\n body: input.body.trim(),\n sendStatus: 'pending' as const,\n };\n if (endpoint.channel === 'email') {\n if (!(account instanceof EmailAccount)) {\n throw new Error('Email routes require an EmailAccount.');\n }\n const address = endpoint.getAddress<{ email?: string }>();\n if (!address.email) throw new Error('Email endpoint has no address.');\n const email = new (ObjectRegistry.resolveEffectiveConstructor(Email))({\n ...base,\n textBody: base.body,\n hasAttachments: Boolean(input.attachments?.length),\n });\n email.setToAddresses([{ address: address.email }]);\n message = email;\n } else {\n message = new (ObjectRegistry.resolveEffectiveConstructor(Message))(\n base,\n );\n }\n await message.initialize();\n await message.save();\n const sendOptions: SendEmailOptions | undefined = input.attachments\n ?.length\n ? { attachments: input.attachments }\n : undefined;\n const delivery = await message.send(sendOptions);\n return {\n routeId: route.id ?? '',\n messageId: message.id ?? '',\n delivery,\n };\n });\n }\n\n private async resolveRoute(\n input: SendPersonaMessageOptions,\n ): Promise<PersonaMessageRoute> {\n const routes = await PersonaMessageRouteCollection.create({\n db: this.options.db,\n });\n if (input.routeId) {\n const route = await routes.get({ id: input.routeId });\n if (\n !route ||\n route.tenantId !== this.options.tenantId ||\n route.personaId !== input.personaId ||\n !route.enabled\n ) {\n throw new Error(\n 'The requested persona messaging route is unavailable.',\n );\n }\n return route;\n }\n\n let candidates = await routes.forPersona(input.personaId);\n if (input.purpose) {\n candidates = candidates.filter(\n (route) => route.purpose === input.purpose,\n );\n } else {\n const defaults = candidates.filter(\n (route) => route.purpose === 'default',\n );\n if (defaults.length > 0) candidates = defaults;\n }\n candidates.sort((left, right) => right.priority - left.priority);\n\n if (input.channel) {\n const endpoints = await MessagingEndpointCollection.create({\n db: this.options.db,\n });\n for (const route of candidates) {\n const endpoint = await endpoints.get({ id: route.endpointId });\n if (endpoint?.channel === input.channel) return route;\n }\n throw new Error(\n `No ${input.channel} route is configured for this persona.`,\n );\n }\n\n const route = candidates[0];\n if (!route)\n throw new Error('No messaging route is configured for this persona.');\n return route;\n }\n}\n","import {\n isUniqueViolationError,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport { UserNotificationCollection } from '../collections/UserNotificationCollection.js';\nimport { withTenant } from '../host.js';\nimport {\n USER_NOTIFICATION_SEVERITIES,\n type UserNotification,\n type UserNotificationSeverity,\n} from '../models/UserNotification.js';\n\n/** What to tell one person. */\nexport interface UserNotificationInput {\n tenantId: string;\n recipientUserId: string;\n /** Host-defined type, e.g. `social-post.failed`. */\n kind: string;\n title: string;\n body?: string;\n href?: string | null;\n severity?: UserNotificationSeverity;\n /**\n * Dedupe key for the underlying event (e.g. `social-post:<id>:failed`). A\n * second `notify()` with the same `(tenantId, recipientUserId, sourceRef)`\n * returns the existing row untouched, read state included. Omit for\n * one-off notifications; a unique ref is generated.\n */\n sourceRef?: string;\n /** When the event happened (default: now). */\n occurredAt?: Date;\n}\n\nexport interface UserNotificationNotifyResult {\n notification: UserNotification;\n /** False when `sourceRef` matched an existing notification. */\n created: boolean;\n}\n\nexport interface UserNotificationListOptions {\n /** Tenants to read (at least one). Each is read under its own tenant scope. */\n tenantIds: readonly string[];\n /** Only rows not yet read. */\n unreadOnly?: boolean;\n /** Include dismissed rows (default false). */\n includeDismissed?: boolean;\n /** Only rows that happened at or after this time. */\n since?: Date;\n /** Newest-first cap across all tenants (default 50, max 200). */\n limit?: number;\n}\n\nexport interface UserNotificationScope {\n tenantId: string;\n}\n\n/** Notification ids are uuids; anything else can match no row. */\nconst UUID_PATTERN =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nconst DEFAULT_LIMIT = 50;\nconst MAX_LIMIT = 200;\n\nfunction requireText(value: string | undefined, name: string): string {\n const text = value?.trim();\n if (!text) throw new Error(`A notification ${name} is required.`);\n return text;\n}\n\nfunction clampLimit(limit: number | undefined): number {\n if (limit === undefined) return DEFAULT_LIMIT;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new Error('Notification list limit must be a positive integer.');\n }\n return Math.min(limit, MAX_LIMIT);\n}\n\n/**\n * Creates, lists, and updates per-user notifications (`UserNotification`).\n *\n * The service is the authorization boundary for the model: every read and\n * write is filtered to one recipient and runs under an explicit tenant\n * scope. The host decides who may be notified (e.g. the poster of a failed\n * social post) and passes the signed-in user's id for reads; it never lets\n * a request choose another user's id.\n */\nexport class UserNotificationService {\n constructor(private readonly options: { db: SmrtClassOptions['db'] }) {}\n\n private collection(): Promise<UserNotificationCollection> {\n return UserNotificationCollection.create({ db: this.options.db });\n }\n\n /** Store a notification unless its `sourceRef` already exists. */\n async notify(\n input: UserNotificationInput,\n ): Promise<UserNotificationNotifyResult> {\n const tenantId = requireText(input.tenantId, 'tenant');\n const recipientUserId = requireText(input.recipientUserId, 'recipient');\n const kind = requireText(input.kind, 'kind');\n const title = requireText(input.title, 'title');\n const severity = input.severity ?? 'info';\n if (!USER_NOTIFICATION_SEVERITIES.includes(severity)) {\n throw new Error(`Unknown notification severity '${severity}'.`);\n }\n const sourceRef =\n input.sourceRef?.trim() || `notification:${crypto.randomUUID()}`;\n\n return withTenant({ tenantId }, async () => {\n const notifications = await this.collection();\n const findExisting = async () =>\n (\n await notifications.list({\n where: { tenantId, recipientUserId, sourceRef },\n limit: 1,\n })\n )[0];\n const existing = await findExisting();\n if (existing) return { notification: existing, created: false };\n\n // Insert-only: a concurrent notify() for the same event may have stored\n // the row since the lookup above. An upsert would then overwrite it —\n // title, and read/dismissed state reset to null — so a collision is\n // resolved by returning the stored row untouched instead.\n let notification: UserNotification;\n try {\n notification = await notifications.create({\n _insertOnly: true,\n tenantId,\n recipientUserId,\n kind,\n title,\n body: input.body?.trim() ?? '',\n href: input.href ?? null,\n severity,\n sourceRef,\n occurredAt: input.occurredAt ?? new Date(),\n readAt: null,\n dismissedAt: null,\n });\n } catch (error) {\n if (!isUniqueViolationError(error)) throw error;\n const winner = await findExisting();\n if (!winner) throw error;\n return { notification: winner, created: false };\n }\n return { notification, created: true };\n });\n }\n\n /** `notify()` for each recipient (duplicates in the list are ignored). */\n async notifyMany(\n recipientUserIds: readonly string[],\n input: Omit<UserNotificationInput, 'recipientUserId'>,\n ): Promise<UserNotificationNotifyResult[]> {\n const results: UserNotificationNotifyResult[] = [];\n for (const recipientUserId of new Set(recipientUserIds)) {\n results.push(await this.notify({ ...input, recipientUserId }));\n }\n return results;\n }\n\n /** A user's notifications across the given tenants, newest first. */\n async listForUser(\n userId: string,\n options: UserNotificationListOptions,\n ): Promise<UserNotification[]> {\n const recipientUserId = requireText(userId, 'recipient');\n const limit = clampLimit(options.limit);\n const tenantIds = [...new Set(options.tenantIds.filter(Boolean))];\n const notifications = await this.collection();\n\n const perTenant = await Promise.all(\n tenantIds.map((tenantId) =>\n withTenant({ tenantId }, () =>\n notifications.list({\n where: {\n tenantId,\n recipientUserId,\n ...(options.includeDismissed ? {} : { dismissedAt: null }),\n ...(options.unreadOnly ? { readAt: null } : {}),\n ...(options.since ? { 'occurredAt >=': options.since } : {}),\n },\n orderBy: 'occurredAt DESC',\n limit,\n }),\n ),\n ),\n );\n\n return perTenant\n .flat()\n .sort((a, b) => b.occurredAt.getTime() - a.occurredAt.getTime())\n .slice(0, limit);\n }\n\n /** Unread, undismissed count across the given tenants. */\n async countUnread(\n userId: string,\n options: Pick<UserNotificationListOptions, 'tenantIds' | 'since'>,\n ): Promise<number> {\n const recipientUserId = requireText(userId, 'recipient');\n const notifications = await this.collection();\n const counts = await Promise.all(\n [...new Set(options.tenantIds.filter(Boolean))].map((tenantId) =>\n withTenant({ tenantId }, () =>\n notifications.count({\n where: {\n tenantId,\n recipientUserId,\n readAt: null,\n dismissedAt: null,\n ...(options.since ? { 'occurredAt >=': options.since } : {}),\n },\n }),\n ),\n ),\n );\n return counts.reduce((sum, count) => sum + Number(count), 0);\n }\n\n /** Mark the user's own notifications read; returns how many changed. */\n async markRead(\n userId: string,\n ids: readonly string[],\n scope: UserNotificationScope,\n ): Promise<number> {\n return this.stamp(userId, ids, scope, 'readAt');\n }\n\n /** Dismiss (and mark read) the user's own notifications. */\n async dismiss(\n userId: string,\n ids: readonly string[],\n scope: UserNotificationScope,\n ): Promise<number> {\n return this.stamp(userId, ids, scope, 'dismissedAt');\n }\n\n /** Mark every unread notification of the user in these tenants read. */\n async markAllRead(\n userId: string,\n options: Pick<UserNotificationListOptions, 'tenantIds'>,\n ): Promise<number> {\n const recipientUserId = requireText(userId, 'recipient');\n const notifications = await this.collection();\n const now = new Date();\n let changed = 0;\n for (const tenantId of new Set(options.tenantIds.filter(Boolean))) {\n changed += await withTenant({ tenantId }, async () => {\n const unread = await notifications.list({\n where: { tenantId, recipientUserId, readAt: null },\n });\n for (const notification of unread) {\n notification.readAt = now;\n await notification.save();\n }\n return unread.length;\n });\n }\n return changed;\n }\n\n private async stamp(\n userId: string,\n ids: readonly string[],\n scope: UserNotificationScope,\n column: 'readAt' | 'dismissedAt',\n ): Promise<number> {\n const recipientUserId = requireText(userId, 'recipient');\n const tenantId = requireText(scope.tenantId, 'tenant');\n // Ids come from requests. A malformed one can match no row, and on a\n // native uuid column (PostgreSQL) it would fail the whole query (22P02)\n // instead, so drop it before querying.\n const wanted = [\n ...new Set(\n ids.filter(\n (id): id is string => typeof id === 'string' && UUID_PATTERN.test(id),\n ),\n ),\n ];\n if (wanted.length === 0) return 0;\n\n return withTenant({ tenantId }, async () => {\n const notifications = await this.collection();\n // The recipient filter is the authorization check: another user's id\n // simply matches nothing.\n const rows = await notifications.list({\n where: { tenantId, recipientUserId, 'id in': wanted },\n });\n const now = new Date();\n let changed = 0;\n for (const notification of rows) {\n if (notification[column] !== null) continue;\n notification[column] = now;\n if (column === 'dismissedAt' && notification.readAt === null) {\n notification.readAt = now;\n }\n await notification.save();\n changed += 1;\n }\n return changed;\n });\n }\n}\n","import { SmrtRecipe } from '@happyvertical/smrt-core';\nimport { Email } from './models/Email.js';\nimport { EmailAccount } from './models/EmailAccount.js';\nimport { SlackAccount } from './models/SlackAccount.js';\nimport { SlackMessage } from './models/SlackMessage.js';\nimport { UserNotification } from './models/UserNotification.js';\n\n/** Email reading and composing with application-owned transport. */\nexport class MailboxRecipe extends SmrtRecipe {\n static id = 'messages.mailbox';\n static label = 'Mailbox';\n static summary = 'Read and compose email from your connected accounts.';\n static synonyms = ['email', 'inbox', 'mail'];\n static group = {\n id: 'messages',\n label: 'Messaging',\n summary: 'Choose email and personal updates independently.',\n };\n static section = {\n id: 'messages',\n label: 'Messaging',\n icon: 'folder',\n description: 'Read email and keep up with updates addressed to you.',\n };\n static models = [Email, EmailAccount];\n static runtime = 'both' as const;\n static surfaces = [\n {\n kind: 'route',\n path: '/messages/mailbox',\n export: '@happyvertical/smrt-messages/svelte#MessageList',\n label: 'Mailbox',\n },\n {\n kind: 'playground',\n export: '@happyvertical/smrt-messages/svelte#MailboxDemo',\n label: 'Mailbox with mocked sending',\n },\n ] as const;\n static providers = [\n {\n id: 'email-inbox',\n kind: 'email',\n options: ['imap', 'pop3', 'gmail', 'jmap'],\n required: true,\n },\n {\n id: 'email-send',\n kind: 'email',\n options: ['smtp', 'gmail'],\n required: false,\n },\n ];\n static demoSeed = {\n data: {\n accounts: [\n {\n id: 'demo-account',\n name: 'Demo Inbox',\n providerType: 'email',\n email: 'you@example.com',\n isActive: true,\n },\n ],\n messages: [\n {\n id: 'demo-welcome',\n type: 'email',\n accountId: 'demo-account',\n subject: 'Welcome to your mailbox',\n body: 'Fictional mail. Sending is mocked; nothing leaves this browser.',\n senderName: 'Demo colleague',\n senderAddress: 'colleague@example.com',\n recipientAddresses: [{ address: 'you@example.com' }],\n date: '2026-01-01T12:00:00Z',\n isRead: false,\n isFlagged: false,\n hasAttachments: false,\n },\n ],\n },\n };\n static nav = [\n {\n label: 'Mailbox',\n model: Email,\n key: 'mailbox',\n icon: 'folder',\n noun: 'email',\n description: 'Read email from your connected accounts.',\n },\n {\n label: 'Failed sends',\n model: Email,\n key: 'failed-sends',\n icon: 'fileText',\n noun: 'email',\n description: 'Review email whose last send attempt failed.',\n filter: { field: 'sendStatus', value: 'failed' },\n },\n ];\n static help = './help/mailbox.md';\n static options = {\n Email: {\n fields: {\n created_at: { help: 'When this email was first recorded.' },\n updated_at: { help: 'When this email record was last changed.' },\n },\n },\n EmailAccount: {\n fields: {\n created_at: {\n help: 'When this mailbox connection was first recorded.',\n },\n updated_at: { help: 'When this mailbox connection was last changed.' },\n },\n },\n } as const;\n}\n\n/** Recipient-scoped in-app notification bell. */\nexport class NotificationsRecipe extends SmrtRecipe {\n static id = 'messages.notifications';\n static label = 'Notifications';\n static summary = 'See updates addressed to you and mark them read.';\n static synonyms = ['alerts', 'notification bell'];\n static group = {\n id: 'messages',\n label: 'Messaging',\n summary: 'Choose email and personal updates independently.',\n };\n static section = {\n id: 'messages',\n label: 'Messaging',\n icon: 'folder',\n description: 'Read email and keep up with updates addressed to you.',\n };\n static models = [UserNotification];\n static runtime = 'both' as const;\n static surfaces = [\n {\n kind: 'shell-widget',\n slot: 'header.end',\n export: '@happyvertical/smrt-svelte/notifications#NotificationBell',\n label: 'Notifications',\n },\n ] as const;\n static providers = [\n {\n id: 'notifications',\n kind: 'notifications',\n options: ['user-notification-service'],\n required: true,\n },\n ];\n static demoSeed = {\n data: {\n items: [\n {\n id: 'demo-notification',\n title: 'You were mentioned',\n body: 'A fictional update for the demo user.',\n occurredAt: '2026-01-01T12:00:00Z',\n severity: 'info',\n readAt: null,\n },\n ],\n },\n };\n // Recipient-scoped reads use the bell provider, never generated model routes.\n static nav = [];\n static help = './help/notifications.md';\n}\n\n/** Slack messages from connected workspaces, read by channel and thread. */\nexport class SlackRecipe extends SmrtRecipe {\n static id = 'messages.slack';\n static label = 'Slack';\n static summary = 'Read Slack messages from your connected workspaces.';\n static synonyms = [\n 'slack',\n 'slack messages',\n 'slack channels',\n 'workspace chat',\n 'team chat',\n ];\n static group = {\n id: 'messages',\n label: 'Messaging',\n summary: 'Choose email and personal updates independently.',\n };\n static section = {\n id: 'messages',\n label: 'Messaging',\n icon: 'folder',\n description: 'Read email and keep up with updates addressed to you.',\n };\n static models = [SlackMessage, SlackAccount];\n static nav = [\n {\n label: 'Slack messages',\n model: SlackMessage,\n key: 'slack-messages',\n icon: 'folder',\n noun: 'message',\n description: 'Read messages from your connected workspaces by channel.',\n },\n {\n label: 'Slack workspaces',\n model: SlackAccount,\n icon: 'users',\n noun: 'workspace',\n description: 'The workspaces your application is connected to.',\n },\n ];\n static help = './help/slack.md';\n static options = {\n SlackMessage: {\n fields: {\n channelName: { label: 'Channel', order: 1 },\n body: { label: 'Message', order: 2 },\n threadId: { label: 'Thread', order: 3 },\n sendStatus: { label: 'Sent status', order: 4 },\n accountId: { label: 'Workspace', order: 5 },\n fromName: { label: 'From', visibility: 'advanced' },\n fromAddress: { visibility: 'advanced' },\n toAddresses: { visibility: 'advanced' },\n subject: { visibility: 'advanced' },\n date: { visibility: 'advanced' },\n isRead: { visibility: 'advanced' },\n isFlagged: { visibility: 'advanced' },\n isEdited: { label: 'Edited', visibility: 'advanced' },\n messageType: { label: 'Message kind', visibility: 'advanced' },\n reactions: { visibility: 'advanced' },\n hasAttachments: { visibility: 'advanced' },\n channelId: { visibility: 'advanced' },\n sentAt: { visibility: 'advanced' },\n sendError: { visibility: 'advanced' },\n scheduledSendAt: { visibility: 'advanced' },\n inReplyToMessageId: { label: 'Replying to', visibility: 'advanced' },\n personaId: { visibility: 'advanced' },\n endpointId: { visibility: 'advanced' },\n retryCount: { visibility: 'hidden' },\n maxRetries: { visibility: 'hidden' },\n size: { visibility: 'hidden' },\n correlationId: { visibility: 'hidden' },\n slackTs: { visibility: 'hidden' },\n slackThreadTs: { visibility: 'hidden' },\n blocks: { visibility: 'hidden' },\n metadata: { visibility: 'hidden' },\n tenantId: { visibility: 'hidden' },\n created_at: { help: 'When this message was first recorded.' },\n updated_at: { help: 'When this message record was last changed.' },\n },\n },\n SlackAccount: {\n fields: {\n name: { order: 1 },\n workspaceName: { label: 'Workspace', order: 2 },\n isActive: { label: 'Enabled', order: 3 },\n lastSyncAt: { label: 'Last checked', order: 4 },\n workspaceId: { visibility: 'advanced' },\n credentialSecretId: { visibility: 'hidden' },\n settings: { visibility: 'hidden' },\n botUserId: { label: 'Bot user', visibility: 'advanced' },\n providerType: { visibility: 'advanced' },\n channelType: { visibility: 'advanced' },\n configuration: { visibility: 'advanced' },\n tenantId: { visibility: 'hidden' },\n created_at: {\n help: 'When this workspace connection was first recorded.',\n },\n updated_at: {\n help: 'When this workspace connection was last changed.',\n },\n },\n },\n } as const;\n}\n","/**\n * @happyvertical/smrt-messages\n *\n * Unified multi-channel messaging with STI-based hierarchies\n *\n * @packageDocumentation\n */\n\n// Self-register this package's manifest before any @smrt() decorator fires\n// downstream. Must come first so the side effect runs ahead of the class\n// module loads below. See __smrt-register__.ts for issue #1132 context.\nimport './__smrt-register__.js';\n\nimport { ensureMailAccessEnforcementRegistered } from './access-enforcement.js';\nimport { ensureMessagingPermissionsRegistered } from './permissions.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Per-account mail access (owner + grants; see access.ts)\n// ─────────────────────────────────────────────────────────────────────────\nexport {\n assertMailAccess,\n canAccessMailAccount,\n configureMailAccess,\n decideMailAccess,\n deniedMailAccountIds,\n type GrantMailAccessInput,\n isMailScope,\n isPersonMailPrincipal,\n MAIL_ACCOUNT_RESOURCE_TYPE,\n MAIL_SCOPES,\n type MailAccessAdmin,\n type MailAccessConfig,\n type MailAccessDecision,\n MailAccessError,\n type MailAccessReason,\n type MailAccessResolver,\n type MailAccessResolverContext,\n MailAccessService,\n type MailAccessSubject,\n type MailPrincipal,\n type MailScope,\n mailScopePermission,\n resetMailAccess,\n resolveMailPrincipal,\n runWithMailSystemAccess,\n} from './access.js';\nexport {\n MailDraftError,\n type MailDraftInput,\n MailDraftService,\n} from './mail-drafts.js';\nexport type {\n MailSyncOptions,\n MailSyncResult,\n MailSyncSkipReason,\n} from './mail-sync.js';\nexport {\n CHANGE_FEED_PROVIDERS,\n type EnqueueMailSyncOptions,\n enqueueDueMailSyncs,\n enqueueMailSync,\n MAIL_SYNC_QUEUE,\n mailSyncDedupeKey,\n} from './mail-sync-jobs.js';\nexport {\n type MailTriageAction,\n type MailTriageActionKind,\n type MailTriageFailure,\n type MailTriageResult,\n type MailWriteBackCapability,\n MailWriteBackUnsupportedError,\n} from './mail-triage.js';\n\nexport {\n type AgentSendPolicyContext,\n APPROVE_HELD_SEND_PERMISSION,\n auditMailAction,\n configureMailSendApprovals,\n effectiveAgentSendPolicy,\n type HeldSendDecisionResult,\n type HeldSendEdits,\n HeldSendError,\n type MailSendApprovalActor,\n type MailSendApprovalCheckResult,\n type MailSendApprovalConfig,\n type MailSendApprovalGate,\n type MailSendApprovalOutcome,\n MailSendApprovalService,\n type MailSendApprovalView,\n mailSendBindingHash,\n resetMailSendApprovals,\n stampHandledBy,\n threadHandledBy,\n} from './send-approval.js';\n\nimport { ensureBuiltinMessagingProvidersRegistered } from './providers.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Base classes (new)\n// ─────────────────────────────────────────────────────────────────────────\n\nexport { AccountCollection } from './collections/AccountCollection';\nexport { AttachmentCollection } from './collections/AttachmentCollection';\nexport { CorrespondentCollection } from './collections/CorrespondentCollection.js';\n// Base collections\nexport { MessageCollection } from './collections/MessageCollection';\nexport { MessagingEndpointCollection } from './collections/MessagingEndpointCollection.js';\nexport { NotificationDeliveryCollection } from './collections/NotificationDeliveryCollection.js';\nexport { NotificationOptOutCollection } from './collections/NotificationOptOutCollection.js';\nexport { PersonaMessageRouteCollection } from './collections/PersonaMessageRouteCollection.js';\nexport { UserNotificationCollection } from './collections/UserNotificationCollection.js';\nexport { Account } from './models/Account';\nexport { Attachment } from './models/Attachment';\nexport {\n Correspondent,\n type CorrespondentOptions,\n} from './models/Correspondent.js';\n// Base models\nexport { Message } from './models/Message';\nexport { MessagingEndpoint } from './models/MessagingEndpoint.js';\nexport {\n NOTIFICATION_DELIVERY_CHANNELS,\n NotificationDelivery,\n type NotificationDeliveryChannel,\n type NotificationDeliveryOptions,\n type NotificationDeliveryStatus,\n type NotificationDeliveryTransition,\n} from './models/NotificationDelivery.js';\nexport {\n isValidNotificationOptOutScope,\n NOTIFICATION_OPT_OUT_ALL_SCOPE,\n NOTIFICATION_OPT_OUT_SCOPE_PATTERN,\n NotificationOptOut,\n type NotificationOptOutOptions,\n} from './models/NotificationOptOut.js';\nexport { PersonaMessageRoute } from './models/PersonaMessageRoute.js';\nexport {\n USER_NOTIFICATION_SEVERITIES,\n UserNotification,\n type UserNotificationOptions,\n type UserNotificationSeverity,\n} from './models/UserNotification.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Email (backward-compatible)\n// ─────────────────────────────────────────────────────────────────────────\n\nexport { EmailAccountCollection } from './collections/EmailAccountCollection';\nexport { EmailAttachmentCollection } from './collections/EmailAttachmentCollection';\n// Email collections\nexport { EmailCollection } from './collections/EmailCollection';\nexport { EmailFolderCollection } from './collections/EmailFolderCollection';\n// Email models\nexport { Email } from './models/Email';\nexport { EmailAccount } from './models/EmailAccount';\nexport { EmailAttachment } from './models/EmailAttachment';\nexport { EmailFolder } from './models/EmailFolder';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Email filtering (whitelist/blacklist)\n// ─────────────────────────────────────────────────────────────────────────\n\nexport { BlacklistCollection } from './collections/BlacklistCollection';\nexport { WhitelistCollection } from './collections/WhitelistCollection';\nexport { Blacklist } from './models/Blacklist';\nexport { Whitelist } from './models/Whitelist';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Provider stubs\n// ─────────────────────────────────────────────────────────────────────────\n\n// Account types\nexport { SlackAccount } from './models/SlackAccount';\nexport { SlackMessage } from './models/SlackMessage';\nexport { TelegramAccount } from './models/TelegramAccount.js';\n// Message types\nexport { Tweet } from './models/Tweet';\nexport { TwitterAccount } from './models/TwitterAccount';\nexport { ZulipAccount } from './models/ZulipAccount.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Senders\n// ─────────────────────────────────────────────────────────────────────────\n\nexport {\n assertMessagingPermission,\n ensureMessagingPermissionsRegistered,\n MANAGE_MESSAGE_CREDENTIALS_PERMISSION,\n MANAGE_MESSAGE_ROUTES_PERMISSION,\n MESSAGES_ROLE_PERMISSION_MATRIX,\n MESSAGING_PERMISSION_DEFINITIONS,\n type MessagingPrincipal,\n messagingPrincipalFromPermissions,\n SEND_MESSAGES_PERMISSION,\n type SeedMessagesRolePermissionsResult,\n seedMessagesRolePermissions,\n} from './permissions.js';\nexport {\n ensureBuiltinMessagingProvidersRegistered,\n getMessagingProvider,\n listMessagingProviders,\n type MessagingProviderDefinition,\n type MessagingProviderField,\n type MessagingProviderFieldType,\n registerMessagingProvider,\n} from './providers.js';\nexport { EmailSender } from './senders/EmailSender';\nexport { SlackSender } from './senders/SlackSender';\nexport { TelegramSender } from './senders/TelegramSender.js';\nexport { TweetSender } from './senders/TweetSender';\nexport { ZulipSender } from './senders/ZulipSender.js';\nexport {\n type CorrespondentRefreshResult,\n CorrespondentService,\n type CorrespondentServiceOptions,\n type CorrespondentView,\n type ListCorrespondentsOptions,\n normalizeCorrespondentAddress,\n} from './services/CorrespondentService.js';\nexport {\n type MailProviderSearchResult,\n type MailSearchHit,\n type MailSearchPage,\n type MailSearchQuery,\n MailSearchService,\n type MailSearchServiceOptions,\n readableMailAccounts,\n} from './services/MailSearchService.js';\nexport {\n type ListAccountsOptions,\n type ListAccountsResult,\n type MessagingAccountInput,\n type MessagingAccountListing,\n type MessagingAccountView,\n type MessagingEndpointInput,\n type MessagingEndpointView,\n MessagingSettingsService,\n type PersonaMessageRouteInput,\n} from './services/MessagingSettingsService.js';\nexport {\n type NotificationOptOutChange,\n type NotificationOptOutDenialReason,\n NotificationOptOutDeniedError,\n type NotificationOptOutKey,\n type NotificationOptOutListRequest,\n type NotificationOptOutPrincipal,\n NotificationOptOutService,\n optOutSuppression,\n} from './services/NotificationOptOutService.js';\nexport {\n buildNotificationLink,\n messageSendTransport,\n type NotificationDispatchOptions,\n type NotificationDispatchOutcome,\n type NotificationDispatchReport,\n type NotificationEmailInput,\n type NotificationEnqueueResult,\n type NotificationOutboxDenialReason,\n NotificationOutboxDeniedError,\n type NotificationOutboxOptions,\n NotificationOutboxService,\n type NotificationProfileRecipientRequest,\n type NotificationProfileSuppressionRequest,\n type NotificationRecipient,\n type NotificationRecipientRequest,\n type NotificationReconcileOutcome,\n type NotificationSuppressionRequest,\n type NotificationTransport,\n type NotificationTransportOutcome,\n type NotificationTransportReconciliation,\n type NotificationTransportRequest,\n notificationDeliveryCorrelationId,\n notificationDeliveryMessageId,\n} from './services/NotificationOutboxService.js';\nexport {\n type PersonaMessageSendResult,\n PersonaMessagingService,\n} from './services/PersonaMessagingService.js';\nexport {\n type UserNotificationInput,\n type UserNotificationListOptions,\n type UserNotificationNotifyResult,\n type UserNotificationScope,\n UserNotificationService,\n} from './services/UserNotificationService.js';\n\n// ─────────────────────────────────────────────────────────────────────────\n// Types\n// ─────────────────────────────────────────────────────────────────────────\n\nexport type {\n AccountOptions,\n AccountSearchFilters,\n AccountType,\n AgentSendPolicy,\n AttachmentOptions,\n // Email options (backward compat)\n EmailAccountOptions,\n EmailAccountSearchFilters,\n EmailAttachmentOptions,\n EmailFolderOptions,\n EmailFolderSearchFilters,\n EmailOptions,\n EmailSearchFilters,\n KnownMessagingChannel,\n // Base options\n MessageOptions,\n // Search filters\n MessageSearchFilters,\n MessageSenderInterface,\n // Send types\n MessageSendResult,\n // Discriminator types\n MessageType,\n MessagingChannel,\n MessagingEndpointOptions,\n PersonaMessageRouteOptions,\n ProviderType,\n SendEmailAttachment,\n SendEmailOptions,\n SendMessageOptions,\n SendPersonaMessageOptions,\n SendSlackOptions,\n SendStatus,\n SendTweetOptions,\n SlackAccountOptions,\n SlackMessageOptions,\n // Sync types\n SyncOptions,\n SyncProgress,\n SyncResult,\n // Provider options\n TweetOptions,\n TwitterAccountOptions,\n} from './types';\n\nensureBuiltinMessagingProvidersRegistered();\nensureMessagingPermissionsRegistered();\nensureMailAccessEnforcementRegistered();\n\nexport {\n assertNotificationProfileRecipientSchema,\n migrateNotificationProfileRecipients,\n type NotificationProfileRecipientEngine,\n type NotificationProfileRecipientPlan,\n planNotificationProfileRecipients,\n} from './migrations/profileRecipients.js';\nexport {\n type NotificationRecipientIdentity,\n PROFILE_NOTIFICATION_POLICY_PREFIX,\n profileNotificationPolicy,\n} from './notification-recipient-identity.js';\nexport { MailboxRecipe, NotificationsRecipe, SlackRecipe } from './recipes.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyCA,IAAM,gBAAsC;CAC1C,SAAS;CACT,OAAO;CACP,aAAa;CACb,YAAY;CACZ,SAAS;CACT,cAAc;CACd,iBAAiB;AACnB;AAEA,SAAS,SAAS,MAAe,MAAwB;CACvD,IAAI,OAAO,SAAS,YAAY,OAAO;CACvC,OACE,SAAS,QACR,KAA+B,qBAC7B;AAEP;AAEA,SAAS,OAAO,WAAmB,SAA0C;CAI3E,MAAM,QAFJ,eAAe,SAAS,QAAQ,sBAAsB,SAAS,KAC/D,eAAe,SAAS,SAAS,EAAA,EACV;CACzB,IAAI,MAAM;EACR,IAAI,SAAS,MAAM,OAAO,GAAG,OAAO;EACpC,IAAI,SAAS,MAAM,WAAW,GAAG,OAAO;EACxC,IAAI,SAAS,MAAM,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