Skip to content
22 changes: 22 additions & 0 deletions .changeset/25802-invitation-role-label-warn-and-expiry.md
Original file line number Diff line number Diff line change
@@ -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`.

<!-- adr-0087: not-required (no-migration-prescription) a send-time refusal of an `auth.invitation` mail that names no `expiresAt`: no authorable key, spelling or stored shape moves, the email-template schema is unchanged, and no stored row is read, rewritten or converted. The repair is a value only the sender holds (the invitation's expiry), which no ledger entry can derive. The other categories are closed on facts: both packages publish (not unpublished); no ADR-0087 id covers this verdict (not already-registered); and the change is a template row's declaration, not a TS interface (not runtime-interface-only). -->
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -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,
Expand Down Expand Up @@ -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() };
}
125 changes: 123 additions & 2 deletions packages/plugins/plugin-auth/src/invitation-role-label.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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' } },
},
Expand Down Expand Up @@ -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 () => {
Expand All @@ -212,13 +228,118 @@ 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 () => {
await expect(invitationRoleLabel('', 'zh-CN', { getI18n: platformI18n })).resolves.toBe('');
});
});

// ── #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', () => {
Expand Down
47 changes: 46 additions & 1 deletion packages/plugins/plugin-auth/src/invitation-role-label.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -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',
Expand All @@ -98,6 +113,23 @@ export async function invitationRoleLabel(
{ role, locale: mailLocale },
);
}
if (!readFailed && !isAuthoredLabelLanguage(mailLocale)) {
const authoredLabels = new Map<string, string>();
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,
Expand All @@ -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' },
Expand Down
Loading
Loading