@happyvertical/smrt-messages 0.62.6 → 0.62.8
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/AGENTS.md +102 -0
- package/dist/access-enforcement.d.ts +20 -0
- package/dist/access-enforcement.d.ts.map +1 -0
- package/dist/access.d.ts +203 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/chunks/AttachmentCollection-DhCoruwp.js +308 -0
- package/dist/chunks/AttachmentCollection-DhCoruwp.js.map +1 -0
- package/dist/chunks/{Email-ChfbMCSF.js → Email-CmNoK1lj.js} +9 -6
- package/dist/chunks/Email-CmNoK1lj.js.map +1 -0
- package/dist/chunks/EmailAccountCollection-CHizpsxL.js +1555 -0
- package/dist/chunks/EmailAccountCollection-CHizpsxL.js.map +1 -0
- package/dist/chunks/EmailCollection-Yo2wBv_1.js +181 -0
- package/dist/chunks/EmailCollection-Yo2wBv_1.js.map +1 -0
- package/dist/chunks/{EmailFolder-XH5eH4Ed.js → EmailFolder-Dks5clxA.js} +25 -6
- package/dist/chunks/EmailFolder-Dks5clxA.js.map +1 -0
- package/dist/chunks/EmailFolderCollection-nIR4Kpcr.js +177 -0
- package/dist/chunks/EmailFolderCollection-nIR4Kpcr.js.map +1 -0
- package/dist/chunks/EmailSender-B-Rtq9du.js +147 -0
- package/dist/chunks/EmailSender-B-Rtq9du.js.map +1 -0
- package/dist/chunks/{Message-C6P1V5C_.js → Message-e99HkbG8.js} +30 -6
- package/dist/chunks/Message-e99HkbG8.js.map +1 -0
- package/dist/chunks/{MessageCollection-CjCT06XE.js → MessageCollection-t8cLUSNJ.js} +2 -2
- package/dist/chunks/{MessageCollection-CjCT06XE.js.map → MessageCollection-t8cLUSNJ.js.map} +1 -1
- package/dist/chunks/MessagingEndpointCollection-CGtAL77R.js +97 -0
- package/dist/chunks/MessagingEndpointCollection-CGtAL77R.js.map +1 -0
- package/dist/chunks/{SlackSender-CjSvwY1K.js → SlackSender-CetlSe6D.js} +2 -2
- package/dist/chunks/{SlackSender-CjSvwY1K.js.map → SlackSender-CetlSe6D.js.map} +1 -1
- package/dist/chunks/{TweetSender-CcLPNNi1.js → TweetSender-Dw-TDxIB.js} +2 -2
- package/dist/chunks/{TweetSender-CcLPNNi1.js.map → TweetSender-Dw-TDxIB.js.map} +1 -1
- package/dist/chunks/{providers-4iLula-V.js → providers-Bz_F_ywF.js} +36 -1
- package/dist/chunks/{providers-4iLula-V.js.map → providers-Bz_F_ywF.js.map} +1 -1
- package/dist/collections/AttachmentCollection.d.ts +6 -0
- package/dist/collections/AttachmentCollection.d.ts.map +1 -1
- package/dist/collections/EmailAccountCollection.d.ts.map +1 -1
- package/dist/connect.d.ts +82 -0
- package/dist/connect.d.ts.map +1 -0
- package/dist/connect.js +126 -0
- package/dist/connect.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +507 -1402
- package/dist/index.js.map +1 -1
- package/dist/mail-sync-jobs.d.ts +48 -0
- package/dist/mail-sync-jobs.d.ts.map +1 -0
- package/dist/mail-sync.d.ts +58 -0
- package/dist/mail-sync.d.ts.map +1 -0
- package/dist/manifest.json +1040 -56
- package/dist/models/Account.d.ts +23 -0
- package/dist/models/Account.d.ts.map +1 -1
- package/dist/models/Attachment.d.ts +14 -0
- package/dist/models/Attachment.d.ts.map +1 -1
- package/dist/models/Email.d.ts +1 -0
- package/dist/models/Email.d.ts.map +1 -1
- package/dist/models/EmailAccount.d.ts +32 -2
- package/dist/models/EmailAccount.d.ts.map +1 -1
- package/dist/models/EmailFolder.d.ts +7 -0
- package/dist/models/EmailFolder.d.ts.map +1 -1
- package/dist/models/Message.d.ts +7 -0
- package/dist/models/Message.d.ts.map +1 -1
- package/dist/permissions.d.ts +11 -0
- package/dist/permissions.d.ts.map +1 -1
- package/dist/providers/email.js +3 -2
- package/dist/providers/email.js.map +1 -1
- package/dist/providers/slack.js +2 -2
- package/dist/providers/twitter.js +2 -2
- package/dist/providers.d.ts.map +1 -1
- package/dist/recipes.d.ts +1 -1
- package/dist/services/MessagingSettingsService.d.ts +86 -0
- package/dist/services/MessagingSettingsService.d.ts.map +1 -1
- package/dist/services/NotificationOutboxService.d.ts +3 -0
- package/dist/services/NotificationOutboxService.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +826 -29
- package/dist/smrt-knowledge.okf.md +4 -2
- package/dist/types.d.ts +10 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +21 -16
- package/dist/chunks/AccountCollection-RP_hLf6L.js +0 -257
- package/dist/chunks/AccountCollection-RP_hLf6L.js.map +0 -1
- package/dist/chunks/Email-ChfbMCSF.js.map +0 -1
- package/dist/chunks/EmailFolder-XH5eH4Ed.js.map +0 -1
- package/dist/chunks/Message-C6P1V5C_.js.map +0 -1
- package/dist/chunks/__smrt-register__-CfOb1uCN.js +0 -6
- package/dist/chunks/__smrt-register__-CfOb1uCN.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"providers-4iLula-V.js","names":[],"sources":["../../src/senders/TelegramSender.ts","../../src/senders/ZulipSender.ts","../../src/providers.ts"],"sourcesContent":["import type { Account } from '../models/Account.js';\nimport type { Message } from '../models/Message.js';\nimport type {\n MessageSenderInterface,\n MessageSendResult,\n SendMessageOptions,\n} from '../types.js';\n\nexport class TelegramSender implements MessageSenderInterface {\n readonly providerType = 'telegram';\n\n constructor(\n private readonly account: Account,\n private readonly fetcher: typeof fetch = globalThis.fetch,\n ) {}\n\n isReady(): boolean {\n return this.account.isActive && this.account.hasCredentials;\n }\n\n async send(\n input: unknown,\n _options?: SendMessageOptions,\n ): Promise<MessageSendResult> {\n const message = input as Message;\n const endpoint = await message.getEndpoint();\n if (endpoint?.channel !== 'telegram' || !endpoint.isActive) {\n return failed(\n 'No active Telegram endpoint is associated with this message',\n );\n }\n\n const credentials = await this.account.getCredentials();\n const botToken =\n typeof credentials?.botToken === 'string' ? credentials.botToken : '';\n if (!botToken || !/^[A-Za-z0-9:_-]+$/.test(botToken)) {\n return failed('Telegram bot token is missing or invalid');\n }\n\n const address = endpoint.getAddress<{\n chatId?: string;\n threadId?: string | number;\n }>();\n if (!address.chatId)\n return failed('Telegram endpoint is missing a chat ID');\n\n const payload: Record<string, unknown> = {\n chat_id: address.chatId,\n text: message.body,\n };\n if (address.threadId !== undefined && address.threadId !== '') {\n const threadId = Number(address.threadId);\n if (!Number.isInteger(threadId) || threadId <= 0) {\n return failed('Telegram endpoint has an invalid topic/thread ID');\n }\n payload.message_thread_id = threadId;\n }\n\n try {\n const response = await this.fetcher(\n `https://api.telegram.org/bot${botToken}/sendMessage`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n },\n );\n const result = (await response.json()) as Record<string, unknown>;\n if (!response.ok || result.ok !== true) {\n return failed(\n typeof result.description === 'string'\n ? result.description\n : `Telegram returned ${response.status}`,\n result,\n );\n }\n const responseMessage = result.result as\n | Record<string, unknown>\n | undefined;\n return {\n success: true,\n providerMessageId: String(responseMessage?.message_id ?? ''),\n providerResponse: result,\n sentAt: new Date(),\n };\n } catch (error) {\n return failed(error instanceof Error ? error.message : String(error));\n }\n }\n}\n\nfunction failed(\n error: string,\n providerResponse?: Record<string, unknown>,\n): MessageSendResult {\n return { success: false, error, providerResponse, sentAt: new Date() };\n}\n","import type { Account } from '../models/Account.js';\nimport type { Message } from '../models/Message.js';\nimport type {\n MessageSenderInterface,\n MessageSendResult,\n SendMessageOptions,\n} from '../types.js';\n\nexport class ZulipSender implements MessageSenderInterface {\n readonly providerType = 'zulip';\n\n constructor(\n private readonly account: Account,\n private readonly fetcher: typeof fetch = globalThis.fetch,\n ) {}\n\n isReady(): boolean {\n return this.account.isActive && this.account.hasCredentials;\n }\n\n async send(\n input: unknown,\n _options?: SendMessageOptions,\n ): Promise<MessageSendResult> {\n const message = input as Message;\n const endpoint = await message.getEndpoint();\n if (endpoint?.channel !== 'zulip' || !endpoint.isActive) {\n return failed('No active Zulip endpoint is associated with this message');\n }\n\n const configuration = this.account.getConfiguration();\n const credentials = await this.account.getCredentials();\n const site =\n typeof configuration.site === 'string' ? configuration.site : '';\n const email =\n typeof configuration.email === 'string' ? configuration.email : '';\n const apiKey =\n typeof credentials?.apiKey === 'string' ? credentials.apiKey : '';\n if (!site || !email || !apiKey)\n return failed('Zulip account is not configured');\n\n let apiUrl: URL;\n try {\n apiUrl = new URL('/api/v1/messages', site);\n if (!['http:', 'https:'].includes(apiUrl.protocol)) throw new Error();\n } catch {\n return failed('Zulip site must be a valid HTTP(S) URL');\n }\n\n const address = endpoint.getAddress<{\n type?: string;\n to?: string;\n topic?: string;\n }>();\n if (\n (address.type !== 'stream' && address.type !== 'private') ||\n !address.to\n ) {\n return failed('Zulip endpoint is missing a valid type or destination');\n }\n\n const form = new URLSearchParams({\n type: address.type,\n to: address.to,\n content: message.body,\n });\n if (address.type === 'stream') {\n form.set('topic', address.topic || message.subject || 'Agent message');\n }\n\n try {\n const response = await this.fetcher(apiUrl, {\n method: 'POST',\n headers: {\n Authorization: `Basic ${Buffer.from(`${email}:${apiKey}`).toString('base64')}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: form,\n });\n const payload = (await response.json()) as Record<string, unknown>;\n if (!response.ok || payload.result !== 'success') {\n return failed(\n typeof payload.msg === 'string'\n ? payload.msg\n : `Zulip returned ${response.status}`,\n payload,\n );\n }\n return {\n success: true,\n providerMessageId: String(payload.id ?? ''),\n providerResponse: payload,\n sentAt: new Date(),\n };\n } catch (error) {\n return failed(error instanceof Error ? error.message : String(error));\n }\n }\n}\n\nfunction failed(\n error: string,\n providerResponse?: Record<string, unknown>,\n): MessageSendResult {\n return { success: false, error, providerResponse, sentAt: new Date() };\n}\n","import type { EmailClient, GetEmailClientOptions } from '@happyvertical/email';\nimport type { Account } from './models/Account.js';\nimport { TelegramSender } from './senders/TelegramSender.js';\nimport { ZulipSender } from './senders/ZulipSender.js';\nimport type {\n MessageClientFactory,\n MessageSenderInterface,\n MessagingChannel,\n} from './types.js';\n\nexport type MessagingProviderFieldType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'select'\n | 'url'\n | 'email'\n | 'password';\n\nexport interface MessagingProviderField {\n id: string;\n label: string;\n type: MessagingProviderFieldType;\n required?: boolean;\n description?: string;\n placeholder?: string;\n options?: Array<{ value: string; label: string }>;\n}\n\n/** Public setup contract. Credential values are never represented here. */\nexport interface MessagingProviderDefinition {\n id: string;\n label: string;\n channel: MessagingChannel;\n available: boolean;\n configurationFields: MessagingProviderField[];\n credentialFields: MessagingProviderField[];\n endpointFields: MessagingProviderField[];\n createSender?: (account: Account) => Promise<MessageSenderInterface>;\n /**\n * Creates the SDK email client for this provider. Absent on the builtin\n * metadata-only definitions — registered by the explicit\n * `@happyvertical/smrt-messages/providers/email` entry point so the\n * @happyvertical/email SDK (googleapis/nodemailer) never enters\n * provider-neutral consumer bundles (#1979).\n */\n createEmailClient?: (options: GetEmailClientOptions) => Promise<EmailClient>;\n /**\n * Creates the SDK message client (Slack, Twitter, …) for this provider.\n * Registered by the matching `@happyvertical/smrt-messages/providers/*`\n * entry point; absent until that entry is imported.\n */\n createMessageClient?: MessageClientFactory;\n}\n\n/**\n * Function-valued definition keys. Stripped by MessagingSettingsService before\n * definitions are serialized to setup UIs.\n */\nexport type MessagingProviderFunctionKey =\n | 'createSender'\n | 'createEmailClient'\n | 'createMessageClient';\n\nconst REGISTRY_KEY = Symbol.for('smrt.messaging.providers');\n\nfunction registry(): Map<string, MessagingProviderDefinition> {\n const root = globalThis as typeof globalThis & {\n [REGISTRY_KEY]?: Map<string, MessagingProviderDefinition>;\n };\n root[REGISTRY_KEY] ??= new Map();\n return root[REGISTRY_KEY];\n}\n\nexport function registerMessagingProvider(\n provider: MessagingProviderDefinition,\n): () => void {\n registry().set(provider.id, provider);\n return () => registry().delete(provider.id);\n}\n\nexport function getMessagingProvider(\n id: string,\n): MessagingProviderDefinition | undefined {\n ensureBuiltinMessagingProvidersRegistered();\n return registry().get(id);\n}\n\nexport function listMessagingProviders(\n options: { includeUnavailable?: boolean } = {},\n) {\n ensureBuiltinMessagingProvidersRegistered();\n return [...registry().values()].filter(\n (provider) => options.includeUnavailable || provider.available,\n );\n}\n\nlet builtinsRegistered = false;\n\n/**\n * Registers a builtin definition only when its id is still absent.\n *\n * The registry lives on globalThis (survives HMR and duplicate module\n * instances) while the `builtinsRegistered` flag is module-scoped, so a\n * second module instance re-runs this function against a registry that may\n * already hold upgraded definitions — e.g. the functional client hooks\n * registered by the explicit `providers/*` entry points (#1979). Builtins\n * therefore only fill gaps; they never overwrite an existing definition.\n */\nfunction registerBuiltinMessagingProvider(\n provider: MessagingProviderDefinition,\n): void {\n if (registry().has(provider.id)) return;\n registerMessagingProvider(provider);\n}\n\nexport function ensureBuiltinMessagingProvidersRegistered(): void {\n if (builtinsRegistered) return;\n builtinsRegistered = true;\n\n const emailEndpoint: MessagingProviderField[] = [\n { id: 'email', label: 'Email address', type: 'email', required: true },\n ];\n const serverConfiguration: MessagingProviderField[] = [\n { id: 'email', label: 'From address', type: 'email', required: true },\n { id: 'host', label: 'Mail server', type: 'string', required: true },\n { id: 'port', label: 'Port', type: 'number', required: true },\n {\n id: 'secure',\n label: 'Use TLS',\n type: 'select',\n options: [\n { value: 'true', label: 'Yes' },\n { value: 'false', label: 'No' },\n ],\n },\n ];\n const passwordCredentials: MessagingProviderField[] = [\n { id: 'username', label: 'Username', type: 'string', required: true },\n { id: 'password', label: 'Password', type: 'password', required: true },\n ];\n\n for (const id of ['smtp', 'imap', 'pop3'] as const) {\n registerBuiltinMessagingProvider({\n id,\n label: id.toUpperCase(),\n channel: 'email',\n // IMAP/POP3 remain registered for existing receive/sync accounts but are\n // not valid outbound transports.\n available: id === 'smtp',\n configurationFields: serverConfiguration,\n credentialFields: passwordCredentials,\n endpointFields: emailEndpoint,\n });\n }\n\n registerBuiltinMessagingProvider({\n id: 'gmail',\n label: 'Gmail',\n channel: 'email',\n available: true,\n configurationFields: [\n { id: 'email', label: 'From address', type: 'email', required: true },\n ],\n credentialFields: [\n {\n id: 'clientId',\n label: 'OAuth client ID',\n type: 'string',\n required: true,\n },\n {\n id: 'clientSecret',\n label: 'OAuth client secret',\n type: 'password',\n required: true,\n },\n {\n id: 'refreshToken',\n label: 'OAuth refresh token',\n type: 'password',\n required: true,\n },\n { id: 'accessToken', label: 'OAuth access token', type: 'password' },\n ],\n endpointFields: emailEndpoint,\n });\n\n registerBuiltinMessagingProvider({\n id: 'zulip',\n label: 'Zulip',\n channel: 'zulip',\n available: true,\n configurationFields: [\n { id: 'site', label: 'Zulip site URL', type: 'url', required: true },\n { id: 'email', label: 'Bot email', type: 'email', required: true },\n ],\n credentialFields: [\n { id: 'apiKey', label: 'Bot API key', type: 'password', required: true },\n ],\n endpointFields: [\n {\n id: 'type',\n label: 'Destination type',\n type: 'select',\n required: true,\n options: [\n { value: 'stream', label: 'Stream' },\n { value: 'private', label: 'Private message' },\n ],\n },\n {\n id: 'to',\n label: 'Stream or recipient',\n type: 'string',\n required: true,\n },\n { id: 'topic', label: 'Topic', type: 'string' },\n ],\n createSender: async (account) => new ZulipSender(account),\n });\n\n registerBuiltinMessagingProvider({\n id: 'telegram',\n label: 'Telegram',\n channel: 'telegram',\n available: true,\n configurationFields: [],\n credentialFields: [\n { id: 'botToken', label: 'Bot token', type: 'password', required: true },\n ],\n endpointFields: [\n { id: 'chatId', label: 'Chat ID', type: 'string', required: true },\n { id: 'threadId', label: 'Topic/thread ID', type: 'number' },\n ],\n createSender: async (account) => new TelegramSender(account),\n });\n\n registerBuiltinMessagingProvider({\n id: 'sms',\n label: 'SMS (provider required)',\n channel: 'sms',\n available: false,\n configurationFields: [],\n credentialFields: [],\n endpointFields: [\n {\n id: 'phoneNumber',\n label: 'Phone number',\n type: 'string',\n required: true,\n },\n ],\n });\n}\n"],"mappings":";;AAQO,IAAM,iBAAN,MAAuD;CAG5D,YACmB,SACA,UAAwB,WAAW,OACpD;EAFiB,KAAA,UAAA;EACA,KAAA,UAAA;CA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qB,CAAC;EACtB,kBAAkB,CAAC;EACnB,gBAAgB,CACd;GACE,IAAI;GACJ,OAAO;GACP,MAAM;GACN,UAAU;EACZ,CACF;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"providers-Bz_F_ywF.js","names":[],"sources":["../../src/senders/TelegramSender.ts","../../src/senders/ZulipSender.ts","../../src/providers.ts"],"sourcesContent":["import type { Account } from '../models/Account.js';\nimport type { Message } from '../models/Message.js';\nimport type {\n MessageSenderInterface,\n MessageSendResult,\n SendMessageOptions,\n} from '../types.js';\n\nexport class TelegramSender implements MessageSenderInterface {\n readonly providerType = 'telegram';\n\n constructor(\n private readonly account: Account,\n private readonly fetcher: typeof fetch = globalThis.fetch,\n ) {}\n\n isReady(): boolean {\n return this.account.isActive && this.account.hasCredentials;\n }\n\n async send(\n input: unknown,\n _options?: SendMessageOptions,\n ): Promise<MessageSendResult> {\n const message = input as Message;\n const endpoint = await message.getEndpoint();\n if (endpoint?.channel !== 'telegram' || !endpoint.isActive) {\n return failed(\n 'No active Telegram endpoint is associated with this message',\n );\n }\n\n const credentials = await this.account.getCredentials();\n const botToken =\n typeof credentials?.botToken === 'string' ? credentials.botToken : '';\n if (!botToken || !/^[A-Za-z0-9:_-]+$/.test(botToken)) {\n return failed('Telegram bot token is missing or invalid');\n }\n\n const address = endpoint.getAddress<{\n chatId?: string;\n threadId?: string | number;\n }>();\n if (!address.chatId)\n return failed('Telegram endpoint is missing a chat ID');\n\n const payload: Record<string, unknown> = {\n chat_id: address.chatId,\n text: message.body,\n };\n if (address.threadId !== undefined && address.threadId !== '') {\n const threadId = Number(address.threadId);\n if (!Number.isInteger(threadId) || threadId <= 0) {\n return failed('Telegram endpoint has an invalid topic/thread ID');\n }\n payload.message_thread_id = threadId;\n }\n\n try {\n const response = await this.fetcher(\n `https://api.telegram.org/bot${botToken}/sendMessage`,\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n },\n );\n const result = (await response.json()) as Record<string, unknown>;\n if (!response.ok || result.ok !== true) {\n return failed(\n typeof result.description === 'string'\n ? result.description\n : `Telegram returned ${response.status}`,\n result,\n );\n }\n const responseMessage = result.result as\n | Record<string, unknown>\n | undefined;\n return {\n success: true,\n providerMessageId: String(responseMessage?.message_id ?? ''),\n providerResponse: result,\n sentAt: new Date(),\n };\n } catch (error) {\n return failed(error instanceof Error ? error.message : String(error));\n }\n }\n}\n\nfunction failed(\n error: string,\n providerResponse?: Record<string, unknown>,\n): MessageSendResult {\n return { success: false, error, providerResponse, sentAt: new Date() };\n}\n","import type { Account } from '../models/Account.js';\nimport type { Message } from '../models/Message.js';\nimport type {\n MessageSenderInterface,\n MessageSendResult,\n SendMessageOptions,\n} from '../types.js';\n\nexport class ZulipSender implements MessageSenderInterface {\n readonly providerType = 'zulip';\n\n constructor(\n private readonly account: Account,\n private readonly fetcher: typeof fetch = globalThis.fetch,\n ) {}\n\n isReady(): boolean {\n return this.account.isActive && this.account.hasCredentials;\n }\n\n async send(\n input: unknown,\n _options?: SendMessageOptions,\n ): Promise<MessageSendResult> {\n const message = input as Message;\n const endpoint = await message.getEndpoint();\n if (endpoint?.channel !== 'zulip' || !endpoint.isActive) {\n return failed('No active Zulip endpoint is associated with this message');\n }\n\n const configuration = this.account.getConfiguration();\n const credentials = await this.account.getCredentials();\n const site =\n typeof configuration.site === 'string' ? configuration.site : '';\n const email =\n typeof configuration.email === 'string' ? configuration.email : '';\n const apiKey =\n typeof credentials?.apiKey === 'string' ? credentials.apiKey : '';\n if (!site || !email || !apiKey)\n return failed('Zulip account is not configured');\n\n let apiUrl: URL;\n try {\n apiUrl = new URL('/api/v1/messages', site);\n if (!['http:', 'https:'].includes(apiUrl.protocol)) throw new Error();\n } catch {\n return failed('Zulip site must be a valid HTTP(S) URL');\n }\n\n const address = endpoint.getAddress<{\n type?: string;\n to?: string;\n topic?: string;\n }>();\n if (\n (address.type !== 'stream' && address.type !== 'private') ||\n !address.to\n ) {\n return failed('Zulip endpoint is missing a valid type or destination');\n }\n\n const form = new URLSearchParams({\n type: address.type,\n to: address.to,\n content: message.body,\n });\n if (address.type === 'stream') {\n form.set('topic', address.topic || message.subject || 'Agent message');\n }\n\n try {\n const response = await this.fetcher(apiUrl, {\n method: 'POST',\n headers: {\n Authorization: `Basic ${Buffer.from(`${email}:${apiKey}`).toString('base64')}`,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: form,\n });\n const payload = (await response.json()) as Record<string, unknown>;\n if (!response.ok || payload.result !== 'success') {\n return failed(\n typeof payload.msg === 'string'\n ? payload.msg\n : `Zulip returned ${response.status}`,\n payload,\n );\n }\n return {\n success: true,\n providerMessageId: String(payload.id ?? ''),\n providerResponse: payload,\n sentAt: new Date(),\n };\n } catch (error) {\n return failed(error instanceof Error ? error.message : String(error));\n }\n }\n}\n\nfunction failed(\n error: string,\n providerResponse?: Record<string, unknown>,\n): MessageSendResult {\n return { success: false, error, providerResponse, sentAt: new Date() };\n}\n","import type { EmailClient, GetEmailClientOptions } from '@happyvertical/email';\nimport type { Account } from './models/Account.js';\nimport { TelegramSender } from './senders/TelegramSender.js';\nimport { ZulipSender } from './senders/ZulipSender.js';\nimport type {\n MessageClientFactory,\n MessageSenderInterface,\n MessagingChannel,\n} from './types.js';\n\nexport type MessagingProviderFieldType =\n | 'string'\n | 'number'\n | 'boolean'\n | 'select'\n | 'url'\n | 'email'\n | 'password';\n\nexport interface MessagingProviderField {\n id: string;\n label: string;\n type: MessagingProviderFieldType;\n required?: boolean;\n description?: string;\n placeholder?: string;\n options?: Array<{ value: string; label: string }>;\n}\n\n/** Public setup contract. Credential values are never represented here. */\nexport interface MessagingProviderDefinition {\n id: string;\n label: string;\n channel: MessagingChannel;\n available: boolean;\n configurationFields: MessagingProviderField[];\n credentialFields: MessagingProviderField[];\n endpointFields: MessagingProviderField[];\n createSender?: (account: Account) => Promise<MessageSenderInterface>;\n /**\n * Creates the SDK email client for this provider. Absent on the builtin\n * metadata-only definitions — registered by the explicit\n * `@happyvertical/smrt-messages/providers/email` entry point so the\n * @happyvertical/email SDK (googleapis/nodemailer) never enters\n * provider-neutral consumer bundles (#1979).\n */\n createEmailClient?: (options: GetEmailClientOptions) => Promise<EmailClient>;\n /**\n * Creates the SDK message client (Slack, Twitter, …) for this provider.\n * Registered by the matching `@happyvertical/smrt-messages/providers/*`\n * entry point; absent until that entry is imported.\n */\n createMessageClient?: MessageClientFactory;\n}\n\n/**\n * Function-valued definition keys. Stripped by MessagingSettingsService before\n * definitions are serialized to setup UIs.\n */\nexport type MessagingProviderFunctionKey =\n | 'createSender'\n | 'createEmailClient'\n | 'createMessageClient';\n\nconst REGISTRY_KEY = Symbol.for('smrt.messaging.providers');\n\nfunction registry(): Map<string, MessagingProviderDefinition> {\n const root = globalThis as typeof globalThis & {\n [REGISTRY_KEY]?: Map<string, MessagingProviderDefinition>;\n };\n root[REGISTRY_KEY] ??= new Map();\n return root[REGISTRY_KEY];\n}\n\nexport function registerMessagingProvider(\n provider: MessagingProviderDefinition,\n): () => void {\n registry().set(provider.id, provider);\n return () => registry().delete(provider.id);\n}\n\nexport function getMessagingProvider(\n id: string,\n): MessagingProviderDefinition | undefined {\n ensureBuiltinMessagingProvidersRegistered();\n return registry().get(id);\n}\n\nexport function listMessagingProviders(\n options: { includeUnavailable?: boolean } = {},\n) {\n ensureBuiltinMessagingProvidersRegistered();\n return [...registry().values()].filter(\n (provider) => options.includeUnavailable || provider.available,\n );\n}\n\nlet builtinsRegistered = false;\n\n/**\n * Registers a builtin definition only when its id is still absent.\n *\n * The registry lives on globalThis (survives HMR and duplicate module\n * instances) while the `builtinsRegistered` flag is module-scoped, so a\n * second module instance re-runs this function against a registry that may\n * already hold upgraded definitions — e.g. the functional client hooks\n * registered by the explicit `providers/*` entry points (#1979). Builtins\n * therefore only fill gaps; they never overwrite an existing definition.\n */\nfunction registerBuiltinMessagingProvider(\n provider: MessagingProviderDefinition,\n): void {\n if (registry().has(provider.id)) return;\n registerMessagingProvider(provider);\n}\n\nexport function ensureBuiltinMessagingProvidersRegistered(): void {\n if (builtinsRegistered) return;\n builtinsRegistered = true;\n\n const emailEndpoint: MessagingProviderField[] = [\n { id: 'email', label: 'Email address', type: 'email', required: true },\n ];\n const serverConfiguration: MessagingProviderField[] = [\n { id: 'email', label: 'From address', type: 'email', required: true },\n { id: 'host', label: 'Mail server', type: 'string', required: true },\n { id: 'port', label: 'Port', type: 'number', required: true },\n {\n id: 'secure',\n label: 'Use TLS',\n type: 'select',\n options: [\n { value: 'true', label: 'Yes' },\n { value: 'false', label: 'No' },\n ],\n },\n ];\n const passwordCredentials: MessagingProviderField[] = [\n { id: 'username', label: 'Username', type: 'string', required: true },\n { id: 'password', label: 'Password', type: 'password', required: true },\n ];\n\n for (const id of ['smtp', 'imap', 'pop3'] as const) {\n registerBuiltinMessagingProvider({\n id,\n label: id.toUpperCase(),\n channel: 'email',\n // IMAP/POP3 remain registered for existing receive/sync accounts but are\n // not valid outbound transports.\n available: id === 'smtp',\n configurationFields: serverConfiguration,\n credentialFields: passwordCredentials,\n endpointFields: emailEndpoint,\n });\n }\n\n // JMAP (RFC 8620/8621): receive and sync only. Mailbox changes arrive through\n // the server's change feed (see `EmailAccount.syncChanges()`); sending stays\n // on SMTP, so JMAP is not offered as an outbound transport.\n registerBuiltinMessagingProvider({\n id: 'jmap',\n label: 'JMAP',\n channel: 'email',\n available: false,\n configurationFields: [\n { id: 'email', label: 'Mailbox address', type: 'email', required: true },\n { id: 'url', label: 'Mail server URL', type: 'string', required: true },\n ],\n credentialFields: [\n { id: 'username', label: 'Username', type: 'string' },\n { id: 'password', label: 'Password', type: 'password' },\n { id: 'token', label: 'Access token', type: 'password' },\n ],\n endpointFields: emailEndpoint,\n });\n\n registerBuiltinMessagingProvider({\n id: 'gmail',\n label: 'Gmail',\n channel: 'email',\n available: true,\n configurationFields: [\n { id: 'email', label: 'From address', type: 'email', required: true },\n ],\n credentialFields: [\n {\n id: 'clientId',\n label: 'OAuth client ID',\n type: 'string',\n required: true,\n },\n {\n id: 'clientSecret',\n label: 'OAuth client secret',\n type: 'password',\n required: true,\n },\n {\n id: 'refreshToken',\n label: 'OAuth refresh token',\n type: 'password',\n required: true,\n },\n { id: 'accessToken', label: 'OAuth access token', type: 'password' },\n ],\n endpointFields: emailEndpoint,\n });\n\n registerBuiltinMessagingProvider({\n id: 'zulip',\n label: 'Zulip',\n channel: 'zulip',\n available: true,\n configurationFields: [\n { id: 'site', label: 'Zulip site URL', type: 'url', required: true },\n { id: 'email', label: 'Bot email', type: 'email', required: true },\n ],\n credentialFields: [\n { id: 'apiKey', label: 'Bot API key', type: 'password', required: true },\n ],\n endpointFields: [\n {\n id: 'type',\n label: 'Destination type',\n type: 'select',\n required: true,\n options: [\n { value: 'stream', label: 'Stream' },\n { value: 'private', label: 'Private message' },\n ],\n },\n {\n id: 'to',\n label: 'Stream or recipient',\n type: 'string',\n required: true,\n },\n { id: 'topic', label: 'Topic', type: 'string' },\n ],\n createSender: async (account) => new ZulipSender(account),\n });\n\n registerBuiltinMessagingProvider({\n id: 'telegram',\n label: 'Telegram',\n channel: 'telegram',\n available: true,\n configurationFields: [],\n credentialFields: [\n { id: 'botToken', label: 'Bot token', type: 'password', required: true },\n ],\n endpointFields: [\n { id: 'chatId', label: 'Chat ID', type: 'string', required: true },\n { id: 'threadId', label: 'Topic/thread ID', type: 'number' },\n ],\n createSender: async (account) => new TelegramSender(account),\n });\n\n registerBuiltinMessagingProvider({\n id: 'sms',\n label: 'SMS (provider required)',\n channel: 'sms',\n available: false,\n configurationFields: [],\n credentialFields: [],\n endpointFields: [\n {\n id: 'phoneNumber',\n label: 'Phone number',\n type: 'string',\n required: true,\n },\n ],\n });\n}\n"],"mappings":";;AAQO,IAAM,iBAAN,MAAuD;CAG5D,YACmB,SACA,UAAwB,WAAW,OACpD;EAFiB,KAAA,UAAA;EACA,KAAA,UAAA;CAChB;CAFgB;CACA;CAJV,eAAe;CAOxB,UAAmB;EACjB,OAAO,KAAK,QAAQ,YAAY,KAAK,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GAAE,IAAI;GAAY,OAAO;GAAa,MAAM;GAAY,UAAU;EAAK,CACzE;EACA,gBAAgB,CACd;GAAE,IAAI;GAAU,OAAO;GAAW,MAAM;GAAU,UAAU;EAAK,GACjE;GAAE,IAAI;GAAY,OAAO;GAAmB,MAAM;EAAS,CAC7D;EACA,cAAc,OAAO,YAAY,IAAI,eAAe,OAAO;CAC7D,CAAC;CAED,iCAAiC;EAC/B,IAAI;EACJ,OAAO;EACP,SAAS;EACT,WAAW;EACX,qBAAqB,CAAC;EACtB,kBAAkB,CAAC;EACnB,gBAAgB,CACd;GACE,IAAI;GACJ,OAAO;GACP,MAAM;GACN,UAAU;EACZ,CACF;CACF,CAAC;AACH"}
|
|
@@ -5,6 +5,12 @@ import { SmrtCollection } from '@happyvertical/smrt-core';
|
|
|
5
5
|
import { Attachment } from "../models/Attachment.js";
|
|
6
6
|
export declare class AttachmentCollection extends SmrtCollection<Attachment> {
|
|
7
7
|
static readonly _itemClass: typeof Attachment;
|
|
8
|
+
/**
|
|
9
|
+
* Fill `accountId` on attachments saved before the column existed, from
|
|
10
|
+
* their message. Run once per tenant after upgrading; safe to repeat.
|
|
11
|
+
* Returns the number of rows updated.
|
|
12
|
+
*/
|
|
13
|
+
backfillAccountIds(): Promise<number>;
|
|
8
14
|
/**
|
|
9
15
|
* Get attachments for a message
|
|
10
16
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AttachmentCollection.d.ts","sourceRoot":"","sources":["../../src/collections/AttachmentCollection.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;
|
|
1
|
+
{"version":3,"file":"AttachmentCollection.d.ts","sourceRoot":"","sources":["../../src/collections/AttachmentCollection.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAG1D,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAsB,CAAC;A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MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;QACf,QAAQ,EAAE,MAAM,CAAC;QACjB,UAAU,EAAE,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;KAC1C,CAAC;IA8Ba,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;IAQvD,UAAU,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;IAIrC,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;CAO1E"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mailbox connect through a generic OAuth 2.0 / OIDC provider, on the shared
|
|
3
|
+
* credential connect kernel in `@happyvertical/smrt-secrets/connect`.
|
|
4
|
+
*
|
|
5
|
+
* A mail server's own OAuth (for example a self-hosted Stalwart) issues the
|
|
6
|
+
* token: the host describes it as a {@link MailOAuthProvider} (issuer or
|
|
7
|
+
* explicit endpoints, scopes, and the non-secret account configuration such as
|
|
8
|
+
* the JMAP or IMAP endpoint) and mounts two routes that call
|
|
9
|
+
* {@link startMailOAuthConnect} and {@link completeMailOAuthConnect}. The
|
|
10
|
+
* single-use state is bound to the tenant and to the signed-in user, who
|
|
11
|
+
* becomes the account owner. Tokens go to smrt-secrets, never to columns.
|
|
12
|
+
*
|
|
13
|
+
* No role checks live here: authorize the user before calling.
|
|
14
|
+
*
|
|
15
|
+
* @packageDocumentation
|
|
16
|
+
*/
|
|
17
|
+
import { type SmrtClassOptions } from '@happyvertical/smrt-core';
|
|
18
|
+
import { ConnectError, type OAuth2Endpoints, type OAuthClientCredentials } from '@happyvertical/smrt-secrets/connect';
|
|
19
|
+
import { EmailAccount } from './models/EmailAccount.js';
|
|
20
|
+
export { ConnectError };
|
|
21
|
+
/** How one mail server's OAuth is reached. Built by the host. */
|
|
22
|
+
export interface MailOAuthProvider {
|
|
23
|
+
/** Stable key for this server, for example `stalwart`. */
|
|
24
|
+
id: string;
|
|
25
|
+
/** Shown in user-facing messages. */
|
|
26
|
+
label: string;
|
|
27
|
+
/** OIDC issuer for discovery; or give `endpoints`. */
|
|
28
|
+
issuer?: string;
|
|
29
|
+
endpoints?: OAuth2Endpoints;
|
|
30
|
+
scopes: string[];
|
|
31
|
+
clientAuth?: 'basic' | 'post';
|
|
32
|
+
authorizeParams?: Record<string, string>;
|
|
33
|
+
/** The registered messaging provider the account uses (`imap`, `smtp`, ...). */
|
|
34
|
+
messagingProviderId: string;
|
|
35
|
+
/** Non-secret account settings: this account's own endpoint. */
|
|
36
|
+
configuration: Record<string, unknown>;
|
|
37
|
+
}
|
|
38
|
+
interface MailConnectContext {
|
|
39
|
+
options: SmrtClassOptions;
|
|
40
|
+
tenantId: string;
|
|
41
|
+
/** The signed-in user. Required: they become the owner. */
|
|
42
|
+
userId: string;
|
|
43
|
+
provider: MailOAuthProvider;
|
|
44
|
+
client: OAuthClientCredentials;
|
|
45
|
+
/** The callback URL registered with the mail server's OAuth. */
|
|
46
|
+
redirectUri: string;
|
|
47
|
+
fetch?: typeof fetch;
|
|
48
|
+
}
|
|
49
|
+
export interface StartMailOAuthConnectOptions extends MailConnectContext {
|
|
50
|
+
/** Same-origin path to return to after the callback. */
|
|
51
|
+
returnTo?: string;
|
|
52
|
+
scopes?: string[];
|
|
53
|
+
/** State lifetime in ms. Default 10 minutes. */
|
|
54
|
+
ttlMs?: number;
|
|
55
|
+
}
|
|
56
|
+
export interface CompleteMailOAuthConnectOptions extends MailConnectContext {
|
|
57
|
+
query: {
|
|
58
|
+
code?: string | null;
|
|
59
|
+
state?: string | null;
|
|
60
|
+
error?: string | null;
|
|
61
|
+
};
|
|
62
|
+
/** Display name for a newly created account. Defaults to the address. */
|
|
63
|
+
name?: string;
|
|
64
|
+
label?: string | null;
|
|
65
|
+
}
|
|
66
|
+
export interface CompletedMailOAuthConnect {
|
|
67
|
+
account: EmailAccount;
|
|
68
|
+
created: boolean;
|
|
69
|
+
/** The same-origin path stored at start, for the host to redirect to. */
|
|
70
|
+
returnTo: string | null;
|
|
71
|
+
}
|
|
72
|
+
/** Begin a connect: returns the URL to redirect the user to. */
|
|
73
|
+
export declare function startMailOAuthConnect(options: StartMailOAuthConnectOptions): Promise<{
|
|
74
|
+
authorizeUrl: string;
|
|
75
|
+
}>;
|
|
76
|
+
/**
|
|
77
|
+
* Finish a connect from the mail server's callback. Creates the account owned
|
|
78
|
+
* by the signed-in user, or reconnects one that user already owns; an account
|
|
79
|
+
* owned by someone else (or by no one) is never taken over this way.
|
|
80
|
+
*/
|
|
81
|
+
export declare function completeMailOAuthConnect(options: CompleteMailOAuthConnectOptions): Promise<CompletedMailOAuthConnect>;
|
|
82
|
+
//# sourceMappingURL=connect.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect.d.ts","sourceRoot":"","sources":["../src/connect.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAEL,KAAK,gBAAgB,EACtB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAGL,YAAY,EAMZ,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC5B,MAAM,qCAAqC,CAAC;AAG7C,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAGxD,OAAO,EAAE,YAAY,EAAE,CAAC;AAExB,iEAAiE;AACjE,MAAM,WAAW,iBAAiB;IAChC,0DAA0D;IAC1D,EAAE,EAAE,MAAM,CAAC;IACX,qCAAqC;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,sDAAsD;IACtD,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACzC,gFAAgF;IAChF,mBAAm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AAO,EAAE,+BAA+B,GACvC,OAAO,CAAC,yBAAyB,CAAC,CA2GpC"}
|
package/dist/connect.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { r as EmailAccount, t as EmailAccountCollection } from "./chunks/EmailAccountCollection-CHizpsxL.js";
|
|
2
|
+
import { withTenant } from "./host.js";
|
|
3
|
+
import { ObjectRegistry } from "@happyvertical/smrt-core";
|
|
4
|
+
import { ConnectError, ConnectStateCollection, beginConnect, buildOAuth2AuthorizeUrl, consumeConnect, discoverOidcEndpoints, exchangeOAuth2Code, fetchOidcUserInfo } from "@happyvertical/smrt-secrets/connect";
|
|
5
|
+
//#region src/connect.ts
|
|
6
|
+
var kindOf = (provider) => `mail:${provider.id}`;
|
|
7
|
+
function requireContext(options) {
|
|
8
|
+
if (!options.tenantId) throw new ConnectError("missing_tenant", "A tenant is required to connect a mailbox.");
|
|
9
|
+
if (!options.userId) throw new ConnectError("forbidden", "Sign in before connecting a mailbox.");
|
|
10
|
+
if (!options.client.clientId || !options.client.clientSecret) throw new ConnectError("missing_client_credentials", `${options.provider.label} is not configured with an OAuth client.`);
|
|
11
|
+
}
|
|
12
|
+
async function resolveEndpoints(options) {
|
|
13
|
+
const { provider } = options;
|
|
14
|
+
if (provider.endpoints) return provider.endpoints;
|
|
15
|
+
if (!provider.issuer) throw new ConnectError("discovery_failed", `${provider.label} has no issuer or endpoints configured.`);
|
|
16
|
+
return discoverOidcEndpoints(provider.issuer, provider.label, options.fetch ?? fetch);
|
|
17
|
+
}
|
|
18
|
+
async function startMailOAuthConnect(options) {
|
|
19
|
+
requireContext(options);
|
|
20
|
+
const endpoints = await resolveEndpoints(options);
|
|
21
|
+
const scopes = options.scopes ?? options.provider.scopes;
|
|
22
|
+
return withTenant({ tenantId: options.tenantId }, async () => {
|
|
23
|
+
const { state, codeChallenge } = await beginConnect({
|
|
24
|
+
store: (await ConnectStateCollection.create(options.options)).asStore(),
|
|
25
|
+
kind: kindOf(options.provider),
|
|
26
|
+
tenantId: options.tenantId,
|
|
27
|
+
userId: options.userId,
|
|
28
|
+
redirectUri: options.redirectUri,
|
|
29
|
+
scopes,
|
|
30
|
+
usesPkce: true,
|
|
31
|
+
returnTo: options.returnTo,
|
|
32
|
+
ttlMs: options.ttlMs
|
|
33
|
+
});
|
|
34
|
+
return { authorizeUrl: buildOAuth2AuthorizeUrl({
|
|
35
|
+
label: options.provider.label,
|
|
36
|
+
clientAuth: options.provider.clientAuth,
|
|
37
|
+
authorizeParams: options.provider.authorizeParams,
|
|
38
|
+
...endpoints
|
|
39
|
+
}, {
|
|
40
|
+
client: options.client,
|
|
41
|
+
redirectUri: options.redirectUri,
|
|
42
|
+
state,
|
|
43
|
+
scopes,
|
|
44
|
+
codeChallenge
|
|
45
|
+
}) };
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
async function completeMailOAuthConnect(options) {
|
|
49
|
+
requireContext(options);
|
|
50
|
+
const { provider } = options;
|
|
51
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
52
|
+
return withTenant({ tenantId: options.tenantId }, async () => {
|
|
53
|
+
const { record, code } = await consumeConnect({
|
|
54
|
+
store: (await ConnectStateCollection.create(options.options)).asStore(),
|
|
55
|
+
kind: kindOf(provider),
|
|
56
|
+
tenantId: options.tenantId,
|
|
57
|
+
userId: options.userId,
|
|
58
|
+
redirectUri: options.redirectUri,
|
|
59
|
+
query: options.query,
|
|
60
|
+
label: provider.label
|
|
61
|
+
});
|
|
62
|
+
const endpoints = await resolveEndpoints(options);
|
|
63
|
+
const config = {
|
|
64
|
+
label: provider.label,
|
|
65
|
+
clientAuth: provider.clientAuth,
|
|
66
|
+
...endpoints
|
|
67
|
+
};
|
|
68
|
+
const tokens = await exchangeOAuth2Code(config, {
|
|
69
|
+
client: options.client,
|
|
70
|
+
redirectUri: record.redirectUri,
|
|
71
|
+
code,
|
|
72
|
+
codeVerifier: record.codeVerifier,
|
|
73
|
+
fetch: fetchImpl
|
|
74
|
+
});
|
|
75
|
+
const profile = await fetchOidcUserInfo(config, tokens.accessToken, fetchImpl);
|
|
76
|
+
const address = profile.email ?? profile.preferredUsername;
|
|
77
|
+
if (!address) throw new ConnectError("profile_lookup_failed", `${provider.label} did not say which mailbox this is.`);
|
|
78
|
+
const matches = await (await EmailAccountCollection.create(options.options)).list({ where: {
|
|
79
|
+
tenantId: options.tenantId,
|
|
80
|
+
providerType: provider.messagingProviderId,
|
|
81
|
+
email: address
|
|
82
|
+
} });
|
|
83
|
+
const existing = matches.find((match) => match.ownerUserId === options.userId);
|
|
84
|
+
if (!existing && matches.length) throw new ConnectError("forbidden", "This mailbox is already connected by someone else.");
|
|
85
|
+
const account = existing ?? new (ObjectRegistry.resolveEffectiveConstructor(EmailAccount))({
|
|
86
|
+
...options.options,
|
|
87
|
+
tenantId: options.tenantId,
|
|
88
|
+
name: options.name?.trim() || address,
|
|
89
|
+
email: address,
|
|
90
|
+
providerType: provider.messagingProviderId,
|
|
91
|
+
ownerUserId: options.userId
|
|
92
|
+
});
|
|
93
|
+
if (!existing) await account.initialize();
|
|
94
|
+
if (options.label !== void 0) account.label = options.label?.trim() || null;
|
|
95
|
+
account.setConfiguration({
|
|
96
|
+
...provider.configuration,
|
|
97
|
+
email: address
|
|
98
|
+
});
|
|
99
|
+
account.isActive = true;
|
|
100
|
+
account.connectionStatus = "connected";
|
|
101
|
+
account.statusMessage = null;
|
|
102
|
+
account.updatedAt = /* @__PURE__ */ new Date();
|
|
103
|
+
await account.save();
|
|
104
|
+
await account.setCredentials({
|
|
105
|
+
authType: "oauth2",
|
|
106
|
+
accessToken: tokens.accessToken,
|
|
107
|
+
...tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {},
|
|
108
|
+
...tokens.tokenType ? { tokenType: tokens.tokenType } : {},
|
|
109
|
+
...tokens.expiresAt ? { expiresAt: tokens.expiresAt.toISOString() } : {},
|
|
110
|
+
scopes: tokens.scopes.length ? tokens.scopes : record.scopes,
|
|
111
|
+
tokenUrl: endpoints.tokenUrl,
|
|
112
|
+
clientId: options.client.clientId,
|
|
113
|
+
clientSecret: options.client.clientSecret,
|
|
114
|
+
username: address
|
|
115
|
+
}, { description: `${provider.label} sign-in for ${address}` });
|
|
116
|
+
return {
|
|
117
|
+
account,
|
|
118
|
+
created: !existing,
|
|
119
|
+
returnTo: record.returnTo ?? null
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
//#endregion
|
|
124
|
+
export { ConnectError, completeMailOAuthConnect, startMailOAuthConnect };
|
|
125
|
+
|
|
126
|
+
//# sourceMappingURL=connect.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"connect.js","names":[],"sources":["../src/connect.ts"],"sourcesContent":["/**\n * Mailbox connect through a generic OAuth 2.0 / OIDC provider, on the shared\n * credential connect kernel in `@happyvertical/smrt-secrets/connect`.\n *\n * A mail server's own OAuth (for example a self-hosted Stalwart) issues the\n * token: the host describes it as a {@link MailOAuthProvider} (issuer or\n * explicit endpoints, scopes, and the non-secret account configuration such as\n * the JMAP or IMAP endpoint) and mounts two routes that call\n * {@link startMailOAuthConnect} and {@link completeMailOAuthConnect}. The\n * single-use state is bound to the tenant and to the signed-in user, who\n * becomes the account owner. Tokens go to smrt-secrets, never to columns.\n *\n * No role checks live here: authorize the user before calling.\n *\n * @packageDocumentation\n */\n\nimport {\n ObjectRegistry,\n type SmrtClassOptions,\n} from '@happyvertical/smrt-core';\nimport {\n beginConnect,\n buildOAuth2AuthorizeUrl,\n ConnectError,\n ConnectStateCollection,\n consumeConnect,\n discoverOidcEndpoints,\n exchangeOAuth2Code,\n fetchOidcUserInfo,\n type OAuth2Endpoints,\n type OAuthClientCredentials,\n} from '@happyvertical/smrt-secrets/connect';\nimport { EmailAccountCollection } from './collections/EmailAccountCollection.js';\nimport { withTenant } from './host.js';\nimport { EmailAccount } from './models/EmailAccount.js';\nimport type { ProviderType } from './types.js';\n\nexport { ConnectError };\n\n/** How one mail server's OAuth is reached. Built by the host. */\nexport interface MailOAuthProvider {\n /** Stable key for this server, for example `stalwart`. */\n id: string;\n /** Shown in user-facing messages. */\n label: string;\n /** OIDC issuer for discovery; or give `endpoints`. */\n issuer?: string;\n endpoints?: OAuth2Endpoints;\n scopes: string[];\n clientAuth?: 'basic' | 'post';\n authorizeParams?: Record<string, string>;\n /** The registered messaging provider the account uses (`imap`, `smtp`, ...). */\n messagingProviderId: string;\n /** Non-secret account settings: this account's own endpoint. */\n configuration: Record<string, unknown>;\n}\n\ninterface MailConnectContext {\n options: SmrtClassOptions;\n tenantId: string;\n /** The signed-in user. Required: they become the owner. */\n userId: string;\n provider: MailOAuthProvider;\n client: OAuthClientCredentials;\n /** The callback URL registered with the mail server's OAuth. */\n redirectUri: string;\n fetch?: typeof fetch;\n}\n\nexport interface StartMailOAuthConnectOptions extends MailConnectContext {\n /** Same-origin path to return to after the callback. */\n returnTo?: string;\n scopes?: string[];\n /** State lifetime in ms. Default 10 minutes. */\n ttlMs?: number;\n}\n\nexport interface CompleteMailOAuthConnectOptions extends MailConnectContext {\n query: { code?: string | null; state?: string | null; error?: string | null };\n /** Display name for a newly created account. Defaults to the address. */\n name?: string;\n label?: string | null;\n}\n\nexport interface CompletedMailOAuthConnect {\n account: EmailAccount;\n created: boolean;\n /** The same-origin path stored at start, for the host to redirect to. */\n returnTo: string | null;\n}\n\nconst kindOf = (provider: MailOAuthProvider) => `mail:${provider.id}`;\n\nfunction requireContext(options: MailConnectContext): void {\n if (!options.tenantId) {\n throw new ConnectError(\n 'missing_tenant',\n 'A tenant is required to connect a mailbox.',\n );\n }\n if (!options.userId) {\n throw new ConnectError('forbidden', 'Sign in before connecting a mailbox.');\n }\n if (!options.client.clientId || !options.client.clientSecret) {\n throw new ConnectError(\n 'missing_client_credentials',\n `${options.provider.label} is not configured with an OAuth client.`,\n );\n }\n}\n\nasync function resolveEndpoints(\n options: MailConnectContext,\n): Promise<OAuth2Endpoints> {\n const { provider } = options;\n if (provider.endpoints) return provider.endpoints;\n if (!provider.issuer) {\n throw new ConnectError(\n 'discovery_failed',\n `${provider.label} has no issuer or endpoints configured.`,\n );\n }\n return discoverOidcEndpoints(\n provider.issuer,\n provider.label,\n options.fetch ?? fetch,\n );\n}\n\n/** Begin a connect: returns the URL to redirect the user to. */\nexport async function startMailOAuthConnect(\n options: StartMailOAuthConnectOptions,\n): Promise<{ authorizeUrl: string }> {\n requireContext(options);\n const endpoints = await resolveEndpoints(options);\n const scopes = options.scopes ?? options.provider.scopes;\n return withTenant({ tenantId: options.tenantId }, async () => {\n const store = (\n await ConnectStateCollection.create(options.options)\n ).asStore();\n const { state, codeChallenge } = await beginConnect({\n store,\n kind: kindOf(options.provider),\n tenantId: options.tenantId,\n userId: options.userId,\n redirectUri: options.redirectUri,\n scopes,\n usesPkce: true,\n returnTo: options.returnTo,\n ttlMs: options.ttlMs,\n });\n return {\n authorizeUrl: buildOAuth2AuthorizeUrl(\n {\n label: options.provider.label,\n clientAuth: options.provider.clientAuth,\n authorizeParams: options.provider.authorizeParams,\n ...endpoints,\n },\n {\n client: options.client,\n redirectUri: options.redirectUri,\n state,\n scopes,\n codeChallenge,\n },\n ),\n };\n });\n}\n\n/**\n * Finish a connect from the mail server's callback. Creates the account owned\n * by the signed-in user, or reconnects one that user already owns; an account\n * owned by someone else (or by no one) is never taken over this way.\n */\nexport async function completeMailOAuthConnect(\n options: CompleteMailOAuthConnectOptions,\n): Promise<CompletedMailOAuthConnect> {\n requireContext(options);\n const { provider } = options;\n const fetchImpl = options.fetch ?? fetch;\n return withTenant({ tenantId: options.tenantId }, async () => {\n const store = (\n await ConnectStateCollection.create(options.options)\n ).asStore();\n const { record, code } = await consumeConnect({\n store,\n kind: kindOf(provider),\n tenantId: options.tenantId,\n userId: options.userId,\n redirectUri: options.redirectUri,\n query: options.query,\n label: provider.label,\n });\n const endpoints = await resolveEndpoints(options);\n const config = {\n label: provider.label,\n clientAuth: provider.clientAuth,\n ...endpoints,\n };\n const tokens = await exchangeOAuth2Code(config, {\n client: options.client,\n redirectUri: record.redirectUri,\n code,\n codeVerifier: record.codeVerifier,\n fetch: fetchImpl,\n });\n const profile = await fetchOidcUserInfo(\n config,\n tokens.accessToken,\n fetchImpl,\n );\n const address = profile.email ?? profile.preferredUsername;\n if (!address) {\n throw new ConnectError(\n 'profile_lookup_failed',\n `${provider.label} did not say which mailbox this is.`,\n );\n }\n\n const accounts = await EmailAccountCollection.create(options.options);\n const matches = (await accounts.list({\n where: {\n tenantId: options.tenantId,\n providerType: provider.messagingProviderId,\n email: address,\n },\n })) as EmailAccount[];\n // Reconnect the signed-in user's own account; any other match (someone\n // else's, or an ownerless legacy account) is never taken over this way.\n const existing = matches.find(\n (match) => match.ownerUserId === options.userId,\n );\n if (!existing && matches.length) {\n throw new ConnectError(\n 'forbidden',\n 'This mailbox is already connected by someone else.',\n );\n }\n\n const account =\n existing ??\n new (ObjectRegistry.resolveEffectiveConstructor(EmailAccount))({\n ...options.options,\n tenantId: options.tenantId,\n name: options.name?.trim() || address,\n email: address,\n providerType: provider.messagingProviderId as ProviderType,\n ownerUserId: options.userId,\n });\n if (!existing) await account.initialize();\n if (options.label !== undefined) {\n account.label = options.label?.trim() || null;\n }\n account.setConfiguration({ ...provider.configuration, email: address });\n account.isActive = true;\n account.connectionStatus = 'connected';\n account.statusMessage = null;\n account.updatedAt = new Date();\n await account.save();\n // The client secret travels with the token so a sync can refresh it.\n await account.setCredentials(\n {\n authType: 'oauth2',\n accessToken: tokens.accessToken,\n ...(tokens.refreshToken ? { refreshToken: tokens.refreshToken } : {}),\n ...(tokens.tokenType ? { tokenType: tokens.tokenType } : {}),\n ...(tokens.expiresAt\n ? { expiresAt: tokens.expiresAt.toISOString() }\n : {}),\n scopes: tokens.scopes.length ? tokens.scopes : record.scopes,\n tokenUrl: endpoints.tokenUrl,\n clientId: options.client.clientId,\n clientSecret: options.client.clientSecret,\n username: address,\n },\n { description: `${provider.label} sign-in for ${address}` },\n );\n return {\n account,\n created: !existing,\n returnTo: record.returnTo ?? null,\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vB,aAAa,QAAQ;EACvB,CAAC;EACH,IAAI,CAAC,UAAU,MAAM,QAAQ,WAAW;EACxC,IAAI,QAAQ,UAAU,KAAA,GACpB,QAAQ,QAAQ,QAAQ,OAAO,KAAK,KAAK;EAE3C,QAAQ,iBAAiB;GAAE,GAAG,SAAS;GAAe,OAAO;EAAQ,CAAC;EACtE,QAAQ,WAAW;EACnB,QAAQ,mBAAmB;EAC3B,QAAQ,gBAAgB;EACxB,QAAQ,4BAAY,IAAI,KAAK;EAC7B,MAAM,QAAQ,KAAK;EAEnB,MAAM,QAAQ,eACZ;GACE,UAAU;GACV,aAAa,OAAO;GACpB,GAAI,OAAO,eAAe,EAAE,cAAc,OAAO,aAAa,IAAI,CAAC;GACnE,GAAI,OAAO,YAAY,EAAE,WAAW,OAAO,UAAU,IAAI,CAAC;GAC1D,GAAI,OAAO,YACP,EAAE,WAAW,OAAO,UAAU,YAAY,EAAE,IAC5C,CAAC;GACL,QAAQ,OAAO,OAAO,SAAS,OAAO,SAAS,OAAO;GACtD,UAAU,UAAU;GACpB,UAAU,QAAQ,OAAO;GACzB,cAAc,QAAQ,OAAO;GAC7B,UAAU;EACZ,GACA,EAAE,aAAa,GAAG,SAAS,MAAK,eAAgB,UAAU,CAC5D;EACA,OAAO;GACL;GACA,SAAS,CAAC;GACV,UAAU,OAAO,YAAY;EAC/B;CACF,CAAC;AACH"}
|
package/dist/index.d.ts
CHANGED
|
@@ -6,6 +6,9 @@
|
|
|
6
6
|
* @packageDocumentation
|
|
7
7
|
*/
|
|
8
8
|
import './__smrt-register__.js';
|
|
9
|
+
export { assertMailAccess, canAccessMailAccount, configureMailAccess, decideMailAccess, deniedMailAccountIds, type GrantMailAccessInput, isMailScope, MAIL_ACCOUNT_RESOURCE_TYPE, MAIL_SCOPES, type MailAccessAdmin, type MailAccessConfig, type MailAccessDecision, MailAccessError, type MailAccessReason, type MailAccessResolver, type MailAccessResolverContext, MailAccessService, type MailAccessSubject, type MailPrincipal, type MailScope, mailScopePermission, resetMailAccess, runWithMailSystemAccess, } from './access.js';
|
|
10
|
+
export type { MailSyncOptions, MailSyncResult, MailSyncSkipReason, } from './mail-sync.js';
|
|
11
|
+
export { CHANGE_FEED_PROVIDERS, type EnqueueMailSyncOptions, enqueueDueMailSyncs, enqueueMailSync, MAIL_SYNC_QUEUE, mailSyncDedupeKey, } from './mail-sync-jobs.js';
|
|
9
12
|
export { AccountCollection } from "./collections/AccountCollection.js";
|
|
10
13
|
export { AttachmentCollection } from "./collections/AttachmentCollection.js";
|
|
11
14
|
export { MessageCollection } from "./collections/MessageCollection.js";
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,wBAAwB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAKH,OAAO,wBAAwB,CAAC;AAQhC,OAAO,EACL,gBAAgB,EAChB,oBAAoB,EACpB,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,EACpB,KAAK,oBAAoB,EACzB,WAAW,EACX,0BAA0B,EAC1B,WAAW,EACX,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,eAAe,EACf,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,KAAK,yBAAyB,EAC9B,iBAAiB,EACjB,KAAK,iBAAiB,EACtB,KAAK,aAAa,EAClB,KAAK,SAAS,EACd,mBAAmB,EACnB,eAAe,EACf,uBAAuB,GACxB,MAAM,aAAa,CAAC;AACrB,YAAY,EACV,eAAe,EACf,cAAc,EACd,kBAAkB,GACnB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,qBAAqB,EACrB,KAAK,sBAAsB,EAC3B,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,iBAAiB,GAClB,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