|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#30509] An approval's own notices also go by e-mail, linking to the |
| 5 | + * request page (objectstack-ai/cloud#2549 ruling B, item ②; the template's |
| 6 | + * location is the ruling recorded on #30509). |
| 7 | + * |
| 8 | + * ## The defect |
| 9 | + * |
| 10 | + * `notify()` emitted with no `channels`, and messaging defaults that to the |
| 11 | + * in-app inbox alone, so an approval request, its reminder and its outcome |
| 12 | + * reached nobody who does not watch the Console bell. |
| 13 | + * |
| 14 | + * ## What this pins |
| 15 | + * |
| 16 | + * The real composition, end to end: a real `ObjectQL` over `SqlDriver` |
| 17 | + * (better-sqlite3, in-memory, real DDL), the real `MessagingServicePlugin` |
| 18 | + * with its durable outbox and dispatcher, the real `ApprovalsServicePlugin`, |
| 19 | + * and an `email` service whose transport records what it is handed — a |
| 20 | + * configured (test) transport. The deployment's address comes from |
| 21 | + * `OS_BASE_URL`, as an unconfigured `publicBaseUrl` option resolves it. |
| 22 | + * |
| 23 | + * - opening a step, the submitter's reminder and the outcome each leave an |
| 24 | + * `email` delivery row that reached `success` beside the `inbox` one, and |
| 25 | + * a sent message whose subject is the notice's title and whose text is its |
| 26 | + * body plus the request page's ABSOLUTE link; |
| 27 | + * - the inbox row still links relatively (`actionUrl`), as the Console routes; |
| 28 | + * - ⛔ no stored row of any table, and no message sent, holds an ADR-0043 |
| 29 | + * action link or token (#24564's storage axis, the same reading |
| 30 | + * `reminder-action-link-at-rest` takes); |
| 31 | + * - an approval topic outside the four (a comment) stays inbox-only. |
| 32 | + */ |
| 33 | + |
| 34 | +import { describe, it, expect, afterEach, vi } from 'vitest'; |
| 35 | +import { ObjectQL } from '@objectstack/objectql'; |
| 36 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 37 | +import { MessagingServicePlugin } from '@objectstack/service-messaging'; |
| 38 | +import type { ApprovalService } from './approval-service.js'; |
| 39 | +import { ApprovalsServicePlugin } from './approvals-plugin.js'; |
| 40 | +import { SysApprovalRequest } from './sys-approval-request.object.js'; |
| 41 | +import { SysApprovalAction } from './sys-approval-action.object.js'; |
| 42 | +import { SysApprovalApprover } from './sys-approval-approver.object.js'; |
| 43 | +import { SysApprovalDelegation } from './sys-approval-delegation.object.js'; |
| 44 | +import { SysApprovalToken } from './sys-approval-token.object.js'; |
| 45 | +import { installDefaultOrganization } from './default-organization.testkit.js'; |
| 46 | + |
| 47 | +const OBJECT = 'mailrest_invoice'; |
| 48 | +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any; |
| 49 | +const asUser = (userId: string) => ({ userId, positions: [], permissions: [] }) as any; |
| 50 | +const SUBMITTER = 'u_submitter'; |
| 51 | +const APPROVER = 'u_approver'; |
| 52 | +const ORIGIN = 'https://app.example.test'; |
| 53 | +/** What an ADR-0043 action-page link looks like in any spelling a row could hold it. */ |
| 54 | +const ACTION_LINK = /\/approvals\/act|[?&]token=/; |
| 55 | + |
| 56 | +interface Rig { |
| 57 | + engine: ObjectQL; |
| 58 | + driver: SqlDriver; |
| 59 | + svc: ApprovalService; |
| 60 | + sent: Array<Record<string, any>>; |
| 61 | + requestId: string; |
| 62 | + stop: () => Promise<void>; |
| 63 | +} |
| 64 | + |
| 65 | +let rig: Rig | undefined; |
| 66 | + |
| 67 | +afterEach(async () => { |
| 68 | + try { await rig?.stop(); } catch { /* noop */ } |
| 69 | + rig = undefined; |
| 70 | + vi.unstubAllEnvs(); |
| 71 | +}); |
| 72 | + |
| 73 | +async function boot(): Promise<Rig> { |
| 74 | + vi.stubEnv('OS_AUTH_URL', undefined); |
| 75 | + vi.stubEnv('BETTER_AUTH_URL', undefined); |
| 76 | + vi.stubEnv('OS_BASE_URL', ORIGIN); |
| 77 | + |
| 78 | + const engine = new ObjectQL(); |
| 79 | + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); |
| 80 | + engine.registerDriver(driver, true); |
| 81 | + await engine.init(); |
| 82 | + |
| 83 | + const sysUser = { |
| 84 | + name: 'sys_user', |
| 85 | + label: 'User', |
| 86 | + fields: { |
| 87 | + id: { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true }, |
| 88 | + name: { name: 'name', label: 'Name', type: 'text' as const }, |
| 89 | + email: { name: 'email', label: 'Email', type: 'text' as const }, |
| 90 | + locale: { name: 'locale', label: 'Locale', type: 'text' as const }, |
| 91 | + }, |
| 92 | + }; |
| 93 | + const invoice = { |
| 94 | + name: OBJECT, |
| 95 | + label: 'Invoice', |
| 96 | + fields: { |
| 97 | + id: { name: 'id', label: 'Id', type: 'text' as const, primaryKey: true }, |
| 98 | + title: { name: 'title', label: 'Title', type: 'text' as const }, |
| 99 | + }, |
| 100 | + }; |
| 101 | + const register = (def: any) => engine.registry.registerObject(def, 'approvals-email-test', 'approvals-email-test'); |
| 102 | + for (const def of [sysUser, invoice, SysApprovalRequest, SysApprovalAction, SysApprovalApprover, SysApprovalDelegation, SysApprovalToken]) { |
| 103 | + register(def); |
| 104 | + } |
| 105 | + |
| 106 | + const sent: Array<Record<string, any>> = []; |
| 107 | + const logger = { info: () => {}, debug: () => {}, warn: () => {}, error: () => {}, child: () => logger }; |
| 108 | + const services: Record<string, unknown> = { |
| 109 | + objectql: engine, |
| 110 | + data: engine, |
| 111 | + // The messaging plugin declares its objects through the manifest service. |
| 112 | + manifest: { register: (m: any) => { for (const def of m.objects ?? []) register(def); } }, |
| 113 | + // A configured transport: what it is handed is what was sent. |
| 114 | + email: { async send(input: any) { sent.push(input); return { id: `mail_${sent.length}` }; } }, |
| 115 | + }; |
| 116 | + const readyHooks: Array<() => Promise<void> | void> = []; |
| 117 | + let collectReady = true; |
| 118 | + const ctx: any = { |
| 119 | + getService: (name: string) => { |
| 120 | + if (!(name in services)) throw new Error(`[Kernel] Service '${name}' not found`); |
| 121 | + return services[name]; |
| 122 | + }, |
| 123 | + registerService: (name: string, svc: unknown) => { services[name] = svc; }, |
| 124 | + hook: (event: string, fn: () => Promise<void> | void) => { if (collectReady && event === 'kernel:ready') readyHooks.push(fn); }, |
| 125 | + logger, |
| 126 | + }; |
| 127 | + |
| 128 | + const messagingPlugin = new MessagingServicePlugin({ dispatchIntervalMs: 10, dispatchMaxIdleIntervalMs: 20 }); |
| 129 | + await messagingPlugin.init(ctx); |
| 130 | + await engine.syncSchemas(); |
| 131 | + await installDefaultOrganization(engine); |
| 132 | + for (const fn of readyHooks) await fn(); |
| 133 | + collectReady = false; |
| 134 | + |
| 135 | + for (const [id, name] of [[SUBMITTER, 'Sam Submitter'], [APPROVER, 'Ada Approver']]) { |
| 136 | + await engine.insert('sys_user', { id, name, email: `${id}@example.com`, locale: 'en' }, { context: SYSTEM } as any); |
| 137 | + } |
| 138 | + await engine.insert(OBJECT, { id: 'inv_1', title: 'March invoice' }, { context: SYSTEM } as any); |
| 139 | + |
| 140 | + await new ApprovalsServicePlugin().start(ctx); |
| 141 | + const svc = services.approvals as ApprovalService; |
| 142 | + |
| 143 | + const opened: any = await svc.openNodeRequest({ |
| 144 | + object: OBJECT, recordId: 'inv_1', runId: 'run_1', nodeId: 'signoff', flowName: 'mail_signoff', |
| 145 | + config: { approvers: [{ type: 'user', value: APPROVER }], behavior: 'first_response' } as any, |
| 146 | + submitterId: SUBMITTER, record: { id: 'inv_1', title: 'March invoice' }, |
| 147 | + }, asUser(SUBMITTER)); |
| 148 | + |
| 149 | + return { |
| 150 | + engine, driver, svc, sent, requestId: String(opened.id), |
| 151 | + stop: async () => { |
| 152 | + await messagingPlugin.destroy?.(); |
| 153 | + await engine.destroy(); |
| 154 | + }, |
| 155 | + }; |
| 156 | +} |
| 157 | + |
| 158 | +async function deliveries(r: Rig, topic: string): Promise<Array<Record<string, any>>> { |
| 159 | + return (await r.driver.getKnex()('sys_notification_delivery').where({ topic }).select('*')) as Array<Record<string, any>>; |
| 160 | +} |
| 161 | + |
| 162 | +/** The topic's deliveries once every one of them has left the outbox's queue. */ |
| 163 | +async function settled(r: Rig, topic: string): Promise<Array<Record<string, any>>> { |
| 164 | + let rows: Array<Record<string, any>> = []; |
| 165 | + await vi.waitFor(async () => { |
| 166 | + rows = await deliveries(r, topic); |
| 167 | + expect(rows.length).toBeGreaterThan(0); |
| 168 | + expect(rows.filter((d) => d.status === 'pending' || d.status === 'in_flight')).toEqual([]); |
| 169 | + }, { timeout: 5000, interval: 25 }); |
| 170 | + return rows; |
| 171 | +} |
| 172 | + |
| 173 | +const mailTo = (r: Rig, userId: string, subject: string) => |
| 174 | + r.sent.filter((m) => m.to === `${userId}@example.com` && m.subject === subject); |
| 175 | + |
| 176 | +describe('approval notices also go by e-mail, linking to the request page (#30509)', () => { |
| 177 | + it('opening a step e-mails each approver: an email delivery row, the title, the body and the absolute link', async () => { |
| 178 | + rig = await boot(); |
| 179 | + const link = `${ORIGIN}/system/approvals?request=${encodeURIComponent(rig.requestId)}`; |
| 180 | + |
| 181 | + const rows = await settled(rig, 'approval.requested'); |
| 182 | + expect(rows.map((d) => `${d.channel}:${d.recipient_id}:${d.status}`).sort()).toEqual([ |
| 183 | + `email:${APPROVER}:success`, |
| 184 | + `inbox:${APPROVER}:success`, |
| 185 | + ]); |
| 186 | + |
| 187 | + const mails = mailTo(rig, APPROVER, 'Approval requested'); |
| 188 | + expect(mails).toHaveLength(1); |
| 189 | + const text = String(mails[0].text); |
| 190 | + // The inbox keeps the relative deep link the Console routes on, and the |
| 191 | + // e-mail says what the inbox says, then links to the same request. |
| 192 | + const inbox = (await rig.driver.getKnex()('sys_inbox_message').where({ user_id: APPROVER }).select('*')) as any[]; |
| 193 | + expect(inbox.map((m) => m.action_url)).toEqual([`/system/approvals?request=${encodeURIComponent(rig.requestId)}`]); |
| 194 | + expect(inbox[0].title).toBe('Approval requested'); |
| 195 | + expect(inbox[0].body_md).toMatch(/^A decision on Invoice .+ is waiting on you\.$/); |
| 196 | + expect(text).toBe(`${inbox[0].body_md}\n\nOpen the approval: ${link}`); |
| 197 | + }); |
| 198 | + |
| 199 | + it("the submitter's reminder and the outcome go by e-mail too, with the same link", async () => { |
| 200 | + rig = await boot(); |
| 201 | + const link = `${ORIGIN}/system/approvals?request=${encodeURIComponent(rig.requestId)}`; |
| 202 | + await settled(rig, 'approval.requested'); |
| 203 | + |
| 204 | + await rig.svc.remind(rig.requestId, { actorId: SUBMITTER }, asUser(SUBMITTER)); |
| 205 | + const reminders = await settled(rig, 'approval.reminder'); |
| 206 | + expect(reminders.map((d) => `${d.channel}:${d.recipient_id}:${d.status}`).sort()).toEqual([ |
| 207 | + `email:${APPROVER}:success`, |
| 208 | + `inbox:${APPROVER}:success`, |
| 209 | + ]); |
| 210 | + const reminderMail = mailTo(rig, APPROVER, 'Approval reminder'); |
| 211 | + expect(reminderMail).toHaveLength(1); |
| 212 | + expect(String(reminderMail[0].text).endsWith(`Open the approval: ${link}`)).toBe(true); |
| 213 | + |
| 214 | + await rig.svc.decide(rig.requestId, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER)); |
| 215 | + const outcomes = await settled(rig, 'approval.approved'); |
| 216 | + expect(outcomes.map((d) => `${d.channel}:${d.recipient_id}:${d.status}`).sort()).toEqual([ |
| 217 | + `email:${SUBMITTER}:success`, |
| 218 | + `inbox:${SUBMITTER}:success`, |
| 219 | + ]); |
| 220 | + const outcomeMail = mailTo(rig, SUBMITTER, 'Request approved'); |
| 221 | + expect(outcomeMail).toHaveLength(1); |
| 222 | + expect(String(outcomeMail[0].text).endsWith(`Open the approval: ${link}`)).toBe(true); |
| 223 | + }); |
| 224 | + |
| 225 | + it('a rejection e-mails the submitter, with the decider\'s comment in the body', async () => { |
| 226 | + rig = await boot(); |
| 227 | + await settled(rig, 'approval.requested'); |
| 228 | + await rig.svc.decide(rig.requestId, { decision: 'reject', actorId: APPROVER, comment: 'Wrong cost centre' }, asUser(APPROVER)); |
| 229 | + const rows = await settled(rig, 'approval.rejected'); |
| 230 | + expect(rows.map((d) => `${d.channel}:${d.recipient_id}:${d.status}`).sort()).toEqual([ |
| 231 | + `email:${SUBMITTER}:success`, |
| 232 | + `inbox:${SUBMITTER}:success`, |
| 233 | + ]); |
| 234 | + const mail = mailTo(rig, SUBMITTER, 'Request rejected'); |
| 235 | + expect(mail).toHaveLength(1); |
| 236 | + expect(String(mail[0].text)).toContain('Wrong cost centre'); |
| 237 | + }); |
| 238 | + |
| 239 | + it('an approval topic outside the four stays inbox-only', async () => { |
| 240 | + rig = await boot(); |
| 241 | + await settled(rig, 'approval.requested'); |
| 242 | + await rig.svc.comment(rig.requestId, { actorId: SUBMITTER, comment: 'Any news?' } as any, asUser(SUBMITTER)); |
| 243 | + const rows = await settled(rig, 'approval.comment'); |
| 244 | + expect(new Set(rows.map((d) => d.channel))).toEqual(new Set(['inbox'])); |
| 245 | + }); |
| 246 | + |
| 247 | + it('⛔ no stored row of any table, and no message sent, holds an ADR-0043 action link or token', async () => { |
| 248 | + rig = await boot(); |
| 249 | + await settled(rig, 'approval.requested'); |
| 250 | + await rig.svc.remind(rig.requestId, { actorId: SUBMITTER }, asUser(SUBMITTER)); |
| 251 | + await settled(rig, 'approval.reminder'); |
| 252 | + await rig.svc.decide(rig.requestId, { decision: 'approve', actorId: APPROVER }, asUser(APPROVER)); |
| 253 | + await settled(rig, 'approval.approved'); |
| 254 | + |
| 255 | + // Not vacuous: three e-mails went, and the stored notification rows carry the request link. |
| 256 | + expect(rig.sent).toHaveLength(3); |
| 257 | + const knex = rig.driver.getKnex(); |
| 258 | + const tables = (await knex('sqlite_master').where({ type: 'table' }).select('name')) as Array<{ name: string }>; |
| 259 | + const leaks: string[] = []; |
| 260 | + let linkRows = 0; |
| 261 | + for (const { name } of tables) { |
| 262 | + if (name.startsWith('sqlite_')) continue; |
| 263 | + for (const row of (await knex(name).select('*')) as Array<Record<string, unknown>>) { |
| 264 | + const text = JSON.stringify(row); |
| 265 | + if (text.includes('/system/approvals?request=')) linkRows++; |
| 266 | + if (ACTION_LINK.test(text)) leaks.push(`${name}: ${text}`); |
| 267 | + } |
| 268 | + } |
| 269 | + expect(linkRows).toBeGreaterThan(0); |
| 270 | + expect(leaks).toEqual([]); |
| 271 | + expect(rig.sent.filter((m) => ACTION_LINK.test(JSON.stringify(m)))).toEqual([]); |
| 272 | + }); |
| 273 | +}); |
0 commit comments