diff --git a/.changeset/34730-slack-dm-delivery.md b/.changeset/34730-slack-dm-delivery.md new file mode 100644 index 00000000000..f7a750b5d36 --- /dev/null +++ b/.changeset/34730-slack-dm-delivery.md @@ -0,0 +1,21 @@ +--- +'@objectstack/service-messaging': minor +'@objectstack/connector-slack': patch +'@objectstack/plugin-approvals': patch +'@objectstack/spec': patch +'@objectstack/cli': patch +--- + +Clause-②: yes (widening) +Metadata-protocol: added + +feat(messaging): Slack DM delivery — a `slack` channel, a per-person link store, approval requests by DM + +An organization can now receive notifications in Slack, as direct messages to each person who connected their own Slack user (ADR-0013 addendum of 2026-11-19, step 2 of #34730). + +- **The install.** An organization administrator (`setup.write` in their current organization) installs the organization's own Slack app with `PUT /api/v1/messaging/slack/account` `{ token }`. Slack proves the bot token (`auth.test`) before it is saved. The app's bot token needs the scopes `chat:write`, `im:write`, `users:read` and `users:read.email` (the methods called are `auth.test`, `users.lookupByEmail`, `conversations.open` and `chat.postMessage`); `auth.test` does not check scopes, so an app without `users:read.email` installs and every proposal then answers 502. The token is kept in `sys_channel_account.bot_token`, a `secret` field: encrypted at rest by the host's `ICryptoProvider`, masked on every read, never returned by any route, and read only by the server when it calls Slack. `GET` and `DELETE` on the same route read and remove the install. +- **A person's link.** `POST /api/v1/messaging/me/slack-link/proposal` proposes a link by the person's email (Slack `users.lookupByEmail`); it delivers nothing until the person confirms it with `POST /api/v1/messaging/me/slack-link/confirm`. A Slack link is proposed only for a verified email and names no one before it is confirmed. `GET` and `DELETE /api/v1/messaging/me/slack-link` read and remove it. An administrator lists links with `GET /api/v1/messaging/slack/links` and removes one with `DELETE /api/v1/messaging/slack/links/:id`; the person is told by inbox and e-mail (topic `messaging.slack_link_removed`) and may link again. A link goes when the person is deleted, banned, or leaves the organization. Links are `sys_channel_user_link` rows; every write names who acted, so the platform's write audit records each one. +- **The channel, only where connector-slack is composed.** `slack` is registered beside inbox, email, sms and push only on a composition where connector-slack's `slack` client service resolves at boot: `ConnectorSlackPlugin` now registers that service, which sends with a caller-held token. On such a composition, and only there, the `/automation` save doors accept `slack` on a `notify` node, and `GET /api/v1/messaging/preference-options` and `GET /api/v1/messaging/me/preferences` list `slack` as a channel. A `notify` node naming `slack` delivers only where connector-slack is composed, the organization installed Slack and the recipient confirmed a link. Without connector-slack, those doors answer as before: a `notify` node naming `slack` is refused 400, and neither preference door lists it. It sends `conversations.open` then `chat.postMessage` with the notification's title linked to its deep link, made absolute under `OS_AUTH_URL` / `OS_BASE_URL`. Preferences, digest and quiet hours apply as on every channel. A recipient with no confirmed link is skipped before any delivery row is written, so nothing is dead-lettered for them; a refused token stops delivery on that install until an administrator sets it again; a rate limit is retried. +- **Approval requests.** `approval.requested` also asks for `slack`, beside inbox and e-mail, only while the `slack` channel is registered and mounted (connector-slack composed). +- `MessagingChannel` gains an optional `reachableRecipients(ctx, { organizationId, recipients })`, consulted once per channel per emit after preferences. A channel without it reaches every recipient, as before. +- `PLATFORM_OBJECTS_BY_PACKAGE['service-messaging']` lists `sys_channel_account` and `sys_channel_user_link`, and the organization ownership inventory gives both a row. diff --git a/docs/adr/0013-bidirectional-messaging.md b/docs/adr/0013-bidirectional-messaging.md index 443135b571e..a715a8191ea 100644 --- a/docs/adr/0013-bidirectional-messaging.md +++ b/docs/adr/0013-bidirectional-messaging.md @@ -815,5 +815,18 @@ Step 2 also says where the open tier keeps an organization's supplied token at r `credentials_ref` into `service-secrets` is Draft and the vault stays enterprise; ADR-0143 and ADR-0100 give the open connector credential path. -**Open — not ruled:** what a person's email that matches more than one Slack user proposes (§8 -risk 4 is Draft); and a manual connect for a person whose email matches no Slack user. +**Step 2 chose** (the change that builds it, under #34730): the administrator doors check +`setup.write` held in the caller's current organization (`ExecutionContext.systemPermissions`, the +capability the in-app message door already asks of an organization administrator), not +`isPlatformAdmin`. The token is `sys_channel_account.bot_token`, a `secret` field (ADR-0100), the +channel `sys_connector_credential` uses (ADR-0143): encrypted on write by the host's +`ICryptoProvider` with the organization in its context, held in `sys_secret`, masked on every read, +and dereferenced only server side through `resolveSecretField()`; the object is engine-owned with +its data API closed. A Slack link is proposed only for a verified email and names no one before it +is confirmed. + +**Open — not ruled:** what a person's email that matches more than one Slack user proposes (Risks & +open questions, item 4, is Draft, and it describes the converse — two `sys_user`s sharing one email — +so neither multi-match case is ruled; step 2 links one Slack user to at most one person per install, +and proposes nothing to a second person whose email resolves to an already linked Slack user); and a +manual connect for a person whose email matches no Slack user. diff --git a/packages/cli/src/utils/organization-ownership-inventory.ts b/packages/cli/src/utils/organization-ownership-inventory.ts index 71478b397d3..4360da43cce 100644 --- a/packages/cli/src/utils/organization-ownership-inventory.ts +++ b/packages/cli/src/utils/organization-ownership-inventory.ts @@ -839,6 +839,11 @@ export const ORGANIZATION_OWNERSHIP_INVENTORY: readonly InventoryEntry[] = [ { object: 'sys_mailbox', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] }, { object: 'sys_mail_message', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach); the message's mailbox carries the organization`, anchors: [parent('mailbox_id', 'sys_mailbox')] }, { object: 'sys_mail_association', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach); the association's message carries the organization`, anchors: [parent('mail_message_id', 'sys_mail_message')] }, + // Slack DM delivery (`@objectstack/service-messaging`, #34730): the link + // store writes an install and each link with its organization stamped, so a + // NULL row has no producer; a link's install is where one would take it. + { object: 'sys_channel_account', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] }, + { object: 'sys_channel_user_link', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach); the link's install carries the organization`, anchors: [parent('account_id', 'sys_channel_account')] }, // Ownership queues (`@objectstack/plugin-sharing`, ADR-0142): an organization // authors its queues, their members and its own assignment rules, and the // assignment engine writes its cursor, each under that organization. A diff --git a/packages/connectors/connector-slack/src/connector-slack-plugin.test.ts b/packages/connectors/connector-slack/src/connector-slack-plugin.test.ts index 74593f34fbd..6ed07d02ec4 100644 --- a/packages/connectors/connector-slack/src/connector-slack-plugin.test.ts +++ b/packages/connectors/connector-slack/src/connector-slack-plugin.test.ts @@ -4,6 +4,7 @@ import { describe, it, expect } from 'vitest'; import { LiteKernel } from '@objectstack/core'; import { AutomationServicePlugin, type AutomationEngine } from '@objectstack/service-automation'; import { ConnectorSlackPlugin } from './connector-slack-plugin.js'; +import type { SlackClientService } from './slack-connector.js'; /** A fetch stub mimicking the Slack Web API (HTTP 200 + ok in the body). */ function stubSlack() { @@ -76,3 +77,25 @@ describe('ConnectorSlackPlugin — end to end with the automation engine', () => await kernel.shutdown(); }); }); + +describe('ConnectorSlackPlugin — the `slack` client service', () => { + it('hands out a client for the caller\'s own token, over the plugin\'s transport options', async () => { + const { impl, calls } = stubSlack(); + const kernel = new LiteKernel(); + kernel.use(new AutomationServicePlugin()); + kernel.use(new ConnectorSlackPlugin({ token: 'xoxb-flow-token', fetchImpl: impl })); + await kernel.bootstrap(); + + const slack = kernel.getService('slack'); + const out = await slack.client('xoxb-organization-token').call({ method: 'conversations.open', params: { users: 'U1' } }); + + expect(out.ok).toBe(true); + expect(calls).toHaveLength(1); + expect(calls[0].url).toBe('https://slack.com/api/conversations.open'); + // The caller's token, never the plugin's static one. + expect((calls[0].init.headers as Record).Authorization).toBe('Bearer xoxb-organization-token'); + expect(calls[0].init.body).toBe('{"users":"U1"}'); + + await kernel.shutdown(); + }); +}); diff --git a/packages/connectors/connector-slack/src/connector-slack-plugin.ts b/packages/connectors/connector-slack/src/connector-slack-plugin.ts index 1dbc4b6766c..2cd3c6fef03 100644 --- a/packages/connectors/connector-slack/src/connector-slack-plugin.ts +++ b/packages/connectors/connector-slack/src/connector-slack-plugin.ts @@ -2,7 +2,7 @@ import type { Plugin, PluginContext } from '@objectstack/core'; import type { Connector } from '@objectstack/spec/integration'; -import { createSlackConnector, type SlackConnectorOptions } from './slack-connector.js'; +import { createSlackClientService, createSlackConnector, type SlackConnectorOptions } from './slack-connector.js'; /** * Minimal surface of the automation engine this plugin depends on — the @@ -35,6 +35,8 @@ export class ConnectorSlackPlugin implements Plugin { name = 'com.objectstack.connector.slack'; version = '1.0.0'; type = 'standard' as const; + /** The client factory init() registers (`SlackClientService`), for the Slack DM channel. */ + providesServices = ['slack']; // Ensure the automation engine (and its connector registry) is started first. dependencies = ['com.objectstack.service-automation']; @@ -46,9 +48,12 @@ export class ConnectorSlackPlugin implements Plugin { this.options = options; } - async init(_ctx: PluginContext): Promise { - // No services to register; the connector is registered in start() once - // the automation engine is available. + async init(ctx: PluginContext): Promise { + // The client, for a token its caller holds: the messaging service's + // Slack DM channel sends with each organization's own bot token. The + // flow connector is registered in start(), once the automation engine + // is available. + ctx.registerService('slack', createSlackClientService(this.options)); } async start(ctx: PluginContext): Promise { diff --git a/packages/connectors/connector-slack/src/index.ts b/packages/connectors/connector-slack/src/index.ts index 39e956e8100..5f2bc5206e2 100644 --- a/packages/connectors/connector-slack/src/index.ts +++ b/packages/connectors/connector-slack/src/index.ts @@ -16,6 +16,8 @@ export { createSlackConnector, + createSlackClientService, + type SlackClientService, type SlackConnectorOptions, type SlackConnectorBundle, type SlackPostMessageInput, diff --git a/packages/connectors/connector-slack/src/slack-connector.ts b/packages/connectors/connector-slack/src/slack-connector.ts index 8eda2f27b21..5ee6a706bd2 100644 --- a/packages/connectors/connector-slack/src/slack-connector.ts +++ b/packages/connectors/connector-slack/src/slack-connector.ts @@ -196,6 +196,36 @@ export function createSlackConnector(opts: SlackConnectorOptions): SlackConnecto }; } +/** + * The `slack` service `ConnectorSlackPlugin` registers: this package's + * client, built for a bot token the CALLER holds. `@objectstack/service-messaging`'s + * Slack DM channel sends through it with each organization's own token + * (ADR-0022 §3, ADR-0013 addendum point 1). It reaches the client through the + * service registry, not a package import: service-messaging importing this + * package would close a workspace dependency cycle through + * `@objectstack/service-automation`. + * + * The other options (`baseUrl`, `defaultHeaders`, `fetchImpl`) apply to every + * client it builds; a static `token` among them is never used here. + */ +export interface SlackClientService { + /** + * A client for `token`: the connector's `call` action — any Web API + * method, `{ method, params }`, answered `{ ok, status, body, error }`. + */ + client(token: string): { call(input: Record): Promise> }; +} + +export function createSlackClientService(options: Omit = {}): SlackClientService { + const { token: _static, ...shared } = options as SlackConnectorOptions; + return { + client: (token) => { + const { handlers } = createSlackConnector({ ...shared, token }); + return { call: (input) => handlers.call(input, undefined) }; + }, + }; +} + function toRecord(r: SlackResult): Record { return { ok: r.ok, status: r.status, body: r.body, error: r.error }; } diff --git a/packages/plugins/plugin-approvals/package.json b/packages/plugins/plugin-approvals/package.json index 06b015144f1..cd8bdfe9fb3 100644 --- a/packages/plugins/plugin-approvals/package.json +++ b/packages/plugins/plugin-approvals/package.json @@ -35,6 +35,7 @@ "@objectstack/types": "workspace:*" }, "devDependencies": { + "@objectstack/connector-slack": "workspace:*", "@objectstack/driver-sql": "workspace:*", "@objectstack/lint": "workspace:*", "@objectstack/metadata-protocol": "workspace:*", diff --git a/packages/plugins/plugin-approvals/src/approval-requested-slack-dm.integration.test.ts b/packages/plugins/plugin-approvals/src/approval-requested-slack-dm.integration.test.ts new file mode 100644 index 00000000000..ebf0731ff75 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/approval-requested-slack-dm.integration.test.ts @@ -0,0 +1,221 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34730 step 2] An approval request also reaches an approver who connected + * Slack, by DM, carrying the e-mail's deep link. + * + * The real composition, end to end, as `approval-email-notification` drives + * it: a real `ObjectQL` over `SqlDriver` (better-sqlite3) with the `secret` + * channel wired, the real `MessagingServicePlugin` with its durable outbox and + * dispatcher, the real `ApprovalsServicePlugin`, a recording `email` + * transport, and connector-slack's real client service with Slack stubbed at + * the HTTP boundary (`fetchImpl`). The organization installs its Slack app + * and the approver links their Slack user through the link store. + * + * - a confirmed link: a `slack` delivery reaches `success`, and Slack is + * asked for a DM with the linked user whose text links the request page at + * the same absolute URL the e-mail carries; + * - the approver muted `slack`, or is in quiet hours: no DM is sent; + * - a proposed link only, or none: inbox and e-mail only — no `slack` row at + * all, so nothing to dead-letter; + * - no connector-slack composed: the request does not ask for `slack`, so no + * refusal is logged on every request. + */ + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysSecret } from '@objectstack/platform-objects'; +import { createSlackClientService } from '@objectstack/connector-slack'; +import { MessagingServicePlugin, SlackLinkStore } from '@objectstack/service-messaging'; +import type { CryptoHandle, ICryptoProvider } from '@objectstack/spec/contracts'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; +import { SysApprovalRequest } from './sys-approval-request.object.js'; +import { SysApprovalAction } from './sys-approval-action.object.js'; +import { SysApprovalApprover } from './sys-approval-approver.object.js'; +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; +import { SysApprovalToken } from './sys-approval-token.object.js'; +import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; + +const OBJECT = 'slackdm_invoice'; +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any; +const asUser = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; +const SUBMITTER = 'u_submitter'; +const APPROVER = 'u_approver'; +const ORIGIN = 'https://app.example.test'; +const TOKEN = 'xoxb-acme'; + +type Setup = 'confirmed' | 'proposed' | 'none' | 'muted' | 'quiet' | 'uncomposed'; + +/** Slack's Web API, stubbed at the HTTP boundary: every request it is sent, and Slack's answers. */ +function slackHttp() { + const requests: Array<{ method: string; auth: string; body: Record }> = []; + const answers: Record> = { + 'auth.test': { team_id: 'T1', team: 'Acme', user_id: 'UBOT' }, + 'users.lookupByEmail': { user: { id: 'UAPPROVER', real_name: 'Ada Approver' } }, + 'conversations.open': { channel: { id: 'D1' } }, + 'chat.postMessage': { ts: '1700.1' }, + }; + const fetchImpl = (async (url: string, init: RequestInit) => { + const method = String(url).replace('https://slack.com/api/', '').split('?')[0]; + requests.push({ method, auth: String((init.headers as Record).Authorization), body: JSON.parse(String(init.body)) }); + return new Response(JSON.stringify({ ok: true, ...answers[method] }), { status: 200, headers: { 'content-type': 'application/json' } }); + }) as unknown as typeof fetch; + return { fetchImpl, requests }; +} + +/** Reversible test crypto: the stored form is a transform, never the token. */ +const crypto: ICryptoProvider = { + async encrypt(plain: string): Promise { + return { id: `sec_${plain.length}`, kmsKeyId: 'local', alg: 'test', version: 1, ciphertext: Buffer.from(plain).toString('base64') }; + }, + async decrypt(handle: CryptoHandle) { return Buffer.from(handle.ciphertext, 'base64').toString(); }, + async rotateKey(handle: CryptoHandle) { return handle; }, + digest: (plain: string) => `d:${plain.length}`, + async keyedDigest(plain: string) { return `k:${plain.length}`; }, +}; + +const hhmm = (ms: number) => new Date(ms).toISOString().slice(11, 16); + +let stop: (() => Promise) | undefined; +afterEach(async () => { + try { await stop?.(); } catch { /* noop */ } + stop = undefined; + vi.unstubAllEnvs(); +}); + +async function boot(setup: Setup) { + vi.stubEnv('OS_AUTH_URL', undefined); + vi.stubEnv('BETTER_AUTH_URL', undefined); + vi.stubEnv('OS_BASE_URL', ORIGIN); + + const engine = new ObjectQL(); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine.registerDriver(driver, true); + await engine.init(); + engine.setCryptoProvider(crypto); + const sysUser = { + name: 'sys_user', label: 'User', + fields: { + id: { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true }, + name: { name: 'name', label: 'Name', type: 'text' as const }, + email: { name: 'email', label: 'Email', type: 'text' as const }, + email_verified: { name: 'email_verified', label: 'Email Verified', type: 'boolean' as const }, + locale: { name: 'locale', label: 'Locale', type: 'text' as const }, + }, + }; + const invoice = { name: OBJECT, label: 'Invoice', fields: { id: { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true }, title: { name: 'title', label: 'Title', type: 'text' as const } } }; + const register = (def: any) => engine.registry.registerObject(def, 'approvals-slack-test', 'approvals-slack-test'); + for (const def of [sysUser, invoice, SysSecret, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) register(def); + + const slack = slackHttp(); + const sent: Array> = []; + const warnings: string[] = []; + const logger = { info: () => {}, debug: () => {}, warn: (m: string) => { warnings.push(String(m)); }, error: () => {}, child: () => logger }; + const services: Record = { + objectql: engine, + data: engine, + manifest: { register: (m: any) => { for (const def of m.objects ?? []) register(def); } }, + email: { async send(input: any) { sent.push(input); return { id: `mail_${sent.length}` }; } }, + }; + // connector-slack's client service, as ConnectorSlackPlugin registers it. + if (setup !== 'uncomposed') services.slack = createSlackClientService({ fetchImpl: slack.fetchImpl }); + const readyHooks: Array<() => Promise | void> = []; + const ctx: any = { + getService: (name: string) => { + if (!(name in services)) throw new Error(`[Kernel] Service '${name}' not found`); + return services[name]; + }, + registerService: (name: string, svc: unknown) => { services[name] = svc; }, + hook: (event: string, fn: () => Promise | void) => { if (event === 'kernel:ready') readyHooks.push(fn); }, + logger, + }; + const messagingPlugin = new MessagingServicePlugin({ dispatchIntervalMs: 10, dispatchMaxIdleIntervalMs: 20 }); + await messagingPlugin.init(ctx); + await engine.syncSchemas(); + await installDefaultOrganization(engine); + for (const fn of readyHooks.splice(0)) await fn(); + stop = async () => { await messagingPlugin.destroy?.(); await engine.destroy(); }; + + for (const [id, name] of [[SUBMITTER, 'Sam Submitter'], [APPROVER, 'Ada Approver']]) { + await engine.insert('sys_user', { id, name, email: `${id}@example.com`, email_verified: true, locale: 'en' }, { context: SYSTEM } as any); + } + await engine.insert(OBJECT, { id: 'inv_1', title: 'March invoice' }, { context: SYSTEM } as any); + + // The organization's administrator installs Slack; the approver links their Slack user. + const links = new SlackLinkStore({ getData: () => engine as any, getSlack: () => services.slack as any, notify: async () => undefined, logger }); + if (setup !== 'uncomposed') await links.install(DEFAULT_ORGANIZATION_ID, TOKEN, 'u_admin'); + if (setup !== 'none' && setup !== 'uncomposed') await links.propose(DEFAULT_ORGANIZATION_ID, APPROVER); + if (setup !== 'none' && setup !== 'uncomposed' && setup !== 'proposed') await links.confirm(DEFAULT_ORGANIZATION_ID, APPROVER); + const preference = (row: Record) => engine.insert('sys_notification_preference', + { id: `pref_${setup}`, organization_id: DEFAULT_ORGANIZATION_ID, user_id: APPROVER, ...row }, { context: SYSTEM } as any); + if (setup === 'muted') await preference({ topic: '*', channel: 'slack', enabled: false }); + if (setup === 'quiet') await preference({ topic: '*', channel: '*', enabled: true, quiet_hours: { start: hhmm(Date.now() - 3_600_000), end: hhmm(Date.now() + 7_200_000) } }); + slack.requests.length = 0; + + await new ApprovalsServicePlugin().start(ctx); + const opened: any = await (services.approvals as any).openNodeRequest({ + object: OBJECT, recordId: 'inv_1', runId: 'run_1', nodeId: 'signoff', flowName: 'slack_signoff', + config: { approvers: [{ type: 'user', value: APPROVER }], behavior: 'first_response' } as any, + submitterId: SUBMITTER, record: { id: 'inv_1', title: 'March invoice' }, + }, asUser(SUBMITTER)); + + const deliveries = async () => (await driver.getKnex()('sys_notification_delivery').where({ topic: 'approval.requested' }).select('*')) as any[]; + const link = `${ORIGIN}/system/approvals?request=${encodeURIComponent(String(opened.id))}`; + return { slack, sent, deliveries, link, warnings }; +} + +/** The deliveries once none is waiting in the outbox. */ +async function settled(deliveries: () => Promise) { + let rows: any[] = []; + await vi.waitFor(async () => { + rows = await deliveries(); + expect(rows.length).toBeGreaterThan(0); + expect(rows.filter((d) => d.status === 'pending' || d.status === 'in_flight')).toEqual([]); + }, { timeout: 5000, interval: 25 }); + return rows.map((d) => `${d.channel}:${d.recipient_id}:${d.status}`).sort(); +} + +describe('an approval request reaches a linked approver by Slack DM (#34730)', () => { + it('a confirmed link: a DM to the linked user, with the organization\'s token, linking the e-mail\'s link', async () => { + const t = await boot('confirmed'); + expect(await settled(t.deliveries)).toEqual([`email:${APPROVER}:success`, `inbox:${APPROVER}:success`, `slack:${APPROVER}:success`]); + expect(t.slack.requests.map((r) => r.method)).toEqual(['conversations.open', 'chat.postMessage']); + expect(t.slack.requests.every((r) => r.auth === `Bearer ${TOKEN}`)).toBe(true); + expect(t.slack.requests[0].body).toEqual({ users: 'UAPPROVER' }); + const dm = t.slack.requests[1].body; + expect(dm).toMatchObject({ channel: 'D1', unfurl_links: false }); + expect(dm.text).toMatch(new RegExp(`^\\*<${t.link.replace(/[.?]/g, '\\$&')}\\|Approval requested>\\*\\nA decision on Invoice .+ is waiting on you\\.$`)); + // The same link the e-mail carries. + const mail = t.sent.find((m) => m.to === `${APPROVER}@example.com`); + expect(String(mail?.text).endsWith(`Open the approval: ${t.link}`)).toBe(true); + }); + + it('the approver muted slack: inbox and e-mail, no DM', async () => { + const t = await boot('muted'); + expect(await settled(t.deliveries)).toEqual([`email:${APPROVER}:success`, `inbox:${APPROVER}:success`]); + expect(t.slack.requests).toEqual([]); + }); + + it('the approver is in quiet hours: the DM is held, not sent', async () => { + const t = await boot('quiet'); + await vi.waitFor(async () => expect((await t.deliveries()).map((d) => d.channel).sort()).toEqual(['email', 'inbox', 'slack'])); + await new Promise((resolve) => setTimeout(resolve, 200)); + const slackRow = (await t.deliveries()).find((d) => d.channel === 'slack'); + expect(slackRow.status).toBe('pending'); + expect(Number(slackRow.next_attempt_at)).toBeGreaterThan(Date.now()); + expect(t.slack.requests).toEqual([]); + }); + + it.each(['proposed', 'none'] as const)('a %s link: inbox and e-mail only — no slack row, nothing dead-lettered', async (setup) => { + const t = await boot(setup); + expect(await settled(t.deliveries)).toEqual([`email:${APPROVER}:success`, `inbox:${APPROVER}:success`]); + expect(t.slack.requests).toEqual([]); + }); + + it('a composition without connector-slack: the request does not ask for slack, so nothing is refused or logged', async () => { + const t = await boot('uncomposed'); + expect(await settled(t.deliveries)).toEqual([`email:${APPROVER}:success`, `inbox:${APPROVER}:success`]); + expect(t.warnings.filter((w) => w.includes("'slack'"))).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 4c675f1e351..65f6e43a307 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -517,6 +517,13 @@ export interface ApprovalMessagingSurface { * notification's title and body alone. */ registerBuiltinTemplates?(templates: readonly ApprovalBuiltinTemplate[]): void; + /** + * [#34730] The channel mounted under `id` right now + * (`MessagingService.getChannel`), or `undefined`. Read to ask for `slack` + * only while the composition mounts it. Optional — a messaging service + * without it is never asked for `slack`. + */ + getChannel?(id: string): unknown; } /** [#30509] One code-declared notification template, as the messaging service takes it. */ @@ -2491,8 +2498,19 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega severity: 'info', ...event, payload, keyedText: part.keyedText, audience: part.audience, // [#30509] The approval lifecycle's own notices also go by e-mail; // every other approval topic stays inbox-only. Preferences filter as - // for any channel. - ...(EMAILED_APPROVAL_TOPICS.has(event.topic) ? { channels: [...APPROVAL_EMAIL_CHANNELS] } : {}), + // for any channel. [#34730] A request also goes by Slack DM to an + // approver who connected Slack (anyone else is skipped, not failed), + // asked only while the composition mounts the channel: without + // connector-slack, asking would log a refusal on every request. + ...(EMAILED_APPROVAL_TOPICS.has(event.topic) + ? { + channels: [ + ...APPROVAL_EMAIL_CHANNELS, + ...(event.topic === 'approval.requested' + && this.messaging.getChannel?.('slack') ? ['slack'] : []), + ], + } + : {}), ...(dedupKey ? { dedupKey } : {}), ...(person ? { actorId: person } : {}), ...(organization ? { organizationId: organization } : {}), diff --git a/packages/plugins/plugin-approvals/vitest.config.ts b/packages/plugins/plugin-approvals/vitest.config.ts index 7fb4e150087..2eb4ecbcca6 100644 --- a/packages/plugins/plugin-approvals/vitest.config.ts +++ b/packages/plugins/plugin-approvals/vitest.config.ts @@ -50,6 +50,13 @@ export default defineConfig({ find: /^@objectstack\/service-messaging$/, replacement: path.resolve(__dirname, '../../services/service-messaging/src/index.ts'), }, + // [#34730] `approval-requested-slack-dm.integration.test.ts` sends the + // DM through connector-slack's REAL client, stubbed at the HTTP + // boundary — the current client's verdict, not a `dist` build's. + { + find: /^@objectstack\/connector-slack$/, + replacement: path.resolve(__dirname, '../../connectors/connector-slack/src/index.ts'), + }, ], }, test: { diff --git a/packages/runtime/src/domains/automation-notify-slack-composition.test.ts b/packages/runtime/src/domains/automation-notify-slack-composition.test.ts new file mode 100644 index 00000000000..0da7b28a541 --- /dev/null +++ b/packages/runtime/src/domains/automation-notify-slack-composition.test.ts @@ -0,0 +1,121 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34730 step 2] A `notify` node naming `slack`, at the `/automation` save + * doors, against the channels a REAL `MessagingServicePlugin` registers: + * + * - a composition without connector-slack's `slack` client service does not + * know the channel, so the node is refused `400 VALIDATION_FAILED`, as it + * was before the Slack channel existed; + * - a composition with it knows the channel, so the same node saves. + * + * The door's own judgment (ruling 6810493176, letter B) is pinned against + * scripted channel lists in `automation-authoring-doors-durable.test.ts`; this + * file pins what the messaging plugin hands it. The preference doors' side is + * pinned in `@objectstack/service-messaging` (`slack-channel-composition.test.ts`). + */ + +import { describe, it, expect, vi } from 'vitest'; +// The dispatcher's reach loads this dependency in a function body; paid here, +// at collection, not inside the first case's clocked window. +import '@objectstack/metadata'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; +import { + assertEngineDeleteDispatch, + assertEngineFindOnePredicate, + assertEngineUpdateDispatch, + type EngineFindOneQueryInput, +} from '@objectstack/metadata-core'; +import { SchemaRegistry } from '@objectstack/objectql'; +import { MessagingServicePlugin } from '@objectstack/service-messaging'; + +import { HttpDispatcher } from '../http-dispatcher.js'; +import type { HttpProtocolContext } from '../http-dispatcher.js'; + +const AUTHOR = (): HttpProtocolContext => ({ + request: {}, + executionContext: { userId: 'u_admin', systemPermissions: ['manage_metadata'] }, +} as HttpProtocolContext); + +const notifyFlow = (name: string, channels: string[]) => ({ + name, label: 'Notify', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'tell_ops', type: 'notify', label: 'Tell ops', config: { recipients: 'team:ops', title: 'Hi', channels } }, + ], + edges: [], +}); + +/** The messaging service a real `MessagingServicePlugin` registers, after its `kernel:ready` handlers ran. */ +async function messagingOf(opts: { slack: boolean }): Promise { + const engine = { + async syncObjectSchema() {}, + async find() { return [] as unknown[]; }, + async findOne(object: string, query?: EngineFindOneQueryInput) { assertEngineFindOnePredicate(object, query); return null; }, + async insert() { return {}; }, + async update(_object: string, data: any, options?: any) { assertEngineUpdateDispatch(data, options); return {}; }, + async delete(_object: string, options?: any) { assertEngineDeleteDispatch(options); return {}; }, + }; + const services = new Map([['data', engine], ['manifest', { register() {} }]]); + // connector-slack's client service, registered at init as ConnectorSlackPlugin does. + if (opts.slack) services.set('slack', { client: () => ({ call: async () => ({ ok: true, status: 200, body: { ok: true } }) }) }); + const readyHooks: Array<() => Promise | void> = []; + const logger: any = { info() {}, warn() {}, error() {}, debug() {}, child() { return logger; } }; + const ctx = { + logger, + getService(name: string) { + if (!services.has(name)) throw new Error(`[Kernel] Service '${name}' not found`); + return services.get(name); + }, + registerService(name: string, svc: unknown) { services.set(name, svc); }, + hook(event: string, fn: () => Promise | void) { if (event === 'kernel:ready') readyHooks.push(fn); }, + } as any; + await new MessagingServicePlugin({ reliableDelivery: false }).init(ctx); + for (const fn of readyHooks) await fn(); + return services.get('messaging'); +} + +async function boot(opts: { slack: boolean }) { + const registry = new SchemaRegistry({ multiTenant: false, collisionPolicy: 'error' }); + const flows = new Map(); + const registerFlow = vi.fn((name: string, definition: unknown) => { flows.set(name, definition); return definition; }); + const unregisterFlow = vi.fn((name: string) => { flows.delete(name); }); + const protocol = new ObjectStackProtocolImplementation({ registry, findOne: async () => null } as never, () => new Map(), undefined); + const saveMetaItem = vi.spyOn(protocol, 'saveMetaItem').mockResolvedValue({ success: true } as never); + const services: Record = { + automation: { handlerReady: true, registerFlow, unregisterFlow, getFlow: async (name: string) => flows.get(name) ?? null }, + protocol, + messaging: await messagingOf(opts), + }; + const resolve = (name: string): unknown => services[name]; + const kernel = { + getService: resolve, + getServiceAsync: async (name: string) => resolve(name), + context: { getService: resolve }, + hasBootPhaseSettled: (phase: string) => phase === 'kernel:ready', + }; + return { dispatcher: new HttpDispatcher(kernel as never), saveMetaItem, flows }; +} + +describe('a notify node naming slack at the /automation save doors (#34730)', () => { + it('is refused 400 where connector-slack is not composed, and nothing is saved', async () => { + const h = await boot({ slack: false }); + const { response } = await h.dispatcher.handleAutomation('', 'POST', notifyFlow('tell_slack', ['inbox', 'slack']), AUTHOR(), undefined); + expect([(response as any)?.status, (response as any)?.body?.error?.code]).toEqual([400, 'VALIDATION_FAILED']); + expect(String((response as any)?.body?.error?.message)).toContain("names channel 'slack' at nodes.1.config.channels.1"); + expect(h.saveMetaItem).not.toHaveBeenCalled(); + expect(h.flows.has('tell_slack')).toBe(false); + + // The control: the same composition saves a node naming only channels it knows. + const known = await h.dispatcher.handleAutomation('', 'POST', notifyFlow('tell_inbox', ['inbox', 'email']), AUTHOR(), undefined); + expect((known.response as any)?.status).toBe(200); + }); + + it('saves where connector-slack is composed', async () => { + const h = await boot({ slack: true }); + const { response } = await h.dispatcher.handleAutomation('', 'POST', notifyFlow('tell_slack', ['inbox', 'slack']), AUTHOR(), undefined); + expect((response as any)?.status).toBe(200); + expect(h.saveMetaItem).toHaveBeenCalledTimes(1); + expect(h.flows.has('tell_slack')).toBe(true); + }); +}); diff --git a/packages/services/service-messaging/scripts/i18n-extract.config.ts b/packages/services/service-messaging/scripts/i18n-extract.config.ts index d1cc4b71c8a..0c4348e7d43 100644 --- a/packages/services/service-messaging/scripts/i18n-extract.config.ts +++ b/packages/services/service-messaging/scripts/i18n-extract.config.ts @@ -44,6 +44,8 @@ import { NotificationTemplate, HttpDelivery, UserDevice, + ChannelAccount, + ChannelUserLink, } from '../src/objects/index.js'; import { enObjects } from '../src/translations/en.objects.generated.js'; import { zhCNObjects } from '../src/translations/zh-CN.objects.generated.js'; @@ -80,6 +82,8 @@ const config: ObjectStackDefinition = defineStack({ NotificationTemplate, HttpDelivery, UserDevice, + ChannelAccount, + ChannelUserLink, ] as any, translations: [ { en: { objects: enObjects } }, diff --git a/packages/services/service-messaging/src/channel.ts b/packages/services/service-messaging/src/channel.ts index cc92410d2fb..80533cfecdf 100644 --- a/packages/services/service-messaging/src/channel.ts +++ b/packages/services/service-messaging/src/channel.ts @@ -196,4 +196,35 @@ export interface MessagingChannel { ctx: MessagingChannelContext, query: ChannelAvailabilityQuery, ): ChannelAvailability | Promise; + + /** + * Optional: which of these recipients can this channel address at all? + * The per-RECIPIENT counterpart of {@link isAvailable} (ADR-0013 addendum, + * step 2): a channel that reaches a person only through a link they set up + * (the `slack` channel: a confirmed `sys_channel_user_link`) answers the + * recipients that have one. + * + * Consulted by fan-out once per channel per emit, after the preference + * filter and BEFORE any delivery row is written. A recipient it leaves out + * is SKIPPED on this channel: no delivery row, no `send()`, no failed + * outcome, and nothing on `sys_notification.suppressed_channels` (that + * column answers for the tenant, not for one person). Their other channels + * are unchanged. + * + * OPTIONAL, and absence means every recipient is addressable. A throw is + * treated as every recipient addressable (fail-open) and logged; `send()` + * then answers an unaddressable recipient itself. + */ + reachableRecipients?( + ctx: MessagingChannelContext, + query: RecipientReachQuery, + ): Promise>; +} + +/** What {@link MessagingChannel.reachableRecipients} is asked about. */ +export interface RecipientReachQuery { + /** Tenant the emit belongs to; absent on single-tenant / background emits. */ + readonly organizationId?: string; + /** The recipients the preference filter left on this channel. */ + readonly recipients: readonly string[]; } diff --git a/packages/services/service-messaging/src/index.ts b/packages/services/service-messaging/src/index.ts index 19a9b026fc6..8f58de36fc6 100644 --- a/packages/services/service-messaging/src/index.ts +++ b/packages/services/service-messaging/src/index.ts @@ -80,6 +80,29 @@ export { export type { SmsChannelOptions, SmsSenderSurface } from './sms-channel.js'; export { createPushChannel } from './push-channel.js'; export type { PushChannelOptions, PushSenderSurface, PushDeviceSurface } from './push-channel.js'; +// [#34730 step 2] Slack DM delivery: the channel, the per-person link store +// and its HTTP doors. +export { createSlackChannel, slackDmText, absoluteLink, deploymentOrigin } from './slack-channel.js'; +export type { SlackChannelOptions } from './slack-channel.js'; +export { + SlackLinkStore, + SlackLinkError, + bindSlackLinkRemovalTriggers, + unbindSlackLinkRemovalTriggers, + CHANNEL_ACCOUNT_OBJECT, + CHANNEL_USER_LINK_OBJECT, + SLACK_CHANNEL_ID, + SLACK_LINK_REMOVED_TOPIC, +} from './slack-links.js'; +export type { SlackAccount, SlackLink, SlackClientSurface, SlackLinkStoreOptions, SlackTriggerEngine } from './slack-links.js'; +export { + registerSlackLinkRoutes, + SLACK_LINK_ROUTE, + SLACK_ACCOUNT_ROUTE, + SLACK_LINKS_ROUTE, + SLACK_ADMIN_CAPABILITY, +} from './slack-link-routes.js'; +export type { SlackLinkRoutesDeps } from './slack-link-routes.js'; // [#24978] Keyed notification text — `EmitInput.keyedText`, rendered per // recipient at delivery from the `i18n` service's catalog. @@ -131,6 +154,9 @@ export type { ChannelAvailability, ChannelAvailabilityQuery, ChannelUnavailableReason, + // [#34730 step 2] The optional per-recipient reach query: a recipient a + // channel cannot reach is skipped before any delivery row. + RecipientReachQuery, } from './channel.js'; export { CHANNEL_UNAVAILABLE_REASONS } from './channel.js'; @@ -233,6 +259,8 @@ export { HttpDelivery, SYS_HTTP_DELIVERY, UserDevice, + ChannelAccount, + ChannelUserLink, } from './objects/index.js'; // Push device registry (ADR-0012 §6) — `INotificationService`'s device members. diff --git a/packages/services/service-messaging/src/messaging-route-ledger.conformance.test.ts b/packages/services/service-messaging/src/messaging-route-ledger.conformance.test.ts index 255c00afdfd..1288764bc1f 100644 --- a/packages/services/service-messaging/src/messaging-route-ledger.conformance.test.ts +++ b/packages/services/service-messaging/src/messaging-route-ledger.conformance.test.ts @@ -15,6 +15,7 @@ import { describe, it, expect, vi } from 'vitest'; import { registerPreferenceOptionsRoutes } from './preference-options-routes.js'; import { registerInAppMessageRoutes } from './in-app-message-routes.js'; import { registerMyPreferencesRoutes } from './my-preferences-routes.js'; +import { registerSlackLinkRoutes } from './slack-link-routes.js'; import { MESSAGING_ROUTE_LEDGER } from './messaging-route-ledger.js'; function createMockServer() { @@ -35,6 +36,7 @@ function enumerateMessagingRoutes(): Set { registerPreferenceOptionsRoutes(server as any, {} as any); registerMyPreferencesRoutes(server as any, {} as any); registerInAppMessageRoutes(server as any, {} as any); + registerSlackLinkRoutes(server as any, {} as any); const keys = new Set(); for (const verb of ['get', 'post', 'put', 'patch', 'delete'] as const) { for (const call of server[verb].mock.calls) keys.add(`${verb.toUpperCase()} ${call[0]}`); diff --git a/packages/services/service-messaging/src/messaging-route-ledger.ts b/packages/services/service-messaging/src/messaging-route-ledger.ts index cfa180757fa..0aadc8cca67 100644 --- a/packages/services/service-messaging/src/messaging-route-ledger.ts +++ b/packages/services/service-messaging/src/messaging-route-ledger.ts @@ -3,8 +3,9 @@ /** * Messaging route ledger — the audited disposition of every HTTP route * `registerPreferenceOptionsRoutes` (`preference-options-routes.ts`), - * `registerMyPreferencesRoutes` (`my-preferences-routes.ts`) and - * `registerInAppMessageRoutes` (`in-app-message-routes.ts`) mount. + * `registerMyPreferencesRoutes` (`my-preferences-routes.ts`), + * `registerInAppMessageRoutes` (`in-app-message-routes.ts`) and + * `registerSlackLinkRoutes` (`slack-link-routes.ts`) mount. * * WHY THIS EXISTS. `MessagingServicePlugin` reaches for the `http-server` * service and registers straight on `IHttpServer`, so neither the dispatcher @@ -18,7 +19,8 @@ * * NOT SDK SURFACE. `@objectstack/client` expresses no method for any: the * consumers are the console's notification preference and template forms, the - * Account app's Notification Settings page, and + * Account app's Notification Settings page (and its Slack link), the Setup + * screen of the organization's Slack install, and * the Setup action "Send in-app message" (a same-origin `type: 'api'` action, * which the action doors also forward for an agent), over plain HTTP. That is * a `server-only` disposition. @@ -60,4 +62,24 @@ export const MESSAGING_ROUTE_LEDGER: readonly MessagingRouteLedgerEntry[] = [ note: 'the signed-in person\'s own effective notification preferences (topic x channel, digest, quiet hours, each with its source), for the Account app\'s Notification Settings page; any signed-in person, about themselves only, read-only' }, { route: 'POST /api/v1/messaging/in-app-messages', family: 'messaging', disposition: 'server-only', note: 'an organization administrator\'s in-app message to everyone in, or picked members of, their current organization; the target of the Setup action send_in_app_message on sys_notification' }, + // [#34730 step 2] The Slack link doors: the person about themselves, then + // the organization administrator (`setup.write` in the current organization). + { route: 'GET /api/v1/messaging/me/slack-link', family: 'messaging', disposition: 'server-only', + note: 'the signed-in person\'s Slack link in their current organization, and the install\'s workspace, for the Account app\'s Notification Settings page; about themselves only' }, + { route: 'POST /api/v1/messaging/me/slack-link/proposal', family: 'messaging', disposition: 'server-only', + note: 'propose a Slack link by the person\'s own verified email (Slack users.lookupByEmail); the proposal names no Slack user and delivers nothing until confirmed' }, + { route: 'POST /api/v1/messaging/me/slack-link/confirm', family: 'messaging', disposition: 'server-only', + note: 'the person confirms their own proposed Slack link; from then on notifications may reach them by Slack DM' }, + { route: 'DELETE /api/v1/messaging/me/slack-link', family: 'messaging', disposition: 'server-only', + note: 'the person removes their own Slack link' }, + { route: 'GET /api/v1/messaging/slack/account', family: 'messaging', disposition: 'server-only', + note: 'an organization administrator reads their organization\'s Slack install (never its token)' }, + { route: 'PUT /api/v1/messaging/slack/account', family: 'messaging', disposition: 'server-only', + note: 'an organization administrator installs Slack or sets its bot token again; Slack proves the token before it is stored, encrypted' }, + { route: 'DELETE /api/v1/messaging/slack/account', family: 'messaging', disposition: 'server-only', + note: 'an organization administrator removes the Slack install and every link to it; each linked person is told' }, + { route: 'GET /api/v1/messaging/slack/links', family: 'messaging', disposition: 'server-only', + note: 'an organization administrator lists every Slack link in their organization' }, + { route: 'DELETE /api/v1/messaging/slack/links/:id', family: 'messaging', disposition: 'server-only', + note: 'an organization administrator removes one person\'s Slack link; the person is told by inbox and email' }, ]; diff --git a/packages/services/service-messaging/src/messaging-service-plugin.test.ts b/packages/services/service-messaging/src/messaging-service-plugin.test.ts index 95d7a5e1967..ff7907f6134 100644 --- a/packages/services/service-messaging/src/messaging-service-plugin.test.ts +++ b/packages/services/service-messaging/src/messaging-service-plugin.test.ts @@ -254,6 +254,7 @@ describe('MessagingServicePlugin — boot provisioning honours skipSchemaSync (# const OBJECTS = [ 'sys_notification', 'sys_inbox_message', 'sys_notification_receipt', 'sys_notification_delivery', 'sys_notification_preference', 'sys_notification_template', 'sys_http_delivery', 'sys_user_device', + 'sys_channel_account', 'sys_channel_user_link', ]; const SKIP = 'NOT provisioned at boot'; @@ -381,6 +382,7 @@ describe('MessagingServicePlugin — a failed provision is an error, once per ob const OBJECTS = [ 'sys_notification', 'sys_inbox_message', 'sys_notification_receipt', 'sys_notification_delivery', 'sys_notification_preference', 'sys_notification_template', 'sys_http_delivery', 'sys_user_device', + 'sys_channel_account', 'sys_channel_user_link', ]; /** Every DDL succeeds except the named object's, which the driver refuses. */ diff --git a/packages/services/service-messaging/src/messaging-service-plugin.ts b/packages/services/service-messaging/src/messaging-service-plugin.ts index 2668f97875c..672f6e3bf12 100644 --- a/packages/services/service-messaging/src/messaging-service-plugin.ts +++ b/packages/services/service-messaging/src/messaging-service-plugin.ts @@ -20,6 +20,15 @@ import { HttpDispatcher } from './http-dispatcher.js'; import { createEmailChannel } from './email-channel.js'; import { createSmsChannel } from './sms-channel.js'; import { createPushChannel } from './push-channel.js'; +import { createSlackChannel } from './slack-channel.js'; +import { + SlackLinkStore, + bindSlackLinkRemovalTriggers, + unbindSlackLinkRemovalTriggers, + type SlackClientSurface, + type SlackTriggerEngine, +} from './slack-links.js'; +import { SLACK_ACCOUNT_ROUTE, SLACK_LINK_ROUTE, registerSlackLinkRoutes } from './slack-link-routes.js'; import { NotificationTemplateStore, TEMPLATE_BUILTINS, @@ -42,6 +51,8 @@ import { NotificationTemplate, HttpDelivery, UserDevice, + ChannelAccount, + ChannelUserLink, } from './objects/index.js'; // The L2 event this service writes on every `emit()`. It is OWNED by // platform-objects (it is in `PLATFORM_OBJECTS_BY_PACKAGE`), and — like @@ -243,6 +254,8 @@ export class MessagingServicePlugin implements Plugin { private httpDispatcher?: HttpDispatcher; /** The engine the template placement hooks are bound to — unbound on teardown. */ private placementEngine?: PlacementHookEngine; + /** The engine the Slack link removal triggers are bound to — unbound on teardown. */ + private slackTriggerEngine?: SlackTriggerEngine; constructor(options: MessagingServicePluginOptions = {}) { const { egressPolicy, ...rest } = options; @@ -365,6 +378,26 @@ export class MessagingServicePlugin implements Plugin { ctx.registerService('messaging', service); + // [#34730 step 2] The Slack link store: the organization's install + // (`sys_channel_account`) and each person's link to their own Slack + // user (`sys_channel_user_link`). Slack is reached through + // connector-slack's `slack` client service, probed per call like + // `email` above, so a composition without ConnectorSlackPlugin has no + // Slack channel and its link doors answer 503. + const getSlack = (): SlackClientSurface | undefined => { + try { + return ctx.getService('slack'); + } catch { + return undefined; + } + }; + const slackLinks = new SlackLinkStore({ + getData, + getSlack, + notify: (input) => service.emit(input), + logger: ctx.logger, + }); + // ADR-0030: the messaging service also backs the `notification` core // service slot — it owns the in-app inbox + receipts, so it answers the // `/api/v1/notifications` REST surface (list / mark-read / mark-all-read) @@ -399,6 +432,10 @@ export class MessagingServicePlugin implements Plugin { // The push device registry (ADR-0012 §6): the // `notification` slot's device members write it. UserDevice, + // The Slack install and the per-person links (#34730 step 2): + // the Slack link doors write them through the link store. + ChannelAccount, + ChannelUserLink, ], navigationContributions: [ { @@ -433,6 +470,17 @@ export class MessagingServicePlugin implements Plugin { + 'for where its body places a hole', ); } + // [ruling 7024100939, rider 3] A person's Slack links go when they + // leave the organization or are banned (their deletion cascades by + // the object's own declaration). See slack-links.ts. + if (bindSlackLinkRemovalTriggers(engine as SlackTriggerEngine | undefined, slackLinks, ctx.logger)) { + this.slackTriggerEngine = engine as SlackTriggerEngine; + } else { + ctx.logger.warn( + '[messaging] no ObjectQL engine with a hook registry — a person who leaves an organization or is banned ' + + 'keeps their Slack link there until an administrator removes it', + ); + } // [#32240] A keyed inbox row reads in the READER's request language: // the same renderer delivery uses, re-rendering the row's stored keys @@ -584,6 +632,25 @@ export class MessagingServicePlugin implements Plugin { logger: ctx.logger, })); }); + + // Slack channel (#34730 step 2): registered only on a composition + // whose connector-slack `slack` client service resolves at + // `kernel:ready` (ConnectorSlackPlugin registers it at init), then + // mounted per lookup like the others. Without it the channel is + // not known at all, so the `/automation` save doors and the + // preference doors (`getKnownChannels`) answer as they do with no + // Slack in the composition. It sends a DM to a recipient's + // confirmed link with their organization's own install token + // (sys_channel_account). + ctx.hook('kernel:ready', async () => { + if (!getSlack()) return; + service.registerChannelProvider('slack', lazyChannelMount({ + resolveTransport: getSlack, + create: () => createSlackChannel({ store: slackLinks }), + announce: '[messaging] slack channel registered (a DM to the recipient\'s confirmed sys_channel_user_link, with their organization\'s sys_channel_account token)', + logger: ctx.logger, + })); + }); } // [#30208 row 6, ruling E on #30527] The preference options door @@ -596,7 +663,7 @@ export class MessagingServicePlugin implements Plugin { // when the HTTP server is registered; everything they read is read // per request. if (typeof ctx.hook === 'function') { - ctx.hook('kernel:ready', async () => this.mountHttpDoors(ctx, service, getData)); + ctx.hook('kernel:ready', async () => this.mountHttpDoors(ctx, service, getData, slackLinks)); } // Reliable delivery (P1): wire the outbox + dispatcher once the engine @@ -677,17 +744,19 @@ export class MessagingServicePlugin implements Plugin { } /** - * Mount the package's two HTTP doors on the kernel's HTTP server: - * `GET /api/v1/messaging/preference-options` and - * `POST /api/v1/messaging/in-app-messages`. A kernel with no HTTP server - * says so once and mounts neither: the preference fields stay plain text - * boxes, the Setup action "Send in-app message" has nothing to call, and - * the in-process service is unchanged. + * Mount the package's HTTP doors on the kernel's HTTP server: + * `GET /api/v1/messaging/preference-options`, the caller's own + * preferences, `POST /api/v1/messaging/in-app-messages` and the Slack + * link doors. A kernel with no HTTP server says so once and mounts none: + * the preference fields stay plain text boxes, the Setup action "Send + * in-app message" has nothing to call, nobody can connect Slack, and the + * in-process service is unchanged. */ private mountHttpDoors( ctx: PluginContext, service: MessagingService, getData: () => IDataEngine | undefined, + slackLinks: SlackLinkStore, ): void { const optional = (name: string): T | undefined => { try { @@ -700,9 +769,10 @@ export class MessagingServicePlugin implements Plugin { if (!http) { ctx.logger.warn( `[messaging] no HTTP server is registered, so neither the preference options list (GET ${PREFERENCE_OPTIONS_ROUTE}), ` + - `the caller's own preferences (GET ${MY_PREFERENCES_ROUTE}) nor the in-app message door (POST ${IN_APP_MESSAGE_ROUTE}) ` + - 'is mounted: the console draws notification topic and channel as plain text boxes, the Account page Notification ' + - 'Settings has nothing to read, and the Setup action "Send in-app message" has nothing to call.', + `the caller's own preferences (GET ${MY_PREFERENCES_ROUTE}), the in-app message door (POST ${IN_APP_MESSAGE_ROUTE}) ` + + `nor the Slack link doors (${SLACK_LINK_ROUTE}, ${SLACK_ACCOUNT_ROUTE}) is mounted: the console draws notification ` + + 'topic and channel as plain text boxes, the Account page Notification Settings has nothing to read, the Setup ' + + 'action "Send in-app message" has nothing to call, and nobody can install Slack or connect to it.', ); return; } @@ -743,6 +813,11 @@ export class MessagingServicePlugin implements Plugin { getData, }); ctx.logger.info(`[messaging] in-app message door mounted at POST ${IN_APP_MESSAGE_ROUTE}`); + registerSlackLinkRoutes(http, { + resolveCaller: (req) => resolveMessagingCaller(req, callerSources), + getStore: () => slackLinks, + }); + ctx.logger.info(`[messaging] Slack link doors mounted at ${SLACK_LINK_ROUTE} and ${SLACK_ACCOUNT_ROUTE}`); } /** @@ -773,7 +848,8 @@ export class MessagingServicePlugin implements Plugin { * cold-start budget) and says once, at `info`, what it did not provision and * why. Not `warn`: nothing is degraded, because the operator declared this. * `os migrate apply`, the documented path, was measured to create all eight - * tables (before `sys_user_device` joined them as the ninth). `syncObjectSchema` itself stays ungated, because it is also how a + * tables (before `sys_user_device` joined them as the ninth, and the two + * Slack link objects as the tenth and eleventh). `syncObjectSchema` itself stays ungated, because it is also how a * runtime publish gives a new object its table. */ private async provisionSystemTables(engine: IDataEngine, ctx: PluginContext): Promise { @@ -791,6 +867,8 @@ export class MessagingServicePlugin implements Plugin { NotificationTemplate, HttpDelivery, UserDevice, + ChannelAccount, + ChannelUserLink, ]; // [#22984] FIRST: see the docblock. One line, naming every skipped object. if (bootSchemaSyncSkipped(engine)) { @@ -863,6 +941,8 @@ export class MessagingServicePlugin implements Plugin { async destroy(): Promise { unbindTemplateHolePlacement(this.placementEngine); this.placementEngine = undefined; + unbindSlackLinkRemovalTriggers(this.slackTriggerEngine); + this.slackTriggerEngine = undefined; await this.dispatcher?.stop(); this.dispatcher = undefined; await this.httpDispatcher?.stop(); diff --git a/packages/services/service-messaging/src/messaging-service.ts b/packages/services/service-messaging/src/messaging-service.ts index 59fd3b3e4d7..e9dc07ed6ba 100644 --- a/packages/services/service-messaging/src/messaging-service.ts +++ b/packages/services/service-messaging/src/messaging-service.ts @@ -1468,7 +1468,7 @@ export class MessagingService { // delivery. With no organization from the producer or the event // row the read stays unscoped, as before. const payload = input.payload ?? {}; - const targets = await this.preferences.filter(recipients, channels, { + let targets = await this.preferences.filter(recipients, channels, { topic: input.topic, organizationId: owned.organizationId, severity: input.severity, @@ -1478,6 +1478,16 @@ export class MessagingService { return { notificationId, deduped: false, deliveries: [], delivered: 0, enqueued: 0, failed: 0, suppressed }; } + // 3c) Per-recipient reach (ADR-0013 addendum, step 2): a channel that + // addresses only some people (Slack: a confirmed link) skips the + // rest here, before a row exists — never a dead-lettered delivery. + const reached = await this.dropUnreachable(targets, owned.organizationId); + if (reached.length === 0) { + this.ctx.logger.info(`[messaging] emit: topic '${input.topic}' reaches no recipient on its remaining channels`); + return { notificationId, deduped: false, deliveries: [], delivered: 0, enqueued: 0, failed: 0, suppressed }; + } + targets = reached; + // 4) Either enqueue durable deliveries (P1 outbox) or fan out inline (P0). if (this.outbox) { const deliveries = await this.enqueueDeliveries(this.outbox, notificationId, targets, owned, payload); @@ -1614,6 +1624,46 @@ export class MessagingService { return { available, suppressed }; } + /** + * Drop each `(recipient × channel)` pair whose channel answers, through + * {@link MessagingChannel.reachableRecipients}, that it cannot address that + * recipient, and every target left with no channel. Asked once per + * channel per emit, with every recipient still on it. A probe that throws + * keeps every recipient (fail-open, said at `warn`): the channel's own + * `send()` answers an unaddressable recipient then. + */ + private async dropUnreachable(targets: PreferenceTarget[], organizationId: string | undefined): Promise { + const asked = new Map>(); + for (const { recipient, channels } of targets) { + for (const id of channels) { + if (!this.getChannel(id)?.reachableRecipients) continue; + let set = asked.get(id); + if (!set) asked.set(id, (set = new Set())); + set.add(recipient); + } + } + const unreachable = new Map>(); + for (const [id, recipients] of asked) { + const channel = this.getChannel(id); + let reachable: ReadonlySet; + try { + reachable = await channel!.reachableRecipients!(this.ctx, { organizationId, recipients: [...recipients] }); + } catch (err) { + this.ctx.logger.warn( + `[messaging] channel '${id}' recipient probe threw (${(err as Error)?.message ?? String(err)}); ` + + 'fanning out to every recipient as before', + ); + continue; + } + const out = [...recipients].filter((r) => !reachable.has(r)); + if (out.length > 0) unreachable.set(id, new Set(out)); + } + if (unreachable.size === 0) return targets; + return targets + .map((t) => ({ ...t, channels: t.channels.filter((c) => !unreachable.get(c)?.has(t.recipient)) })) + .filter((t) => t.channels.length > 0); + } + /** * Enqueue one `pending` delivery row per `(channel × recipient)`. The * dispatcher does the actual send + retry; here `ok` means "accepted for diff --git a/packages/services/service-messaging/src/objects/channel-account.object.ts b/packages/services/service-messaging/src/objects/channel-account.object.ts new file mode 100644 index 00000000000..81825f8c5aa --- /dev/null +++ b/packages/services/service-messaging/src/objects/channel-account.object.ts @@ -0,0 +1,62 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +/** + * `sys_channel_account` — one organization's install of a chat app (ADR-0013 + * §4, narrowed by its accepted addendum of 2026-11-19): for Slack, the + * organization's own Slack app, installed into its workspace, and the bot + * token it was issued. One row per organization and channel. + * + * **The token at rest** (`bot_token`) is the `secret` channel (ADR-0100), the + * one the open connector credential store uses (`sys_connector_credential`, + * ADR-0143): the engine encrypts it on write through the host's + * `ICryptoProvider` (refusing the write with none), masks it on every read + * path, and only the privileged `resolveSecretField()` dereferences it, server + * side, when the Slack channel or the link door calls Slack. ADR-0013 §4's + * `credentials_ref` into a vault stays Draft and enterprise. + * + * Engine-owned: written only through the link store (`../slack-links.ts`) — + * by the Slack link door (`../slack-link-routes.ts`) under a system context + * naming the administrator, and by the Slack channel marking a token Slack + * refused as revoked. ⛔ The generic data API + * neither reads nor writes it (`apiEnabled: false`), and `access: private` + * keeps a plain `'*'` wildcard grant off it (ADR-0066 D2). + */ +export const ChannelAccount = ObjectSchema.create({ + name: 'sys_channel_account', + label: 'Channel Account', + pluralLabel: 'Channel Accounts', + icon: 'plug', + isSystem: true, + managedBy: 'engine-owned', + access: { default: 'private' }, + description: "An organization's install of a chat app, such as its own Slack app, with the bot token it was issued.", + nameField: 'display_name', // [ADR-0079] canonical primary-title pointer + + fields: { + // The messaging channel the install serves: `slack`. + channel_id: Field.text({ label: 'Channel', required: true, maxLength: 64 }), + // The workspace name and id the chat app reported for the token. + display_name: Field.text({ label: 'Workspace', required: true, maxLength: 255 }), + external_id: Field.text({ label: 'Workspace ID', required: true, maxLength: 64 }), + // Encrypted at rest and masked on every read; read only by the server, to send. + bot_token: Field.secret({ label: 'Bot Token', required: true }), + // Revoked once the chat app refused the token; setting the token again restores it. + status: Field.select([{ label: 'Active', value: 'active' }, { label: 'Revoked', value: 'revoked' }], { + label: 'Status', required: true, defaultValue: 'active', + }), + }, + + indexes: [ + // One install per organization and channel. + { fields: ['channel_id'], unique: 'organization' }, + ], + + enable: { + trackHistory: false, + searchable: false, + apiEnabled: false, + apiMethods: [], + }, +}); diff --git a/packages/services/service-messaging/src/objects/channel-user-link.object.ts b/packages/services/service-messaging/src/objects/channel-user-link.object.ts new file mode 100644 index 00000000000..6eb19df3c80 --- /dev/null +++ b/packages/services/service-messaging/src/objects/channel-user-link.object.ts @@ -0,0 +1,62 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +/** + * `sys_channel_user_link` — a person's link to their own user in a chat + * workspace (ADR-0013 §8, narrowed by its accepted addendum of 2026-11-19): + * the platform user, the organization's install (`sys_channel_account`), and + * the chat user id, recorded when the person confirms. + * + * A link is `proposed` by matching the person's verified email against the + * workspace's users and delivers nothing until the person `confirmed` it, + * once, while that email is still verified and still theirs + * (`proposal_email_hash`). A person, + * or an administrator of the organization, may remove it; it goes with the + * person (`user_id` cascades, as `sys_user_device`), with the install + * (`account_id` cascades), and the link store removes it when the person is + * banned or leaves the organization (`../slack-links.ts`). + * + * Every write is an engine write under a context naming who acted, so the + * platform's write audit records each creation, confirmation and removal. + * Engine-owned; ⛔ the generic data API neither reads nor writes it. + */ +export const ChannelUserLink = ObjectSchema.create({ + name: 'sys_channel_user_link', + label: 'Channel User Link', + pluralLabel: 'Channel User Links', + icon: 'link', + isSystem: true, + managedBy: 'engine-owned', + access: { default: 'private' }, + description: "A person's link to their own user in a chat workspace: proposed by email match, delivering once they confirm it.", + nameField: 'external_display_name', // [ADR-0079] canonical primary-title pointer + + fields: { + account_id: Field.lookup('sys_channel_account', { label: 'Account', required: true, deleteBehavior: 'cascade' }), + // [ADR-0118] A person's links go with the person, as their devices do. + user_id: Field.lookup('sys_user', { label: 'User', required: true, deleteBehavior: 'cascade' }), + external_user_id: Field.text({ label: 'Chat User ID', maxLength: 64 }), + external_display_name: Field.text({ label: 'Chat User Name', maxLength: 255 }), + // Proposed by an email match; nothing is delivered until the person confirms. + state: Field.select([{ label: 'Proposed', value: 'proposed' }, { label: 'Confirmed', value: 'confirmed' }], { + label: 'State', required: true, defaultValue: 'proposed', + }), + confirmed_at: Field.datetime({ label: 'Confirmed At' }), + // SHA-256 of the email the proposal was made for; a confirmation requires the person's verified email to still match it. + proposal_email_hash: Field.text({ label: 'Proposal Email Hash', maxLength: 64 }), + }, + + indexes: [ + // One link per person per install, and one person per chat user. + { fields: ['account_id', 'user_id'], unique: 'global' }, + { fields: ['account_id', 'external_user_id'], unique: 'global' }, + ], + + enable: { + trackHistory: false, + searchable: false, + apiEnabled: false, + apiMethods: [], + }, +}); diff --git a/packages/services/service-messaging/src/objects/index.ts b/packages/services/service-messaging/src/objects/index.ts index 2ca5bdfd65f..0a017c7c8ff 100644 --- a/packages/services/service-messaging/src/objects/index.ts +++ b/packages/services/service-messaging/src/objects/index.ts @@ -7,3 +7,5 @@ export { NotificationPreference } from './notification-preference.object.js'; export { NotificationTemplate } from './notification-template.object.js'; export { HttpDelivery, SYS_HTTP_DELIVERY } from './http-delivery.object.js'; export { UserDevice } from './user-device.object.js'; +export { ChannelAccount } from './channel-account.object.js'; +export { ChannelUserLink } from './channel-user-link.object.js'; diff --git a/packages/services/service-messaging/src/preference-options.ts b/packages/services/service-messaging/src/preference-options.ts index 44fda59f04e..8a5f4dc0f9f 100644 --- a/packages/services/service-messaging/src/preference-options.ts +++ b/packages/services/service-messaging/src/preference-options.ts @@ -46,8 +46,9 @@ * The platform's fixed notification topics, measured from their send and * template sites: `plugin-approvals` (`approval.*`), `plugin-audit` * (`collab.mention`), `plugin-security` (`security.access_upgrade`, - * `system.upgrade_impact`) and `plugin-auth` (the two phone SMS template - * topics). Kept sorted; a feature that starts sending a new fixed topic adds + * `system.upgrade_impact`), `plugin-auth` (the two phone SMS template + * topics) and this package's Slack link store (`messaging.slack_link_removed`). + * Kept sorted; a feature that starts sending a new fixed topic adds * it here. */ export const PLATFORM_NOTIFICATION_TOPICS: readonly string[] = [ @@ -64,6 +65,7 @@ export const PLATFORM_NOTIFICATION_TOPICS: readonly string[] = [ 'auth.phone_invite', 'auth.phone_otp', 'collab.mention', + 'messaging.slack_link_removed', 'security.access_upgrade', 'system.upgrade_impact', ]; diff --git a/packages/services/service-messaging/src/recipient-reach.test.ts b/packages/services/service-messaging/src/recipient-reach.test.ts new file mode 100644 index 00000000000..b13cc4873a7 --- /dev/null +++ b/packages/services/service-messaging/src/recipient-reach.test.ts @@ -0,0 +1,59 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34730 step 2] Fan-out asks a channel that addresses only some people + * (`reachableRecipients`, the Slack channel's confirmed links) whom it can + * reach, once per emit, and skips the rest before any row exists: no delivery + * row, no send, no failure, no `suppressed_channels` entry — the other + * channels of the same emit are untouched. A channel without the member + * reaches everyone, and a probe that throws keeps everyone (fail-open). + */ + +import { describe, it, expect } from 'vitest'; +import { MessagingService } from './messaging-service.js'; +import { MemoryNotificationOutbox } from './memory-outbox.js'; +import type { MessagingChannel, RecipientReachQuery } from './channel.js'; + +const silent = { info: () => {}, warn: () => {}, error: () => {} }; + +function service(reach: (q: RecipientReachQuery) => ReadonlySet) { + const outbox = new MemoryNotificationOutbox(1); + const inserts: Array> = []; + const svc = new MessagingService({ + logger: silent, + outbox, + getData: () => ({ async insert(_o: string, row: Record) { inserts.push(row); return { id: 'evt_1', ...row }; }, async find() { return []; } }) as never, + }); + const probes: RecipientReachQuery[] = []; + const plain = (id: string): MessagingChannel => ({ id, async send() { return { ok: true }; } }); + svc.registerChannel(plain('inbox')); + svc.registerChannel({ ...plain('slack'), async reachableRecipients(_ctx, q) { probes.push(q); return reach(q); } }); + const emit = (channels = ['inbox', 'slack']) => + svc.emit({ topic: 'approval.requested', audience: ['u_ada', 'u_bob'], channels, organizationId: 'org_a', payload: { title: 'Approve PO-7' } }); + const rows = async () => (await outbox.list()).map((r) => `${r.channel}:${r.recipientId}`).sort(); + return { emit, rows, probes, inserts }; +} + +describe('per-recipient reach at fan-out', () => { + it('skips the unreached recipient on that channel only, with no row and no suppression, asking once', async () => { + const t = service(() => new Set(['u_ada'])); + const result = await t.emit(); + expect(await t.rows()).toEqual(['inbox:u_ada', 'inbox:u_bob', 'slack:u_ada']); + expect(t.probes).toEqual([{ organizationId: 'org_a', recipients: ['u_ada', 'u_bob'] }]); + expect(result).toMatchObject({ enqueued: 3, failed: 0, suppressed: [] }); + expect(t.inserts[0].suppressed_channels ?? []).toEqual([]); + }); + + it('a probe that throws keeps every recipient', async () => { + const t = service(() => { throw new Error('link store unreachable'); }); + await t.emit(); + expect(await t.rows()).toEqual(['inbox:u_ada', 'inbox:u_bob', 'slack:u_ada', 'slack:u_bob']); + }); + + it('an emit only that channel can carry, reaching nobody, writes no row', async () => { + const t = service(() => new Set()); + const result = await t.emit(['slack']); + expect(await t.rows()).toEqual([]); + expect(result).toMatchObject({ enqueued: 0, failed: 0 }); + }); +}); diff --git a/packages/services/service-messaging/src/slack-channel-composition.test.ts b/packages/services/service-messaging/src/slack-channel-composition.test.ts new file mode 100644 index 00000000000..6872770e186 --- /dev/null +++ b/packages/services/service-messaging/src/slack-channel-composition.test.ts @@ -0,0 +1,120 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34730 step 2] Whether the messaging service knows the `slack` channel is a + * composition fact: `MessagingServicePlugin` registers its provider only where + * connector-slack's `slack` client service resolves at `kernel:ready`. + * + * - without that service, `getKnownChannels()` does not list `slack`, so the + * two preference doors (`GET /api/v1/messaging/preference-options`, + * `GET /api/v1/messaging/me/preferences`) answer the channels they answer + * on a composition with no Slack at all; + * - with it, `slack` is known and mounted, and both doors list it. + * + * The `/automation` save doors read the same list; their side is pinned in + * `@objectstack/runtime` (`automation-notify-slack-composition.test.ts`). + */ + +import { describe, it, expect } from 'vitest'; +import { + assertEngineDeleteDispatch, + assertEngineFindOnePredicate, + assertEngineUpdateDispatch, + type EngineFindOneQueryInput, +} from '@objectstack/metadata-core'; +import { MessagingServicePlugin } from './messaging-service-plugin.js'; +import type { MessagingService } from './messaging-service.js'; +import { MY_PREFERENCES_ROUTE } from './my-preferences-routes.js'; +import { PREFERENCE_OPTIONS_ROUTE } from './preference-options-routes.js'; + +const USER = 'usr_alice'; +const ORG = 'org_a'; + +/** A plugin context with a fake engine, an HTTP server that keeps its handlers, and a session for one member. */ +async function compose(opts: { slack: boolean }) { + const tables = new Set(); + const engine = { + async syncObjectSchema(name: string) { tables.add(name); }, + async find(object: string, q: any = {}) { + if (object === 'sys_member') { + const where = q?.where ?? {}; + return where.user_id === USER && where.organization_id === ORG + ? [{ id: 'mem_alice', user_id: USER, organization_id: ORG, role: 'member' }] + : []; + } + return [] as unknown[]; + }, + async aggregate() { return [] as unknown[]; }, + async count() { return 0; }, + async insert() { return {}; }, + async findOne(object: string, query?: EngineFindOneQueryInput) { assertEngineFindOnePredicate(object, query); return null; }, + async update(_object: string, data: any, options?: any) { assertEngineUpdateDispatch(data, options); return {}; }, + async delete(_object: string, options?: any) { assertEngineDeleteDispatch(options); return {}; }, + }; + const handlers = new Map Promise>(); + const mount = (verb: string) => (path: string, handler: (req: unknown, res: unknown) => Promise) => { handlers.set(`${verb} ${path}`, handler); }; + const services = new Map([ + ['data', engine], + ['objectql', engine], + ['manifest', { register() {} }], + ['http-server', { get: mount('GET'), post: mount('POST'), put: mount('PUT'), delete: mount('DELETE'), patch: mount('PATCH'), use() {} }], + ['auth', { + api: { + getSession: async ({ headers }: { headers: Headers }) => headers.get('authorization') === 'Bearer alice' + ? { user: { id: USER, email: `${USER}@example.test` }, session: { id: 'ses_alice', userId: USER, activeOrganizationId: ORG } } + : null, + }, + }], + ]); + // connector-slack's client service, registered at init as ConnectorSlackPlugin does. + if (opts.slack) services.set('slack', { client: () => ({ call: async () => ({ ok: true, status: 200, body: { ok: true } }) }) }); + const readyHooks: Array<() => Promise | void> = []; + const logger: any = { info() {}, warn() {}, error() {}, debug() {}, child() { return logger; } }; + const ctx = { + logger, + getService(name: string) { + if (!services.has(name)) throw new Error(`[Kernel] Service '${name}' not found`); + return services.get(name); + }, + registerService(name: string, svc: unknown) { services.set(name, svc); }, + hook(event: string, fn: () => Promise | void) { if (event === 'kernel:ready') readyHooks.push(fn); }, + } as any; + await new MessagingServicePlugin({ reliableDelivery: false }).init(ctx); + for (const fn of readyHooks) await fn(); + + async function get(route: string) { + const handler = handlers.get(`GET ${route}`); + if (!handler) throw new Error(`no GET ${route}`); + const out: { status: number; body: any } = { status: 0, body: undefined }; + const res = { status: (c: number) => { out.status = c; return res; }, json: (b: unknown) => { out.body = b; }, header: () => res, send: () => undefined }; + await handler({ params: {}, query: {}, headers: { authorization: 'Bearer alice' }, method: 'GET', path: route }, res); + expect(out.status, JSON.stringify(out.body)).toBe(200); + return out.body.data; + } + return { + messaging: services.get('messaging') as MessagingService, + optionChannels: async () => (await get(PREFERENCE_OPTIONS_ROUTE)).channels.map((c: any) => c.value), + myChannels: async () => (await get(MY_PREFERENCES_ROUTE)).channels.map((c: any) => c.channel), + }; +} + +describe('the slack channel is known only where connector-slack is composed', () => { + it('without a slack service: not known, not mounted, and neither preference door lists it', async () => { + const c = await compose({ slack: false }); + expect(c.messaging.getKnownChannels().map((k) => k.id)).not.toContain('slack'); + expect(c.messaging.getChannel('slack')).toBeUndefined(); + expect(await c.optionChannels()).not.toContain('slack'); + expect(await c.myChannels()).not.toContain('slack'); + // The control: the channels the doors list are the service's own. + expect(await c.optionChannels()).toContain('inbox'); + expect(await c.myChannels()).toContain('inbox'); + }); + + it('with a slack service: known and mounted, and both preference doors list it', async () => { + const c = await compose({ slack: true }); + expect(c.messaging.getKnownChannels()).toContainEqual({ id: 'slack', configured: true }); + expect(c.messaging.getChannel('slack')?.id).toBe('slack'); + expect(await c.optionChannels()).toContain('slack'); + expect(await c.myChannels()).toContain('slack'); + }); +}); diff --git a/packages/services/service-messaging/src/slack-channel.test.ts b/packages/services/service-messaging/src/slack-channel.test.ts new file mode 100644 index 00000000000..f4c8f319a9f --- /dev/null +++ b/packages/services/service-messaging/src/slack-channel.test.ts @@ -0,0 +1,107 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34730 step 2] The `slack` channel's send and its error classification, + * over a link store whose Slack answers are scripted: a revoked token is + * permanent and marks the install revoked, a user Slack cannot DM and a + * missing link are an invalid recipient (suppressed, never dead-lettered), a + * rate limit is retried. Plus the DM text and its absolute deep link. + */ + +import { describe, it, expect } from 'vitest'; +import type { Delivery } from './channel.js'; +import { absoluteLink, createSlackChannel, deploymentOrigin, slackDmText } from './slack-channel.js'; +import type { SlackAnswer, SlackLinkStore } from './slack-links.js'; + +const ACCOUNT = { id: 'acc_1', organizationId: 'org_a', displayName: 'Acme', externalId: 'T1', status: 'active' as const }; +const LINK = { id: 'l_1', accountId: 'acc_1', userId: 'u_ada', externalUserId: 'UADA', state: 'confirmed' as const }; +const ok = (body: Record): SlackAnswer => ({ ok: true, status: 200, body: { ok: true, ...body } }); +const refused = (error: string, status = 200): SlackAnswer => ({ ok: false, status, body: { ok: false, error }, error }); + +function channelOver(answers: Record, opts: { linked?: boolean } = {}) { + const sent: Array<{ method: string; params?: Record }> = []; + const revoked: string[] = []; + const store = { + async account() { return ACCOUNT; }, + async confirmedUsers(_org: string, ids: readonly string[]) { return new Set(ids.filter((id) => id === 'u_ada')); }, + async deliveryTarget(_org: string, user: string) { return opts.linked !== false && user === 'u_ada' ? { account: ACCOUNT, link: LINK } : undefined; }, + async slackFor() { + return async (method: string, params?: Record) => { sent.push({ method, params }); return answers[method] ?? ok({}); }; + }, + async markRevoked(a: { id: string }) { revoked.push(a.id); }, + } as unknown as SlackLinkStore; + const channel = createSlackChannel({ store, getPublicOrigin: () => 'https://os.example.com' }); + const delivery = (recipient = 'u_ada'): Delivery => ({ + channel: 'slack', + recipient, + notification: { organizationId: 'org_a', title: 'Approve ', body: 'Ada & Bob asked.', recipients: [recipient], actionUrl: '/system/approvals?request=r1' }, + }); + return { channel, sent, revoked, delivery }; +} + +describe('the slack channel — send', () => { + it('opens a DM with the linked user and posts the title linked to the absolute deep link, then the body', async () => { + const t = channelOver({ 'conversations.open': ok({ channel: { id: 'D1' } }), 'chat.postMessage': ok({ ts: '1700.1' }) }); + expect(await t.channel.send({} as never, t.delivery())).toEqual({ ok: true, externalId: '1700.1' }); + expect(t.sent).toEqual([ + { method: 'conversations.open', params: { users: 'UADA' } }, + { + method: 'chat.postMessage', + params: { + channel: 'D1', + text: '**\nAda & Bob asked.', + unfurl_links: false, + unfurl_media: false, + }, + }, + ]); + }); + + it.each([ + ['a revoked token', { 'conversations.open': refused('token_revoked') }, 'permanent', ['acc_1']], + ['an invalid token on post', { 'conversations.open': ok({ channel: { id: 'D1' } }), 'chat.postMessage': refused('invalid_auth') }, 'permanent', ['acc_1']], + ['a user Slack cannot find', { 'conversations.open': refused('user_not_found') }, 'invalid_recipient', []], + ['a rate limit', { 'conversations.open': refused('ratelimited', 429) }, 'rate_limited', []], + ['any other Slack refusal', { 'conversations.open': ok({ channel: { id: 'D1' } }), 'chat.postMessage': refused('msg_too_long') }, 'retryable', []], + ] as const)('%s is classified %s', async (_name, answers, expected, revoked) => { + const t = channelOver(answers as Record); + const result = await t.channel.send({} as never, t.delivery()); + expect(result.ok).toBe(false); + expect(t.channel.classifyError!(result.error)).toBe(expected); + expect(t.revoked).toEqual(revoked); + }); + + it('a recipient with no confirmed link by send time is an invalid recipient, and Slack is not called', async () => { + const t = channelOver({}, { linked: false }); + const result = await t.channel.send({} as never, t.delivery()); + expect(t.channel.classifyError!(result.error)).toBe('invalid_recipient'); + expect(t.sent).toEqual([]); + }); + + it('answers who it can reach, per organization', async () => { + const t = channelOver({}); + expect(await t.channel.reachableRecipients!({} as never, { organizationId: 'org_a', recipients: ['u_ada', 'u_bob'] })).toEqual(new Set(['u_ada'])); + expect(await t.channel.reachableRecipients!({} as never, { recipients: ['u_ada'] })).toEqual(new Set()); + expect(await t.channel.isAvailable!({} as never, { organizationId: 'org_a' })).toEqual({ available: true }); + expect(await t.channel.isAvailable!({} as never, {})).toEqual({ available: false, reason: 'transport_not_configured' }); + }); +}); + +describe('the slack channel — the deep link', () => { + it('makes a path absolute under the origin, keeps an absolute http(s) link, and drops what a DM reader cannot open', () => { + expect(absoluteLink('/a?b=1|2', 'https://os.example.com')).toBe('https://os.example.com/a?b=1%7C2'); + expect(absoluteLink('https://elsewhere.example/x', undefined)).toBe('https://elsewhere.example/x'); + expect(absoluteLink('/a', undefined)).toBeUndefined(); + expect(absoluteLink('//evil.example/a', 'https://os.example.com')).toBeUndefined(); + expect(absoluteLink('javascript:alert(1)', 'https://os.example.com')).toBeUndefined(); + expect(slackDmText({ title: 'T', body: '', actionUrl: '/a' }, undefined)).toBe('*T*'); + }); + + it('reads the deployment origin in the order the approval e-mail\'s link does', () => { + expect(deploymentOrigin({ OS_AUTH_URL: 'https://auth.example.com/', OS_BASE_URL: 'https://base.example.com' })).toBe('https://auth.example.com'); + expect(deploymentOrigin({ BETTER_AUTH_URL: 'https://legacy.example.com' })).toBe('https://legacy.example.com'); + expect(deploymentOrigin({ OS_BASE_URL: 'https://base.example.com/app/' })).toBe('https://base.example.com/app'); + expect(deploymentOrigin({ OS_BASE_URL: 'ftp://base.example.com' })).toBeUndefined(); + expect(deploymentOrigin({})).toBeUndefined(); + }); +}); diff --git a/packages/services/service-messaging/src/slack-channel.ts b/packages/services/service-messaging/src/slack-channel.ts new file mode 100644 index 00000000000..b230119c871 --- /dev/null +++ b/packages/services/service-messaging/src/slack-channel.ts @@ -0,0 +1,172 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { + ChannelAvailability, + ChannelAvailabilityQuery, + Delivery, + ErrorClass, + MessagingChannel, + MessagingChannelContext, + Notification, + RecipientReachQuery, + SendResult, +} from './channel.js'; +import { SLACK_CHANNEL_ID, isTokenRefusal, type SlackAnswer, type SlackLinkStore } from './slack-links.js'; + +/** + * Error-string prefixes, read back by `classifyError` (the dispatcher hands it + * the `SendResult.error` string), the convention the sms and push channels use. + */ +const NOT_LINKED = 'slack_not_linked'; +const USER_UNREACHABLE = 'slack_user_unreachable'; +const TOKEN_REFUSED = 'slack_token_refused'; +const TOKEN_UNREADABLE = 'slack_token_unreadable'; +const RATE_LIMITED = 'slack_rate_limited'; +/** Slack answers that mean this person cannot be sent a DM. */ +const USER_REFUSALS = new Set(['user_not_found', 'user_disabled', 'cannot_dm_bot', 'user_not_visible', 'users_not_found']); + +export interface SlackChannelOptions { + store: SlackLinkStore; + /** + * The deployment's public origin a relative `actionUrl` is made absolute + * under; default {@link deploymentOrigin}, read per delivery. + */ + getPublicOrigin?(): string | undefined; +} + +/** + * The `slack` channel (ADR-0013 addendum of 2026-11-19, ADR-0022 §3) — a + * direct message to the recipient's own Slack user, through connector-slack's + * client (the `slack` service) with the organization's own bot token. + * + * - **Who can be sent to.** A recipient with a CONFIRMED link to their + * organization's active install. {@link MessagingChannel.isAvailable} answers + * the organization (an active install, else `transport_not_configured`); + * {@link MessagingChannel.reachableRecipients} answers the people, so a + * person with no link, or a proposal only, is skipped before any delivery + * row exists. Preferences, digest and quiet hours apply as on every + * channel: they run in fan-out and the dispatcher, before this. + * - **What is sent.** `conversations.open` with the linked user, then + * `chat.postMessage`: the title in bold, linked to the notification's deep + * link made absolute, then the body; both already in the recipient's + * language. No text of its own, so nothing here needs translating. + * - **Outcome.** A link gone or never confirmed by the time a row is sent, + * or a Slack user Slack no longer finds ⇒ `invalid_recipient` (suppressed, + * not dead-lettered). A refused token ⇒ `permanent`, and the install is + * marked revoked so later emits skip it. Rate limited ⇒ `rate_limited` + * (retried). Anything else ⇒ `retryable`. + */ +export function createSlackChannel(opts: SlackChannelOptions): MessagingChannel { + const { store } = opts; + const origin = () => (opts.getPublicOrigin ?? deploymentOrigin)(); + + return { + id: SLACK_CHANNEL_ID, + + async isAvailable(_ctx: MessagingChannelContext, query: ChannelAvailabilityQuery): Promise { + const account = query.organizationId ? await store.account(query.organizationId) : undefined; + return account?.status === 'active' ? { available: true } : { available: false, reason: 'transport_not_configured' }; + }, + + async reachableRecipients(_ctx: MessagingChannelContext, query: RecipientReachQuery): Promise> { + return query.organizationId ? store.confirmedUsers(query.organizationId, query.recipients) : new Set(); + }, + + async send(_ctx: MessagingChannelContext, delivery: Delivery): Promise { + const n = delivery.notification; + const target = n.organizationId ? await store.deliveryTarget(n.organizationId, delivery.recipient) : undefined; + if (!target) { + return { ok: false, error: `${NOT_LINKED}: '${delivery.recipient}' has no confirmed Slack link to an active install in this organization` }; + } + let call; + try { + call = await store.slackFor(target.account); + } catch (err) { + return { ok: false, error: `${TOKEN_UNREADABLE}: ${(err as Error)?.message ?? String(err)}` }; + } + const opened = await call('conversations.open', { users: target.link.externalUserId }); + const channel = opened.body.channel?.id; + if (!opened.ok || typeof channel !== 'string') return failure(store, target.account, opened); + const posted = await call('chat.postMessage', { + channel, + text: slackDmText(n, origin()), + unfurl_links: false, + unfurl_media: false, + }); + if (!posted.ok) return failure(store, target.account, posted); + return { ok: true, externalId: typeof posted.body.ts === 'string' ? posted.body.ts : undefined }; + }, + + classifyError(err: unknown): ErrorClass { + const message = typeof err === 'string' ? err : (err as Error)?.message ?? ''; + if (message.startsWith(NOT_LINKED) || message.startsWith(USER_UNREACHABLE)) return 'invalid_recipient'; + if (message.startsWith(TOKEN_REFUSED) || message.startsWith(TOKEN_UNREADABLE)) return 'permanent'; + if (message.startsWith(RATE_LIMITED)) return 'rate_limited'; + return 'retryable'; + }, + }; +} + +async function failure(store: SlackLinkStore, account: Parameters[0], answer: SlackAnswer): Promise { + const why = answer.error ?? `HTTP ${answer.status}`; + if (isTokenRefusal(answer.error)) { + await store.markRevoked(account); + return { ok: false, error: `${TOKEN_REFUSED}: Slack refused the install's token (${why}); an administrator sets it again` }; + } + if (answer.error && USER_REFUSALS.has(answer.error)) return { ok: false, error: `${USER_UNREACHABLE}: ${why}` }; + if (answer.status === 429 || answer.error === 'ratelimited') return { ok: false, error: `${RATE_LIMITED}: ${why}` }; + return { ok: false, error: `slack_failed: ${why}` }; +} + +/** Slack's mrkdwn control characters, escaped as Slack asks. */ +function escapeSlack(text: string): string { + return text.replace(/&/g, '&').replace(//g, '>'); +} + +/** + * The DM's text: the title in bold, linked to the deep link when one can be + * made absolute, then the body. + */ +export function slackDmText(n: Pick, origin: string | undefined): string { + const title = escapeSlack(n.title); + const link = absoluteLink(n.actionUrl, origin); + const head = link ? `*<${link}|${title}>*` : `*${title}*`; + return n.body ? `${head}\n${escapeSlack(n.body)}` : head; +} + +/** + * `actionUrl` as an absolute `http(s)` URL: as it is when it already is one, + * under `origin` when it is a path on this server, else none (a DM reader is + * outside the Console, so a relative link opens nothing). + */ +export function absoluteLink(actionUrl: string | undefined, origin: string | undefined): string | undefined { + if (!actionUrl) return undefined; + let url: URL | undefined; + try { + url = actionUrl.startsWith('/') && !actionUrl.startsWith('//') + ? (origin ? new URL(`${origin}${actionUrl}`) : undefined) + : new URL(actionUrl); + } catch { + url = undefined; + } + if (!url || (url.protocol !== 'http:' && url.protocol !== 'https:')) return undefined; + // `|` ends a Slack link's URL part. + return url.href.replace(/\|/g, '%7C'); +} + +/** + * The deployment's public origin, in the order the approval e-mail's link + * reads it: `OS_AUTH_URL` (legacy `BETTER_AUTH_URL`), then `OS_BASE_URL`; an + * absolute `http(s)` URL with no trailing slash, else `undefined`. + */ +export function deploymentOrigin(env: Readonly> = process.env): string | undefined { + const raw = env.OS_AUTH_URL ?? env.BETTER_AUTH_URL ?? env.OS_BASE_URL; + if (!raw?.trim()) return undefined; + try { + const url = new URL(raw.trim()); + if (url.protocol !== 'http:' && url.protocol !== 'https:') return undefined; + return `${url.protocol}//${url.host}${url.pathname.replace(/\/+$/, '')}`; + } catch { + return undefined; + } +} diff --git a/packages/services/service-messaging/src/slack-link-routes.ts b/packages/services/service-messaging/src/slack-link-routes.ts new file mode 100644 index 00000000000..b8d624341c0 --- /dev/null +++ b/packages/services/service-messaging/src/slack-link-routes.ts @@ -0,0 +1,222 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { + ANONYMOUS_DENY_CODE, + ANONYMOUS_DENY_MESSAGE, + ANONYMOUS_DENY_STATUS, + evaluateAuthGate, + isApiKeyLifecycleRefusalError, + isAuthzStoreUnavailableError, + resolveOfferedLocale, + shouldDenyAnonymous, +} from '@objectstack/core'; +import type { ErrorCode } from '@objectstack/spec/api'; +import type { IHttpRequest, IHttpResponse, IHttpServer } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { sendError, sendOk, sendServerFault } from '@objectstack/types'; +import { SlackLinkError, type SlackAccount, type SlackLink, type SlackLinkStore } from './slack-links.js'; +import { enMessages, messagingMessages, type MessagingLocale, type MessagingMessageId } from './translations/messages.js'; + +/** + * The Slack link doors (ADR-0013 addendum of 2026-11-19, step 2), the server + * half of step 3's notification settings page and Setup screen. + * + * ## The person — about themselves, in their current organization + * + * - `GET /api/v1/messaging/me/slack-link` — the install (its workspace) and + * their link, each `null` when there is none. + * - `POST /api/v1/messaging/me/slack-link/proposal` — propose a link by + * their verified email; `link: null` when nothing matched or the email is + * not verified, and `link: { state: 'proposed' }` — no Slack user's name + * or id — when a match was found. + * - `POST /api/v1/messaging/me/slack-link/confirm` — confirm the proposal, + * while the email is still verified and still the one it was proposed for. + * - `DELETE /api/v1/messaging/me/slack-link` — remove their link. + * + * ## An organization administrator — in their current organization + * + * {@link SLACK_ADMIN_CAPABILITY}, `setup.write`, held in the caller's CURRENT + * organization (`ExecutionContext.systemPermissions`): the organization + * administrator's capability the in-app message door asks + * (`in-app-message-routes.ts`), which both organization-administrator sets and + * the platform administrator's grant hold and `member_default` does not + * (ruling `7024100939`, rider 5). Not `isPlatformAdmin`: an install and its + * links belong to one organization. + * + * - `GET /api/v1/messaging/slack/account` — the install, without its token. + * - `PUT /api/v1/messaging/slack/account` — `{ token }`: install, or set + * the token again; Slack proves it (`auth.test`) before anything is saved. + * - `DELETE /api/v1/messaging/slack/account` — remove the install and every + * link to it; each linked person is told. + * - `GET /api/v1/messaging/slack/links` — every link to the install. + * - `DELETE /api/v1/messaging/slack/links/:id` — remove one; the person is + * told, and may confirm a new link at once (rider 4). + * + * Every door: the caller through the platform's one composition, a held + * sign-in `403`, anonymous `401`, then the CLOSED query set, which is empty + * (AGENTS.md route rule 5), then no current organization `403`. ⛔ No answer + * carries the token, and no answer names the Slack user of a link before it is + * confirmed. + */ + +export const SLACK_LINK_ROUTE = '/api/v1/messaging/me/slack-link'; +export const SLACK_ACCOUNT_ROUTE = '/api/v1/messaging/slack/account'; +export const SLACK_LINKS_ROUTE = '/api/v1/messaging/slack/links'; +/** The capability every administrator door demands in the caller's current organization. */ +export const SLACK_ADMIN_CAPABILITY = 'setup.write'; +/** The body keys `PUT /slack/account` reads — the whole closed set. */ +const ACCOUNT_BODY_KEYS = ['token']; +/** A Slack bot token is far shorter; a longer value is not one. */ +const TOKEN_MAX = 512; + +export interface SlackLinkRoutesDeps { + resolveCaller(req: IHttpRequest): Promise; + getStore(): SlackLinkStore; +} + +interface Caller { + readonly userId: string; + readonly organizationId: string; +} + +type Handler = (req: IHttpRequest, caller: Caller, store: SlackLinkStore) => Promise; + +export function registerSlackLinkRoutes(http: IHttpServer, deps: SlackLinkRoutesDeps): void { + const person = (method: string, path: string, run: Handler) => door(deps, method, path, false, run); + const admin = (method: string, path: string, run: Handler) => door(deps, method, path, true, run); + + http.get(SLACK_LINK_ROUTE, person('GET', SLACK_LINK_ROUTE, async (_req, c, store) => { + const account = await store.account(c.organizationId); + const link = account ? await store.linkOf(c.organizationId, c.userId) : undefined; + return { account: account ? accountView(account) : null, link: link ? ownLinkView(link) : null }; + })); + http.post(`${SLACK_LINK_ROUTE}/proposal`, person('POST', `${SLACK_LINK_ROUTE}/proposal`, async (_req, c, store) => { + const link = await store.propose(c.organizationId, c.userId); + return { link: link ? ownLinkView(link) : null }; + })); + http.post(`${SLACK_LINK_ROUTE}/confirm`, person('POST', `${SLACK_LINK_ROUTE}/confirm`, async (_req, c, store) => ( + { link: ownLinkView(await store.confirm(c.organizationId, c.userId)) } + ))); + http.delete(SLACK_LINK_ROUTE, person('DELETE', SLACK_LINK_ROUTE, async (_req, c, store) => ( + { removed: await store.removeOwn(c.organizationId, c.userId) } + ))); + + http.get(SLACK_ACCOUNT_ROUTE, admin('GET', SLACK_ACCOUNT_ROUTE, async (_req, c, store) => { + const account = await store.account(c.organizationId); + return { account: account ? accountView(account) : null }; + })); + http.put(SLACK_ACCOUNT_ROUTE, admin('PUT', SLACK_ACCOUNT_ROUTE, async (req, c, store) => ( + { account: accountView(await store.install(c.organizationId, parseToken(req.body), c.userId)) } + ))); + http.delete(SLACK_ACCOUNT_ROUTE, admin('DELETE', SLACK_ACCOUNT_ROUTE, async (_req, c, store) => ( + { removed: await store.uninstall(c.organizationId, c.userId) } + ))); + http.get(SLACK_LINKS_ROUTE, admin('GET', SLACK_LINKS_ROUTE, async (_req, c, store) => ( + { links: (await store.links(c.organizationId)).map(linkView) } + ))); + http.delete(`${SLACK_LINKS_ROUTE}/:id`, admin('DELETE', `${SLACK_LINKS_ROUTE}/:id`, async (req, c, store) => { + if (!(await store.removeByAdmin(c.organizationId, String(req.params?.id ?? ''), c.userId))) { + throw new SlackLinkError(404, 'RESOURCE_NOT_FOUND', 'No Slack link with this id exists in your current organization. Nothing was changed.'); + } + return { removed: true }; + })); +} + +function door(deps: SlackLinkRoutesDeps, method: string, path: string, admin: boolean, run: Handler) { + return async (req: IHttpRequest, res: IHttpResponse): Promise => { + let context: ExecutionContext | undefined; + try { + context = await deps.resolveCaller(req); + } catch (err) { + if (isAuthzStoreUnavailableError(err) || isApiKeyLifecycleRefusalError(err)) { + sendError(res, err.status, err.code, err.message); + return; + } + sendServerFault(res, 500, 'INTERNAL_ERROR', 'The caller of this request could not be resolved.', err, { method, path }); + return; + } + const gate = evaluateAuthGate(context, ''); + if (gate) { + sendError(res, 403, gate.code as ErrorCode, gate.message); + return; + } + if (!context || !context.userId || shouldDenyAnonymous({ userId: context.userId, method: req.method })) { + sendError(res, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE); + return; + } + const query = Object.keys(req.query ?? {}); + if (query.length > 0) { + sendError(res, 400, 'VALIDATION_ERROR', + `This Slack link door takes no query parameter, and this request carries ${query.map((q) => `'${q}'`).join(', ')}. Nothing was changed.`); + return; + } + if (admin && !(Array.isArray(context.systemPermissions) && context.systemPermissions.includes(SLACK_ADMIN_CAPABILITY))) { + sendError(res, 403, 'PERMISSION_DENIED', + `Managing your organization's Slack install and links requires the \`${SLACK_ADMIN_CAPABILITY}\` capability in your current ` + + 'organization, which its administrators hold. Nothing was changed.'); + return; + } + const organizationId = typeof context.tenantId === 'string' && context.tenantId !== '' ? context.tenantId : undefined; + if (!organizationId) { + sendError(res, 403, 'PERMISSION_DENIED', + 'This request has no current organization, and Slack is installed and linked per organization: select one and retry. Nothing was changed.'); + return; + } + try { + sendOk(res, await run(req, { userId: context.userId, organizationId }, deps.getStore())); + } catch (err) { + if (err instanceof SlackLinkError) { + sendError(res, err.status, err.code as ErrorCode, err.message, + err.messageId ? { userMessage: inCallerLanguage(err.messageId, context.locale) } : undefined); + return; + } + sendServerFault(res, 500, 'INTERNAL_ERROR', 'The Slack link request could not be completed.', err, { method, path }); + } + }; +} + +/** A Slack token's alphabet: letters, digits, `.`, `_` and `-`. Any other value is not a token. */ +const TOKEN_SHAPE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/; + +function parseToken(body: unknown): string { + const fields = body && typeof body === 'object' && !Array.isArray(body) ? (body as Record) : {}; + const unknown = Object.keys(fields).filter((k) => !ACCOUNT_BODY_KEYS.includes(k)); + if (unknown.length > 0) { + throw new SlackLinkError(400, 'VALIDATION_ERROR', + `Installing Slack reads only { token }, and this body carries ${unknown.map((k) => `'${k}'`).join(', ')}. Nothing was saved.`); + } + const token = typeof fields.token === 'string' ? fields.token.trim() : ''; + if (!token || token.length > TOKEN_MAX || !TOKEN_SHAPE.test(token)) { + throw new SlackLinkError(400, 'VALIDATION_ERROR', + "Installing Slack needs { token }: your Slack app's bot token (it starts with xoxb-). Nothing was saved."); + } + return token; +} + +function accountView(a: SlackAccount) { + return { id: a.id, workspace: a.displayName, workspaceId: a.externalId, status: a.status }; +} + +/** A link as an administrator reads it: the Slack user is named only once the person confirmed. */ +function linkView(l: SlackLink) { + const confirmed = l.state === 'confirmed'; + return { + id: l.id, + userId: l.userId, + slackUserId: confirmed ? l.externalUserId ?? null : null, + slackUserName: confirmed ? l.externalDisplayName ?? null : null, + state: l.state, + confirmedAt: l.confirmedAt ?? null, + }; +} + +/** The person's own link: before they confirm, only that a match was found. */ +function ownLinkView(l: SlackLink) { + return l.state === 'confirmed' ? linkView(l) : { state: l.state }; +} + +/** A refusal's sentence in the caller's language (`ExecutionContext.locale`), else in English. */ +function inCallerLanguage(id: MessagingMessageId, locale: string | undefined): string { + const offered = locale ? resolveOfferedLocale(locale, Object.keys(messagingMessages)) : undefined; + return (offered ? messagingMessages[offered as MessagingLocale][id] : undefined) ?? enMessages[id]; +} diff --git a/packages/services/service-messaging/src/slack-links.integration.test.ts b/packages/services/service-messaging/src/slack-links.integration.test.ts new file mode 100644 index 00000000000..f0463d47371 --- /dev/null +++ b/packages/services/service-messaging/src/slack-links.integration.test.ts @@ -0,0 +1,505 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34730 step 2] The Slack link store and its doors, over a real `ObjectQL` + * on `SqlDriver` (better-sqlite3) with the `secret` channel wired, Slack + * answered by a scripted `slack` client service: + * + * - the install: an administrator's token is proven by Slack, stored + * encrypted (never in the row, never in an answer), and read back only by + * the privileged dereference under its own organization; + * - the person: a proposal by email delivers nothing until confirmed; + * - the proposal rule: a Slack link is proposed only for a verified email + * and names no one before it is confirmed, and a confirmation holds only + * while that email is still verified and still the person's, and applies + * only to the proposal that was checked; a proposal stores no Slack user, + * the confirmation records the one Slack names for the email then; + * - the token: a value that is not a Slack token is refused before Slack is + * asked; + * - the riders of ruling 7024100939: (1) every removal is a write the audit + * hook sees, attributed to who removed it; (2) an administrator's removal + * tells the person by inbox and email; (3) a link goes with the person's + * deletion, their ban and their leaving the organization; (4) an + * administrator's removal does not stop a new link; (5) the administrator + * doors demand `setup.write`. + */ + +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysMember, SysSecret } from '@objectstack/platform-objects'; +import { envelopeViolations } from '@objectstack/spec/api'; +import type { CryptoContext, CryptoHandle, ICryptoProvider } from '@objectstack/spec/contracts'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { ChannelAccount, ChannelUserLink } from './objects/index.js'; +import { + CHANNEL_ACCOUNT_OBJECT, + CHANNEL_USER_LINK_OBJECT, + SLACK_LINK_REMOVED_TOPIC, + SlackLinkStore, + bindSlackLinkRemovalTriggers, + type SlackClientSurface, +} from './slack-links.js'; +import { SLACK_ACCOUNT_ROUTE, SLACK_ADMIN_CAPABILITY, SLACK_LINK_ROUTE, SLACK_LINKS_ROUTE, registerSlackLinkRoutes } from './slack-link-routes.js'; +import { enMessages, frMessages } from './translations/messages.js'; + +const SYSTEM = { context: { isSystem: true } as ExecutionContext }; +const SYS_ORGANIZATION = { name: 'sys_organization', label: 'Organization', managedBy: 'better-auth', fields: { name: { type: 'text', label: 'Name' } } }; +const SYS_USER = { + name: 'sys_user', label: 'User', managedBy: 'better-auth', + fields: { + name: { type: 'text', label: 'Name' }, + email: { type: 'text', label: 'Email' }, + email_verified: { type: 'boolean', label: 'Email Verified' }, + banned: { type: 'boolean', label: 'Banned' }, + }, +}; +const silent: any = { debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return silent; } }; +const GOOD = 'xoxb-acme'; + +/** The callers, by bearer. `setup.write` is the organization administrator's capability. */ +const CONTEXTS: Record = { + admin_a: { userId: 'u_admin', tenantId: 'org_a', systemPermissions: ['setup.access', 'setup.write'] } as ExecutionContext, + ada: { userId: 'u_ada', tenantId: 'org_a', systemPermissions: ['setup.access'] } as ExecutionContext, + bob: { userId: 'u_bob', tenantId: 'org_a', systemPermissions: [] } as ExecutionContext, + bob_fr: { userId: 'u_bob', tenantId: 'org_a', locale: 'fr-FR', systemPermissions: [] } as ExecutionContext, + ada_no_org: { userId: 'u_ada', systemPermissions: [] } as ExecutionContext, + admin_b: { userId: 'u_admin', tenantId: 'org_b', systemPermissions: ['setup.access', 'setup.write'] } as ExecutionContext, +}; + +/** Reversible test crypto that binds the organization: a handle opens only under the tenant it was sealed for. */ +function tenantBoundCrypto(): ICryptoProvider { + let n = 0; + return { + async encrypt(plain: string, ctx: CryptoContext): Promise { + return { id: `sec_${++n}`, kmsKeyId: 'local', alg: 'test', version: 1, ciphertext: Buffer.from(`${ctx.tenantId}|${plain}`).toString('base64') }; + }, + async decrypt(handle: CryptoHandle, ctx: CryptoContext): Promise { + const [tenant, ...rest] = Buffer.from(handle.ciphertext, 'base64').toString().split('|'); + if (tenant !== String(ctx.tenantId)) throw new Error('AAD mismatch'); + return rest.join('|'); + }, + async rotateKey(handle: CryptoHandle): Promise { return handle; }, + digest: (plain: string) => `d:${plain.length}`, + async keyedDigest(plain: string) { return `k:${plain.length}`; }, + }; +} + +/** Slack, scripted: who holds which email, and the tokens it accepts. */ +function scriptedSlack() { + const directory: Record = { + 'u_ada@example.test': { id: 'UADA', real_name: 'Ada' }, + 'u_bob@example.test': { id: 'UBOB', real_name: 'Bob' }, + 'u_admin@example.test': { id: 'UADM', real_name: 'Admin' }, + 'ada.new@example.test': { id: 'UADA2', real_name: 'Ada New' }, + }; + const calls: Array<{ token: string; method: string }> = []; + const answer = (ok: boolean, body: Record) => ({ ok, status: 200, body: { ok, ...body }, error: ok ? undefined : body.error }); + const slack: SlackClientSurface = { + client: (token) => ({ + async call(input) { + const method = String(input.method); + calls.push({ token, method }); + if (token !== GOOD) return answer(false, { error: 'invalid_auth' }); + if (method === 'auth.test') return answer(true, { team_id: 'T1', team: 'Acme', user_id: 'UBOT' }); + const email = decodeURIComponent(method.split('email=')[1] ?? ''); + const user = directory[email]; + return user ? answer(true, { user }) : answer(false, { error: 'users_not_found' }); + }, + }), + }; + return { slack, calls, directory }; +} + +let engine: ObjectQL | undefined; +afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + engine = undefined; +}); + +async function boot(opts: { linkPageSize?: number } = {}) { + const ql = new ObjectQL({ logger: silent }); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + ql.registerDriver(driver, true); + await ql.init(); + for (const def of [SYS_ORGANIZATION, SYS_USER, SysMember, SysSecret, ChannelAccount, ChannelUserLink]) { + ql.registry.registerObject(def as any, '@objectstack/service-messaging'); + } + await ql.syncSchemas(); + ql.setTenancyPostureProvider(() => 'single'); + ql.setCryptoProvider(tenantBoundCrypto()); + for (const id of ['org_a', 'org_b']) await ql.insert('sys_organization', { id, name: id }, SYSTEM); + for (const id of ['u_admin', 'u_ada', 'u_bob']) { + await ql.insert('sys_user', { id, name: id, email: `${id}@example.test`, email_verified: true }, SYSTEM); + } + for (const [id, user] of [['m_admin', 'u_admin'], ['m_ada', 'u_ada'], ['m_bob', 'u_bob']]) { + await ql.insert('sys_member', { id, user_id: user, organization_id: 'org_a', role: 'member' }, SYSTEM); + } + engine = ql; + + const { slack, calls, directory } = scriptedSlack(); + const notices: any[] = []; + // The engine the store writes through; `beforeLinkUpdate` runs once, just before the store's next link write. + const race: { beforeLinkUpdate?: () => Promise } = {}; + const data = new Proxy(ql, { + get(target, prop) { + if (prop === 'update') { + return async (object: string, values: unknown, options: unknown) => { + const before = object === CHANNEL_USER_LINK_OBJECT ? race.beforeLinkUpdate : undefined; + race.beforeLinkUpdate = undefined; + if (before) await before(); + return ql.update(object, values, options as never); + }; + } + const member = Reflect.get(target, prop, target); + return typeof member === 'function' ? member.bind(target) : member; + }, + }); + const store = new SlackLinkStore({ + getData: () => data as any, getSlack: () => slack, notify: async (i) => notices.push(i), logger: silent, + ...(opts.linkPageSize ? { linkPageSize: opts.linkPageSize } : {}), + }); + expect(bindSlackLinkRemovalTriggers(ql as any, store, silent)).toBe(true); + // The platform's write audit (plugin-audit) is an `after*` hook attributing `session.userId`; this stands in for it. + const audit: Array<{ event: string; id: unknown; by: unknown; written: string }> = []; + for (const event of ['afterInsert', 'afterUpdate', 'afterDelete']) { + ql.registerHook(event, async (ctx: any) => { + audit.push({ event, id: ctx.input?.id ?? ctx.result?.id, by: ctx.session?.userId, written: JSON.stringify([ctx.input?.data ?? null, ctx.result ?? null]) }); + }, { object: CHANNEL_USER_LINK_OBJECT }); + } + + const handlers = new Map Promise>(); + const mount = (verb: string) => vi.fn((path: string, h: any) => handlers.set(`${verb} ${path}`, h)); + const http = { get: mount('GET'), post: mount('POST'), put: mount('PUT'), delete: mount('DELETE'), patch: vi.fn(), use: vi.fn() }; + registerSlackLinkRoutes(http as never, { resolveCaller: async (req: any) => CONTEXTS[req.headers.authorization], getStore: () => store }); + + async function call(verb: string, route: string, bearer: string, opts: { body?: unknown; query?: Record; id?: string } = {}) { + const handler = handlers.get(`${verb} ${route}`); + if (!handler) throw new Error(`no ${verb} ${route}`); + const out: { status: number; body: any } = { status: 0, body: undefined }; + const res = { status: (c: number) => { out.status = c; return res; }, json: (b: unknown) => { out.body = b; }, header: () => res, send: () => undefined }; + await handler({ params: opts.id ? { id: opts.id } : {}, query: opts.query ?? {}, headers: { authorization: bearer }, method: verb, path: route, body: opts.body }, res); + expect(envelopeViolations(out.body), JSON.stringify(out.body)).toEqual([]); + return out; + } + const links = async () => (await ql.find(CHANNEL_USER_LINK_OBJECT, { fields: ['user_id', 'state', 'external_user_id'] }, SYSTEM)) as any[]; + const install = () => call('PUT', SLACK_ACCOUNT_ROUTE, 'admin_a', { body: { token: GOOD } }); + const connect = async (bearer: string) => { + await call('POST', `${SLACK_LINK_ROUTE}/proposal`, bearer); + return call('POST', `${SLACK_LINK_ROUTE}/confirm`, bearer); + }; + const setUser = (id: string, values: Record) => ql.update('sys_user', values, { where: { id }, ...SYSTEM } as never); + return { ql, driver, store, call, links, install, connect, setUser, race, calls, directory, notices, audit }; +} + +describe('the Slack install — an administrator\'s token, at rest', () => { + it('is proven by Slack, encrypted in the row, never answered, and opens only under its organization', async () => { + const t = await boot(); + const put = await t.call('PUT', SLACK_ACCOUNT_ROUTE, 'admin_a', { body: { token: GOOD } }); + expect(put.status).toBe(200); + expect(put.body.data.account).toMatchObject({ workspace: 'Acme', workspaceId: 'T1', status: 'active' }); + expect(t.calls.map((c) => c.method)).toEqual(['auth.test']); + expect(JSON.stringify(put.body)).not.toContain(GOOD); + expect(JSON.stringify((await t.call('GET', SLACK_ACCOUNT_ROUTE, 'admin_a')).body)).not.toContain(GOOD); + + // The stored row, read below the engine: the column holds a reference, never the token. + const raw = await t.driver.find(CHANNEL_ACCOUNT_OBJECT, { where: {} } as never); + expect(raw).toHaveLength(1); + expect(JSON.stringify(raw)).not.toContain(GOOD); + const id = String((raw as any[])[0].id); + expect(await t.ql.resolveSecretField(CHANNEL_ACCOUNT_OBJECT, id, 'bot_token', { tenantId: 'org_a' })).toBe(GOOD); + await expect(t.ql.resolveSecretField(CHANNEL_ACCOUNT_OBJECT, id, 'bot_token', { tenantId: 'org_b' })).rejects.toThrow(); + }); + + it('a value that is not a Slack token is refused before Slack is asked, and nothing is saved', async () => { + const t = await boot(); + for (const token of ['xoxb:acme', 'xoxb/acme', 'xoxb-åcme', 'xoxb acme', 'xoxb-acme\n']) { + const put = await t.call('PUT', SLACK_ACCOUNT_ROUTE, 'admin_a', { body: { token: `${token}x` } }); + expect([put.body.error.code, put.status], token).toEqual(['VALIDATION_ERROR', 400]); + } + expect(t.calls).toEqual([]); + expect(await t.ql.find(CHANNEL_ACCOUNT_OBJECT, {}, SYSTEM)).toHaveLength(0); + }); + + it('a token Slack refuses is not saved', async () => { + const t = await boot(); + const put = await t.call('PUT', SLACK_ACCOUNT_ROUTE, 'admin_a', { body: { token: 'xoxb-wrong' } }); + expect([put.body.error.code, put.status]).toEqual(['VALIDATION_ERROR', 400]); + expect(await t.ql.find(CHANNEL_ACCOUNT_OBJECT, {}, SYSTEM)).toHaveLength(0); + }); +}); + +describe('a person\'s link — proposed by email, delivering once confirmed', () => { + it('proposes by email match, confirms once, and answers no proposal when no Slack user holds the email', async () => { + const t = await boot(); + await t.install(); + const proposed = await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada'); + expect(proposed.body.data.link).toEqual({ state: 'proposed' }); + expect(await t.store.confirmedUsers('org_a', ['u_ada'])).toEqual(new Set()); + + const confirmed = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'ada'); + expect(confirmed.body.data.link).toMatchObject({ slackUserId: 'UADA', slackUserName: 'Ada', state: 'confirmed' }); + expect(await t.store.confirmedUsers('org_a', ['u_ada', 'u_bob'])).toEqual(new Set(['u_ada'])); + expect((await t.call('GET', SLACK_LINK_ROUTE, 'ada')).body.data).toMatchObject({ account: { workspace: 'Acme' }, link: { state: 'confirmed' } }); + + await t.ql.update('sys_user', { email: 'nobody@example.test' }, { where: { id: 'u_bob' }, ...SYSTEM } as never); + expect((await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'bob')).body.data.link).toBeNull(); + expect(await t.links()).toHaveLength(1); + }); + + it('refuses with no install, no proposal to confirm, no current organization, and any query parameter', async () => { + const t = await boot(); + const noInstall = await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada'); + expect([noInstall.body.error.code, noInstall.status]).toEqual(['RESOURCE_CONFLICT', 409]); + await t.install(); + const nothing = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'ada'); + expect([nothing.body.error.code, nothing.status]).toEqual(['RESOURCE_NOT_FOUND', 404]); + const noOrg = await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada_no_org'); + expect([noOrg.body.error.code, noOrg.status]).toEqual(['PERMISSION_DENIED', 403]); + const query = await t.call('GET', SLACK_LINK_ROUTE, 'ada', { query: { user: 'u_bob' } }); + expect([query.body.error.code, query.status]).toEqual(['VALIDATION_ERROR', 400]); + expect(await t.links()).toHaveLength(0); + }); +}); + +describe('the proposal rule — a verified email, and no one named before it is confirmed', () => { + const lookups = (calls: Array<{ method: string }>) => calls.filter((c) => c.method.startsWith('users.lookupByEmail')); + + it('an unverified email is answered exactly as no match, and Slack is not asked', async () => { + const t = await boot(); + await t.install(); + await t.setUser('u_bob', { email: 'nobody@example.test' }); + const noMatch = await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'bob'); + expect(lookups(t.calls)).toHaveLength(1); + + await t.setUser('u_ada', { email_verified: false }); + const unverified = await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada'); + expect([unverified.status, unverified.body]).toEqual([noMatch.status, noMatch.body]); + expect(unverified.body.data).toEqual({ link: null }); + expect(lookups(t.calls)).toHaveLength(1); + expect(JSON.stringify(unverified.body)).not.toMatch(/UADA|Ada/); + expect(await t.links()).toEqual([]); + }); + + it('a match names no Slack user, to the person or an administrator, until the person confirms it', async () => { + const t = await boot(); + await t.install(); + const proposed = await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada'); + const own = await t.call('GET', SLACK_LINK_ROUTE, 'ada'); + const listed = await t.call('GET', SLACK_LINKS_ROUTE, 'admin_a'); + expect(proposed.body.data).toEqual({ link: { state: 'proposed' } }); + expect(own.body.data.link).toEqual({ state: 'proposed' }); + expect(listed.body.data.links).toMatchObject([{ userId: 'u_ada', slackUserId: null, slackUserName: null, state: 'proposed' }]); + for (const answer of [proposed, own, listed]) expect(JSON.stringify(answer.body)).not.toMatch(/UADA|Ada/); + + const confirmed = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'ada'); + expect(confirmed.body.data.link).toMatchObject({ slackUserId: 'UADA', slackUserName: 'Ada', state: 'confirmed' }); + expect((await t.call('GET', SLACK_LINKS_ROUTE, 'admin_a')).body.data.links).toMatchObject([{ slackUserId: 'UADA', slackUserName: 'Ada' }]); + }); + + it('a confirmation is refused once the email changed or is no longer verified, and holds while it is unchanged', async () => { + const t = await boot(); + await t.install(); + await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada'); + await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'bob'); + await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'admin_a'); + + await t.setUser('u_ada', { email: 'ada.new@example.test' }); + const changed = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'ada'); + expect([changed.body.error.code, changed.status]).toEqual(['RESOURCE_CONFLICT', 409]); + expect(changed.body.error.userMessage).toBe(enMessages.slackLinkProposalOutdated); + + await t.setUser('u_bob', { email_verified: false }); + const unverified = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'bob_fr'); + expect([unverified.body.error.code, unverified.status]).toEqual(['RESOURCE_CONFLICT', 409]); + expect(unverified.body.error.userMessage).toBe(frMessages.slackLinkProposalOutdated); + + const unchanged = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'admin_a'); + expect(unchanged.body.data.link).toMatchObject({ slackUserId: 'UADM', state: 'confirmed' }); + expect(await t.store.confirmedUsers('org_a', ['u_ada', 'u_bob', 'u_admin'])).toEqual(new Set(['u_admin'])); + expect((await t.links()).filter((l) => l.state === 'proposed').map((l) => l.user_id).sort()).toEqual(['u_ada', 'u_bob']); + }); + + it('a confirmation applies only to the proposal that was checked: a row changed before the write is not confirmed', async () => { + const t = await boot(); + await t.install(); + await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada'); + const [row] = (await t.ql.find(CHANNEL_USER_LINK_OBJECT, { fields: ['id'] }, SYSTEM)) as any[]; + t.race.beforeLinkUpdate = () => t.ql.update(CHANNEL_USER_LINK_OBJECT, { proposal_email_hash: 'f'.repeat(64) }, { where: { id: row.id }, ...SYSTEM } as never); + const raced = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'ada'); + expect(t.race.beforeLinkUpdate).toBeUndefined(); + expect([raced.body.error.code, raced.status]).toEqual(['RESOURCE_CONFLICT', 409]); + const [after] = (await t.ql.find(CHANNEL_USER_LINK_OBJECT, { fields: ['state', 'confirmed_at'] }, SYSTEM)) as any[]; + expect([after.state, after.confirmed_at ?? null]).toEqual(['proposed', null]); + expect(await t.store.confirmedUsers('org_a', ['u_ada'])).toEqual(new Set()); + }); + + it('a proposal stores no Slack user; the confirmation records the one Slack names for the verified email', async () => { + const t = await boot(); + await t.install(); + await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada'); + const stored = async () => (await t.driver.find(CHANNEL_USER_LINK_OBJECT, { where: {} } as never)) as any[]; + const [proposed] = await stored(); + expect([proposed.state, proposed.external_user_id ?? null, proposed.external_display_name ?? null]).toEqual(['proposed', null, null]); + const inserted = t.audit.filter((a) => a.event === 'afterInsert'); + expect(inserted).toHaveLength(1); + expect(inserted[0]!.written).not.toMatch(/UADA|Ada/); + expect(lookups(t.calls)).toHaveLength(1); + + const confirmed = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'ada'); + expect(confirmed.body.data.link).toMatchObject({ slackUserId: 'UADA', slackUserName: 'Ada', state: 'confirmed' }); + expect(lookups(t.calls)).toHaveLength(2); + const [row] = await stored(); + expect([row.state, row.external_user_id, row.external_display_name]).toEqual(['confirmed', 'UADA', 'Ada']); + }); + + it('a confirmation is refused when Slack no longer names a user for the email, or names one linked to someone else', async () => { + const t = await boot(); + await t.install(); + await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada'); + delete t.directory['u_ada@example.test']; + const gone = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'ada'); + expect([gone.body.error.code, gone.status]).toEqual(['RESOURCE_CONFLICT', 409]); + + // Two people whose verified email Slack resolves to one user: the first to confirm holds it. + await t.setUser('u_admin', { email: 'u_bob@example.test' }); + await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'bob'); + await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'admin_a'); + expect((await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'bob')).body.data.link).toMatchObject({ slackUserId: 'UBOB', state: 'confirmed' }); + const taken = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'admin_a'); + expect([taken.body.error.code, taken.status]).toEqual(['RESOURCE_CONFLICT', 409]); + expect(await t.store.confirmedUsers('org_a', ['u_ada', 'u_bob', 'u_admin'])).toEqual(new Set(['u_bob'])); + }); + + it('a new proposal replaces one made for another email, and confirms for the new one', async () => { + const t = await boot(); + await t.install(); + await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada'); + await t.setUser('u_ada', { email: 'ada.new@example.test' }); + expect((await t.call('POST', `${SLACK_LINK_ROUTE}/proposal`, 'ada')).body.data).toEqual({ link: { state: 'proposed' } }); + expect(await t.links()).toHaveLength(1); + const confirmed = await t.call('POST', `${SLACK_LINK_ROUTE}/confirm`, 'ada'); + expect(confirmed.body.data.link).toMatchObject({ slackUserId: 'UADA2', state: 'confirmed' }); + expect(t.audit.filter((a) => a.event === 'afterDelete').map((a) => a.by)).toEqual(['u_ada']); + }); +}); + +describe('the riders of ruling 7024100939', () => { + it('(5) every administrator door demands setup.write in the current organization; a person holding none is refused before anything is read', async () => { + expect(SLACK_ADMIN_CAPABILITY).toBe('setup.write'); + const t = await boot(); + await t.install(); + await t.connect('bob'); + const [link] = await t.links(); + for (const [verb, route, opts] of [ + ['GET', SLACK_ACCOUNT_ROUTE, {}], ['PUT', SLACK_ACCOUNT_ROUTE, { body: { token: GOOD } }], ['DELETE', SLACK_ACCOUNT_ROUTE, {}], + ['GET', SLACK_LINKS_ROUTE, {}], ['DELETE', `${SLACK_LINKS_ROUTE}/:id`, { id: 'whatever' }], + ] as const) { + const refused = await t.call(verb, route, 'ada', opts as never); + expect([refused.body.error.code, refused.status], `${verb} ${route}`).toEqual(['PERMISSION_DENIED', 403]); + } + expect(await t.links()).toEqual([link]); + expect((await t.call('GET', SLACK_LINKS_ROUTE, 'admin_a')).body.data.links).toMatchObject([{ userId: 'u_bob', state: 'confirmed' }]); + }); + + it('(1)(2)(4) an administrator\'s removal is audited as theirs, tells the person by inbox and email, and the person may link again', async () => { + const t = await boot(); + await t.install(); + await t.connect('ada'); + const [row] = (await t.ql.find(CHANNEL_USER_LINK_OBJECT, { fields: ['id'] }, SYSTEM)) as any[]; + const removed = await t.call('DELETE', `${SLACK_LINKS_ROUTE}/:id`, 'admin_a', { id: String(row.id) }); + expect(removed.body.data).toEqual({ removed: true }); + expect(t.audit.filter((a) => a.event === 'afterDelete').map(({ event, id, by }) => ({ event, id, by }))).toEqual([{ event: 'afterDelete', id: row.id, by: 'u_admin' }]); + expect(t.notices).toHaveLength(1); + expect(t.notices[0]).toMatchObject({ + topic: SLACK_LINK_REMOVED_TOPIC, audience: ['user:u_ada'], organizationId: 'org_a', channels: ['inbox', 'email'], actorId: 'u_admin', + keyedText: { titleKey: 'messages.slackLinkRemovedTitle', bodyKey: 'messages.slackLinkRemovedBody', params: { workspace: 'Acme' } }, + }); + + const again = await t.connect('ada'); + expect(again.body.data.link).toMatchObject({ slackUserId: 'UADA', state: 'confirmed' }); + expect(t.audit.filter((a) => a.event === 'afterInsert').map((a) => a.by)).toEqual(['u_ada', 'u_ada']); + }); + + it('(2) an administrator removes only a link to their own organization\'s install', async () => { + const t = await boot(); + await t.install(); + await t.connect('ada'); + await t.call('PUT', SLACK_ACCOUNT_ROUTE, 'admin_b', { body: { token: GOOD } }); + const [row] = (await t.ql.find(CHANNEL_USER_LINK_OBJECT, { fields: ['id'] }, SYSTEM)) as any[]; + const other = await t.call('DELETE', `${SLACK_LINKS_ROUTE}/:id`, 'admin_b', { id: String(row.id) }); + expect([other.body.error?.code, other.status]).toEqual(['RESOURCE_NOT_FOUND', 404]); + expect(await t.links()).toHaveLength(1); + expect(t.notices).toEqual([]); + }); + + it('(2) the uninstall tells every linked person, however many pages their links take', async () => { + const t = await boot({ linkPageSize: 2 }); + await t.install(); + for (const bearer of ['ada', 'bob', 'admin_a']) await t.connect(bearer); + expect((await t.call('DELETE', SLACK_ACCOUNT_ROUTE, 'admin_a')).body.data).toEqual({ removed: true }); + expect(t.notices.map((n) => n.audience[0]).sort()).toEqual(['user:u_ada', 'user:u_admin', 'user:u_bob']); + expect(t.audit.filter((a) => a.event === 'afterDelete').map((a) => a.by)).toEqual(['u_admin', 'u_admin', 'u_admin']); + expect(await t.links()).toEqual([]); + }); + + it('(1) the person\'s own removal and the uninstall are audited as their actor; only the administrator\'s tells anyone', async () => { + const t = await boot(); + await t.install(); + await t.connect('ada'); + await t.connect('bob'); + expect((await t.call('DELETE', SLACK_LINK_ROUTE, 'ada')).body.data).toEqual({ removed: true }); + expect(t.notices).toHaveLength(0); + expect((await t.call('DELETE', SLACK_ACCOUNT_ROUTE, 'admin_a')).body.data).toEqual({ removed: true }); + expect(t.audit.filter((a) => a.event === 'afterDelete').map((a) => a.by)).toEqual(['u_ada', 'u_admin']); + expect(t.notices.map((n) => n.audience)).toEqual([['user:u_bob']]); + expect(await t.links()).toEqual([]); + expect(await t.ql.find(CHANNEL_ACCOUNT_OBJECT, {}, SYSTEM)).toHaveLength(0); + }); + + it('(3) a link goes when the person leaves the organization, is banned, or is deleted — each removal audited', async () => { + const t = await boot(); + await t.install(); + await t.connect('ada'); + await t.connect('bob'); + await t.connect('admin_a'); + const left = { context: { isSystem: true, userId: 'u_admin' } as ExecutionContext }; + await t.ql.delete('sys_member', { where: { id: 'm_ada' }, ...left } as never); + expect((await t.links()).map((l) => l.user_id).sort()).toEqual(['u_admin', 'u_bob']); + await t.ql.update('sys_user', { banned: true }, { where: { id: 'u_bob' }, ...left } as never); + expect((await t.links()).map((l) => l.user_id)).toEqual(['u_admin']); + await t.ql.delete('sys_user', { where: { id: 'u_admin' }, ...SYSTEM } as never); + expect(await t.links()).toEqual([]); + expect(t.audit.filter((a) => a.event === 'afterDelete')).toHaveLength(3); + expect(t.audit.filter((a) => a.event === 'afterDelete').slice(0, 2).map((a) => a.by)).toEqual(['u_admin', 'u_admin']); + }); + + it('(3) a ban removes the person\'s links in every organization in one write, each removal audited', async () => { + const t = await boot(); + await t.install(); + await t.call('PUT', SLACK_ACCOUNT_ROUTE, 'admin_b', { body: { token: GOOD } }); + await t.connect('admin_a'); + await t.connect('admin_b'); + await t.connect('ada'); + expect((await t.links()).map((l) => l.user_id).sort()).toEqual(['u_ada', 'u_admin', 'u_admin']); + const deletes = vi.spyOn(t.ql, 'delete'); + await t.ql.update('sys_user', { banned: true }, { where: { id: 'u_admin' }, context: { isSystem: true, userId: 'u_ada' } } as never); + expect(deletes.mock.calls.filter(([object]) => object === CHANNEL_USER_LINK_OBJECT)).toHaveLength(1); + expect((await t.links()).map((l) => l.user_id)).toEqual(['u_ada']); + expect(t.audit.filter((a) => a.event === 'afterDelete').map((a) => a.by)).toEqual(['u_ada', 'u_ada']); + }); + + it('(3) a link goes when the person\'s membership moves to another organization, audited as who moved it', async () => { + const t = await boot(); + await t.install(); + await t.connect('ada'); + await t.connect('bob'); + const mover = { context: { isSystem: true, userId: 'u_admin' } as ExecutionContext }; + await t.ql.update('sys_member', { organization_id: 'org_b' }, { where: { id: 'm_bob' }, ...mover } as never); + expect((await t.links()).map((l) => l.user_id)).toEqual(['u_ada']); + expect(t.audit.filter((a) => a.event === 'afterDelete').map((a) => a.by)).toEqual(['u_admin']); + // A write that leaves the organization as it was removes nothing. + await t.ql.update('sys_member', { role: 'admin' }, { where: { id: 'm_ada' }, ...mover } as never); + expect((await t.links()).map((l) => l.user_id)).toEqual(['u_ada']); + }); +}); diff --git a/packages/services/service-messaging/src/slack-links.ts b/packages/services/service-messaging/src/slack-links.ts new file mode 100644 index 00000000000..6f5c4e4222d --- /dev/null +++ b/packages/services/service-messaging/src/slack-links.ts @@ -0,0 +1,561 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The Slack binding store (ADR-0013 addendum of 2026-11-19, step 2): an + * organization's install (`sys_channel_account`) and each person's link to + * their Slack user (`sys_channel_user_link`), proposed by email match and + * confirmed once by the person. + * + * ## The proposal + * + * A Slack link is proposed only for a verified email, and names no one before + * it is confirmed: {@link SlackLinkStore.propose} looks a Slack user up only + * for the person's email while `sys_user.email_verified` reads verified, and + * answers an unverified email exactly as it answers no match. The proposal + * records a digest of the email it was made for, and no Slack user; + * {@link SlackLinkStore.confirm} confirms only while the person's email is + * still verified and still that email, looks it up again, records the Slack + * user it names, and applies only to the proposal that was checked. A new + * proposal replaces one made for another email. + * + * ## What every write carries + * + * Each write is an ENGINE write under a system context that names the person + * who acted (`userId`), and the organization (`tenantId`) on the install's + * writes. So the platform's write audit (`afterInsert` / `afterUpdate` / + * `afterDelete`, which these objects are not excluded from) records the + * proposal, the confirmation (ADR-0013 §8 item 2's one-time row) and every + * removal, with who did it (ruling `7024100939`, rider 1). A cascade (the + * person or the install deleted) runs the same hooks on each link it removes. + * + * ## The token + * + * `bot_token` is a `secret` field: the engine encrypts it on write (the + * install's organization in the encryption context) and masks it on every + * read. {@link SlackLinkStore.slackFor} is its one reader, through the + * engine's privileged `resolveSecretField`, and hands it only to the `slack` + * client service. No answer of this module, and no route, carries it. + * + * ## Removal triggers (rider 3) + * + * {@link bindSlackLinkRemovalTriggers}: a person who leaves an organization + * (`sys_member` deleted, or moved to another organization) loses their links + * there; a banned person loses all of theirs. The deletion of the person + * cascades by the object's own declaration. Engine hooks, as the session + * trigger in plugin-auth: a write below the engine (a raw driver delete) is + * not seen, and the per-delivery check in the Slack channel still requires a + * confirmed link on an active install. + */ + +import { createHash, randomUUID } from 'node:crypto'; +import type { IDataEngine } from '@objectstack/spec/contracts'; +import { isEmailVerifiedUserRow } from '@objectstack/types'; +import type { EmitInput } from './messaging-service.js'; +import { enMessages, type MessagingMessageId } from './translations/messages.js'; + +export const CHANNEL_ACCOUNT_OBJECT = 'sys_channel_account'; +export const CHANNEL_USER_LINK_OBJECT = 'sys_channel_user_link'; +export const SLACK_CHANNEL_ID = 'slack'; +/** The topic of the notice a person gets when an administrator removes their link (rider 2). */ +export const SLACK_LINK_REMOVED_TOPIC = 'messaging.slack_link_removed'; +const TOKEN_FIELD = 'bot_token'; +const USER_OBJECT = 'sys_user'; +const MEMBER_OBJECT = 'sys_member'; +/** Slack answers that mean the install's token no longer works. */ +const TOKEN_REFUSALS = new Set(['invalid_auth', 'token_revoked', 'token_expired', 'account_inactive', 'not_authed']); + +/** + * connector-slack's client, as its plugin registers it under the `slack` + * service (`SlackClientService`). Declared here, structurally, because this + * package cannot import connector-slack: that dependency would close a + * workspace cycle through `@objectstack/service-automation`. + */ +export interface SlackClientSurface { + client(token: string): { call(input: Record): Promise> }; +} + +/** One Slack Web API answer, read off connector-slack's `call` result. */ +export interface SlackAnswer { + readonly ok: boolean; + readonly status: number; + readonly body: Record; + readonly error?: string; +} + +/** One API client for one install: `method` with `params`. */ +export type SlackCall = (method: string, params?: Record) => Promise; + +export interface SlackAccount { + readonly id: string; + readonly organizationId: string; + readonly displayName: string; + readonly externalId: string; + readonly status: 'active' | 'revoked'; +} + +export interface SlackLink { + readonly id: string; + readonly accountId: string; + readonly userId: string; + /** The linked Slack user: recorded at confirmation, so a proposal has none. */ + readonly externalUserId?: string; + readonly externalDisplayName?: string; + readonly state: 'proposed' | 'confirmed'; + readonly confirmedAt?: string; + /** The digest of the email the proposal was made for ({@link emailDigest}). Never answered. */ + readonly proposalEmailHash?: string; +} + +/** + * A refusal a door answers with its own status and code. `messageId` names the + * refusal's sentence in the messaging catalog (`translations/messages.ts`), + * whose `en` entry is `message`; the door answers it in the caller's language. + */ +export class SlackLinkError extends Error { + constructor(readonly status: number, readonly code: string, message: string, readonly messageId?: MessagingMessageId) { + super(message); + this.name = 'SlackLinkError'; + } +} + +/** The digest a proposal records of the email it was made for: SHA-256 of the trimmed, lower-cased address. */ +export function emailDigest(email: string): string { + return createHash('sha256').update(email.trim().toLowerCase()).digest('hex'); +} + +type SecretEngine = IDataEngine & { + resolveSecretField?(object: string, recordId: string, field: string, opts?: { tenantId?: string }): Promise; +}; + +export interface SlackLinkStoreOptions { + getData(): IDataEngine | undefined; + /** The `slack` client service; `undefined` when connector-slack is not composed. */ + getSlack(): SlackClientSurface | undefined; + /** The messaging ingress, for the notice an administrator's removal sends (rider 2). */ + notify(input: EmitInput): Promise; + logger: { warn(...args: unknown[]): void }; + now?(): string; + /** How many links one read takes when every link of an install is removed (default {@link LINK_PAGE}). */ + linkPageSize?: number; +} + +/** The page an install's removal reads its links in, so it reaches every one of them. */ +const LINK_PAGE = 500; + +const READ = { context: { isSystem: true } } as const; +const by = (userId: string | undefined, organizationId?: string) => ({ + context: { isSystem: true, ...(userId ? { userId } : {}), ...(organizationId ? { tenantId: organizationId } : {}) }, +}); +const str = (v: unknown): string | undefined => (v == null || v === '' ? undefined : String(v)); + +function toAccount(row: Record): SlackAccount { + return { + id: String(row.id), + organizationId: String(row.organization_id ?? ''), + displayName: String(row.display_name ?? ''), + externalId: String(row.external_id ?? ''), + status: row.status === 'revoked' ? 'revoked' : 'active', + }; +} + +function toLink(row: Record): SlackLink { + return { + id: String(row.id), + accountId: String(row.account_id), + userId: String(row.user_id), + ...(str(row.external_user_id) ? { externalUserId: String(row.external_user_id) } : {}), + ...(str(row.external_display_name) ? { externalDisplayName: String(row.external_display_name) } : {}), + state: row.state === 'confirmed' ? 'confirmed' : 'proposed', + ...(str(row.confirmed_at) ? { confirmedAt: String(row.confirmed_at) } : {}), + ...(str(row.proposal_email_hash) ? { proposalEmailHash: String(row.proposal_email_hash) } : {}), + }; +} + +export class SlackLinkStore { + constructor(private readonly opts: SlackLinkStoreOptions) {} + + private data(): SecretEngine { + const data = this.opts.getData(); + if (!data) throw new SlackLinkError(503, 'SERVICE_UNAVAILABLE', 'This server has no data engine, so Slack links cannot be read or changed.'); + return data as SecretEngine; + } + + private slack(): SlackClientSurface { + const slack = this.opts.getSlack(); + if (!slack) { + throw new SlackLinkError(503, 'SERVICE_UNAVAILABLE', + 'This server has no Slack transport: compose ConnectorSlackPlugin (@objectstack/connector-slack) to install Slack and connect people to it. Nothing was changed.'); + } + return slack; + } + + /** The organization's Slack install, or `undefined`. */ + async account(organizationId: string): Promise { + const row = await this.data().findOne(CHANNEL_ACCOUNT_OBJECT, { + where: { organization_id: organizationId, channel_id: SLACK_CHANNEL_ID }, + fields: ['id', 'organization_id', 'display_name', 'external_id', 'status'], + }, READ); + return row ? toAccount(row) : undefined; + } + + /** + * Install (or replace the token of) the organization's own Slack app. The + * token is proven with `auth.test` first, and its workspace is what the + * row records; a token for another workspace than the one installed is + * refused, since every link names a user of the installed one. + */ + async install(organizationId: string, token: string, actor: string): Promise { + const answer = await callWith(this.slack(), token)('auth.test'); + const teamId = str(answer.body.team_id); + if (!answer.ok || !teamId) { + throw new SlackLinkError(400, 'VALIDATION_ERROR', + `Slack did not accept this token (${answer.error ?? `HTTP ${answer.status}`}). Nothing was saved.`); + } + const values = { + display_name: str(answer.body.team) ?? teamId, + external_id: teamId, + [TOKEN_FIELD]: token, + status: 'active', + }; + const data = this.data(); + const existing = await this.account(organizationId); + if (existing && existing.externalId !== teamId) { + throw new SlackLinkError(409, 'RESOURCE_CONFLICT', + `This token belongs to another Slack workspace than the one installed (${existing.displayName}). ` + + 'Remove the install first, which removes every link to it. Nothing was saved.'); + } + if (existing) { + await data.update(CHANNEL_ACCOUNT_OBJECT, values, { where: { id: existing.id }, ...by(actor, organizationId) } as never); + } else { + await data.insert(CHANNEL_ACCOUNT_OBJECT, + { id: randomUUID(), organization_id: organizationId, channel_id: SLACK_CHANNEL_ID, ...values }, by(actor, organizationId)); + } + return (await this.account(organizationId))!; + } + + /** + * Remove the install and, first, every link to it, each as an administrator's + * removal that tells the person. The links are read in pages, in id order, + * until a page comes back short, so every linked person is reached. + */ + async uninstall(organizationId: string, actor: string): Promise { + const account = await this.account(organizationId); + if (!account) return false; + const data = this.data(); + const size = Math.max(1, this.opts.linkPageSize ?? LINK_PAGE); + for (let after: string | undefined; ;) { + const rows = await data.find(CHANNEL_USER_LINK_OBJECT, { + where: { account_id: account.id, ...(after === undefined ? {} : { id: { $gt: after } }) }, + orderBy: [{ field: 'id', order: 'asc' }], + limit: size, + }, READ); + const page = (rows ?? []).map(toLink); + for (const link of page) await this.removeLink(link, account, actor, true); + if (page.length < size) break; + after = page[page.length - 1]!.id; + } + await data.delete(CHANNEL_ACCOUNT_OBJECT, { where: { id: account.id }, ...by(actor, organizationId) } as never); + return true; + } + + /** Every link to the organization's install. */ + async links(organizationId: string): Promise { + const account = await this.account(organizationId); + if (!account) return []; + const rows = await this.data().find(CHANNEL_USER_LINK_OBJECT, { where: { account_id: account.id }, limit: 10000 }, READ); + return (rows ?? []).map(toLink); + } + + /** The person's link to the organization's install, or `undefined`. */ + async linkOf(organizationId: string, userId: string): Promise { + const account = await this.account(organizationId); + if (!account) return undefined; + const row = await this.data().findOne(CHANNEL_USER_LINK_OBJECT, { where: { account_id: account.id, user_id: userId } }, READ); + return row ? toLink(row) : undefined; + } + + /** + * Propose a link by the person's verified email (Slack + * `users.lookupByEmail`). A confirmed link, or a proposal made for the + * person's current verified email, is answered as it is; a proposal made + * for another email, or for one no longer verified, is replaced. + * `undefined` — nothing proposed, and Slack is not asked — when the person + * has no verified email; `undefined` too when no Slack user holds it, or + * that Slack user is already linked to another person in this install. + */ + async propose(organizationId: string, userId: string): Promise { + const account = await this.requireActive(organizationId); + const email = await this.verifiedEmail(userId); + const existing = await this.linkOf(organizationId, userId); + if (existing) { + if (existing.state === 'confirmed' || (email && existing.proposalEmailHash === emailDigest(email))) return existing; + await this.removeLink(existing, undefined, userId, false); + } + if (!email) return undefined; + const data = this.data(); + // `users.lookupByEmail` reads its argument from the query string or a + // form body, not JSON (Slack's accepted content types for the method). + const answer = await (await this.slackFor(account))(`users.lookupByEmail?email=${encodeURIComponent(email)}`); + if (!answer.ok) { + if (answer.error === 'users_not_found') return undefined; + throw await this.slackFault(account, answer); + } + if (!(await this.linkableUser(account, answer))) return undefined; + await data.insert(CHANNEL_USER_LINK_OBJECT, { + id: randomUUID(), + organization_id: organizationId, + account_id: account.id, + user_id: userId, + proposal_email_hash: emailDigest(email), + state: 'proposed', + }, by(userId, organizationId)); + return this.linkOf(organizationId, userId); + } + + /** + * The person confirms their proposal: from now on it delivers. Only while + * their email is still verified and still the email the proposal was made + * for, and while Slack still names a user for it that no one else in the + * install is linked to; otherwise refused, and the person asks for a new + * proposal. The Slack user is recorded here. The write applies only to the + * proposal that was checked: it is conditioned on the row's id, its + * `proposed` state and that email's digest, and a write that matches no + * row is refused the same way. + */ + async confirm(organizationId: string, userId: string): Promise { + const link = await this.linkOf(organizationId, userId); + if (!link) { + throw new SlackLinkError(404, 'RESOURCE_NOT_FOUND', + 'You have no proposed Slack link in this organization to confirm: ask for a proposal first. Nothing was changed.'); + } + if (link.state === 'confirmed') return link; + const outdated = () => new SlackLinkError(409, 'RESOURCE_CONFLICT', enMessages.slackLinkProposalOutdated, 'slackLinkProposalOutdated'); + const email = await this.verifiedEmail(userId); + const digest = email ? emailDigest(email) : undefined; + if (!email || !digest || link.proposalEmailHash !== digest) throw outdated(); + const account = await this.requireActive(organizationId); + const answer = await (await this.slackFor(account))(`users.lookupByEmail?email=${encodeURIComponent(email)}`); + if (!answer.ok && answer.error !== 'users_not_found') throw await this.slackFault(account, answer); + const found = answer.ok ? await this.linkableUser(account, answer) : undefined; + if (!found) throw outdated(); + // A predicate write (`multi: true`), so every `where` key is evaluated + // and the answer is the count of rows it changed: at most this one. + const written = await this.data().update(CHANNEL_USER_LINK_OBJECT, { + state: 'confirmed', + confirmed_at: this.opts.now?.() ?? new Date().toISOString(), + external_user_id: found.id, + external_display_name: found.name ?? null, + }, { where: { id: link.id, state: 'proposed', proposal_email_hash: digest }, multi: true, ...by(userId, organizationId) } as never); + if (!written) throw outdated(); + return (await this.linkOf(organizationId, userId))!; + } + + /** The person removes their own link. */ + async removeOwn(organizationId: string, userId: string): Promise { + const link = await this.linkOf(organizationId, userId); + if (!link) return false; + await this.removeLink(link, undefined, userId, false); + return true; + } + + /** An administrator removes one person's link in their organization; the person is told (rider 2). */ + async removeByAdmin(organizationId: string, linkId: string, actor: string): Promise { + const account = await this.account(organizationId); + if (!account) return false; + const row = await this.data().findOne(CHANNEL_USER_LINK_OBJECT, { where: { id: linkId, account_id: account.id } }, READ); + if (!row) return false; + await this.removeLink(toLink(row), account, actor, true); + return true; + } + + /** + * Remove every link of `userId` — in `organizationId`, or everywhere when + * it is absent — attributed to `actor` (rider 3's triggers). One predicate + * delete (`multi: true`); the engine runs the delete hooks once per row it + * removes, so each removal is audited as before. Answers how many went. + */ + async removeAllOf(userId: string, organizationId: string | undefined, actor: string | undefined): Promise { + const where: Record = { user_id: userId }; + if (organizationId) where.organization_id = organizationId; + const removed = await this.data().delete(CHANNEL_USER_LINK_OBJECT, { where, multi: true, ...by(actor) } as never); + return Number(removed) || 0; + } + + /** The recipients among `userIds` with a confirmed link to the organization's ACTIVE install. */ + async confirmedUsers(organizationId: string, userIds: readonly string[]): Promise> { + const account = await this.account(organizationId); + if (!account || account.status !== 'active' || userIds.length === 0) return new Set(); + const rows = await this.data().find(CHANNEL_USER_LINK_OBJECT, { + where: { account_id: account.id, state: 'confirmed', user_id: { $in: [...userIds] } }, + fields: ['user_id'], + limit: userIds.length, + }, READ); + return new Set((rows ?? []).map((r: any) => String(r.user_id))); + } + + /** Where to deliver to `userId`: their confirmed link and the active install, or `undefined`. */ + async deliveryTarget(organizationId: string, userId: string): Promise<{ account: SlackAccount; link: SlackLink } | undefined> { + const account = await this.account(organizationId); + if (!account || account.status !== 'active') return undefined; + const link = await this.linkOf(organizationId, userId); + return link?.state === 'confirmed' && link.externalUserId ? { account, link } : undefined; + } + + /** A Slack API client for the install, with its token read through the privileged dereference. */ + async slackFor(account: SlackAccount): Promise { + const slack = this.slack(); + const data = this.data(); + if (typeof data.resolveSecretField !== 'function') { + throw new SlackLinkError(503, 'SERVICE_UNAVAILABLE', 'This data engine cannot read an encrypted field, so the Slack token cannot be used.'); + } + const token = await data.resolveSecretField(CHANNEL_ACCOUNT_OBJECT, account.id, TOKEN_FIELD, { tenantId: account.organizationId }); + if (!token) throw new SlackLinkError(503, 'SERVICE_UNAVAILABLE', 'The Slack install has no readable token: set it again.'); + return callWith(slack, token); + } + + /** Record that Slack refused the install's token, so no further delivery is attempted on it. */ + async markRevoked(account: SlackAccount): Promise { + try { + await this.data().update(CHANNEL_ACCOUNT_OBJECT, { status: 'revoked' }, { where: { id: account.id }, ...by(undefined, account.organizationId) } as never); + } catch (err) { + this.opts.logger.warn(`[slack] Slack refused the token of the install '${account.id}', which could not be marked revoked: ${(err as Error)?.message}`); + } + } + + /** The person's email while `sys_user.email_verified` reads verified, else `undefined`. */ + private async verifiedEmail(userId: string): Promise { + const user = await this.data().findOne(USER_OBJECT, { where: { id: userId }, fields: ['email', 'email_verified'] }, READ); + return isEmailVerifiedUserRow(user) ? str(user?.email) : undefined; + } + + /** + * The Slack user a `users.lookupByEmail` answer names, while it can be + * linked: a person, not deleted, and linked to no one in this install. + */ + private async linkableUser(account: SlackAccount, answer: SlackAnswer): Promise<{ id: string; name?: string } | undefined> { + const found = answer.body.user ?? {}; + const id = str(found.id); + if (!id || found.deleted === true || found.is_bot === true) return undefined; + const taken = await this.data().findOne(CHANNEL_USER_LINK_OBJECT, { where: { account_id: account.id, external_user_id: id } }, READ); + if (taken) return undefined; + const name = str(found.real_name) ?? str(found.name); + return name ? { id, name } : { id }; + } + + private async requireActive(organizationId: string): Promise { + const account = await this.account(organizationId); + if (!account || account.status !== 'active') { + throw new SlackLinkError(409, 'RESOURCE_CONFLICT', + account + ? 'Slack refused this organization\'s token: an administrator sets it again before anyone can connect. Nothing was changed.' + : 'Slack is not installed for this organization: an administrator installs it first. Nothing was changed.'); + } + return account; + } + + private async slackFault(account: SlackAccount, answer: SlackAnswer): Promise { + if (answer.error && TOKEN_REFUSALS.has(answer.error)) await this.markRevoked(account); + return new SlackLinkError(502, 'EXTERNAL_SERVICE_ERROR', `Slack answered ${answer.error ?? `HTTP ${answer.status}`}. Nothing was changed.`); + } + + private async removeLink(link: SlackLink, account: SlackAccount | undefined, actor: string, byAdmin: boolean): Promise { + await this.data().delete(CHANNEL_USER_LINK_OBJECT, { where: { id: link.id }, ...by(actor) } as never); + if (!byAdmin || !account) return; + const workspace = account.displayName; + try { + await this.opts.notify({ + topic: SLACK_LINK_REMOVED_TOPIC, + audience: [`user:${link.userId}`], + organizationId: account.organizationId, + channels: ['inbox', 'email'], + actorId: actor, + severity: 'info', + payload: { + title: enMessages.slackLinkRemovedTitle, + body: enMessages.slackLinkRemovedBody.replace('{{workspace}}', workspace), + }, + keyedText: { + titleKey: 'messages.slackLinkRemovedTitle', + bodyKey: 'messages.slackLinkRemovedBody', + params: { workspace }, + }, + }); + } catch (err) { + this.opts.logger.warn( + `[slack] the link of '${link.userId}' was removed by '${actor}', but the notice telling them failed: ${(err as Error)?.message}`, + ); + } + } +} + +/** The answer of connector-slack's `call`, normalised. */ +export function callWith(slack: SlackClientSurface, token: string): SlackCall { + const api = slack.client(token); + return async (method, params = {}) => { + const out = await api.call({ method, params }); + return { + ok: out.ok === true, + status: Number(out.status ?? 0), + body: (out.body && typeof out.body === 'object' ? out.body : {}) as Record, + ...(typeof out.error === 'string' ? { error: out.error } : {}), + }; + }; +} + +/** Is this Slack error code a refusal of the install's token? */ +export function isTokenRefusal(error: string | undefined): boolean { + return error !== undefined && TOKEN_REFUSALS.has(error); +} + +/** The slice of the engine the triggers need. */ +export interface SlackTriggerEngine { + registerHook?(event: string, handler: (ctx: any) => Promise, opts: { object: string; packageId: string }): void; + unregisterHooksByPackage?(packageId: string): number; +} + +const TRIGGER_PACKAGE = 'com.objectstack.service.messaging.slack-links'; + +/** + * Rider 3: remove a person's links when they leave an organization or are + * banned. Never throws into the write that triggered it: a failure is said at + * `error`, because the person keeps a link that should be gone while + * everything looks normal. + */ +export function bindSlackLinkRemovalTriggers( + engine: SlackTriggerEngine | null | undefined, + store: SlackLinkStore, + logger: { error(...args: unknown[]): void }, +): boolean { + if (!engine || typeof engine.registerHook !== 'function') return false; + const register = engine.registerHook.bind(engine); + const remove = async (userId: string | undefined, organizationId: string | undefined, actor: string | undefined, why: string) => { + if (!userId) return; + try { + await store.removeAllOf(userId, organizationId, actor); + } catch (err) { + logger.error( + `[slack] '${userId}' ${why}, but their Slack links could not be removed (${(err as Error)?.message}): they keep ` + + 'receiving notifications on Slack until an administrator removes the link (DELETE /api/v1/messaging/slack/links/:id).', + ); + } + }; + register('afterDelete', async (ctx) => { + await remove(str(ctx?.previous?.user_id), str(ctx?.previous?.organization_id), str(ctx?.session?.userId), 'left an organization'); + }, { object: MEMBER_OBJECT, packageId: TRIGGER_PACKAGE }); + register('afterUpdate', async (ctx) => { + const data = ctx?.input?.data; + const before = str(ctx?.previous?.organization_id); + if (!data || !('organization_id' in data) || !before || before === str(data.organization_id)) return; + await remove(str(ctx?.previous?.user_id), before, str(ctx?.session?.userId), 'left an organization'); + }, { object: MEMBER_OBJECT, packageId: TRIGGER_PACKAGE }); + register('afterUpdate', async (ctx) => { + if (ctx?.input?.data?.banned !== true) return; + await remove(str(ctx?.input?.id) ?? str(ctx?.previous?.id), undefined, str(ctx?.session?.userId), 'was banned'); + }, { object: USER_OBJECT, packageId: TRIGGER_PACKAGE }); + return true; +} + +/** Unbind {@link bindSlackLinkRemovalTriggers} (plugin teardown). */ +export function unbindSlackLinkRemovalTriggers(engine: SlackTriggerEngine | null | undefined): void { + engine?.unregisterHooksByPackage?.(TRIGGER_PACKAGE); +} diff --git a/packages/services/service-messaging/src/translations/ar.objects.generated.ts b/packages/services/service-messaging/src/translations/ar.objects.generated.ts index 715a6030669..24afac05601 100644 --- a/packages/services/service-messaging/src/translations/ar.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/ar.objects.generated.ts @@ -489,5 +489,63 @@ export const arObjects: NonNullable = { label: "تاريخ الإنشاء" } } + }, + sys_channel_account: { + label: "حساب القناة", + pluralLabel: "حسابات القنوات", + description: "تثبيت مؤسسة لتطبيق دردشة، مثل تطبيق Slack الخاص بها، مع رمز البوت الصادر له.", + fields: { + channel_id: { + label: "القناة" + }, + display_name: { + label: "مساحة العمل" + }, + external_id: { + label: "معرّف مساحة العمل" + }, + bot_token: { + label: "رمز البوت" + }, + status: { + label: "الحالة", + options: { + active: "نشط", + revoked: "مُلغى" + } + } + } + }, + sys_channel_user_link: { + label: "ربط مستخدم القناة", + pluralLabel: "روابط مستخدمي القنوات", + description: "ربط شخص بمستخدمه الخاص في مساحة عمل دردشة: يُقترح بمطابقة البريد الإلكتروني، ويبدأ التسليم بعد أن يؤكده الشخص.", + fields: { + account_id: { + label: "الحساب" + }, + user_id: { + label: "المستخدم" + }, + external_user_id: { + label: "معرّف مستخدم الدردشة" + }, + external_display_name: { + label: "اسم مستخدم الدردشة" + }, + state: { + label: "الحالة", + options: { + proposed: "مقترح", + confirmed: "مؤكد" + } + }, + confirmed_at: { + label: "تاريخ التأكيد" + }, + proposal_email_hash: { + label: "تجزئة البريد الإلكتروني للاقتراح" + } + } } }; diff --git a/packages/services/service-messaging/src/translations/bundle-ownership.test.ts b/packages/services/service-messaging/src/translations/bundle-ownership.test.ts index b30899d8924..a79e516a900 100644 --- a/packages/services/service-messaging/src/translations/bundle-ownership.test.ts +++ b/packages/services/service-messaging/src/translations/bundle-ownership.test.ts @@ -24,6 +24,8 @@ const OWNED_OBJECTS = new Set([ 'sys_notification_template', 'sys_http_delivery', 'sys_user_device', + 'sys_channel_account', + 'sys_channel_user_link', ]); describe('objects translation bundle ownership (ADR-0029 D8)', () => { diff --git a/packages/services/service-messaging/src/translations/de.objects.generated.ts b/packages/services/service-messaging/src/translations/de.objects.generated.ts index e499afea701..c862231d46a 100644 --- a/packages/services/service-messaging/src/translations/de.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/de.objects.generated.ts @@ -489,5 +489,63 @@ export const deObjects: NonNullable = { label: "Erstellt am" } } + }, + sys_channel_account: { + label: "Kanalkonto", + pluralLabel: "Kanalkonten", + description: "Die Installation einer Chat-App durch eine Organisation, etwa ihrer eigenen Slack-App, mit dem dafür ausgestellten Bot-Token.", + fields: { + channel_id: { + label: "Kanal" + }, + display_name: { + label: "Workspace" + }, + external_id: { + label: "Workspace-ID" + }, + bot_token: { + label: "Bot-Token" + }, + status: { + label: "Status", + options: { + active: "Aktiv", + revoked: "Widerrufen" + } + } + } + }, + sys_channel_user_link: { + label: "Kanal-Benutzerverknüpfung", + pluralLabel: "Kanal-Benutzerverknüpfungen", + description: "Die Verknüpfung einer Person mit ihrem eigenen Benutzer in einem Chat-Workspace: per E-Mail-Abgleich vorgeschlagen, zugestellt wird erst nach ihrer Bestätigung.", + fields: { + account_id: { + label: "Konto" + }, + user_id: { + label: "Benutzer" + }, + external_user_id: { + label: "Chat-Benutzer-ID" + }, + external_display_name: { + label: "Chat-Benutzername" + }, + state: { + label: "Zustand", + options: { + proposed: "Vorgeschlagen", + confirmed: "Bestätigt" + } + }, + confirmed_at: { + label: "Bestätigt am" + }, + proposal_email_hash: { + label: "Hash der Vorschlags-E-Mail" + } + } } }; diff --git a/packages/services/service-messaging/src/translations/de.source-hashes.generated.ts b/packages/services/service-messaging/src/translations/de.source-hashes.generated.ts index af38a4cb4a4..27210239fc2 100644 --- a/packages/services/service-messaging/src/translations/de.source-hashes.generated.ts +++ b/packages/services/service-messaging/src/translations/de.source-hashes.generated.ts @@ -18,6 +18,8 @@ */ export const deGeneratedSourceHashes: Readonly> = { + "objects.sys_channel_account.fields.display_name.label": "f25b78f28461e4d7", + "objects.sys_channel_account.fields.status.label": "64a420165247654b", "objects.sys_http_delivery.fields.partition_key.label": "ff6e8336a279020a", "objects.sys_http_delivery.fields.status.help": "e437ecf81dfb4715", "objects.sys_http_delivery.fields.status.label": "64a420165247654b", diff --git a/packages/services/service-messaging/src/translations/en.objects.generated.ts b/packages/services/service-messaging/src/translations/en.objects.generated.ts index 2c66ac1d5c7..fabe172e909 100644 --- a/packages/services/service-messaging/src/translations/en.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/en.objects.generated.ts @@ -489,5 +489,63 @@ export const enObjects: NonNullable = { label: "Created At" } } + }, + sys_channel_account: { + label: "Channel Account", + pluralLabel: "Channel Accounts", + description: "An organization's install of a chat app, such as its own Slack app, with the bot token it was issued.", + fields: { + channel_id: { + label: "Channel" + }, + display_name: { + label: "Workspace" + }, + external_id: { + label: "Workspace ID" + }, + bot_token: { + label: "Bot Token" + }, + status: { + label: "Status", + options: { + active: "Active", + revoked: "Revoked" + } + } + } + }, + sys_channel_user_link: { + label: "Channel User Link", + pluralLabel: "Channel User Links", + description: "A person's link to their own user in a chat workspace: proposed by email match, delivering once they confirm it.", + fields: { + account_id: { + label: "Account" + }, + user_id: { + label: "User" + }, + external_user_id: { + label: "Chat User ID" + }, + external_display_name: { + label: "Chat User Name" + }, + state: { + label: "State", + options: { + proposed: "Proposed", + confirmed: "Confirmed" + } + }, + confirmed_at: { + label: "Confirmed At" + }, + proposal_email_hash: { + label: "Proposal Email Hash" + } + } } }; diff --git a/packages/services/service-messaging/src/translations/es-ES.objects.generated.ts b/packages/services/service-messaging/src/translations/es-ES.objects.generated.ts index dc3186faba5..d4ad4770d9e 100644 --- a/packages/services/service-messaging/src/translations/es-ES.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/es-ES.objects.generated.ts @@ -489,5 +489,63 @@ export const esESObjects: NonNullable = { label: "Creado el" } } + }, + sys_channel_account: { + label: "Cuenta de canal", + pluralLabel: "Cuentas de canal", + description: "La instalación de una app de chat de una organización, como su propia app de Slack, con el token de bot que se le emitió.", + fields: { + channel_id: { + label: "Canal" + }, + display_name: { + label: "Espacio de trabajo" + }, + external_id: { + label: "ID del espacio de trabajo" + }, + bot_token: { + label: "Token del bot" + }, + status: { + label: "Estado", + options: { + active: "Activa", + revoked: "Revocada" + } + } + } + }, + sys_channel_user_link: { + label: "Vínculo de usuario del canal", + pluralLabel: "Vínculos de usuario del canal", + description: "El vínculo de una persona con su propio usuario en un espacio de trabajo de chat: se propone por coincidencia de correo y entrega en cuanto la persona lo confirma.", + fields: { + account_id: { + label: "Cuenta" + }, + user_id: { + label: "Usuario" + }, + external_user_id: { + label: "ID de usuario del chat" + }, + external_display_name: { + label: "Nombre de usuario del chat" + }, + state: { + label: "Estado", + options: { + proposed: "Propuesto", + confirmed: "Confirmado" + } + }, + confirmed_at: { + label: "Confirmado el" + }, + proposal_email_hash: { + label: "Hash del correo de la propuesta" + } + } } }; diff --git a/packages/services/service-messaging/src/translations/fr.objects.generated.ts b/packages/services/service-messaging/src/translations/fr.objects.generated.ts index d7378b16482..1aa77e5d199 100644 --- a/packages/services/service-messaging/src/translations/fr.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/fr.objects.generated.ts @@ -489,5 +489,63 @@ export const frObjects: NonNullable = { label: "Créé le" } } + }, + sys_channel_account: { + label: "Compte de canal", + pluralLabel: "Comptes de canal", + description: "L’installation d’une application de chat par une organisation, comme sa propre application Slack, avec le jeton de bot qui lui a été délivré.", + fields: { + channel_id: { + label: "Canal" + }, + display_name: { + label: "Espace de travail" + }, + external_id: { + label: "ID de l’espace de travail" + }, + bot_token: { + label: "Jeton du bot" + }, + status: { + label: "Statut", + options: { + active: "Actif", + revoked: "Révoqué" + } + } + } + }, + sys_channel_user_link: { + label: "Lien d’utilisateur de canal", + pluralLabel: "Liens d’utilisateur de canal", + description: "Le lien d’une personne avec son propre utilisateur dans un espace de travail de chat : proposé par correspondance d’e-mail, il livre dès que la personne le confirme.", + fields: { + account_id: { + label: "Compte" + }, + user_id: { + label: "Utilisateur" + }, + external_user_id: { + label: "ID d’utilisateur du chat" + }, + external_display_name: { + label: "Nom d’utilisateur du chat" + }, + state: { + label: "État", + options: { + proposed: "Proposé", + confirmed: "Confirmé" + } + }, + confirmed_at: { + label: "Confirmé le" + }, + proposal_email_hash: { + label: "Hachage de l’e-mail de la proposition" + } + } } }; diff --git a/packages/services/service-messaging/src/translations/ja-JP.objects.generated.ts b/packages/services/service-messaging/src/translations/ja-JP.objects.generated.ts index e1a1e8622fa..d9152d463b7 100644 --- a/packages/services/service-messaging/src/translations/ja-JP.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/ja-JP.objects.generated.ts @@ -489,5 +489,63 @@ export const jaJPObjects: NonNullable = { label: "作成日時" } } + }, + sys_channel_account: { + label: "チャネルアカウント", + pluralLabel: "チャネルアカウント", + description: "組織がインストールしたチャットアプリ(組織独自の Slack アプリなど)と、発行されたボットトークン。", + fields: { + channel_id: { + label: "チャネル" + }, + display_name: { + label: "ワークスペース" + }, + external_id: { + label: "ワークスペース ID" + }, + bot_token: { + label: "ボットトークン" + }, + status: { + label: "ステータス", + options: { + active: "有効", + revoked: "取り消し済み" + } + } + } + }, + sys_channel_user_link: { + label: "チャネルユーザーリンク", + pluralLabel: "チャネルユーザーリンク", + description: "チャットワークスペース内の本人のユーザーとのリンク。メールアドレスの一致で提案され、本人が確認すると配信が始まります。", + fields: { + account_id: { + label: "アカウント" + }, + user_id: { + label: "ユーザー" + }, + external_user_id: { + label: "チャットユーザー ID" + }, + external_display_name: { + label: "チャットユーザー名" + }, + state: { + label: "状態", + options: { + proposed: "提案済み", + confirmed: "確認済み" + } + }, + confirmed_at: { + label: "確認日時" + }, + proposal_email_hash: { + label: "提案時のメールアドレスのハッシュ" + } + } } }; diff --git a/packages/services/service-messaging/src/translations/ko.objects.generated.ts b/packages/services/service-messaging/src/translations/ko.objects.generated.ts index 8503b72479e..54a997a3152 100644 --- a/packages/services/service-messaging/src/translations/ko.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/ko.objects.generated.ts @@ -489,5 +489,63 @@ export const koObjects: NonNullable = { label: "생성 일시" } } + }, + sys_channel_account: { + label: "채널 계정", + pluralLabel: "채널 계정", + description: "조직이 설치한 채팅 앱(예: 조직 자체의 Slack 앱)과 발급받은 봇 토큰입니다.", + fields: { + channel_id: { + label: "채널" + }, + display_name: { + label: "워크스페이스" + }, + external_id: { + label: "워크스페이스 ID" + }, + bot_token: { + label: "봇 토큰" + }, + status: { + label: "상태", + options: { + active: "활성", + revoked: "취소됨" + } + } + } + }, + sys_channel_user_link: { + label: "채널 사용자 연결", + pluralLabel: "채널 사용자 연결", + description: "채팅 워크스페이스에 있는 본인 사용자와의 연결입니다. 이메일 일치로 제안되며 본인이 확인해야 전달이 시작됩니다.", + fields: { + account_id: { + label: "계정" + }, + user_id: { + label: "사용자" + }, + external_user_id: { + label: "채팅 사용자 ID" + }, + external_display_name: { + label: "채팅 사용자 이름" + }, + state: { + label: "상태", + options: { + proposed: "제안됨", + confirmed: "확인됨" + } + }, + confirmed_at: { + label: "확인 일시" + }, + proposal_email_hash: { + label: "제안 이메일 해시" + } + } } }; diff --git a/packages/services/service-messaging/src/translations/messages.ts b/packages/services/service-messaging/src/translations/messages.ts index 5120db42312..19a3f0ad213 100644 --- a/packages/services/service-messaging/src/translations/messages.ts +++ b/packages/services/service-messaging/src/translations/messages.ts @@ -12,9 +12,14 @@ * `MessagingTranslations` (ADR-0029 D8), and read by * `t('messages.', locale, params)`. * - * Today that is one sentence: the heading of a digest of two or more items - * (`digest-render.ts`). A one-item digest carries that item's own title, so - * this heading is never rendered for fewer than two. + * Three kinds today: the heading of a digest of two or more items + * (`digest-render.ts`; a one-item digest carries that item's own title, so + * this heading is never rendered for fewer than two), the notice a person + * gets when an administrator removes their Slack link (`slack-links.ts`, + * holes `{{workspace}}`: the Slack workspace's name), and the refusal a person + * gets when they confirm a Slack link proposal that no longer holds + * (`slackLinkProposalOutdated`, answered by the Slack link doors as the + * envelope's `userMessage` in the caller's language; `en` is its `message`). * * ## Keeping the copy honest * @@ -55,6 +60,9 @@ type Messages = NonNullable; /** The ids, as `en` spells them — every other locale carries exactly these. */ export const enMessages = { notificationDigestTitle: 'You have {{count}} notifications', + slackLinkRemovedTitle: 'Your Slack link was removed', + slackLinkRemovedBody: 'An administrator removed the link between your account and your Slack user in {{workspace}}. Notifications no longer reach you on Slack; you can connect again from your notification settings.', + slackLinkProposalOutdated: 'Your email is no longer verified, or is not the email this Slack link was proposed for: ask for a new proposal. Nothing was changed.', } as const satisfies Messages; /** One messaging sentence's id. */ @@ -64,42 +72,72 @@ type MessagingMessages = Readonly>; export const zhCNMessages: MessagingMessages = { notificationDigestTitle: '您有 {{count}} 条通知', + slackLinkRemovedTitle: '您的 Slack 关联已被移除', + slackLinkRemovedBody: '管理员移除了您的账户与 {{workspace}} 中您的 Slack 用户之间的关联。通知将不再通过 Slack 发送给您;您可以在通知设置中重新关联。', + slackLinkProposalOutdated: '您的邮箱已不再经过验证,或已不是提议此 Slack 关联时使用的邮箱:请重新获取提议。未作任何更改。', }; export const jaJPMessages: MessagingMessages = { notificationDigestTitle: '{{count}} 件の通知があります', + slackLinkRemovedTitle: 'Slack の連携が解除されました', + slackLinkRemovedBody: '管理者が、あなたのアカウントと {{workspace}} のあなたの Slack ユーザーとの連携を解除しました。今後、通知は Slack に届きません。通知設定から再度連携できます。', + slackLinkProposalOutdated: 'メールアドレスが確認済みではなくなったか、この Slack 連携が提案されたときのメールアドレスではありません。新しい提案を取得してください。変更は行われていません。', }; export const esESMessages: MessagingMessages = { notificationDigestTitle: 'Tiene {{count}} notificaciones', + slackLinkRemovedTitle: 'Se ha eliminado su vínculo con Slack', + slackLinkRemovedBody: 'Un administrador ha eliminado el vínculo entre su cuenta y su usuario de Slack en {{workspace}}. Las notificaciones ya no le llegarán por Slack; puede volver a conectarse desde la configuración de notificaciones.', + slackLinkProposalOutdated: 'Su correo electrónico ya no está verificado o no es el correo para el que se propuso este vínculo con Slack: solicite una nueva propuesta. No se ha cambiado nada.', }; export const zhHantMessages: MessagingMessages = { notificationDigestTitle: '您有 {{count}} 則通知', + slackLinkRemovedTitle: '您的 Slack 連結已被移除', + slackLinkRemovedBody: '管理員移除了您的帳戶與 {{workspace}} 中您的 Slack 使用者之間的連結。通知將不再透過 Slack 傳送給您;您可以在通知設定中重新連結。', + slackLinkProposalOutdated: '您的電子郵件已不再經過驗證,或已不是提議此 Slack 連結時使用的電子郵件:請重新取得提議。未進行任何變更。', }; export const arMessages: MessagingMessages = { notificationDigestTitle: 'عدد الإشعارات لديك: {{count}}', + slackLinkRemovedTitle: 'تمت إزالة ربط Slack الخاص بك', + slackLinkRemovedBody: 'أزال أحد المسؤولين الربط بين حسابك ومستخدم Slack الخاص بك في {{workspace}}. لن تصلك الإشعارات بعد الآن على Slack؛ ويمكنك الربط مرة أخرى من إعدادات الإشعارات.', + slackLinkProposalOutdated: 'لم يعد بريدك الإلكتروني موثَّقًا، أو لم يعد البريد الذي اقتُرح له ربط Slack هذا: اطلب اقتراحًا جديدًا. لم يتم تغيير أي شيء.', }; export const frMessages: MessagingMessages = { notificationDigestTitle: 'Vous avez {{count}} notifications', + slackLinkRemovedTitle: 'Votre lien Slack a été supprimé', + slackLinkRemovedBody: 'Un administrateur a supprimé le lien entre votre compte et votre utilisateur Slack dans {{workspace}}. Les notifications ne vous parviennent plus sur Slack ; vous pouvez vous reconnecter depuis vos paramètres de notification.', + slackLinkProposalOutdated: 'Votre adresse e-mail n’est plus vérifiée, ou n’est pas celle pour laquelle ce lien Slack a été proposé : demandez une nouvelle proposition. Rien n’a été modifié.', }; export const ptBRMessages: MessagingMessages = { notificationDigestTitle: 'Você tem {{count}} notificações', + slackLinkRemovedTitle: 'Seu vínculo com o Slack foi removido', + slackLinkRemovedBody: 'Um administrador removeu o vínculo entre sua conta e seu usuário do Slack em {{workspace}}. As notificações não chegarão mais a você pelo Slack; você pode se conectar novamente nas configurações de notificação.', + slackLinkProposalOutdated: 'Seu e-mail não está mais verificado ou não é o e-mail para o qual este vínculo com o Slack foi proposto: solicite uma nova proposta. Nada foi alterado.', }; export const ruMessages: MessagingMessages = { notificationDigestTitle: 'Уведомлений: {{count}}', + slackLinkRemovedTitle: 'Ваша привязка к Slack удалена', + slackLinkRemovedBody: 'Администратор удалил привязку вашей учётной записи к вашему пользователю Slack в {{workspace}}. Уведомления больше не приходят вам в Slack; вы можете подключиться снова в настройках уведомлений.', + slackLinkProposalOutdated: 'Ваш адрес электронной почты больше не подтверждён или это не тот адрес, для которого была предложена эта привязка к Slack: запросите новое предложение. Ничего не изменено.', }; export const deMessages: MessagingMessages = { notificationDigestTitle: 'Sie haben {{count}} Benachrichtigungen', + slackLinkRemovedTitle: 'Ihre Slack-Verknüpfung wurde entfernt', + slackLinkRemovedBody: 'Ein Administrator hat die Verknüpfung zwischen Ihrem Konto und Ihrem Slack-Benutzer in {{workspace}} entfernt. Benachrichtigungen erreichen Sie nicht mehr über Slack; Sie können sich in Ihren Benachrichtigungseinstellungen erneut verbinden.', + slackLinkProposalOutdated: 'Ihre E-Mail-Adresse ist nicht mehr bestätigt oder nicht die Adresse, für die diese Slack-Verknüpfung vorgeschlagen wurde: Fordern Sie einen neuen Vorschlag an. Es wurde nichts geändert.', }; export const koMessages: MessagingMessages = { notificationDigestTitle: '알림이 {{count}}개 있습니다', + slackLinkRemovedTitle: 'Slack 연결이 해제되었습니다', + slackLinkRemovedBody: '관리자가 {{workspace}}에서 회원님의 계정과 Slack 사용자 간의 연결을 해제했습니다. 이제 알림이 Slack으로 전송되지 않으며, 알림 설정에서 다시 연결할 수 있습니다.', + slackLinkProposalOutdated: '이메일이 더 이상 인증된 상태가 아니거나 이 Slack 연결이 제안된 이메일이 아닙니다. 새 제안을 요청하세요. 변경된 내용은 없습니다.', }; /** The shipped locales, keyed as the bundle beside this file keys them. */ diff --git a/packages/services/service-messaging/src/translations/pt-BR.objects.generated.ts b/packages/services/service-messaging/src/translations/pt-BR.objects.generated.ts index 68a875c0959..e0c6dd90bd8 100644 --- a/packages/services/service-messaging/src/translations/pt-BR.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/pt-BR.objects.generated.ts @@ -489,5 +489,63 @@ export const ptBRObjects: NonNullable = { label: "Criado em" } } + }, + sys_channel_account: { + label: "Conta de canal", + pluralLabel: "Contas de canal", + description: "A instalação de um app de chat por uma organização, como o próprio app do Slack, com o token de bot emitido para ela.", + fields: { + channel_id: { + label: "Canal" + }, + display_name: { + label: "Espaço de trabalho" + }, + external_id: { + label: "ID do espaço de trabalho" + }, + bot_token: { + label: "Token do bot" + }, + status: { + label: "Status", + options: { + active: "Ativa", + revoked: "Revogada" + } + } + } + }, + sys_channel_user_link: { + label: "Vínculo de usuário do canal", + pluralLabel: "Vínculos de usuário do canal", + description: "O vínculo de uma pessoa com o próprio usuário em um espaço de trabalho de chat: proposto pela correspondência de e-mail, passa a entregar quando a pessoa o confirma.", + fields: { + account_id: { + label: "Conta" + }, + user_id: { + label: "Usuário" + }, + external_user_id: { + label: "ID do usuário no chat" + }, + external_display_name: { + label: "Nome do usuário no chat" + }, + state: { + label: "Estado", + options: { + proposed: "Proposto", + confirmed: "Confirmado" + } + }, + confirmed_at: { + label: "Confirmado em" + }, + proposal_email_hash: { + label: "Hash do e-mail da proposta" + } + } } }; diff --git a/packages/services/service-messaging/src/translations/pt-BR.source-hashes.generated.ts b/packages/services/service-messaging/src/translations/pt-BR.source-hashes.generated.ts index 056fb4c019d..c867d02d757 100644 --- a/packages/services/service-messaging/src/translations/pt-BR.source-hashes.generated.ts +++ b/packages/services/service-messaging/src/translations/pt-BR.source-hashes.generated.ts @@ -18,6 +18,7 @@ */ export const ptBRGeneratedSourceHashes: Readonly> = { + "objects.sys_channel_account.fields.status.label": "64a420165247654b", "objects.sys_http_delivery.fields.status.help": "e437ecf81dfb4715", "objects.sys_http_delivery.fields.status.label": "64a420165247654b", "objects.sys_notification_delivery.fields.status.label": "64a420165247654b", diff --git a/packages/services/service-messaging/src/translations/ru.objects.generated.ts b/packages/services/service-messaging/src/translations/ru.objects.generated.ts index ca8df0a21ee..b9788144056 100644 --- a/packages/services/service-messaging/src/translations/ru.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/ru.objects.generated.ts @@ -489,5 +489,63 @@ export const ruObjects: NonNullable = { label: "Создано" } } + }, + sys_channel_account: { + label: "Учётная запись канала", + pluralLabel: "Учётные записи каналов", + description: "Установка чат-приложения организацией, например её собственного приложения Slack, с выданным ему токеном бота.", + fields: { + channel_id: { + label: "Канал" + }, + display_name: { + label: "Рабочее пространство" + }, + external_id: { + label: "ID рабочего пространства" + }, + bot_token: { + label: "Токен бота" + }, + status: { + label: "Статус", + options: { + active: "Активна", + revoked: "Отозвана" + } + } + } + }, + sys_channel_user_link: { + label: "Связь пользователя канала", + pluralLabel: "Связи пользователей каналов", + description: "Связь человека с его собственным пользователем в рабочем пространстве чата: предлагается по совпадению адреса электронной почты, доставка начинается после подтверждения.", + fields: { + account_id: { + label: "Учётная запись" + }, + user_id: { + label: "Пользователь" + }, + external_user_id: { + label: "ID пользователя чата" + }, + external_display_name: { + label: "Имя пользователя чата" + }, + state: { + label: "Состояние", + options: { + proposed: "Предложена", + confirmed: "Подтверждена" + } + }, + confirmed_at: { + label: "Дата подтверждения" + }, + proposal_email_hash: { + label: "Хеш адреса электронной почты предложения" + } + } } }; diff --git a/packages/services/service-messaging/src/translations/zh-CN.objects.generated.ts b/packages/services/service-messaging/src/translations/zh-CN.objects.generated.ts index ad3fa9441f3..467bda38b54 100644 --- a/packages/services/service-messaging/src/translations/zh-CN.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/zh-CN.objects.generated.ts @@ -489,5 +489,63 @@ export const zhCNObjects: NonNullable = { label: "创建时间" } } + }, + sys_channel_account: { + label: "通道账户", + pluralLabel: "通道账户", + description: "组织安装的聊天应用(例如其自有的 Slack 应用)及其获颁的机器人令牌。", + fields: { + channel_id: { + label: "通道" + }, + display_name: { + label: "工作区" + }, + external_id: { + label: "工作区 ID" + }, + bot_token: { + label: "机器人令牌" + }, + status: { + label: "状态", + options: { + active: "有效", + revoked: "已撤销" + } + } + } + }, + sys_channel_user_link: { + label: "通道用户关联", + pluralLabel: "通道用户关联", + description: "某人与其在聊天工作区中本人用户之间的关联:按邮箱匹配提议,本人确认后才开始投递。", + fields: { + account_id: { + label: "账户" + }, + user_id: { + label: "用户" + }, + external_user_id: { + label: "聊天用户 ID" + }, + external_display_name: { + label: "聊天用户名" + }, + state: { + label: "状态", + options: { + proposed: "已提议", + confirmed: "已确认" + } + }, + confirmed_at: { + label: "确认时间" + }, + proposal_email_hash: { + label: "提议邮箱哈希" + } + } } }; diff --git a/packages/services/service-messaging/src/translations/zh-Hant.objects.generated.ts b/packages/services/service-messaging/src/translations/zh-Hant.objects.generated.ts index 456fa5d07bf..76875a79ad4 100644 --- a/packages/services/service-messaging/src/translations/zh-Hant.objects.generated.ts +++ b/packages/services/service-messaging/src/translations/zh-Hant.objects.generated.ts @@ -489,5 +489,63 @@ export const zhHantObjects: NonNullable = { label: "建立時間" } } + }, + sys_channel_account: { + label: "通道帳戶", + pluralLabel: "通道帳戶", + description: "組織安裝的聊天應用程式(例如其自有的 Slack 應用程式)及其取得的機器人權杖。", + fields: { + channel_id: { + label: "通道" + }, + display_name: { + label: "工作區" + }, + external_id: { + label: "工作區 ID" + }, + bot_token: { + label: "機器人權杖" + }, + status: { + label: "狀態", + options: { + active: "有效", + revoked: "已撤銷" + } + } + } + }, + sys_channel_user_link: { + label: "通道使用者連結", + pluralLabel: "通道使用者連結", + description: "使用者與其在聊天工作區中本人帳號之間的連結:依電子郵件比對提議,本人確認後才開始傳送。", + fields: { + account_id: { + label: "帳戶" + }, + user_id: { + label: "使用者" + }, + external_user_id: { + label: "聊天使用者 ID" + }, + external_display_name: { + label: "聊天使用者名稱" + }, + state: { + label: "狀態", + options: { + proposed: "已提議", + confirmed: "已確認" + } + }, + confirmed_at: { + label: "確認時間" + }, + proposal_email_hash: { + label: "提議電子郵件雜湊" + } + } } }; diff --git a/packages/spec/src/system/constants/platform-object-names.test.ts b/packages/spec/src/system/constants/platform-object-names.test.ts index a12f687d957..9b62b08b0e5 100644 --- a/packages/spec/src/system/constants/platform-object-names.test.ts +++ b/packages/spec/src/system/constants/platform-object-names.test.ts @@ -233,6 +233,8 @@ describe('platform-object predicates', () => { // left in deployed databases; the name no longer resolves as a platform // object (semantic entry `sys-notification-subscription-retired`). expect(PLATFORM_OBJECTS_BY_PACKAGE['service-messaging']).toEqual([ + 'sys_channel_account', + 'sys_channel_user_link', 'sys_http_delivery', 'sys_inbox_message', 'sys_notification_delivery', diff --git a/packages/spec/src/system/constants/platform-object-names.ts b/packages/spec/src/system/constants/platform-object-names.ts index 917ddad63f9..94d4b106fec 100644 --- a/packages/spec/src/system/constants/platform-object-names.ts +++ b/packages/spec/src/system/constants/platform-object-names.ts @@ -154,6 +154,8 @@ export const PLATFORM_OBJECTS_BY_PACKAGE: Readonly