diff --git a/.changeset/25802-invitation-role-label-warn-and-expiry.md b/.changeset/25802-invitation-role-label-warn-and-expiry.md new file mode 100644 index 00000000000..b8c0f86ab4b --- /dev/null +++ b/.changeset/25802-invitation-role-label-warn-and-expiry.md @@ -0,0 +1,22 @@ +--- +'@objectstack/plugin-auth': patch +'@objectstack/plugin-email': patch +--- + +fix(plugin-auth,plugin-email)!: the invitation mail says when its role label stayed English, and states when the invitation expires + +**The role label.** The organization invitation mail names the invitee's role by its `sys_member.role` option label in the mail's locale (`成员`, `メンバー`, `Miembro`). When the i18n service answered without a translation for that locale, the mail named the English label (`Member`) inside a Chinese, Japanese or Spanish sentence, and logged nothing. Only a read that threw was reported. That happens when there is no i18n service, when the service holds no bundle for the locale, or when its reported locales (`i18n.supportedLocales`, when declared) do not name the locale as the bundles spell it. Now one `warn` is logged for the send: `[AuthManager] invitation mail: no 'zh-CN' label was found for the membership role(s) 'member'; …`. It names the locale, the roles and what to check. The mail is still sent as before. A mail in English, or a read that already warned because it threw, logs nothing extra. + +**The expiry.** The `auth.invitation` mail never said when its link stops working (better-auth's window, 48 hours by default), so an invitation opened late failed at the accept page with no warning. The sender now passes `invitation.expiresAt` as a new template variable, `expiresAt`, as an ISO-8601 instant. Each of the four built-in bodies, HTML and text, ends with one sentence that renders it with the `datetime:long` formatter. The date reads in the mail's locale and the send's reference timezone, with the zone named: 「此邀请将于 2031年3月4日 UTC 05:06:07 过期。」 / "This invitation expires on March 4, 2031 at 5:06:07 AM UTC.". The template engine has no conditionals, so every body states the expiry, and the built-in rows declare `expiresAt` **required**. A send without it is refused (`MISSING_VARIABLES: expiresAt`) and is never sent with a dangling sentence. The built-in sender always has better-auth's expiry. If the value does not read as a date, the sender leaves it out and logs one `warn` naming the invitation id and saying the mail will be refused, so the invitation can be resent. A tenant or app override of `auth.invitation` keeps its own bodies and variables, and can use `{{ expiresAt | datetime:long }}`. + +Clause-②: no (narrowing: the built-in `auth.invitation` rows declare a new required variable, `expiresAt`, so a `sendTemplate` of `auth.invitation` that names no `expiresAt` is now refused with `MISSING_VARIABLES` where it used to be sent) + +Metadata-protocol: none (a built-in template row's declared variables, read by the email service at send time; no spec key, authorable spelling or stored shape moves) + +**BREAKING** for code that sends `auth.invitation` itself (the built-in organization-invitation sender already passes the value). + +- **Before.** `auth.invitation` declared no expiry, and a send naming `inviter`, `organization`, `role`, `acceptUrl` and `appName` was delivered. +- **Now.** The same send is refused with `MISSING_VARIABLES: expiresAt`. +- **Fix (one line).** Add the invitation's expiry instant to the send's `data` as `expiresAt`. + + diff --git a/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts b/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts index 4c950b9be79..a92daab5258 100644 --- a/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-manager-organization-plugin.ts @@ -609,6 +609,16 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { warn: (msg, meta) => this.config.logger ? this.config.logger.warn(msg, meta) : console.warn(msg, meta), }); + const expiry = invitationExpiryArg(invitation.expiresAt); + if (expiry.expiresAt === undefined) { + const msg = + `[AuthManager] invitation mail: invitation '${invitation.id}' carries no readable expiry, ` + + 'so the auth.invitation mail (which states when it expires) will be refused and not sent; ' + + 'resend the invitation once its expiry is set'; + const meta = { invitationId: invitation.id, expiresAt: String(invitation.expiresAt) }; + if (this.config.logger) this.config.logger.warn(msg, meta); + else console.warn(msg, meta); + } try { await emailService.sendTemplate({ template: 'auth.invitation', @@ -623,6 +633,14 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { role: roleLabel, acceptUrl, appName: this.getAppName(), + // When the link stops working (better-auth's window, 48 h by + // default): every body says so, so an invitation opened late is + // not a surprise at the accept page. Handed over as an ISO-8601 + // instant; the template's `datetime` formatter renders it in the + // mail's locale. The template declares it REQUIRED, so an + // unreadable value is never invented: it is left out, said so + // once below, and the send is refused (`MISSING_VARIABLES`). + ...expiry, }, relatedObject: 'sys_invitation', relatedId: invitation.id, @@ -681,3 +699,17 @@ export async function buildOrganizationPlugin(this: OrganizationPluginHost) { } return organizationPlugin; } + +/** + * The `expiresAt` fragment of the invitation mail's data: the invitation's + * expiry as an ISO-8601 instant, or nothing when the value does not read as a + * date. better-auth hands the callback a `Date`; a string or epoch number is + * read the same way. A value that is not a real instant is left out rather + * than rendered as `Invalid Date`; the template declares the variable + * required, so that send is refused rather than sent with a dangling sentence. + */ +function invitationExpiryArg(expiresAt: unknown): { expiresAt?: string } { + if (!(expiresAt instanceof Date) && typeof expiresAt !== 'string' && typeof expiresAt !== 'number') return {}; + const instant = new Date(expiresAt); + return Number.isNaN(instant.getTime()) ? {} : { expiresAt: instant.toISOString() }; +} diff --git a/packages/plugins/plugin-auth/src/invitation-role-label.test.ts b/packages/plugins/plugin-auth/src/invitation-role-label.test.ts index 61007dffcf9..3ed2c675202 100644 --- a/packages/plugins/plugin-auth/src/invitation-role-label.test.ts +++ b/packages/plugins/plugin-auth/src/invitation-role-label.test.ts @@ -67,6 +67,11 @@ async function invite(opts: { getI18n?: () => unknown; /** The INVITER's browser language — better-auth hands this callback its request. */ header?: string; + /** + * better-auth's `invitation.expiresAt`; omitted = a real expiry (the row + * always carries one), passed as `undefined` = the row carries none. + */ + expiresAt?: unknown; }) { const { betterAuth } = await import('better-auth'); let captured: any; @@ -100,7 +105,16 @@ async function invite(opts: { await org._opts.sendInvitationEmail( { email: 'invitee@example.com', - invitation: { id: 'inv1', organizationId: 'o1', role: opts.role }, + invitation: { + id: 'inv1', + organizationId: 'o1', + role: opts.role, + ...('expiresAt' in opts + ? opts.expiresAt !== undefined + ? { expiresAt: opts.expiresAt } + : {} + : { expiresAt: new Date('2031-03-04T05:06:07.000Z') }), + }, organization: { name: 'Northwind' }, inviter: { user: { email: 'dana@example.com', name: 'Dana' } }, }, @@ -198,7 +212,9 @@ describe('#24154 — a value with no label, or no i18n service, falls back as st it('no i18n service names the authored label, never the stored value', async () => { const { input, warns } = await invite({ role: 'member', deployment: 'zh-CN' }); expect(input.data.role).toBe('Member'); - expect(warns.filter((w) => w.msg.includes('invitation mail'))).toHaveLength(0); + // #25802 — and says once that the zh-CN mail carries an English label. + expect(warns.filter((w) => w.msg.includes('invitation mail'))).toHaveLength(1); + expect(untranslatedWarns(warns)).toHaveLength(1); }); it('a throwing i18n service still delivers the mail, with the authored label and one warn', async () => { @@ -212,6 +228,9 @@ describe('#24154 — a value with no label, or no i18n service, falls back as st expect(input.data.role).toBe('Member'); const degraded = warns.filter((w) => w.msg.includes('could not be read from the i18n service')); expect(degraded).toHaveLength(1); + // One warn for one degradation: the thrown read already said why the + // label is English, so the untranslated-label warn does not repeat it. + expect(warns.filter((w) => w.msg.includes('invitation mail'))).toHaveLength(1); }); it('an empty value stays empty — there is no role to name', async () => { @@ -219,6 +238,108 @@ describe('#24154 — a value with no label, or no i18n service, falls back as st }); }); +// ── #25802 — a label with no translation in the mail locale is said once ── + +/** The warns that name an untranslated role label. */ +function untranslatedWarns(warns: Array<{ msg: string; meta?: unknown }>) { + return warns.filter((w) => w.msg.includes('label was found for the membership role')); +} + +/** + * The platform bundles loaded, and the deployment's declared + * `i18n.supportedLocales` set on the service — the read + * `translateMetaList` takes its bundle from (`getLocales()`). + */ +function declaringI18n(supportedLocales: string[]) { + const i18n = platformI18n(); + i18n.setSupportedLocales(supportedLocales); + return i18n; +} + +describe('#25802 — a zh-CN mail whose role label stayed English says so, once', () => { + it('the platform bundles reach the zh-CN mail: 成员, and no warn', async () => { + const { input, warns } = await invite({ role: 'member', deployment: 'zh-CN', getI18n: platformI18n }); + expect(input.data.role).toBe('成员'); + expect(warns.filter((w) => w.msg.includes('invitation mail'))).toHaveLength(0); + }); + + it('a service whose locales omit zh-CN names Member, with one warn naming the role and the locale', async () => { + // The reported shape: the label read answers without throwing, holds no + // zh-CN entry, and the authored English label lands in a Chinese sentence. + const i18n = declaringI18n(['en']); + const { input, warns } = await invite({ role: 'member', deployment: 'zh-CN', getI18n: () => i18n }); + expect(input.data.role).toBe('Member'); + const named = untranslatedWarns(warns); + expect(named).toHaveLength(1); + expect(named[0]!.msg).toContain("no 'zh-CN' label"); + expect(named[0]!.msg).toContain("'member'"); + expect(named[0]!.meta).toMatchObject({ role: 'member', locale: 'zh-CN', i18nService: true }); + }); + + it('a list warns once, naming every token that stayed English', async () => { + const i18n = declaringI18n(['en']); + const { input, warns } = await invite({ role: 'admin,member', deployment: 'ja-JP', getI18n: () => i18n }); + expect(input.data.role).toContain('Admin'); + expect(input.data.role).toContain('Member'); + const named = untranslatedWarns(warns); + expect(named).toHaveLength(1); + expect(named[0]!.msg).toContain("'admin', 'member'"); + }); + + it('a value outside the option list is not counted twice', async () => { + const i18n = declaringI18n(['en']); + const { warns } = await invite({ role: 'auditor', deployment: 'zh-CN', getI18n: () => i18n }); + expect(warns.filter((w) => w.msg.includes("'auditor'"))).toHaveLength(1); + expect(untranslatedWarns(warns)).toHaveLength(0); + }); + + it.each(['en-US', 'en-GB'])('an %s mail reads the authored label as its own text: no warn', async (locale) => { + const { input, warns } = await invite({ role: 'member', deployment: locale }); + expect(input.data.role).toBe('Member'); + expect(warns.filter((w) => w.msg.includes('invitation mail'))).toHaveLength(0); + }); +}); + +// ── #25802 — the mail states when the invitation expires ─────────────────── + +describe('#25802 — the sender hands the template the invitation expiry', () => { + it('a Date expiry reaches the template as its ISO-8601 instant', async () => { + const { input } = await invite({ + role: 'member', + deployment: 'zh-CN', + getI18n: platformI18n, + expiresAt: new Date('2031-03-04T05:06:07.000Z'), + }); + expect(input.data.expiresAt).toBe('2031-03-04T05:06:07.000Z'); + }); + + it('a string expiry is read the same way', async () => { + const { input } = await invite({ role: 'member', deployment: 'en-US', expiresAt: '2031-03-04T05:06:07Z' }); + expect(input.data.expiresAt).toBe('2031-03-04T05:06:07.000Z'); + }); + + it.each([ + ['no expiry', undefined], + ['an unreadable one', 'not-a-date'], + ])('%s is left out rather than invented, with one warn naming the invitation and the refusal', async (_label, expiresAt) => { + // The template declares `expiresAt` required, so the real email service + // refuses this send (`MISSING_VARIABLES`, pinned in plugin-email's + // `auth-templates-locales.test.ts`); the warn makes the lost mail visible. + const { input, warns } = await invite({ role: 'member', deployment: 'en-US', expiresAt }); + expect(Object.prototype.hasOwnProperty.call(input.data, 'expiresAt')).toBe(false); + const named = warns.filter((w) => w.msg.includes('carries no readable expiry')); + expect(named).toHaveLength(1); + expect(named[0]!.msg).toContain("invitation 'inv1'"); + expect(named[0]!.msg).toContain('will be refused and not sent'); + expect(named[0]!.meta).toMatchObject({ invitationId: 'inv1' }); + }); + + it('a readable expiry logs no expiry warn', async () => { + const { warns } = await invite({ role: 'member', deployment: 'en-US' }); + expect(warns.filter((w) => w.msg.includes('carries no readable expiry'))).toHaveLength(0); + }); +}); + // ── the composition: AuthPlugin hands the manager the kernel's i18n ──────── describe('#24154 — AuthPlugin wires the i18n accessor lazily', () => { diff --git a/packages/plugins/plugin-auth/src/invitation-role-label.ts b/packages/plugins/plugin-auth/src/invitation-role-label.ts index 9f118a8ca2f..5e6e70aa2a3 100644 --- a/packages/plugins/plugin-auth/src/invitation-role-label.ts +++ b/packages/plugins/plugin-auth/src/invitation-role-label.ts @@ -39,6 +39,18 @@ import { EMAIL_TEMPLATE_FLOOR_LOCALE } from '@objectstack/spec/system'; * dropped, never an empty string — and one `warn` names it. An i18n read that * throws degrades to the authored (English) labels with one `warn`; it never * blocks the invitation. + * + * ## A label with no translation in the mail's locale is said so once, too + * + * The read can also answer without throwing and still leave the mail in two + * languages: no i18n service at all, a service holding no bundle for the + * mail's locale, or one whose bundle has no entry for the option — each one + * hands back the authored label (`Member`), or the English fallback-chain + * entry that repeats it, inside a Chinese sentence. When the mail's locale is + * not the authored labels' own language ({@link AUTHORED_LABEL_LANGUAGE}) and + * a token's label is still its authored text, one `warn` names the tokens and + * the locale, the same way the thrown read does. The mail still goes; the + * deployment learns that its i18n service never reached this locale's labels. */ export async function invitationRoleLabel( role: string, @@ -68,10 +80,12 @@ export async function invitationRoleLabel( if (typeof label === 'string' && label.length > 0) labels.set(String(option.value), label); } }; + let readFailed = false; + let i18nService: unknown; try { const [translated] = (await translateMetaList( { - resolveI18nService: async () => deps.getI18n?.(), + resolveI18nService: async () => (i18nService = deps.getI18n?.()), // A packaged base only decides between a catalog and an OVERRIDDEN // object scalar; option labels never consult it. resolveProtocol: async () => undefined, @@ -82,6 +96,7 @@ export async function invitationRoleLabel( )) as Array<{ fields?: { role?: { options?: unknown } } }>; collect(translated?.fields?.role?.options); } catch (err) { + readFailed = true; deps.warn?.( '[AuthManager] invitation mail: the membership role labels could not be read from the i18n service; ' + 'the mail names the authored (English) labels instead', @@ -98,6 +113,23 @@ export async function invitationRoleLabel( { role, locale: mailLocale }, ); } + if (!readFailed && !isAuthoredLabelLanguage(mailLocale)) { + const authoredLabels = new Map(); + for (const option of (authored?.options ?? []) as Array<{ value?: unknown; label?: unknown }>) { + if (typeof option?.label === 'string') authoredLabels.set(String(option.value), option.label); + } + const untranslated = tokens.filter((token) => labels.has(token) && labels.get(token) === authoredLabels.get(token)); + if (untranslated.length > 0) { + deps.warn?.( + `[AuthManager] invitation mail: no '${mailLocale}' label was found for the membership role(s) ` + + `${untranslated.map((t) => `'${t}'`).join(', ')}; the mail names the authored (English) label instead. ` + + 'The i18n service served no translation of sys_member.role for this locale: check that it holds the ' + + 'platform translation bundles and that its locales (i18n.supportedLocales, when declared) name this ' + + 'locale as the bundles spell it (zh-CN, not zh)', + { role, locale: mailLocale, i18nService: i18nService !== undefined }, + ); + } + } const named = tokens.map((token) => labels.get(token) ?? token); if (named.length === 1) return named[0]!; // `Intl.ListFormat` is ES2021; this package compiles against the ES2020 lib, @@ -111,6 +143,19 @@ export async function invitationRoleLabel( return named.join(', '); } +/** + * The language `sys_member.role`'s authored option labels are written in: + * `platform-objects` authors its metadata in English, and its `en` bundle is + * regenerated from that source. A mail in this language reads the authored + * label as its own text, so only a mail in any OTHER language can be left + * untranslated. + */ +const AUTHORED_LABEL_LANGUAGE = 'en'; + +function isAuthoredLabelLanguage(locale: string): boolean { + return locale.trim().toLowerCase().split(/[-_]/)[0] === AUTHORED_LABEL_LANGUAGE; +} + type IntlListFormatConstructor = new ( locale: string, options: { type: 'conjunction' }, diff --git a/packages/plugins/plugin-email/src/auth-templates-locales.test.ts b/packages/plugins/plugin-email/src/auth-templates-locales.test.ts index 2127c7c4405..33260aa57bc 100644 --- a/packages/plugins/plugin-email/src/auth-templates-locales.test.ts +++ b/packages/plugins/plugin-email/src/auth-templates-locales.test.ts @@ -126,6 +126,7 @@ const DATA: Record> = { role: 'admin', acceptUrl: 'https://acme.test/accept/INV1', appName: 'Acme', + expiresAt: '2031-03-04T05:06:07.000Z', }, 'auth.two_factor_otp': { otp: '482915', @@ -315,14 +316,20 @@ describe('#8195 — a zh-CN send renders NO en-US text', () => { // ── #24154 — the invitation's role clause, in both faces ─────────────────── /** The invitation's two bodies, apart: the card is about what EACH one says. */ -async function renderInvitationFaces(locale: Locale, data: Record) { +async function renderInvitationFaces(locale: Locale, data: Record, timezone?: string) { const transport = new CaptureTransport(); const svc = new EmailService({ transport, defaultFrom: { address: 'no-reply@acme.test' }, templateLoader: seededLoader, }); - await svc.sendTemplate({ template: 'auth.invitation', to: 'recipient@acme.test', locale, data }); + await svc.sendTemplate({ + template: 'auth.invitation', + to: 'recipient@acme.test', + locale, + data, + ...(timezone ? { timezone } : {}), + }); const sent = transport.sent[0]; expect(sent, `auth.invitation @ ${locale} was never handed to the transport`).toBeDefined(); return { html: sent!.html ?? '', text: sent!.text ?? '' }; @@ -331,6 +338,8 @@ async function renderInvitationFaces(locale: Locale, data: Record = { 'inviter.name': 'INVITER_NAME_X', @@ -339,6 +348,7 @@ const INVITATION_FACT_BY_VARIABLE: Record = { role: 'ROLE_LABEL_X', acceptUrl: 'https://acme.test/accept/ACCEPT_X', appName: 'APP_NAME_X', + expiresAt: '2031', }; const INVITATION_FACTS = { inviter: { name: 'INVITER_NAME_X', email: 'inviter-email-x@acme.test' }, @@ -346,6 +356,7 @@ const INVITATION_FACTS = { role: 'ROLE_LABEL_X', acceptUrl: 'https://acme.test/accept/ACCEPT_X', appName: 'APP_NAME_X', + expiresAt: '2031-03-04T05:06:07.000Z', }; describe('#24154 — the invitation names the role label, and both faces say the same thing', () => { @@ -370,6 +381,77 @@ describe('#24154 — the invitation names the role label, and both faces say the }); }); +// ── #25802 — the invitation says when it expires, in the mail's locale ───── + +/** + * The expiry sentence FRAME each locale's bodies wrap around the date, written + * out by hand: `[before, after]` the formatted instant. + */ +const EXPIRY_FRAME: Record = { + 'en-US': ['This invitation expires on ', '.'], + 'zh-CN': ['此邀请将于 ', ' 过期。'], + 'ja-JP': ['この招待の有効期限は ', ' です。'], + 'es-ES': ['Esta invitación caduca el ', '.'], +}; + +/** + * The instant as the `datetime:long` formatter must render it: the long date + * and time in that locale and zone, computed HERE with the running Node's own + * `Intl`, never copied from a render. The wording inside it is ICU locale + * data and moves between releases (es-ES reads `2031, 5:06:07` on ICU 77 and + * `2031 a las 5:06:07` on ICU 78), so a literal would pin the ICU build, not + * the template. What does not move is pinned beside it: the year and the + * zone's name are in it, because a date with no zone is the ambiguity the + * long style exists to remove. + */ +function longInstant(locale: Locale, timeZone: string): string { + return new Intl.DateTimeFormat(locale, { dateStyle: 'long', timeStyle: 'long', timeZone }).format( + new Date(INVITATION_FACTS.expiresAt), + ); +} + +describe('#25802 — the invitation states its expiry in the mail locale', () => { + it.each(SUPPORTED_LOCALES)('%s: both faces carry the expiry sentence, in the send timezone', async (locale) => { + const { html, text } = await renderInvitationFaces(locale, INVITATION_FACTS, 'UTC'); + const instant = longInstant(locale, 'UTC'); + expect(instant).toContain('2031'); + expect(instant).toContain('UTC'); + const [before, after] = EXPIRY_FRAME[locale]; + expect(text, `${locale} text body`).toContain(`${before}${instant}${after}`); + // The HTML face escapes the hole; no locale's long date carries a character it escapes. + expect(html, `${locale} HTML body`).toContain(`${before}${instant}${after}`); + }); + + it('the reference timezone the send names moves the wall-clock, and the zone is named', async () => { + const { text } = await renderInvitationFaces('zh-CN', INVITATION_FACTS, 'Asia/Shanghai'); + const shanghai = longInstant('zh-CN', 'Asia/Shanghai'); + expect(shanghai).not.toBe(longInstant('zh-CN', 'UTC')); + expect(shanghai).toContain('13:06:07'); + expect(text).toContain(`此邀请将于 ${shanghai} 过期。`); + }); + + it.each(SUPPORTED_LOCALES)('%s: a send without expiresAt is refused (MISSING_VARIABLES), never sent with a dangling sentence', async (locale) => { + // The engine has no conditionals, so every body states the expiry; the + // row declares the variable required and the service refuses the send. + const transport = new CaptureTransport(); + const svc = new EmailService({ + transport, + defaultFrom: { address: 'no-reply@acme.test' }, + templateLoader: seededLoader, + }); + const { expiresAt: _omitted, ...withoutExpiry } = INVITATION_FACTS; + await expect( + svc.sendTemplate({ template: 'auth.invitation', to: 'recipient@acme.test', locale, data: withoutExpiry }), + ).rejects.toThrow(/^MISSING_VARIABLES: expiresAt$/); + expect(transport.sent).toHaveLength(0); + }); + + it('a zh-CN invitation carries no English expiry sentence', async () => { + const { html, text } = await renderInvitationFaces('zh-CN', INVITATION_FACTS, 'UTC'); + for (const face of [html, text]) expect(face).not.toContain('expires'); + }); +}); + // ── #25060 — auth.existing_account_sign_up, in all four locales ──────────── /** diff --git a/packages/plugins/plugin-email/src/builtin-auth-render-identity.test.ts b/packages/plugins/plugin-email/src/builtin-auth-render-identity.test.ts index 177592dc10b..395c2e1f659 100644 --- a/packages/plugins/plugin-email/src/builtin-auth-render-identity.test.ts +++ b/packages/plugins/plugin-email/src/builtin-auth-render-identity.test.ts @@ -49,6 +49,10 @@ const DATA = { role: 'admin', inviter: { name: 'Grace ', email: 'grace@example.test' }, organization: { name: 'Analytical & Engines' }, + // [#25802] The invitation's expiry instant, rendered by a date formatter in + // the timezone the render names (UTC below) so the bytes never follow the + // machine's zone. + expiresAt: '2031-03-04T05:06:07.000Z', }; /** @@ -120,25 +124,28 @@ const RENDERED: Record // bodies gained the role clause their HTML bodies carry (each recomputed // from its expected string by hand, not copied from a run); the subject and // HTML pins are the row path's, unchanged. + // [#25802] The four invitation rows gained the expiry sentence; their bodies + // are re-pinned from the registry render in that commit, with the formatted + // instant cut to EXPIRY_HOLE (every other row's bytes were unchanged by it). 'auth.invitation@en-US': { subject: 'Grace invited you to Analytical & Engines', - html: '58aa661450e6d836a02267bede0e644f2f6cfcce2f125e63e4a4cc661d424069', - text: '80f58fec58593820cc25e500532d7749044829ff81313430087a8ee534c2c3d9', + html: '3e211033743dc60b2cdefc3ebc75496f92521e6928d39aa5a8b7f4ae939b6522', + text: '9ad810e17f17ec421a549070c88d8c41c99eb2018c0f3211ec5142c3a85a6120', }, 'auth.invitation@zh-CN': { subject: 'Grace 邀请您加入 Analytical & Engines', - html: '6789d8a1f8fe77ae9dac42694c4512df93be52edac56bfe91bbfad0a453e63fe', - text: '6590d3d0c00efdddbdfd9e6883a8f8955f22c0dbd88c8c315c3bf66be2d19841', + html: '0481419a8f4983cec604f915466ae22f263705945a93c1f389d591591f047044', + text: '847c2c5dca77944ec27125d8f24ce2c89a75fd0629edecd0193a72947f4b84fb', }, 'auth.invitation@ja-JP': { subject: 'Grace さんが Analytical & Engines に招待しています', - html: '6f5123d67393d721038b50292106bf83676d946f1950bf45869f16c2e977ef0f', - text: 'c8856c71f961085c3953f58886896d06506c453c7bddcec94460bfe12a13010e', + html: 'faee1bc20d4b0e4d42bbf4ed0b3838e3c49c6d63f540a33d12f1d427aa3d0954', + text: '79fd55bb6aad81c1e6f59d8c4bd4d387827c4d6b988a4f2887f996da9aba9dd3', }, 'auth.invitation@es-ES': { subject: 'Grace te ha invitado a Analytical & Engines', - html: '9f49cf12933faf499b1000b8895d29c4dbfba9b051e695bd845e885b22e7db02', - text: '53e0aa5ea929c9d1da42c129d5289f51557790a3a88ddc22c68bf47cdebd6b10', + html: '58f4b3f845eb870fc6cc494e8e4b95e102d988ba7e97cbc384267275fddc70ae', + text: 'fb576ed4a00198bd02ac3e54aa1d27239b2f1025562fa5be7a8da15ff3d78388', }, // [#23343] Declared after the row path was deleted, so these four never had // a seeded row: they are pinned against their first registry render, in the @@ -228,6 +235,9 @@ const RENDERED: Record }, }; +/** What the expiry instant is replaced with before a face is digested. */ +const EXPIRY_HOLE = '{{EXPIRES_AT_LONG}}'; + const sha256 = (s: string) => createHash('sha256').update(s, 'utf8').digest('hex'); /** Boot the plugin over a real ObjectQL and hand back the `email` service it installs. */ @@ -259,8 +269,29 @@ describe('every built-in auth mail renders byte-identical from the registry', () const svc = await bootEmailService(); const rendered: Record = {}; for (const tpl of BUILTIN_AUTH_TEMPLATES) { - const r = await svc.renderTemplate({ template: tpl.name, locale: tpl.locale, data: DATA }); - rendered[`${tpl.name}@${tpl.locale}`] = { subject: r.subject, html: sha256(r.html), text: sha256(r.text) }; + const r = await svc.renderTemplate({ template: tpl.name, locale: tpl.locale, data: DATA, timezone: 'UTC' }); + // [#25802] The one hole whose bytes are ICU locale data, not template + // text: the long-formatted expiry. Its wording moves between ICU + // releases (es-ES `2031, 5:06:07` on ICU 77, `2031 a las 5:06:07` on + // ICU 78), so it is cut out at its exact position and the digest pins + // every other byte; that the template renders exactly that instant is + // asserted here, against this Node's own `Intl`. + const instant = new Intl.DateTimeFormat(tpl.locale, { + dateStyle: 'long', + timeStyle: 'long', + timeZone: 'UTC', + }).format(new Date(DATA.expiresAt)); + const cut = (face: string) => face.split(instant); + const html = cut(r.html); + const text = cut(r.text); + const expected = tpl.name === 'auth.invitation' ? 2 : 1; + expect(html, `${tpl.name}@${tpl.locale} HTML expiry holes`).toHaveLength(expected); + expect(text, `${tpl.name}@${tpl.locale} text expiry holes`).toHaveLength(expected); + rendered[`${tpl.name}@${tpl.locale}`] = { + subject: r.subject, + html: sha256(html.join(EXPIRY_HOLE)), + text: sha256(text.join(EXPIRY_HOLE)), + }; } expect(Object.keys(rendered)).toHaveLength(32); diff --git a/packages/plugins/plugin-email/src/plain-text-faces.test.ts b/packages/plugins/plugin-email/src/plain-text-faces.test.ts index 84a9e7e6824..54a4a4f1e4b 100644 --- a/packages/plugins/plugin-email/src/plain-text-faces.test.ts +++ b/packages/plugins/plugin-email/src/plain-text-faces.test.ts @@ -100,6 +100,7 @@ const LINK_SENDS = [ role: 'member', acceptUrl: LINK, appName: 'Acme', + expiresAt: '2031-03-04T05:06:07.000Z', }, }, { template: 'auth.magic_link', data: { magicLinkUrl: LINK, expiresInMinutes: 10, appName: 'Acme' } }, @@ -156,6 +157,7 @@ describe('control: a value carrying markup characters, per face', () => { template: 'auth.invitation', to: 'alice@acme.test', locale: 'en-US', + timezone: 'UTC', data: { inviter: { name: "O'Brien", email: 'ob@acme.test' }, organization: { name: 'R&D ' }, @@ -163,15 +165,22 @@ describe('control: a value carrying markup characters, per face', () => { role: 'Member', acceptUrl: LINK, appName: 'Acme', + // #25802 — and the expiry, which the text body states after the link. + expiresAt: '2031-03-04T05:06:07.000Z', }, }); const sent = transport.sent[0]; expect(sent.html).toContain('R&D <Lab>'); expect(sent.html).toContain('O'Brien'); - expect(sent.text).toBe( + const [body, expiry] = (sent.text ?? '').split('\n\nThis invitation expires on '); + expect(body).toBe( "O'Brien (ob@acme.test) invited you to join R&D on Acme as Member.\n\n" + `Accept: ${LINK}`, ); + // The long date is ICU locale data, so it is computed with this Node's own `Intl`. + const instant = new Intl.DateTimeFormat('en-US', { dateStyle: 'long', timeStyle: 'long', timeZone: 'UTC' }) + .format(new Date('2031-03-04T05:06:07.000Z')); + expect(expiry).toBe(`${instant}.`); expect(sent.subject).toBe("O'Brien invited you to R&D "); expect(rows[0].subject).toBe("O'Brien invited you to R&D "); }); diff --git a/packages/plugins/plugin-email/src/templates/auth-templates.ts b/packages/plugins/plugin-email/src/templates/auth-templates.ts index bce567cb40a..853b3f4c834 100644 --- a/packages/plugins/plugin-email/src/templates/auth-templates.ts +++ b/packages/plugins/plugin-email/src/templates/auth-templates.ts @@ -346,10 +346,13 @@ export const AUTH_INVITATION_TEMPLATE: EmailTemplate = {

{{inviter.name}} ({{inviter.email}}) has invited you to join {{organization.name}} on {{appName}} as {{role}}.

Accept invitation

Or paste:
{{acceptUrl}}

+

This invitation expires on {{ expiresAt | datetime:long }}.

`), bodyText: `{{inviter.name}} ({{inviter.email}}) invited you to join {{organization.name}} on {{appName}} as {{role}}. -Accept: {{acceptUrl}}`, +Accept: {{acceptUrl}} + +This invitation expires on {{ expiresAt | datetime:long }}.`, variables: [ { name: 'inviter.name', type: 'string', required: false }, { name: 'inviter.email', type: 'string', required: false }, @@ -365,6 +368,21 @@ Accept: {{acceptUrl}}`, }, { name: 'acceptUrl', type: 'url', required: true }, { name: 'appName', type: 'string', required: false }, + // The instant the invitation stops being acceptable (better-auth's + // `invitation.expiresAt`, an ISO-8601 string). Every body renders it + // through the `datetime:long` formatter, so the date reads in the row's + // own locale and the reference timezone the send names — and the long + // style prints that zone, so the reader is never left guessing it. + // Required: the engine has no conditionals, so every body states the + // expiry unconditionally, and a send without it would ship a dangling + // "expires on ." sentence. Declared required, it is refused loudly + // (`MISSING_VARIABLES`) instead. + { + name: 'expiresAt', + type: 'date', + required: true, + description: 'When the invitation expires (ISO-8601 instant), rendered in the mail locale', + }, ], active: true, description: 'Sent by better-auth organization plugin when a user is invited to an org.', @@ -379,10 +397,13 @@ export const AUTH_INVITATION_TEMPLATE_ZH_CN: EmailTemplate = {

{{inviter.name}}({{inviter.email}})邀请您以 {{role}} 的身份加入 {{appName}} 上的 {{organization.name}}。

接受邀请

或复制以下链接:
{{acceptUrl}}

+

此邀请将于 {{ expiresAt | datetime:long }} 过期。

`, FOOTER_ZH_CN), bodyText: `{{inviter.name}}({{inviter.email}})邀请您以 {{role}} 的身份加入 {{appName}} 上的 {{organization.name}}。 -接受邀请:{{acceptUrl}}`, +接受邀请:{{acceptUrl}} + +此邀请将于 {{ expiresAt | datetime:long }} 过期。`, description: '当用户被邀请加入组织时,由 better-auth organization 插件发送。', }; @@ -395,10 +416,13 @@ export const AUTH_INVITATION_TEMPLATE_JA_JP: EmailTemplate = {

{{inviter.name}}({{inviter.email}})さんが、{{appName}} の {{organization.name}} に {{role}} として参加するようあなたを招待しました。

招待を承認する

または、次のリンクを貼り付けてください:
{{acceptUrl}}

+

この招待の有効期限は {{ expiresAt | datetime:long }} です。

`, FOOTER_JA_JP), bodyText: `{{inviter.name}}({{inviter.email}})さんが、{{appName}} の {{organization.name}} に {{role}} として参加するようあなたを招待しました。 -承認する: {{acceptUrl}}`, +承認する: {{acceptUrl}} + +この招待の有効期限は {{ expiresAt | datetime:long }} です。`, description: 'ユーザーが組織に招待されたときに better-auth organization プラグインが送信します。', }; @@ -411,10 +435,13 @@ export const AUTH_INVITATION_TEMPLATE_ES_ES: EmailTemplate = {

{{inviter.name}} ({{inviter.email}}) te ha invitado a unirte a {{organization.name}} en {{appName}} como {{role}}.

Aceptar invitación

O pega este enlace:
{{acceptUrl}}

+

Esta invitación caduca el {{ expiresAt | datetime:long }}.

`, FOOTER_ES_ES), bodyText: `{{inviter.name}} ({{inviter.email}}) te ha invitado a unirte a {{organization.name}} en {{appName}} como {{role}}. -Aceptar: {{acceptUrl}}`, +Aceptar: {{acceptUrl}} + +Esta invitación caduca el {{ expiresAt | datetime:long }}.`, description: 'Lo envía el plugin de organización de better-auth cuando se invita a alguien a una organización.', };