Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

feat: invites expire and can be renewed under a new link (#541)

Pasqual Troncone22f69523a569
diff --git a/apps/api/AGENTS.md b/apps/api/AGENTS.md
index a1fdf7e7..18ce284f 100644
--- a/apps/api/AGENTS.md
+++ b/apps/api/AGENTS.md
@@ -164,7 +164,10 @@ Enforced declaratively through macros, never imperative calls in handlers.
pending invite per (team, email) and per (project, email) — partial unique indexes →
409, and so is an address already in the team or in the project: accepting such an
invite would rewrite the membership it already holds, demoting an owner past the
- last-owner check. `members/` removes (last owner protected).
+ last-owner check. An expired invite gives way: inviting the address again, or
+ renewing it (`.../invites/:inviteId/renew`), replaces it with a new invite under a new
+ link. A link is never reissued, and an expired one is neither accepted nor mailed.
+ `members/` removes (last owner protected).
- The member list of a project is governed by its role matrix **or** by the team that
owns it: `memberAdmin: ["members_manage", "<action>"]` passes an owner or manager of
the team without a `project_member` row of their own, and every member route uses it
diff --git a/apps/api/src/__tests__/helpers/auth.ts b/apps/api/src/__tests__/helpers/auth.ts
index 9ebeda5e..5f7c9f4e 100644
--- a/apps/api/src/__tests__/helpers/auth.ts
+++ b/apps/api/src/__tests__/helpers/auth.ts
@@ -1,6 +1,8 @@
+import { createHash } from 'node:crypto';
import { auth } from '@repo/auth';
import { db, instanceWorkspaceId } from '@repo/db';
import { insertOwnedTeam } from '#modules/teams/service';
+import { app } from './app';
export interface TestUser {
// The session cookie header to pass to authenticated requests, e.g.
@@ -62,3 +64,23 @@ export async function signUpTestUser(
return { cookie, userId, email, username };
}
+
+// Opens a magic link for `email` as the web asks for one (errorCallbackURL on the sign-in
+// page) and returns where it redirects. The token is written straight into the
+// verification table, as better-auth stores it (`storeToken: 'hashed'`), because the
+// real one only travels in the email.
+export async function openMagicLink(email: string, token: string): Promise<URL> {
+ const context = await auth.$context;
+ await context.internalAdapter.createVerificationValue({
+ identifier: `magic-link:${createHash('sha256').update(token).digest('base64url')}`,
+ value: JSON.stringify({ type: 'magic-link', email }),
+ expiresAt: new Date(Date.now() + 60_000),
+ });
+ const res = await app.handle(
+ new Request(
+ `http://localhost/api/auth/magic-link/verify?token=${token}&callbackURL=/&errorCallbackURL=/login`,
+ ),
+ );
+ if (res.status !== 302) throw new Error(`magic link answered ${res.status}`);
+ return new URL(res.headers.get('location') ?? '', 'http://localhost');
+}
diff --git a/apps/api/src/__tests__/helpers/mcp.ts b/apps/api/src/__tests__/helpers/mcp.ts
index 30c8e9ea..3752a6ab 100644
--- a/apps/api/src/__tests__/helpers/mcp.ts
+++ b/apps/api/src/__tests__/helpers/mcp.ts
@@ -11,3 +11,65 @@ export function untaggedRoutes(match: (route: string) => boolean): string[] {
.filter(match)
.filter((route) => !tagged.has(route));
}
+
+const REDIRECT_URI = 'https://client.example.com/callback';
+const MCP_RESOURCE = `${process.env.API_URL}/mcp`;
+// The RFC 7636 example pair: the challenge is the S256 of the verifier.
+const CODE_VERIFIER = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
+const CODE_CHALLENGE = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM';
+
+// The MCP OAuth token a person gets by approving a client: register, authorize with
+// their session, consent, and exchange the code.
+export async function mcpAccessToken(cookie: string): Promise<string> {
+ const registered = await app.handle(
+ new Request('http://localhost/api/auth/oauth2/register', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ redirect_uris: [REDIRECT_URI],
+ token_endpoint_auth_method: 'none',
+ client_name: 'Test client',
+ }),
+ }),
+ );
+ const clientId = ((await registered.json()) as { client_id: string }).client_id;
+ const authorize = await app.handle(
+ new Request(
+ `http://localhost/api/auth/oauth2/authorize?${new URLSearchParams({
+ response_type: 'code',
+ client_id: clientId,
+ redirect_uri: REDIRECT_URI,
+ code_challenge: CODE_CHALLENGE,
+ code_challenge_method: 'S256',
+ scope: 'openid',
+ state: 'st',
+ resource: MCP_RESOURCE,
+ })}`,
+ { headers: { cookie } },
+ ),
+ );
+ // The consent page receives the signed authorization request and posts it back.
+ const consentPage = new URL(authorize.headers.get('location') ?? '');
+ const consent = await app.handle(
+ new Request('http://localhost/api/auth/oauth2/consent', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', cookie },
+ body: JSON.stringify({ accept: true, oauth_query: consentPage.search.slice(1) }),
+ }),
+ );
+ const { url } = (await consent.json()) as { url: string };
+ const token = await app.handle(
+ new Request('http://localhost/api/auth/oauth2/token', {
+ method: 'POST',
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
+ body: new URLSearchParams({
+ grant_type: 'authorization_code',
+ code: new URL(url).searchParams.get('code') ?? '',
+ redirect_uri: REDIRECT_URI,
+ client_id: clientId,
+ code_verifier: CODE_VERIFIER,
+ }),
+ }),
+ );
+ return ((await token.json()) as { access_token: string }).access_token;
+}
diff --git a/apps/api/src/__tests__/integration/invite-forms.test.ts b/apps/api/src/__tests__/integration/invite-forms.test.ts
new file mode 100644
index 00000000..77f8b582
--- /dev/null
+++ b/apps/api/src/__tests__/integration/invite-forms.test.ts
@@ -0,0 +1,214 @@
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { auth, setAuthSettings } from '@repo/auth';
+import { db, teamInvite } from '@repo/db';
+import { eq } from 'drizzle-orm';
+import { app, authedApi, apiKeyApi } from '#tests/helpers/app';
+import { openMagicLink, signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+import { mcpAccessToken } from '#tests/helpers/mcp';
+
+// The invite lifecycle and the registration gate hold on every way into the instance,
+// not only on the provider round trip: the email form (with and without a username),
+// the magic link, an instance without personal workspaces, an API key on the REST
+// routes, and the MCP tools with an API key or an OAuth token.
+// invite-expiry.test.ts covers the session routes.
+
+const DAY = 24 * 60 * 60 * 1000;
+
+async function setup() {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ const project = await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ return { owner, asOwner, teamId: project.data!.teamId };
+}
+
+async function invite(asOwner: ReturnType<typeof authedApi>, email: string, ageDays = 0) {
+ const created = await asOwner
+ .projects({ projectKey: 'MKT' })
+ .invites.post({ email, role: 'member' });
+ if (ageDays > 0) {
+ await db
+ .update(teamInvite)
+ .set({ createdAt: new Date(Date.now() - ageDays * DAY) })
+ .where(eq(teamInvite.token, created.data!.token));
+ }
+ return created.data!;
+}
+
+const signUp = (email: string, extra: Record<string, string> = {}) =>
+ auth.api.signUpEmail({
+ body: { email, password: 'test-password-123', name: 'Newcomer', ...extra },
+ asResponse: true,
+ });
+
+async function refusalCode(promise: Promise<unknown>): Promise<string | null> {
+ try {
+ await promise;
+ return null;
+ } catch (err) {
+ return (err as { body?: { code?: string } }).body?.code ?? 'unknown';
+ }
+}
+
+describe('the email form and the registration gate', () => {
+ beforeEach(resetDb);
+
+ it('creates the account on an open instance', async () => {
+ await setup();
+ await setAuthSettings({ registration: 'open' });
+ expect((await signUp('[email protected]')).status).toBe(200);
+ });
+
+ it('refuses it on a closed instance with REGISTRATION_CLOSED', async () => {
+ await setup();
+ await setAuthSettings({ registration: 'closed' });
+ expect(await refusalCode(signUp('[email protected]'))).toBe('REGISTRATION_CLOSED');
+ });
+
+ it('refuses an address with no invite on an invite-only instance with INVITE_ONLY', async () => {
+ await setup();
+ await setAuthSettings({ registration: 'invite' });
+ expect(await refusalCode(signUp('[email protected]'))).toBe('INVITE_ONLY');
+ });
+
+ it('applies the same gate to a sign-up that carries a username', async () => {
+ await setup();
+ await setAuthSettings({ registration: 'invite' });
+ expect(await refusalCode(signUp('[email protected]', { username: 'named-newcomer' }))).toBe(
+ 'INVITE_ONLY',
+ );
+ });
+
+ // The email form is open to anyone, so it must not reveal that an address was invited.
+ it('refuses an address whose invite expired as plainly invite-only', async () => {
+ const { asOwner } = await setup();
+ await setAuthSettings({ registration: 'invite' });
+ await invite(asOwner, '[email protected]', 8);
+ expect(await refusalCode(signUp('[email protected]'))).toBe('INVITE_ONLY');
+ });
+
+ it('refuses a username sign-up whose invite expired as plainly invite-only', async () => {
+ const { asOwner } = await setup();
+ await setAuthSettings({ registration: 'invite' });
+ await invite(asOwner, '[email protected]', 8);
+ expect(await refusalCode(signUp('[email protected]', { username: 'lapsed-newcomer' }))).toBe(
+ 'INVITE_ONLY',
+ );
+ });
+
+ it('lets an invited address in on an instance without personal workspaces', async () => {
+ const { asOwner } = await setup();
+ await setAuthSettings({ registration: 'invite', personalWorkspaces: false });
+ await invite(asOwner, '[email protected]');
+ expect((await signUp('[email protected]')).status).toBe(200);
+ });
+});
+
+describe('the magic link and the registration gate', () => {
+ beforeEach(resetDb);
+
+ // A magic link proves the address, so it may be told that its invite expired.
+ it('refuses an address whose invite expired with INVITE_EXPIRED', async () => {
+ const { asOwner } = await setup();
+ await setAuthSettings({ registration: 'invite' });
+ await invite(asOwner, '[email protected]', 8);
+ const location = await openMagicLink('[email protected]', 'magic-lapsed');
+ expect(location.searchParams.get('error')).toBe('INVITE_EXPIRED');
+ });
+
+ it('creates the account of an invited address and signs it in', async () => {
+ const { asOwner } = await setup();
+ await setAuthSettings({ registration: 'invite' });
+ await invite(asOwner, '[email protected]');
+ const location = await openMagicLink('[email protected]', 'magic-invited');
+ expect(location.searchParams.get('error')).toBeNull();
+ });
+});
+
+describe('invites over an API key', () => {
+ beforeEach(resetDb);
+
+ it('creates, lists and renews a project invite through the REST routes', async () => {
+ const { owner, asOwner } = await setup();
+ const { key } = await auth.api.createApiKey({ body: { userId: owner.userId, name: 'ci' } });
+ const asKey = apiKeyApi(key).projects({ projectKey: 'MKT' });
+
+ const created = await asKey.invites.post({ email: '[email protected]', role: 'member' });
+ expect(created.status).toBe(201);
+ await db
+ .update(teamInvite)
+ .set({ createdAt: new Date(Date.now() - 8 * DAY) })
+ .where(eq(teamInvite.token, created.data!.token));
+
+ const listed = (await asKey.invites.get()).data!;
+ expect(new Date(listed[0].expiresAt!).getTime()).toBeLessThan(Date.now());
+
+ const renewed = await asKey.invites({ inviteId: created.data!.id }).renew.post();
+ expect(renewed.status).toBe(201);
+ expect(renewed.data!.token).not.toBe(created.data!.token);
+ // The session client sees the same single pending invite.
+ const pending = (await asOwner.projects({ projectKey: 'MKT' }).invites.get()).data!;
+ expect(pending.filter((i) => i.status === 'pending')).toHaveLength(1);
+ });
+});
+
+describe('invites over MCP', () => {
+ beforeEach(resetDb);
+
+ async function rpc(bearer: string, method: string, params: Record<string, unknown> = {}) {
+ const res = await app.handle(
+ new Request('http://localhost/mcp', {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${bearer}`,
+ 'content-type': 'application/json',
+ accept: 'application/json, text/event-stream',
+ },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ }),
+ );
+ const text = await res.text();
+ return JSON.parse(text.slice(text.indexOf('data: ') + 6)).result;
+ }
+
+ async function call(bearer: string, name: string, args: Record<string, unknown>) {
+ const result = await rpc(bearer, 'tools/call', { name, arguments: args });
+ return { text: result.content[0].text as string, isError: result.isError === true };
+ }
+
+ it('renews an expired invite and refuses to mail it before that', async () => {
+ const { owner, asOwner } = await setup();
+ const { key } = await auth.api.createApiKey({ body: { userId: owner.userId, name: 'mcp' } });
+ const old = await invite(asOwner, '[email protected]', 8);
+
+ const mailed = await call(key, 'send_invite_email', { projectKey: 'MKT', inviteId: old.id });
+ expect(mailed.isError).toBe(true);
+
+ const renewed = await call(key, 'renew_invite', { projectKey: 'MKT', inviteId: old.id });
+ expect(renewed.isError).toBe(false);
+ const body = JSON.parse(renewed.text) as { token: string; expiresAt: string };
+ expect(body.token).not.toBe(old.token);
+ expect(new Date(body.expiresAt).getTime()).toBeGreaterThan(Date.now());
+ });
+
+ // An OAuth client takes the other branch of /mcp, where the token is forwarded to the
+ // REST route instead of an x-api-key header.
+ it('applies the same rules to a client connected over OAuth', async () => {
+ const { owner, asOwner } = await setup();
+ const accessToken = await mcpAccessToken(owner.cookie);
+ const old = await invite(asOwner, '[email protected]', 8);
+
+ const mailed = await call(accessToken, 'send_invite_email', {
+ projectKey: 'MKT',
+ inviteId: old.id,
+ });
+ expect(mailed.isError).toBe(true);
+
+ const renewed = await call(accessToken, 'renew_invite', {
+ projectKey: 'MKT',
+ inviteId: old.id,
+ });
+ expect(renewed.isError).toBe(false);
+ expect((JSON.parse(renewed.text) as { token: string }).token).not.toBe(old.token);
+ });
+});
diff --git a/apps/api/src/modules/god/__tests__/integration/god-deactivate.test.ts b/apps/api/src/modules/god/__tests__/integration/god-deactivate.test.ts
index ae47f75e..78810d15 100644
--- a/apps/api/src/modules/god/__tests__/integration/god-deactivate.test.ts
+++ b/apps/api/src/modules/god/__tests__/integration/god-deactivate.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it } from 'bun:test';
import { auth } from '@repo/auth';
import { apiKeyApi, app, authedApi } from '#tests/helpers/app';
import { signUpTestUser } from '#tests/helpers/auth';
+import { mcpAccessToken } from '#tests/helpers/mcp';
import { resetDb } from '#tests/helpers/db';
import { setupScim } from '#modules/scim/__tests__/helpers';
import { createAgentUser, setup } from '../helpers';
@@ -15,68 +16,6 @@ async function signIn(email: string) {
});
}
-const REDIRECT_URI = 'https://client.example.com/callback';
-const MCP_RESOURCE = `${process.env.API_URL}/mcp`;
-// The RFC 7636 example pair: the challenge is the S256 of the verifier.
-const CODE_VERIFIER = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk';
-const CODE_CHALLENGE = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM';
-
-// The MCP OAuth token a person gets by approving a client: register, authorize with
-// their session, consent, and exchange the code.
-async function mcpAccessToken(cookie: string): Promise<string> {
- const registered = await app.handle(
- new Request('http://localhost/api/auth/oauth2/register', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- redirect_uris: [REDIRECT_URI],
- token_endpoint_auth_method: 'none',
- client_name: 'Test client',
- }),
- }),
- );
- const clientId = ((await registered.json()) as { client_id: string }).client_id;
- const authorize = await app.handle(
- new Request(
- `http://localhost/api/auth/oauth2/authorize?${new URLSearchParams({
- response_type: 'code',
- client_id: clientId,
- redirect_uri: REDIRECT_URI,
- code_challenge: CODE_CHALLENGE,
- code_challenge_method: 'S256',
- scope: 'openid',
- state: 'st',
- resource: MCP_RESOURCE,
- })}`,
- { headers: { cookie } },
- ),
- );
- // The consent page receives the signed authorization request and posts it back.
- const consentPage = new URL(authorize.headers.get('location') ?? '');
- const consent = await app.handle(
- new Request('http://localhost/api/auth/oauth2/consent', {
- method: 'POST',
- headers: { 'content-type': 'application/json', cookie },
- body: JSON.stringify({ accept: true, oauth_query: consentPage.search.slice(1) }),
- }),
- );
- const { url } = (await consent.json()) as { url: string };
- const token = await app.handle(
- new Request('http://localhost/api/auth/oauth2/token', {
- method: 'POST',
- headers: { 'content-type': 'application/x-www-form-urlencoded' },
- body: new URLSearchParams({
- grant_type: 'authorization_code',
- code: new URL(url).searchParams.get('code') ?? '',
- redirect_uri: REDIRECT_URI,
- client_id: clientId,
- code_verifier: CODE_VERIFIER,
- }),
- }),
- );
- return ((await token.json()) as { access_token: string }).access_token;
-}
-
async function mcpInitialize(bearer: string) {
return app.handle(
new Request('http://localhost/mcp', {
diff --git a/apps/api/src/modules/god/index.ts b/apps/api/src/modules/god/index.ts
index 6caa38bb..7180234e 100644
--- a/apps/api/src/modules/god/index.ts
+++ b/apps/api/src/modules/god/index.ts
@@ -140,7 +140,8 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
response: { 200: AuthSettingsResponse, ...errors(401, 403) },
detail: {
summary: 'Get authentication settings',
- description: 'Get the instance registration mode and email-dependent auth options.',
+ description:
+ 'Get the instance registration mode, invite lifetime and email-dependent auth options.',
},
},
)
@@ -168,7 +169,8 @@ export const godRoutes = new Elysia({ name: 'god', detail: { tags: ['God'] } })
response: { 200: AuthSettingsResponse, ...errors(400, 401, 403) },
detail: {
summary: 'Update authentication settings',
- description: 'Update the instance registration mode and email-dependent auth options.',
+ description:
+ 'Update the instance registration mode, invite lifetime and email-dependent auth options.',
},
},
)
diff --git a/apps/api/src/modules/god/model.ts b/apps/api/src/modules/god/model.ts
index 3e1253e4..fead6ab3 100644
--- a/apps/api/src/modules/god/model.ts
+++ b/apps/api/src/modules/god/model.ts
@@ -38,6 +38,7 @@ export const AuthSettingsResponse = t.Object({
emailPassword: t.Boolean(),
trustProviderEmails: t.Boolean(),
personalWorkspaces: t.Boolean(),
+ inviteTtlDays: t.Integer(),
// The settings that depend on outbound email cannot be turned on without a mail
// provider, and the UI explains why.
hasEmailProvider: t.Boolean(),
@@ -55,6 +56,8 @@ export const AuthSettingsBody = t.Object({
emailPassword: t.Optional(t.Boolean()),
trustProviderEmails: t.Optional(t.Boolean()),
personalWorkspaces: t.Optional(t.Boolean()),
+ // The cap keeps createdAt plus the lifetime inside the range a Date can hold.
+ inviteTtlDays: t.Optional(t.Integer({ minimum: 0, maximum: 3650 })),
});
export const EmailSettingsResponse = t.Object({
diff --git a/apps/api/src/modules/invites/__tests__/integration/invite-expiry.test.ts b/apps/api/src/modules/invites/__tests__/integration/invite-expiry.test.ts
new file mode 100644
index 00000000..c9305850
--- /dev/null
+++ b/apps/api/src/modules/invites/__tests__/integration/invite-expiry.test.ts
@@ -0,0 +1,345 @@
+import { beforeEach, describe, expect, it } from 'bun:test';
+import { auth, setAuthSettings } from '@repo/auth';
+import { db, teamInvite } from '@repo/db';
+import { eq } from 'drizzle-orm';
+import { authedApi, type Api } from '#tests/helpers/app';
+import { createRole } from '#tests/helpers/roles';
+import { signUpTestUser } from '#tests/helpers/auth';
+import { resetDb } from '#tests/helpers/db';
+
+// Invites expire (default 7 days). An expired invite neither gates registration nor
+// can be accepted, and a pending invite is deleted when its creator is removed.
+async function setup() {
+ const owner = await signUpTestUser({ name: 'Owner' });
+ const asOwner = authedApi(owner.cookie);
+ const project = await asOwner.projects.post({ key: 'MKT', name: 'Marketing' });
+ return { asOwner, teamId: project.data!.teamId };
+}
+
+const project = (api: Api) => api.projects({ projectKey: 'MKT' });
+
+async function backdate(token: string, days: number) {
+ await db
+ .update(teamInvite)
+ .set({ createdAt: new Date(Date.now() - days * 24 * 60 * 60 * 1000) })
+ .where(eq(teamInvite.token, token));
+}
+
+describe('invite expiry and cleanup', () => {
+ beforeEach(resetDb);
+
+ it('refuses to accept an invite older than the TTL', async () => {
+ const { asOwner } = await setup();
+ const invitee = await signUpTestUser({ team: false });
+ const asInvitee = authedApi(invitee.cookie);
+ const invite = await project(asOwner).invites.post({ email: invitee.email, role: 'member' });
+ const token = invite.data!.token;
+
+ await backdate(token, 8);
+ expect((await asInvitee.invites({ token }).accept.post()).status).toBe(409);
+ });
+
+ it('accepts an invite one day inside the TTL', async () => {
+ const { asOwner } = await setup();
+ const invitee = await signUpTestUser({ team: false });
+ const asInvitee = authedApi(invitee.cookie);
+ const invite = await project(asOwner).invites.post({ email: invitee.email, role: 'member' });
+ const token = invite.data!.token;
+
+ await backdate(token, 6);
+ expect((await asInvitee.invites({ token }).accept.post()).status).toBe(200);
+ });
+
+ it('accepts an old invite when the TTL is 0', async () => {
+ const { asOwner } = await setup();
+ await setAuthSettings({ inviteTtlDays: 0 });
+ const invitee = await signUpTestUser({ team: false });
+ const asInvitee = authedApi(invitee.cookie);
+ const invite = await project(asOwner).invites.post({ email: invitee.email, role: 'member' });
+ const token = invite.data!.token;
+
+ await backdate(token, 400);
+ expect((await asInvitee.invites({ token }).accept.post()).status).toBe(200);
+ });
+
+ it('lets an invited address register on an invite-only instance only while the invite is valid', async () => {
+ const { asOwner } = await setup();
+ await setAuthSettings({ registration: 'invite' });
+ const signUp = (email: string) =>
+ auth.api.signUpEmail({
+ body: { email, password: 'test-password-123', name: 'Guest' },
+ asResponse: true,
+ });
+
+ const expired = await project(asOwner).invites.post({
+ email: '[email protected]',
+ role: 'member',
+ });
+ await backdate(expired.data!.token, 8);
+ await expect(signUp('[email protected]')).rejects.toThrow('This instance is invite-only');
+
+ await project(asOwner).invites.post({ email: '[email protected]', role: 'member' });
+ expect((await signUp('[email protected]')).status).toBe(200);
+ });
+
+ it('still accepts a fresh invite', async () => {
+ const { asOwner } = await setup();
+ const invitee = await signUpTestUser({ team: false });
+ const asInvitee = authedApi(invitee.cookie);
+ const invite = await project(asOwner).invites.post({ email: invitee.email, role: 'member' });
+
+ expect((await asInvitee.invites({ token: invite.data!.token }).accept.post()).status).toBe(200);
+ });
+
+ it('deletes a pending invite when its creator is removed from the team', async () => {
+ const { asOwner, teamId } = await setup();
+ const roleId = (
+ await createRole(asOwner, 'MKT', {
+ name: 'Inviter',
+ permissions: { members_invite: { read: true, create: true } },
+ })
+ ).data!.id;
+
+ // A member who can invite joins through an invite of their own.
+ const member = await signUpTestUser({ team: false });
+ const asMember = authedApi(member.cookie);
+ const memberInvite = await project(asOwner).invites.post({
+ email: member.email,
+ role: 'member',
+ roleId,
+ });
+ await asMember.invites({ token: memberInvite.data!.token }).accept.post();
+
+ // They invite someone, then the owner removes them from the team.
+ const guest = await signUpTestUser({ team: false });
+ const asGuest = authedApi(guest.cookie);
+ const guestInvite = await project(asMember).invites.post({
+ email: guest.email,
+ role: 'member',
+ });
+ const guestToken = guestInvite.data!.token;
+
+ await asOwner.teams({ teamId }).members({ userId: member.userId }).delete();
+
+ // The guest's invite is gone.
+ expect((await asGuest.invites({ token: guestToken }).accept.post()).status).toBe(404);
+ });
+});
+
+// An expired invite is never revived: inviting again or renewing hands out a new link
+// with a fresh validity, and the old link stops existing.
+describe('renewing an expired invite', () => {
+ beforeEach(resetDb);
+
+ it('lets the same address be invited again once the old invite expired', async () => {
+ const { asOwner } = await setup();
+ const first = await project(asOwner).invites.post({
+ email: '[email protected]',
+ role: 'member',
+ });
+ expect(
+ (await project(asOwner).invites.post({ email: '[email protected]', role: 'member' })).status,
+ ).toBe(409);
+
+ await backdate(first.data!.token, 8);
+ const second = await project(asOwner).invites.post({
+ email: '[email protected]',
+ role: 'member',
+ });
+ expect(second.status).toBe(201);
+ expect(second.data!.token).not.toBe(first.data!.token);
+ expect((await asOwner.invites({ token: first.data!.token }).get()).status).toBe(404);
+ });
+
+ it('shows when a pending invite expires, and that an old one has', async () => {
+ const { asOwner } = await setup();
+ const invite = await project(asOwner).invites.post({
+ email: '[email protected]',
+ role: 'member',
+ });
+ const listed = (await project(asOwner).invites.get()).data!;
+ expect(new Date(listed[0].expiresAt!).getTime()).toBeGreaterThan(Date.now());
+
+ await backdate(invite.data!.token, 8);
+ expect((await asOwner.invites({ token: invite.data!.token }).get()).data!.expired).toBe(true);
+ });
+
+ it('queues the email of a renewed project invite, as creating one does', async () => {
+ const { asOwner } = await setup();
+ const configured = await asOwner.god['email-settings'].put({
+ from: "It's a Plan <[email protected]>",
+ resend: { enabled: true, apiKey: 're_test_key' },
+ allowProjects: false,
+ });
+ expect(configured.status).toBe(200);
+ const old = await project(asOwner).invites.post({
+ email: '[email protected]',
+ role: 'member',
+ });
+ await backdate(old.data!.token, 8);
+
+ const renewed = await project(asOwner).invites({ inviteId: old.data!.id }).renew.post();
+ expect(renewed.status).toBe(201);
+ expect(renewed.data!.emailQueued).toBe(true);
+ });
+
+ it('renews an expired project invite under a new link for the same role', async () => {
+ const { asOwner } = await setup();
+ const invitee = await signUpTestUser({ team: false });
+ const old = await project(asOwner).invites.post({ email: invitee.email, role: 'owner' });
+ await backdate(old.data!.token, 8);
+
+ const renewed = await project(asOwner).invites({ inviteId: old.data!.id }).renew.post();
+ expect(renewed.status).toBe(201);
+ expect(renewed.data!.token).not.toBe(old.data!.token);
+ expect(renewed.data!.role).toBe('owner');
+
+ const asInvitee = authedApi(invitee.cookie);
+ expect((await asInvitee.invites({ token: old.data!.token }).accept.post()).status).toBe(404);
+ expect((await asInvitee.invites({ token: renewed.data!.token }).accept.post()).status).toBe(
+ 200,
+ );
+ });
+
+ it('does not renew an invite that is still valid, nor mail an expired one', async () => {
+ const { asOwner } = await setup();
+ const invite = await project(asOwner).invites.post({
+ email: '[email protected]',
+ role: 'member',
+ });
+ const id = invite.data!.id;
+ expect((await project(asOwner).invites({ inviteId: id }).renew.post()).status).toBe(409);
+
+ await backdate(invite.data!.token, 8);
+ expect((await project(asOwner).invites({ inviteId: id }).email.post()).status).toBe(409);
+ });
+
+ it('renews an expired team invite from the team', async () => {
+ const { asOwner, teamId } = await setup();
+ const old = await asOwner
+ .teams({ teamId })
+ .invites.post({ email: '[email protected]', role: 'member' });
+ await backdate(old.data!.token, 8);
+
+ const renewed = await asOwner
+ .teams({ teamId })
+ .invites({ inviteId: old.data!.id })
+ .renew.post();
+ expect(renewed.status).toBe(201);
+ expect(renewed.data!.token).not.toBe(old.data!.token);
+ // A team invite has no email of its own: its new link is returned to share.
+ expect(renewed.data!.emailQueued).toBe(false);
+ const pending = (await asOwner.teams({ teamId }).invites.get()).data!.filter(
+ (i) => i.status === 'pending',
+ );
+ expect(pending.map((i) => i.token)).toEqual([renewed.data!.token]);
+ });
+
+ it('holds a renewal to the rank rules of creating the invite', async () => {
+ const { asOwner, teamId } = await setup();
+ const old = await asOwner
+ .teams({ teamId })
+ .invites.post({ email: '[email protected]', role: 'manager' });
+ await backdate(old.data!.token, 8);
+
+ const manager = await signUpTestUser({ team: false });
+ const managerInvite = await asOwner.teams({ teamId }).invites.post({
+ email: manager.email,
+ role: 'manager',
+ });
+ const asManager = authedApi(manager.cookie);
+ await asManager.invites({ token: managerInvite.data!.token }).accept.post();
+
+ const renew = asManager.teams({ teamId }).invites({ inviteId: old.data!.id }).renew;
+ expect((await renew.post()).status).toBe(403);
+ });
+
+ it("holds a project renewal to who may hand out the project's ownership", async () => {
+ const { asOwner } = await setup();
+ const roleId = (
+ await createRole(asOwner, 'MKT', {
+ name: 'Inviter',
+ permissions: { members_invite: { read: true, create: true } },
+ })
+ ).data!.id;
+ const member = await signUpTestUser({ team: false });
+ const asMember = authedApi(member.cookie);
+ const memberInvite = await project(asOwner).invites.post({
+ email: member.email,
+ role: 'member',
+ roleId,
+ });
+ await asMember.invites({ token: memberInvite.data!.token }).accept.post();
+
+ const ownership = await project(asOwner).invites.post({
+ email: '[email protected]',
+ role: 'owner',
+ });
+ const plain = await project(asOwner).invites.post({
+ email: '[email protected]',
+ role: 'member',
+ });
+ await backdate(ownership.data!.token, 8);
+ await backdate(plain.data!.token, 8);
+
+ const renew = (id: number) => project(asMember).invites({ inviteId: id }).renew.post();
+ expect((await renew(ownership.data!.id)).status).toBe(403);
+ expect((await renew(plain.data!.id)).status).toBe(201);
+ });
+
+ it('does not renew from a project or a team the invite does not belong to', async () => {
+ const { asOwner, teamId } = await setup();
+ await asOwner.projects.post({ key: 'OPS', name: 'Operations' });
+ const elsewhere = await asOwner
+ .projects({ projectKey: 'OPS' })
+ .invites.post({ email: '[email protected]', role: 'member' });
+ await backdate(elsewhere.data!.token, 8);
+ const renewFromMkt = project(asOwner).invites({ inviteId: elsewhere.data!.id }).renew;
+ expect((await renewFromMkt.post()).status).toBe(404);
+
+ const other = await signUpTestUser({ name: 'Other' });
+ const asOther = authedApi(other.cookie);
+ const otherTeam = (await asOther.projects.post({ key: 'OTH', name: 'Other' })).data!.teamId;
+ const foreign = await asOther
+ .teams({ teamId: otherTeam })
+ .invites.post({ email: '[email protected]', role: 'member' });
+ await backdate(foreign.data!.token, 8);
+ const renewFromTeam = asOwner.teams({ teamId }).invites({ inviteId: foreign.data!.id }).renew;
+ expect((await renewFromTeam.post()).status).toBe(404);
+ });
+
+ it('does not renew a team invite that is still valid', async () => {
+ const { asOwner, teamId } = await setup();
+ const live = await asOwner
+ .teams({ teamId })
+ .invites.post({ email: '[email protected]', role: 'member' });
+
+ const renew = asOwner.teams({ teamId }).invites({ inviteId: live.data!.id }).renew;
+ expect((await renew.post()).status).toBe(409);
+ });
+
+ it('renews an expired project invite from the team list', async () => {
+ const { asOwner, teamId } = await setup();
+ const old = await project(asOwner).invites.post({ email: '[email protected]', role: 'member' });
+ await backdate(old.data!.token, 8);
+
+ const renewed = await asOwner
+ .teams({ teamId })
+ .invites({ inviteId: old.data!.id })
+ .renew.post();
+ expect(renewed.status).toBe(201);
+ expect(renewed.data!.projectKey).toBe('MKT');
+ expect(renewed.data!.token).not.toBe(old.data!.token);
+ });
+});
+
+describe('invite lifetime setting', () => {
+ beforeEach(resetDb);
+
+ it('refuses a lifetime past what a date can hold', async () => {
+ const owner = await signUpTestUser({ name: 'God' });
+ const asGod = authedApi(owner.cookie);
+ expect((await asGod.god['auth-settings'].put({ inviteTtlDays: 3651 })).status).toBe(400);
+ expect((await asGod.god['auth-settings'].put({ inviteTtlDays: 30 })).status).toBe(200);
+ });
+});
diff --git a/apps/api/src/modules/invites/email.ts b/apps/api/src/modules/invites/email.ts
index 5d8648c0..38a985c3 100644
--- a/apps/api/src/modules/invites/email.ts
+++ b/apps/api/src/modules/invites/email.ts
@@ -5,7 +5,7 @@ import { hasEmailProvider } from '@repo/mailer';
import { and, eq, sql } from 'drizzle-orm';
import type { InviteRow } from './service';
-interface InviteProject {
+export interface InviteProject {
id: number;
name: string;
}
diff --git a/apps/api/src/modules/invites/index.ts b/apps/api/src/modules/invites/index.ts
index 63b2eb06..542fbfed 100644
--- a/apps/api/src/modules/invites/index.ts
+++ b/apps/api/src/modules/invites/index.ts
@@ -4,6 +4,7 @@ import { noContent } from '#shared/http';
import { authContext } from '#shared/auth-context';
import { guards } from '#shared/guards';
import { requireUser, type AuthUser } from '#shared/access';
+import { inviteValidSince } from '@repo/auth';
import { HttpError } from '#shared/lib';
import { accessErrors, commonErrors, errors } from '#shared/responses';
import { getRole } from '#modules/roles/service';
@@ -31,10 +32,13 @@ import {
getInviteById,
getInviteByToken,
getInviteRowByToken,
+ getInviteGrant,
+ renewInvite,
acceptInvite,
rejectInvite,
+ type InviteRow,
} from './service';
-import { enqueueInviteEmail } from './email';
+import { enqueueInviteEmail, type InviteProject } from './email';
// Shared by accept and reject: an invite is actionable only by the account whose
// email it names, and only while it is still pending.
@@ -43,6 +47,8 @@ async function loadActionableInvite(token: string, user: AuthUser | undefined |
const invite = await getInviteRowByToken(token);
if (!invite) throw new HttpError(404, 'Invite not found');
if (invite.status !== 'pending') throw new HttpError(409, 'This invite is no longer pending');
+ const since = await inviteValidSince();
+ if (since && invite.createdAt < since) throw new HttpError(409, 'This invite has expired');
if ((current.email ?? '').toLowerCase() !== invite.email) {
throw new HttpError(403, 'This invite was sent to a different email');
}
@@ -67,6 +73,17 @@ async function assertStillGrantable(invite: {
}
}
+// Creating or renewing the invite link is the primary operation. A transient outbox
+// failure must not discard a valid link that can still be copied.
+async function queueEmail(project: InviteProject, invite: InviteRow): Promise<boolean> {
+ try {
+ return await enqueueInviteEmail(project, invite);
+ } catch (err) {
+ console.error('[invites] email enqueue failed:', err);
+ return false;
+ }
+}
+
export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invites'] } })
.use(authContext)
.use(guards)
@@ -113,14 +130,7 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
roleId,
invitedByUserId: invitedBy,
});
- let emailQueued = false;
- try {
- emailQueued = await enqueueInviteEmail(project, invite);
- } catch (err) {
- // Creating the invite link is the primary operation. A transient outbox
- // failure must not discard a valid link that can still be copied.
- console.error('[invites] email enqueue failed:', err);
- }
+ const emailQueued = await queueEmail(project, invite);
set.status = 201;
return { ...invite, emailQueued };
},
@@ -149,6 +159,10 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
if (invite.status !== 'pending') {
throw new HttpError(409, 'This invite is no longer pending');
}
+ // Mailing a dead link only leads the invitee to an error; renewing sends a live one.
+ if (invite.expiresAt && new Date(invite.expiresAt) < new Date()) {
+ throw new HttpError(409, 'This invite has expired. Renew it to send a new link.');
+ }
return { emailQueued: await enqueueInviteEmail(project, invite) };
},
{
@@ -159,12 +173,45 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
summary: 'Send an invite email',
description:
'Queue an email for a pending project invite. Returns false when the instance email ' +
- 'provider is not configured.',
+ 'provider is not configured. An expired invite is refused: renew it instead.',
...mcpTool('send_invite_email'),
},
},
)
+ .post(
+ '/projects/:projectKey/invites/:inviteId/renew',
+ async ({ project, params, user, set }) => {
+ const renewedBy = requireUser(user).id;
+ const grant = await getInviteGrant(params.inviteId);
+ if (!grant || grant.projectId !== project.id) throw new HttpError(404, 'Invite not found');
+ // Renewing hands the grant out again, so it is held to the same rules as creating it.
+ if (!(await mayGrantInviteRanks(grant, renewedBy))) {
+ throw new HttpError(
+ 403,
+ 'Only a project owner or a team owner or manager can invite an owner',
+ );
+ }
+ const invite = await renewInvite(grant, renewedBy);
+ const emailQueued = await queueEmail(project, invite);
+ set.status = 201;
+ return { ...invite, emailQueued };
+ },
+ {
+ params: inviteParams,
+ memberAdmin: ['members_invite', 'create'],
+ response: { 201: InviteCreateResponse, ...commonErrors, ...errors(409) },
+ detail: {
+ summary: 'Renew an expired invite',
+ description:
+ 'Replace an expired project invite with a new one for the same email and role: a new ' +
+ 'link, valid again for the instance invite lifetime. Emails it when the instance ' +
+ 'email provider is configured. An invite that has not expired is refused.',
+ ...mcpTool('renew_invite'),
+ },
+ },
+ )
+
.get(
'/projects/:projectKey/invites',
async ({ project }) => {
@@ -252,6 +299,43 @@ export const inviteRoutes = new Elysia({ name: 'invites', detail: { tags: ['Invi
},
)
+ // The team list also shows the invites that name one of its projects, so this renews
+ // those too, queueing their email as their project would. A team invite has no email.
+ .post(
+ '/teams/:teamId/invites/:inviteId/renew',
+ async ({ membership, params, set }) => {
+ const grant = await getInviteGrant(params.inviteId);
+ if (!grant || grant.teamId !== membership.teamId) {
+ throw new HttpError(404, 'Invite not found');
+ }
+ if (!(await mayGrantInviteRanks(grant, membership.userId))) {
+ throw new HttpError(403, 'Only a team owner can invite an owner or a manager');
+ }
+ const invite = await renewInvite(grant, membership.userId);
+ const { projectId } = grant;
+ const projectName = invite.projectName;
+ const emailQueued =
+ projectId != null && projectName != null
+ ? await queueEmail({ id: projectId, name: projectName }, invite)
+ : false;
+ set.status = 201;
+ return { ...invite, emailQueued };
+ },
+ {
+ teamManager: true,
+ params: teamInviteParams,
+ response: { 201: InviteCreateResponse, ...errors(401, 403, 404, 409) },
+ detail: {
+ summary: 'Renew an expired invite of the team',
+ description:
+ 'Replace an expired invite into the team, or into one of its projects, with a new one ' +
+ 'for the same email and rank: a new link, valid again for the instance invite ' +
+ 'lifetime. Queues the email of a project invite when the instance email provider is ' +
+ 'configured; a team invite returns its link to share.',
+ },
+ },
+ )
+
.delete(
'/teams/:teamId/invites/:inviteId',
async ({ membership, params }) => {
diff --git a/apps/api/src/modules/invites/model.ts b/apps/api/src/modules/invites/model.ts
index e4df7e0a..2702166e 100644
--- a/apps/api/src/modules/invites/model.ts
+++ b/apps/api/src/modules/invites/model.ts
@@ -38,6 +38,7 @@ export const InviteRowResponse = t.Object({
roleName: t.Nullable(t.String()),
status: inviteStatus,
createdAt: t.String(),
+ expiresAt: t.Nullable(t.String()),
respondedAt: t.Nullable(t.String()),
invitedByName: t.Nullable(t.String()),
invitedByEmail: t.Nullable(t.String()),
@@ -66,6 +67,7 @@ export const InviteViewResponse = t.Object({
roleName: t.Nullable(t.String()),
status: inviteStatus,
createdAt: t.String(),
+ expired: t.Boolean(),
hasAccount: t.Boolean(),
});
diff --git a/apps/api/src/modules/invites/service.ts b/apps/api/src/modules/invites/service.ts
index 01235483..c0d71c22 100644
--- a/apps/api/src/modules/invites/service.ts
+++ b/apps/api/src/modules/invites/service.ts
@@ -1,5 +1,6 @@
import { db, teamInvite, teamMember, projectMember, teamRole, team, project, user } from '@repo/db';
-import { and, desc, eq, inArray, sql } from 'drizzle-orm';
+import { and, desc, eq, inArray, isNull, lt, sql } from 'drizzle-orm';
+import { getAuthSettings, inviteValidSince } from '@repo/auth';
import { HttpError, iso, pgErrorCode } from '#shared/lib';
import { getProjectAccess, getTeamAccess } from '#shared/access';
import { teamRef } from '#modules/teams/ref';
@@ -45,6 +46,8 @@ export interface InviteRow {
roleName: string | null;
status: InviteStatus;
createdAt: string;
+ // When a pending invite expires; null once resolved or when invites never expire.
+ expiresAt: string | null;
respondedAt: string | null;
invitedByName: string | null;
invitedByEmail: string | null;
@@ -66,6 +69,8 @@ export interface InviteView {
roleName: string | null;
status: InviteStatus;
createdAt: string;
+ // A pending invite past its validity: the screen says so instead of offering to accept.
+ expired: boolean;
// Whether the invited email already has an account. Lets the accept screen
// open in sign-in mode instead of registration. Scoped to the one email bound
// to this (unguessable) token, so it is not a general existence oracle.
@@ -122,7 +127,16 @@ function selectInvites() {
type InviteSelection = Awaited<ReturnType<ReturnType<typeof selectInvites>['execute']>>[number];
-function toRow(r: InviteSelection): InviteRow {
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+function expiresAt(createdAt: Date, status: string, ttlDays: number): string | null {
+ if (status !== 'pending' || ttlDays <= 0) return null;
+ return iso(new Date(createdAt.getTime() + ttlDays * DAY_MS));
+}
+
+const inviteTtlDays = async () => (await getAuthSettings()).inviteTtlDays;
+
+function toRow(r: InviteSelection, ttlDays: number): InviteRow {
return {
id: r.id,
token: r.token,
@@ -135,6 +149,7 @@ function toRow(r: InviteSelection): InviteRow {
roleName: r.roleName,
status: r.status as InviteStatus,
createdAt: iso(r.createdAt),
+ expiresAt: expiresAt(r.createdAt, r.status, ttlDays),
respondedAt: r.respondedAt ? iso(r.respondedAt) : null,
invitedByName: r.invitedByName,
invitedByEmail: r.invitedByEmail,
@@ -213,20 +228,40 @@ export async function createInvite(input: NewInvite): Promise<InviteRow> {
await assertNotAlreadyMember(input, email);
// Project owners bypass roles, so an owner invite never carries a role_id.
const roleId = input.projectRole === 'member' ? input.roleId : null;
+ // An expired invite still holds the one pending slot per address; it gives way to the
+ // new one, so inviting again (or renewing) works without revoking it first.
+ const since = await inviteValidSince();
let row;
try {
- [row] = await db
- .insert(teamInvite)
- .values({
- teamId: input.teamId,
- projectId: input.projectId,
- email,
- teamRole: input.teamRole,
- projectRole: input.projectRole,
- roleId,
- invitedByUserId: input.invitedByUserId,
- })
- .returning({ id: teamInvite.id });
+ [row] = await db.transaction(async (tx) => {
+ if (since) {
+ await tx
+ .delete(teamInvite)
+ .where(
+ and(
+ eq(teamInvite.teamId, input.teamId),
+ input.projectId == null
+ ? isNull(teamInvite.projectId)
+ : eq(teamInvite.projectId, input.projectId),
+ eq(teamInvite.email, email),
+ eq(teamInvite.status, 'pending'),
+ lt(teamInvite.createdAt, since),
+ ),
+ );
+ }
+ return tx
+ .insert(teamInvite)
+ .values({
+ teamId: input.teamId,
+ projectId: input.projectId,
+ email,
+ teamRole: input.teamRole,
+ projectRole: input.projectRole,
+ roleId,
+ invitedByUserId: input.invitedByUserId,
+ })
+ .returning({ id: teamInvite.id });
+ });
} catch (err) {
if (pgErrorCode(err) === '23505') {
throw new HttpError(
@@ -242,14 +277,15 @@ export async function createInvite(input: NewInvite): Promise<InviteRow> {
export async function getInviteById(id: number): Promise<InviteRow | null> {
const rows = await selectInvites().where(eq(teamInvite.id, id));
- return rows[0] ? toRow(rows[0]) : null;
+ return rows[0] ? toRow(rows[0], await inviteTtlDays()) : null;
}
export async function listProjectInvites(projectId: number): Promise<InviteRow[]> {
const rows = await selectInvites()
.where(eq(teamInvite.projectId, projectId))
.orderBy(desc(teamInvite.createdAt));
- return rows.map(toRow);
+ const ttlDays = await inviteTtlDays();
+ return rows.map((r) => toRow(r, ttlDays));
}
// Every invite of the team, including the ones that also name one of its projects:
@@ -258,7 +294,8 @@ export async function listTeamInvites(teamId: number): Promise<InviteRow[]> {
const rows = await selectInvites()
.where(eq(teamInvite.teamId, teamId))
.orderBy(desc(teamInvite.createdAt));
- return rows.map(toRow);
+ const ttlDays = await inviteTtlDays();
+ return rows.map((r) => toRow(r, ttlDays));
}
// Removes an invite of the given project. Returns true when one existed. Used to
@@ -306,6 +343,7 @@ export async function getInviteByToken(token: string): Promise<InviteView | null
const r = rows[0];
if (!r) return null;
const account = await findAccount(r.email);
+ const until = expiresAt(r.createdAt, r.status, await inviteTtlDays());
return {
token: r.token,
teamName: r.teamName,
@@ -319,10 +357,52 @@ export async function getInviteByToken(token: string): Promise<InviteView | null
roleName: r.roleName,
status: r.status as InviteStatus,
createdAt: iso(r.createdAt),
+ expired: until != null && new Date(until) < new Date(),
hasAccount: account != null,
};
}
+// The stored fields an expired invite is renewed from: the same grant, under a new
+// link and a fresh validity.
+export async function getInviteGrant(id: number) {
+ const [row] = await db
+ .select({
+ teamId: teamInvite.teamId,
+ projectId: teamInvite.projectId,
+ email: teamInvite.email,
+ teamRole: teamInvite.teamRole,
+ projectRole: teamInvite.projectRole,
+ roleId: teamInvite.roleId,
+ status: teamInvite.status,
+ createdAt: teamInvite.createdAt,
+ })
+ .from(teamInvite)
+ .where(eq(teamInvite.id, id));
+ return row ?? null;
+}
+
+// A link is never handed out twice: renewing creates a new invite for the same grant,
+// which replaces the expired one (see createInvite). A live invite is not renewed.
+export async function renewInvite(
+ grant: NonNullable<Awaited<ReturnType<typeof getInviteGrant>>>,
+ invitedByUserId: string,
+): Promise<InviteRow> {
+ if (grant.status !== 'pending') throw new HttpError(409, 'This invite is no longer pending');
+ const since = await inviteValidSince();
+ if (!since || grant.createdAt >= since) {
+ throw new HttpError(409, 'This invite has not expired');
+ }
+ return createInvite({
+ teamId: grant.teamId,
+ projectId: grant.projectId,
+ email: grant.email,
+ teamRole: grant.teamRole as InviteTeamRole,
+ projectRole: grant.projectRole as MemberRole | null,
+ roleId: grant.roleId,
+ invitedByUserId,
+ });
+}
+
// The raw invite fields needed to act on it (accept/reject/match email).
export async function getInviteRowByToken(token: string) {
const rows = await db
@@ -336,6 +416,7 @@ export async function getInviteRowByToken(token: string) {
roleId: teamInvite.roleId,
status: teamInvite.status,
invitedByUserId: teamInvite.invitedByUserId,
+ createdAt: teamInvite.createdAt,
})
.from(teamInvite)
.where(eq(teamInvite.token, token));
diff --git a/apps/api/src/modules/teams/service.ts b/apps/api/src/modules/teams/service.ts
index dddfa357..16762f6b 100644
--- a/apps/api/src/modules/teams/service.ts
+++ b/apps/api/src/modules/teams/service.ts
@@ -12,6 +12,7 @@ import {
projectColumn,
projectMember,
team,
+ teamInvite,
teamMember,
teamRole,
user,
@@ -1026,6 +1027,17 @@ async function dropTeamMembership(tx: Transaction, teamId: number, userId: strin
await tx
.delete(projectMember)
.where(and(eq(projectMember.userId, userId), inArray(projectMember.projectId, teamProjects)));
+ // A pending invite this member created outlives them otherwise, keeping the
+ // registration gate open on their behalf after they were removed.
+ await tx
+ .delete(teamInvite)
+ .where(
+ and(
+ eq(teamInvite.teamId, teamId),
+ eq(teamInvite.invitedByUserId, userId),
+ eq(teamInvite.status, 'pending'),
+ ),
+ );
// A column cannot keep assigning issues to someone who no longer belongs to the
// project, the same rule remove_member follows.
await tx
diff --git a/apps/web/messages/ar/auth.json b/apps/web/messages/ar/auth.json
index 8b96181c..e4e3579c 100644
--- a/apps/web/messages/ar/auth.json
+++ b/apps/web/messages/ar/auth.json
@@ -86,6 +86,7 @@
"passwordsDoNotMatch": "كلمتا المرور غير متطابقتين.",
"linkRefused": "العنوان ده ليه حساب بالفعل. سجّل دخولك بكلمة مروره وأكّد العنوان، وبعدين حاول تاني.",
"signupDisabled": "هذه النسخة لا تقبل حسابات جديدة.",
+ "inviteExpired": "انتهت صلاحية الدعوة لهذا العنوان. اطلب ممن دعاك أن يرسل دعوة جديدة.",
"emailNotFound": "مزوّد تسجيل الدخول مرجّعش عنوان بريد. اطلب من المسؤول يراجع scopes المزوّد.",
"tokenExpired": "رابط التأكيد ده انتهت صلاحيته. سجّل دخولك من تحت عشان يوصلك رابط جديد.",
"invalidToken": "رابط التأكيد ده مش صالح. سجّل دخولك من تحت عشان يوصلك رابط جديد.",
diff --git a/apps/web/messages/ar/god.json b/apps/web/messages/ar/god.json
index aa4d79ee..2375db7d 100644
--- a/apps/web/messages/ar/god.json
+++ b/apps/web/messages/ar/god.json
@@ -190,6 +190,9 @@
"saved": "تم حفظ إعدادات المصادقة",
"registration": "التسجيل",
"registrationHint": "مين اللي يقدر يعمل حساب على النسخة دي.",
+ "inviteTtlDays": "مدة صلاحية الدعوات (بالأيام)",
+ "inviteTtlDaysHint": "بعد انقضاء هذه المدة يتوقف رابط الدعوة عن العمل، ومع التسجيل بالدعوة فقط لا يعود يسمح بالتسجيل. مع القيمة 0 لا تنتهي صلاحية الدعوات.",
+ "inviteTtlDaysInvalid": "أدخل عددًا صحيحًا من الأيام من 0 إلى {max}.",
"modes": {
"open": {
"label": "مفتوح",
diff --git a/apps/web/messages/ar/invite.json b/apps/web/messages/ar/invite.json
index 46b0c103..91520ac6 100644
--- a/apps/web/messages/ar/invite.json
+++ b/apps/web/messages/ar/invite.json
@@ -3,14 +3,14 @@
"subtitle": "اقبلها وابدأ الشغل مع الفريق",
"notFoundTitle": "الدعوة غير موجودة",
"notFoundSubtitle": "الرابط ده مش صالح أو مبقاش شغال",
- "notFoundMessage": "رابط الدعوة ده مش صالح أو اتلغى.",
"goToSignIn": "الانتقال إلى تسجيل الدخول",
"closedTitle": "الدعوة مُغلقة",
"closedSubtitle": "هذه الدعوة {status, select, accepted {مقبولة} rejected {مرفوضة} other {مُغلقة}} بالفعل",
+ "expiredTitle": "انتهت صلاحية الدعوة",
+ "expiredSubtitle": "اطلب ممن دعاك أن يرسل دعوة جديدة",
"brandSubtitle": "اتدعيت تشتغل مع الفريق.",
"teamLabel": "الفريق",
"projectLabel": "المشروع",
- "alreadyHandled": "هذه الدعوة {status, select, accepted {مقبولة} rejected {مرفوضة} other {مُغلقة}} بالفعل.",
"goToApp": "الانتقال إلى التطبيق",
"alreadyMember": "أنت عضو في هذا المشروع بالفعل، فلا شيء لقبوله.",
"goToProject": "فتح المشروع",
diff --git a/apps/web/messages/ar/members.json b/apps/web/messages/ar/members.json
index 62cd9a6e..7b7b6a7a 100644
--- a/apps/web/messages/ar/members.json
+++ b/apps/web/messages/ar/members.json
@@ -60,15 +60,22 @@
"resendUnavailable": "البريد الإلكتروني غير مهيأ. انسخ رابط الدعوة وشاركه.",
"resendEmail": "إرسال إيميل",
"resendingEmail": "جارٍ الإضافة…",
+ "renew": "تجديد",
+ "renewing": "جارٍ التجديد…",
+ "renewed": "تم تجديد الدعوة: أُرسل رابط جديد بالبريد الإلكتروني",
+ "renewedNoEmail": "تم تجديد الدعوة. البريد الإلكتروني غير مُعدّ: انسخ الرابط الجديد لمشاركته.",
+ "renewedCopyLink": "تم تجديد الدعوة. انسخ الرابط الجديد لمشاركته.",
"revokeAction": "إلغاء الدعوة",
"removeAction": "إزالة الدعوة",
"invitedBy": "بدعوة من {name} · ",
"createdAt": "أُنشئت {date}",
+ "expiredAt": "انتهت في {date}",
"respondedAt": "{status, select, accepted {قُبلت} rejected {رُفضت} other {حُدّثت}} {date}",
"status": {
"pending": "معلّقة",
"accepted": "مقبولة",
- "rejected": "مرفوضة"
+ "rejected": "مرفوضة",
+ "expired": "منتهية"
},
"revokeTitle": "إلغاء الدعوة إلى {email}",
"revokeConfirm": "إلغاء الدعوة",
diff --git a/apps/web/messages/ar/teams.json b/apps/web/messages/ar/teams.json
index 8feef4fc..450d5fbd 100644
--- a/apps/web/messages/ar/teams.json
+++ b/apps/web/messages/ar/teams.json
@@ -111,7 +111,10 @@
"revokeTitle": "إلغاء دعوة {email}؟",
"revokeConfirm": "إلغاء الدعوة",
"revokeDescription": "الرابط هيبطل يشتغل. تقدر تدعوه تاني بعدين.",
- "pending": "مدعو"
+ "pending": "مدعو",
+ "expiredAt": "انتهت في {date}",
+ "renew": "تجديد",
+ "renewing": "جارٍ التجديد…"
},
"manage": {
"label": "إدارة الفرق",
diff --git a/apps/web/messages/en/auth.json b/apps/web/messages/en/auth.json
index 2ee87df2..d6abb62d 100644
--- a/apps/web/messages/en/auth.json
+++ b/apps/web/messages/en/auth.json
@@ -86,6 +86,7 @@
"passwordsDoNotMatch": "Passwords do not match.",
"linkRefused": "This email address already has an account. Sign in with its password and confirm the address, then try again.",
"signupDisabled": "This instance is not accepting new accounts.",
+ "inviteExpired": "The invitation for this address has expired. Ask whoever invited you to send a new one.",
"emailNotFound": "The sign-in provider did not return an email address. Ask your administrator to check the provider's scopes.",
"tokenExpired": "This confirmation link has expired. Sign in below to get a new one.",
"invalidToken": "This confirmation link is not valid. Sign in below to get a new one.",
diff --git a/apps/web/messages/en/god.json b/apps/web/messages/en/god.json
index f52f8471..a98174f7 100644
--- a/apps/web/messages/en/god.json
+++ b/apps/web/messages/en/god.json
@@ -190,6 +190,9 @@
"saved": "Authentication settings saved",
"registration": "Registration",
"registrationHint": "Who may create an account on this instance.",
+ "inviteTtlDays": "Invite expiry (days)",
+ "inviteTtlDaysHint": "After this many days an invite link stops working and, with invite-only registration, no longer lets its address sign up. 0 keeps invites valid until they are answered.",
+ "inviteTtlDaysInvalid": "Enter a whole number of days from 0 to {max}.",
"modes": {
"open": {
"label": "Open",
diff --git a/apps/web/messages/en/invite.json b/apps/web/messages/en/invite.json
index a5003dc4..e1df3b6b 100644
--- a/apps/web/messages/en/invite.json
+++ b/apps/web/messages/en/invite.json
@@ -3,14 +3,14 @@
"subtitle": "Accept it to start collaborating",
"notFoundTitle": "Invite not found",
"notFoundSubtitle": "This link is invalid or no longer active",
- "notFoundMessage": "This invite link is invalid or has been revoked.",
"goToSignIn": "Go to sign in",
"closedTitle": "Invitation closed",
"closedSubtitle": "This invite was already {status, select, accepted {accepted} rejected {declined} other {closed}}",
+ "expiredTitle": "Invitation expired",
+ "expiredSubtitle": "Ask whoever invited you to send a new one",
"brandSubtitle": "You have been invited to collaborate.",
"teamLabel": "Team",
"projectLabel": "Project",
- "alreadyHandled": "This invite has already been {status, select, accepted {accepted} rejected {declined} other {closed}}.",
"goToApp": "Go to the app",
"alreadyMember": "You are already a member of this project, so there is nothing to accept.",
"goToProject": "Open the project",
diff --git a/apps/web/messages/en/members.json b/apps/web/messages/en/members.json
index 8e962b1a..2b1e4385 100644
--- a/apps/web/messages/en/members.json
+++ b/apps/web/messages/en/members.json
@@ -60,15 +60,22 @@
"resendUnavailable": "Email is not configured. Copy the invitation link to share it.",
"resendEmail": "Send email",
"resendingEmail": "Queueing…",
+ "renew": "Renew",
+ "renewing": "Renewing…",
+ "renewed": "Invite renewed: a new link was emailed",
+ "renewedNoEmail": "Invite renewed. Email is not configured: copy the new link to share it.",
+ "renewedCopyLink": "Invite renewed. Copy the new link to share it.",
"revokeAction": "Revoke invite",
"removeAction": "Remove invite",
"invitedBy": "Invited by {name} · ",
"createdAt": "created {date}",
+ "expiredAt": "expired {date}",
"respondedAt": "{status, select, accepted {accepted} rejected {rejected} other {updated}} {date}",
"status": {
"pending": "Pending",
"accepted": "Accepted",
- "rejected": "Rejected"
+ "rejected": "Rejected",
+ "expired": "Expired"
},
"revokeTitle": "Revoke invite for {email}",
"revokeConfirm": "Revoke invite",
diff --git a/apps/web/messages/en/teams.json b/apps/web/messages/en/teams.json
index 78beede3..5a1bc9fc 100644
--- a/apps/web/messages/en/teams.json
+++ b/apps/web/messages/en/teams.json
@@ -111,7 +111,10 @@
"revokeTitle": "Revoke invite for {email}?",
"revokeConfirm": "Revoke invite",
"revokeDescription": "The link stops working. You can invite them again later.",
- "pending": "Invited"
+ "pending": "Invited",
+ "expiredAt": "expired {date}",
+ "renew": "Renew",
+ "renewing": "Renewing…"
},
"manage": {
"label": "Manage teams",
diff --git a/apps/web/messages/es-ES/auth.json b/apps/web/messages/es-ES/auth.json
index a234f70c..54220854 100644
--- a/apps/web/messages/es-ES/auth.json
+++ b/apps/web/messages/es-ES/auth.json
@@ -86,6 +86,7 @@
"passwordsDoNotMatch": "Las contraseñas no coinciden.",
"linkRefused": "Este correo ya tiene una cuenta. Inicia sesión con su contraseña y confirma la dirección; después inténtalo otra vez.",
"signupDisabled": "Esta instancia no está aceptando cuentas nuevas.",
+ "inviteExpired": "La invitación para esta dirección ha caducado. Pide a quien te invitó que te envíe una nueva.",
"emailNotFound": "El proveedor de inicio de sesión no ha devuelto una dirección de correo. Pide a tu administrador que revise los scopes del proveedor.",
"tokenExpired": "Este enlace de confirmación ha expirado. Inicia sesión abajo para conseguir uno nuevo.",
"invalidToken": "Este enlace de confirmación no es válido. Inicia sesión abajo para conseguir uno nuevo.",
diff --git a/apps/web/messages/es-ES/god.json b/apps/web/messages/es-ES/god.json
index d0fe157f..4c3020d5 100644
--- a/apps/web/messages/es-ES/god.json
+++ b/apps/web/messages/es-ES/god.json
@@ -190,6 +190,9 @@
"saved": "Los ajustes de autenticación se han guardado",
"registration": "Registro",
"registrationHint": "Quién puede crear una cuenta en esta instancia.",
+ "inviteTtlDays": "Caducidad de las invitaciones (días)",
+ "inviteTtlDaysHint": "Pasado este plazo, el enlace de una invitación deja de funcionar y, con el registro por invitación, ya no permite darse de alta. Con 0, las invitaciones no caducan.",
+ "inviteTtlDaysInvalid": "Escribe un número entero de días entre 0 y {max}.",
"modes": {
"open": {
"label": "Abierto",
diff --git a/apps/web/messages/es-ES/invite.json b/apps/web/messages/es-ES/invite.json
index 62db379a..b9e716b0 100644
--- a/apps/web/messages/es-ES/invite.json
+++ b/apps/web/messages/es-ES/invite.json
@@ -3,14 +3,14 @@
"subtitle": "Acéptala para empezar a colaborar",
"notFoundTitle": "No se ha encontrado la invitación",
"notFoundSubtitle": "Este enlace no es válido o ya no está activo",
- "notFoundMessage": "Este enlace de invitación no es válido o ha sido revocado.",
"goToSignIn": "Ir a iniciar sesión",
"closedTitle": "Invitación cerrada",
"closedSubtitle": "Esta invitación ya ha sido {status, select, accepted {aceptada} rejected {rechazada} other {cerrada}}",
+ "expiredTitle": "Invitación caducada",
+ "expiredSubtitle": "Pide a quien te invitó que te envíe una nueva",
"brandSubtitle": "Te han invitado a colaborar.",
"teamLabel": "Equipo",
"projectLabel": "Proyecto",
- "alreadyHandled": "Esta invitación ya ha sido {status, select, accepted {aceptada} rejected {rechazada} other {cerrada}}.",
"goToApp": "Ir a la aplicación",
"alreadyMember": "Ya eres miembro de este proyecto, así que no hay nada que aceptar.",
"goToProject": "Abrir el proyecto",
diff --git a/apps/web/messages/es-ES/members.json b/apps/web/messages/es-ES/members.json
index 71a907d0..b649ccb7 100644
--- a/apps/web/messages/es-ES/members.json
+++ b/apps/web/messages/es-ES/members.json
@@ -60,15 +60,22 @@
"resendUnavailable": "El correo no está configurado. Copia el enlace de invitación para compartirlo.",
"resendEmail": "Enviar correo",
"resendingEmail": "Poniendo en cola…",
+ "renew": "Renovar",
+ "renewing": "Renovando…",
+ "renewed": "Invitación renovada: se ha enviado un enlace nuevo por correo",
+ "renewedNoEmail": "Invitación renovada. El correo no está configurado: copia el enlace nuevo para compartirlo.",
+ "renewedCopyLink": "Invitación renovada. Copia el enlace nuevo para compartirlo.",
"revokeAction": "Revocar invitación",
"removeAction": "Quitar invitación",
"invitedBy": "Invitado por {name} · ",
"createdAt": "creada el {date}",
+ "expiredAt": "caducó el {date}",
"respondedAt": "{status, select, accepted {aceptada} rejected {rechazada} other {actualizada}} el {date}",
"status": {
"pending": "Pendiente",
"accepted": "Aceptada",
- "rejected": "Rechazada"
+ "rejected": "Rechazada",
+ "expired": "Caducada"
},
"revokeTitle": "Revocar la invitación de {email}",
"revokeConfirm": "Revocar invitación",
diff --git a/apps/web/messages/es-ES/teams.json b/apps/web/messages/es-ES/teams.json
index 90f6df65..ad6aba20 100644
--- a/apps/web/messages/es-ES/teams.json
+++ b/apps/web/messages/es-ES/teams.json
@@ -111,7 +111,10 @@
"revokeTitle": "¿Revocar la invitación de {email}?",
"revokeConfirm": "Revocar invitación",
"revokeDescription": "El enlace deja de funcionar. Puedes volver a invitarlo más tarde.",
- "pending": "Invitado"
+ "pending": "Invitado",
+ "expiredAt": "caducó el {date}",
+ "renew": "Renovar",
+ "renewing": "Renovando…"
},
"manage": {
"label": "Gestionar equipos",
diff --git a/apps/web/messages/fr/auth.json b/apps/web/messages/fr/auth.json
index 605b1d4d..8c9fd81b 100644
--- a/apps/web/messages/fr/auth.json
+++ b/apps/web/messages/fr/auth.json
@@ -86,6 +86,7 @@
"passwordsDoNotMatch": "Les mots de passe ne correspondent pas.",
"linkRefused": "Cette adresse e-mail a déjà un compte. Connectez-vous avec son mot de passe, confirmez l'adresse, puis réessayez.",
"signupDisabled": "Cette instance n'accepte pas de nouveaux comptes.",
+ "inviteExpired": "L'invitation pour cette adresse a expiré. Demandez à la personne qui vous a invité de vous en envoyer une nouvelle.",
"emailNotFound": "Le fournisseur de connexion n'a pas renvoyé d'adresse e-mail. Demandez à votre administrateur de vérifier les scopes du fournisseur.",
"tokenExpired": "Ce lien de confirmation a expiré. Connectez-vous ci-dessous pour en recevoir un nouveau.",
"invalidToken": "Ce lien de confirmation n'est pas valide. Connectez-vous ci-dessous pour en recevoir un nouveau.",
diff --git a/apps/web/messages/fr/god.json b/apps/web/messages/fr/god.json
index e12e550e..af552d9e 100644
--- a/apps/web/messages/fr/god.json
+++ b/apps/web/messages/fr/god.json
@@ -190,6 +190,9 @@
"saved": "Paramètres d'authentification enregistrés",
"registration": "Inscription",
"registrationHint": "Qui peut créer un compte sur cette instance.",
+ "inviteTtlDays": "Expiration des invitations (jours)",
+ "inviteTtlDaysHint": "Passé ce délai, le lien d'invitation ne fonctionne plus et, avec l'inscription sur invitation, ne permet plus de créer un compte. Avec 0, les invitations n'expirent pas.",
+ "inviteTtlDaysInvalid": "Saisissez un nombre entier de jours entre 0 et {max}.",
"modes": {
"open": {
"label": "Ouverte",
diff --git a/apps/web/messages/fr/invite.json b/apps/web/messages/fr/invite.json
index d7e820ce..655f54c4 100644
--- a/apps/web/messages/fr/invite.json
+++ b/apps/web/messages/fr/invite.json
@@ -3,14 +3,14 @@
"subtitle": "Acceptez votre invitation pour commencer à collaborer",
"notFoundTitle": "Invitation introuvable",
"notFoundSubtitle": "Ce lien est invalide ou n'est plus actif",
- "notFoundMessage": "Ce lien d'invitation est invalide ou a été révoqué.",
"goToSignIn": "Aller à la connexion",
"closedTitle": "Invitation clôturée",
"closedSubtitle": "Cette invitation a déjà été {status, select, accepted {acceptée} rejected {refusée} other {clôturée}}",
+ "expiredTitle": "Invitation expirée",
+ "expiredSubtitle": "Demandez à la personne qui vous a invité de vous en envoyer une nouvelle",
"brandSubtitle": "Vous avez été invité à collaborer sur un projet.",
"teamLabel": "Équipe",
"projectLabel": "Projet",
- "alreadyHandled": "Cette invitation a déjà été {status, select, accepted {acceptée} rejected {refusée} other {clôturée}}.",
"goToApp": "Aller à l'application",
"alreadyMember": "Vous êtes déjà membre de ce projet, il n'y a rien à accepter.",
"goToProject": "Ouvrir le projet",
diff --git a/apps/web/messages/fr/members.json b/apps/web/messages/fr/members.json
index a012cddc..187fa711 100644
--- a/apps/web/messages/fr/members.json
+++ b/apps/web/messages/fr/members.json
@@ -60,15 +60,22 @@
"resendUnavailable": "L'e-mail n'est pas configuré. Copiez le lien d'invitation pour le partager.",
"resendEmail": "Envoyer l'e-mail",
"resendingEmail": "Mise en file d'attente…",
+ "renew": "Renouveler",
+ "renewing": "Renouvellement…",
+ "renewed": "Invitation renouvelée : un nouveau lien a été envoyé par e-mail",
+ "renewedNoEmail": "Invitation renouvelée. L'e-mail n'est pas configuré : copiez le nouveau lien pour le partager.",
+ "renewedCopyLink": "Invitation renouvelée. Copiez le nouveau lien pour le partager.",
"revokeAction": "Révoquer l'invitation",
"removeAction": "Supprimer l'invitation",
"invitedBy": "Invité par {name} · ",
"createdAt": "créée {date}",
+ "expiredAt": "expirée le {date}",
"respondedAt": "{status, select, accepted {acceptée} rejected {refusée} other {mise à jour}} {date}",
"status": {
"pending": "En attente",
"accepted": "Acceptée",
- "rejected": "Refusée"
+ "rejected": "Refusée",
+ "expired": "Expirée"
},
"revokeTitle": "Révoquer l'invitation de {email}",
"revokeConfirm": "Révoquer l'invitation",
diff --git a/apps/web/messages/fr/teams.json b/apps/web/messages/fr/teams.json
index 7ee1286a..5439374d 100644
--- a/apps/web/messages/fr/teams.json
+++ b/apps/web/messages/fr/teams.json
@@ -111,7 +111,10 @@
"revokeTitle": "Révoquer l'invitation de {email} ?",
"revokeConfirm": "Révoquer l'invitation",
"revokeDescription": "Le lien cesse de fonctionner. Vous pourrez réinviter cette personne plus tard.",
- "pending": "Invité"
+ "pending": "Invité",
+ "expiredAt": "expirée le {date}",
+ "renew": "Renouveler",
+ "renewing": "Renouvellement…"
},
"manage": {
"label": "Gérer les équipes",
diff --git a/apps/web/messages/id/auth.json b/apps/web/messages/id/auth.json
index fe3ed45d..d9d65e0e 100644
--- a/apps/web/messages/id/auth.json
+++ b/apps/web/messages/id/auth.json
@@ -86,6 +86,7 @@
"passwordsDoNotMatch": "Kata sandi tidak cocok.",
"linkRefused": "Alamat email ini sudah memiliki akun. Masuk dengan kata sandinya dan konfirmasikan alamat email tersebut, lalu coba lagi.",
"signupDisabled": "Instance ini tidak menerima akun baru.",
+ "inviteExpired": "Undangan untuk alamat ini sudah kedaluwarsa. Minta orang yang mengundang Anda untuk mengirim undangan baru.",
"emailNotFound": "Penyedia login tidak mengembalikan alamat email. Minta administrator Anda memeriksa cakupan izin penyedia.",
"tokenExpired": "Tautan konfirmasi ini telah kedaluwarsa. Masuk di bawah ini untuk mendapatkan yang baru.",
"invalidToken": "Tautan konfirmasi ini tidak valid. Masuk di bawah ini untuk mendapatkan yang baru.",
diff --git a/apps/web/messages/id/god.json b/apps/web/messages/id/god.json
index ee384829..c4bd2704 100644
--- a/apps/web/messages/id/god.json
+++ b/apps/web/messages/id/god.json
@@ -190,6 +190,9 @@
"saved": "Pengaturan autentikasi disimpan",
"registration": "Pendaftaran",
"registrationHint": "Siapa yang boleh membuat akun di instance ini.",
+ "inviteTtlDays": "Masa berlaku undangan (hari)",
+ "inviteTtlDaysHint": "Setelah jangka waktu ini, tautan undangan tidak berfungsi lagi dan, dengan pendaftaran khusus undangan, tidak bisa lagi dipakai untuk mendaftar. Dengan 0, undangan tidak kedaluwarsa.",
+ "inviteTtlDaysInvalid": "Masukkan jumlah hari berupa bilangan bulat dari 0 sampai {max}.",
"modes": {
"open": {
"label": "Terbuka",
diff --git a/apps/web/messages/id/invite.json b/apps/web/messages/id/invite.json
index 5381aabd..98cbe70b 100644
--- a/apps/web/messages/id/invite.json
+++ b/apps/web/messages/id/invite.json
@@ -3,14 +3,14 @@
"subtitle": "Terima undangan untuk mulai berkolaborasi",
"notFoundTitle": "Undangan tidak ditemukan",
"notFoundSubtitle": "Tautan ini tidak valid atau sudah tidak aktif",
- "notFoundMessage": "Tautan undangan ini tidak valid atau telah dicabut.",
"goToSignIn": "Buka halaman masuk",
"closedTitle": "Undangan ditutup",
"closedSubtitle": "Undangan ini sudah {status, select, accepted {diterima} rejected {ditolak} other {ditutup}}",
+ "expiredTitle": "Undangan kedaluwarsa",
+ "expiredSubtitle": "Minta orang yang mengundang Anda untuk mengirim undangan baru",
"brandSubtitle": "Anda telah diundang untuk berkolaborasi.",
"teamLabel": "Tim",
"projectLabel": "Proyek",
- "alreadyHandled": "Undangan ini sudah {status, select, accepted {diterima} rejected {ditolak} other {ditutup}}.",
"goToApp": "Buka aplikasi",
"alreadyMember": "Anda sudah menjadi anggota proyek ini, jadi tidak ada yang perlu diterima.",
"goToProject": "Buka proyek",
diff --git a/apps/web/messages/id/members.json b/apps/web/messages/id/members.json
index 1edc014e..a26ba96c 100644
--- a/apps/web/messages/id/members.json
+++ b/apps/web/messages/id/members.json
@@ -60,15 +60,22 @@
"resendUnavailable": "Email tidak dikonfigurasi. Salin tautan undangan untuk membagikannya.",
"resendEmail": "Kirim email",
"resendingEmail": "Mengantrekan…",
+ "renew": "Perbarui",
+ "renewing": "Memperbarui…",
+ "renewed": "Undangan diperbarui: tautan baru telah dikirim lewat email",
+ "renewedNoEmail": "Undangan diperbarui. Email belum dikonfigurasi: salin tautan baru untuk membagikannya.",
+ "renewedCopyLink": "Undangan diperbarui. Salin tautan baru untuk membagikannya.",
"revokeAction": "Cabut undangan",
"removeAction": "Hapus undangan",
"invitedBy": "Diundang oleh {name} · ",
"createdAt": "dibuat {date}",
+ "expiredAt": "kedaluwarsa {date}",
"respondedAt": "{status, select, accepted {diterima} rejected {ditolak} other {diperbarui}} {date}",
"status": {
"pending": "Tertunda",
"accepted": "Diterima",
- "rejected": "Ditolak"
+ "rejected": "Ditolak",
+ "expired": "Kedaluwarsa"
},
"revokeTitle": "Cabut undangan untuk {email}",
"revokeConfirm": "Cabut undangan",
diff --git a/apps/web/messages/id/teams.json b/apps/web/messages/id/teams.json
index d1fdeaac..8b884664 100644
--- a/apps/web/messages/id/teams.json
+++ b/apps/web/messages/id/teams.json
@@ -111,7 +111,10 @@
"revokeTitle": "Cabut undangan untuk {email}?",
"revokeConfirm": "Cabut undangan",
"revokeDescription": "Tautan tidak akan berfungsi lagi. Anda dapat mengundangnya lagi nanti.",
- "pending": "Diundang"
+ "pending": "Diundang",
+ "expiredAt": "kedaluwarsa {date}",
+ "renew": "Perbarui",
+ "renewing": "Memperbarui…"
},
"manage": {
"label": "Kelola tim",
diff --git a/apps/web/messages/ko/auth.json b/apps/web/messages/ko/auth.json
index ee0411cd..bca851d0 100644
--- a/apps/web/messages/ko/auth.json
+++ b/apps/web/messages/ko/auth.json
@@ -86,6 +86,7 @@
"passwordsDoNotMatch": "비밀번호가 일치하지 않습니다.",
"linkRefused": "이 이메일 주소로 생성된 계정이 이미 있습니다. 비밀번호로 로그인하여 이메일 주소를 인증한 후 다시 시도해 주세요.",
"signupDisabled": "현재 이 서버에서는 새 계정을 생성할 수 없습니다.",
+ "inviteExpired": "이 주소의 초대가 만료되었습니다. 초대한 사람에게 새 초대를 보내 달라고 요청하세요.",
"emailNotFound": "로그인 공급자에서 이메일 주소를 받지 못했습니다. 관리자에게 공급자의 권한 범위를 확인해 달라고 요청하세요.",
"tokenExpired": "인증 링크가 만료되었습니다. 아래에서 로그인하여 새 링크를 받으세요.",
"invalidToken": "유효하지 않은 인증 링크입니다. 아래에서 로그인하여 새 링크를 받으세요.",
diff --git a/apps/web/messages/ko/god.json b/apps/web/messages/ko/god.json
index 0977b45d..7e3bb498 100644
--- a/apps/web/messages/ko/god.json
+++ b/apps/web/messages/ko/god.json
@@ -190,6 +190,9 @@
"saved": "인증 설정이 저장되었습니다",
"registration": "회원가입",
"registrationHint": "이 인스턴스에서 계정을 생성할 수 있는 사용자를 설정합니다.",
+ "inviteTtlDays": "초대 유효 기간(일)",
+ "inviteTtlDaysHint": "초대 링크는 이 일수가 지나면 더 이상 작동하지 않으며, 초대 전용 회원가입에서는 해당 주소로 가입할 수 없게 됩니다. 0으로 설정하면 초대에 응답할 때까지 유효합니다.",
+ "inviteTtlDaysInvalid": "0에서 {max} 사이의 정수 일수를 입력하세요.",
"modes": {
"open": {
"label": "공개",
diff --git a/apps/web/messages/ko/invite.json b/apps/web/messages/ko/invite.json
index 40deea2d..3b8e1722 100644
--- a/apps/web/messages/ko/invite.json
+++ b/apps/web/messages/ko/invite.json
@@ -3,14 +3,14 @@
"subtitle": "초대를 수락하고 함께 작업을 시작하세요",
"notFoundTitle": "초대를 찾을 수 없습니다",
"notFoundSubtitle": "유효하지 않거나 더 이상 사용할 수 없는 링크입니다",
- "notFoundMessage": "이 초대 링크는 유효하지 않거나 취소되었습니다.",
"goToSignIn": "로그인으로 이동",
"closedTitle": "종료된 초대",
"closedSubtitle": "이 초대는 이미 {status, select, accepted {수락되었습니다} rejected {거절되었습니다} other {종료되었습니다}}",
+ "expiredTitle": "만료된 초대",
+ "expiredSubtitle": "초대한 사람에게 새 초대를 보내 달라고 요청하세요",
"brandSubtitle": "함께 작업할 수 있도록 초대되었습니다.",
"teamLabel": "팀",
"projectLabel": "프로젝트",
- "alreadyHandled": "이 초대는 이미 {status, select, accepted {수락되었습니다} rejected {거절되었습니다} other {종료되었습니다}}.",
"goToApp": "앱으로 이동",
"alreadyMember": "이미 이 프로젝트의 멤버이므로 초대를 수락할 필요가 없습니다.",
"goToProject": "프로젝트 열기",
diff --git a/apps/web/messages/ko/members.json b/apps/web/messages/ko/members.json
index c3e9135e..c5b61d32 100644
--- a/apps/web/messages/ko/members.json
+++ b/apps/web/messages/ko/members.json
@@ -60,15 +60,22 @@
"resendUnavailable": "이메일이 설정되어 있지 않습니다. 초대 링크를 복사하여 공유하세요.",
"resendEmail": "이메일 보내기",
"resendingEmail": "전송 대기열에 추가 중…",
+ "renew": "갱신",
+ "renewing": "갱신 중…",
+ "renewed": "초대가 갱신되었습니다. 새 링크를 이메일로 보냈습니다",
+ "renewedNoEmail": "초대가 갱신되었습니다. 이메일이 설정되어 있지 않습니다. 새 링크를 복사하여 공유하세요.",
+ "renewedCopyLink": "초대가 갱신되었습니다. 새 링크를 복사하여 공유하세요.",
"revokeAction": "초대 취소",
"removeAction": "초대 삭제",
"invitedBy": "{name}이(가) 초대 · ",
"createdAt": "{date}에 생성",
+ "expiredAt": "{date}에 만료",
"respondedAt": "{status, select, accepted {수락} rejected {거절} other {업데이트}} · {date}",
"status": {
"pending": "대기 중",
"accepted": "수락됨",
- "rejected": "거절됨"
+ "rejected": "거절됨",
+ "expired": "만료됨"
},
"revokeTitle": "{email} 초대 취소",
"revokeConfirm": "초대 취소",
diff --git a/apps/web/messages/ko/teams.json b/apps/web/messages/ko/teams.json
index d78c4c0f..02244d04 100644
--- a/apps/web/messages/ko/teams.json
+++ b/apps/web/messages/ko/teams.json
@@ -111,7 +111,10 @@
"revokeTitle": "{email} 초대를 취소하시겠습니까?",
"revokeConfirm": "초대 취소",
"revokeDescription": "초대 링크를 더 이상 사용할 수 없습니다. 나중에 다시 초대할 수 있습니다.",
- "pending": "초대됨"
+ "pending": "초대됨",
+ "expiredAt": "{date}에 만료",
+ "renew": "갱신",
+ "renewing": "갱신 중…"
},
"manage": {
"label": "팀 관리",
@@ -466,12 +469,12 @@
"searchTools": "도구 검색",
"advanced": "고급",
"advancedHint": "샘플링, 단계 제한 및 메모리",
+ "temperature": "Temperature",
"reasoningEffort": "추론 수준",
"reasoningEffortDefault": "공급자 기본값",
"reasoningEffortLow": "낮음",
"reasoningEffortMedium": "중간",
"reasoningEffortHigh": "높음",
- "temperature": "Temperature",
"optional": "선택 사항",
"maxSteps": "최대 단계 수",
"memory": "대화 메모리",
diff --git a/apps/web/messages/pt-BR/auth.json b/apps/web/messages/pt-BR/auth.json
index ccc9f7fe..a9c88c45 100644
--- a/apps/web/messages/pt-BR/auth.json
+++ b/apps/web/messages/pt-BR/auth.json
@@ -86,6 +86,7 @@
"passwordsDoNotMatch": "As senhas não coincidem.",
"linkRefused": "Este endereço de e-mail já tem uma conta. Entre com a senha dela, confirme o endereço e tente de novo.",
"signupDisabled": "Esta instância não está aceitando novas contas.",
+ "inviteExpired": "O convite para este endereço expirou. Peça a quem convidou você que envie um novo.",
"emailNotFound": "O provedor de login não retornou um endereço de e-mail. Peça ao administrador para verificar os scopes do provedor.",
"tokenExpired": "Este link de confirmação expirou. Entre abaixo para obter um novo.",
"invalidToken": "Este link de confirmação não é válido. Entre abaixo para obter um novo.",
diff --git a/apps/web/messages/pt-BR/god.json b/apps/web/messages/pt-BR/god.json
index 613fdd65..cf927068 100644
--- a/apps/web/messages/pt-BR/god.json
+++ b/apps/web/messages/pt-BR/god.json
@@ -190,6 +190,9 @@
"saved": "Configurações de autenticação salvas",
"registration": "Registro",
"registrationHint": "Quem pode criar uma conta nesta instância.",
+ "inviteTtlDays": "Validade dos convites (dias)",
+ "inviteTtlDaysHint": "Depois desse prazo, o link do convite deixa de funcionar e, com o cadastro somente por convite, não permite mais criar a conta. Com 0, os convites não expiram.",
+ "inviteTtlDaysInvalid": "Informe um número inteiro de dias entre 0 e {max}.",
"modes": {
"open": {
"label": "Aberto",
diff --git a/apps/web/messages/pt-BR/invite.json b/apps/web/messages/pt-BR/invite.json
index 9f28d6d7..b3778532 100644
--- a/apps/web/messages/pt-BR/invite.json
+++ b/apps/web/messages/pt-BR/invite.json
@@ -3,14 +3,14 @@
"subtitle": "Aceite-o para começar a colaborar",
"notFoundTitle": "Convite não encontrado",
"notFoundSubtitle": "Este link é inválido ou não está mais ativo",
- "notFoundMessage": "Este link de convite é inválido ou foi revogado.",
"goToSignIn": "Ir para o login",
"closedTitle": "Convite encerrado",
"closedSubtitle": "Este convite já foi {status, select, accepted {aceito} rejected {recusado} other {encerrado}}",
+ "expiredTitle": "Convite expirado",
+ "expiredSubtitle": "Peça a quem convidou você que envie um novo",
"brandSubtitle": "Você foi convidado a colaborar.",
"teamLabel": "Time",
"projectLabel": "Projeto",
- "alreadyHandled": "Este convite já foi {status, select, accepted {aceito} rejected {recusado} other {encerrado}}.",
"goToApp": "Ir para o app",
"alreadyMember": "Você já é membro deste projeto, então não há nada para aceitar.",
"goToProject": "Abrir o projeto",
diff --git a/apps/web/messages/pt-BR/members.json b/apps/web/messages/pt-BR/members.json
index b8831a95..0ae6db50 100644
--- a/apps/web/messages/pt-BR/members.json
+++ b/apps/web/messages/pt-BR/members.json
@@ -60,15 +60,22 @@
"resendUnavailable": "E-mail não está configurado. Copie o link do convite para compartilhá-lo.",
"resendEmail": "Enviar e-mail",
"resendingEmail": "Colocando na fila…",
+ "renew": "Renovar",
+ "renewing": "Renovando…",
+ "renewed": "Convite renovado: um novo link foi enviado por e-mail",
+ "renewedNoEmail": "Convite renovado. O e-mail não está configurado: copie o novo link para compartilhá-lo.",
+ "renewedCopyLink": "Convite renovado. Copie o novo link para compartilhá-lo.",
"revokeAction": "Revogar convite",
"removeAction": "Remover convite",
"invitedBy": "Convidado por {name} · ",
"createdAt": "criado em {date}",
+ "expiredAt": "expirou em {date}",
"respondedAt": "{status, select, accepted {aceito} rejected {recusado} other {atualizado}} em {date}",
"status": {
"pending": "Pendente",
"accepted": "Aceito",
- "rejected": "Recusado"
+ "rejected": "Recusado",
+ "expired": "Expirado"
},
"revokeTitle": "Revogar convite de {email}",
"revokeConfirm": "Revogar convite",
diff --git a/apps/web/messages/pt-BR/teams.json b/apps/web/messages/pt-BR/teams.json
index fcd36d2a..331cbc07 100644
--- a/apps/web/messages/pt-BR/teams.json
+++ b/apps/web/messages/pt-BR/teams.json
@@ -111,7 +111,10 @@
"revokeTitle": "Revogar convite de {email}?",
"revokeConfirm": "Revogar convite",
"revokeDescription": "O link deixa de funcionar. Você pode convidá-lo de novo depois.",
- "pending": "Convidado"
+ "pending": "Convidado",
+ "expiredAt": "expirou em {date}",
+ "renew": "Renovar",
+ "renewing": "Renovando…"
},
"manage": {
"label": "Gerenciar times",
diff --git a/apps/web/messages/ru/auth.json b/apps/web/messages/ru/auth.json
index a3f534cc..64ea6135 100644
--- a/apps/web/messages/ru/auth.json
+++ b/apps/web/messages/ru/auth.json
@@ -86,6 +86,7 @@
"passwordsDoNotMatch": "Пароли не совпадают.",
"linkRefused": "Для этого адреса уже есть аккаунт. Войдите с его паролем, подтвердите адрес и попробуйте снова.",
"signupDisabled": "Этот инстанс не принимает новые аккаунты.",
+ "inviteExpired": "Срок приглашения для этого адреса истёк. Попросите пригласившего вас отправить новое.",
"emailNotFound": "Поставщик входа не вернул адрес почты. Попросите администратора проверить scopes поставщика.",
"tokenExpired": "Срок действия ссылки для подтверждения истёк. Войдите ниже, чтобы получить новую.",
"invalidToken": "Ссылка для подтверждения недействительна. Войдите ниже, чтобы получить новую.",
diff --git a/apps/web/messages/ru/god.json b/apps/web/messages/ru/god.json
index b72b09ed..054e31ee 100644
--- a/apps/web/messages/ru/god.json
+++ b/apps/web/messages/ru/god.json
@@ -190,6 +190,9 @@
"saved": "Настройки аутентификации сохранены",
"registration": "Регистрация",
"registrationHint": "Кто может создать аккаунт в этом инстансе.",
+ "inviteTtlDays": "Срок действия приглашений (дни)",
+ "inviteTtlDaysHint": "По истечении этого срока ссылка приглашения перестаёт работать и при регистрации только по приглашению больше не позволяет зарегистрироваться. При 0 приглашения не истекают.",
+ "inviteTtlDaysInvalid": "Введите целое число дней от 0 до {max}.",
"modes": {
"open": {
"label": "Открытая",
diff --git a/apps/web/messages/ru/invite.json b/apps/web/messages/ru/invite.json
index ec3a538f..135b7cd0 100644
--- a/apps/web/messages/ru/invite.json
+++ b/apps/web/messages/ru/invite.json
@@ -3,14 +3,14 @@
"subtitle": "Примите приглашение, чтобы начать работу",
"notFoundTitle": "Приглашение не найдено",
"notFoundSubtitle": "Эта ссылка недействительна или больше не активна",
- "notFoundMessage": "Эта ссылка-приглашение недействительна или была отозвана.",
"goToSignIn": "Перейти ко входу",
"closedTitle": "Приглашение закрыто",
"closedSubtitle": "Это приглашение уже {status, select, accepted {принято} rejected {отклонено} other {закрыто}}",
+ "expiredTitle": "Срок приглашения истёк",
+ "expiredSubtitle": "Попросите пригласившего вас отправить новое",
"brandSubtitle": "Вас пригласили к совместной работе.",
"teamLabel": "Команда",
"projectLabel": "Проект",
- "alreadyHandled": "Это приглашение уже {status, select, accepted {принято} rejected {отклонено} other {закрыто}}.",
"goToApp": "Перейти в приложение",
"alreadyMember": "Вы уже участник этого проекта — принимать нечего.",
"goToProject": "Открыть проект",
diff --git a/apps/web/messages/ru/members.json b/apps/web/messages/ru/members.json
index f12a26fb..6ee79302 100644
--- a/apps/web/messages/ru/members.json
+++ b/apps/web/messages/ru/members.json
@@ -60,15 +60,22 @@
"resendUnavailable": "Почта не настроена. Скопируйте ссылку на приглашение.",
"resendEmail": "Отправить письмо",
"resendingEmail": "В очередь…",
+ "renew": "Обновить",
+ "renewing": "Обновление…",
+ "renewed": "Приглашение обновлено: новая ссылка отправлена по почте",
+ "renewedNoEmail": "Приглашение обновлено. Почта не настроена: скопируйте новую ссылку, чтобы поделиться ею.",
+ "renewedCopyLink": "Приглашение обновлено. Скопируйте новую ссылку, чтобы поделиться ею.",
"revokeAction": "Отозвать приглашение",
"removeAction": "Убрать приглашение",
"invitedBy": "Пригласил {name} · ",
"createdAt": "создано {date}",
+ "expiredAt": "истекло {date}",
"respondedAt": "{status, select, accepted {принято} rejected {отклонено} other {обновлено}} {date}",
"status": {
"pending": "В ожидании",
"accepted": "Принято",
- "rejected": "Отклонено"
+ "rejected": "Отклонено",
+ "expired": "Истекло"
},
"revokeTitle": "Отозвать приглашение для {email}",
"revokeConfirm": "Отозвать приглашение",
diff --git a/apps/web/messages/ru/teams.json b/apps/web/messages/ru/teams.json
index e797e7f7..3bab9f3e 100644
--- a/apps/web/messages/ru/teams.json
+++ b/apps/web/messages/ru/teams.json
@@ -111,7 +111,10 @@
"revokeTitle": "Отозвать приглашение для {email}?",
"revokeConfirm": "Отозвать приглашение",
"revokeDescription": "Ссылка перестанет работать. Пригласить можно будет заново.",
- "pending": "Приглашён"
+ "pending": "Приглашён",
+ "expiredAt": "истекло {date}",
+ "renew": "Обновить",
+ "renewing": "Обновление…"
},
"manage": {
"label": "Управление командами",
diff --git a/apps/web/messages/uk/auth.json b/apps/web/messages/uk/auth.json
index 226ef769..6eb3853d 100644
--- a/apps/web/messages/uk/auth.json
+++ b/apps/web/messages/uk/auth.json
@@ -86,6 +86,7 @@
"passwordsDoNotMatch": "Паролі не збігаються.",
"linkRefused": "Для цієї адреси вже є акаунт. Увійдіть із його паролем, підтвердіть адресу і спробуйте ще раз.",
"signupDisabled": "Цей інстанс не приймає нових акаунтів.",
+ "inviteExpired": "Термін запрошення для цієї адреси минув. Попросіть того, хто вас запросив, надіслати нове.",
"emailNotFound": "Постачальник входу не повернув адресу пошти. Попросіть адміністратора перевірити scopes постачальника.",
"tokenExpired": "Термін дії посилання для підтвердження минув. Увійдіть нижче, щоб отримати нове.",
"invalidToken": "Посилання для підтвердження недійсне. Увійдіть нижче, щоб отримати нове.",
diff --git a/apps/web/messages/uk/god.json b/apps/web/messages/uk/god.json
index 7f2a9972..594dfa79 100644
--- a/apps/web/messages/uk/god.json
+++ b/apps/web/messages/uk/god.json
@@ -190,6 +190,9 @@
"saved": "Налаштування автентифікації збережено",
"registration": "Реєстрація",
"registrationHint": "Хто може створити акаунт у цьому інстансі.",
+ "inviteTtlDays": "Термін дії запрошень (дні)",
+ "inviteTtlDaysHint": "Після цього терміну посилання запрошення перестає працювати і, з реєстрацією лише за запрошенням, більше не дозволяє зареєструватися. При 0 запрошення не спливають.",
+ "inviteTtlDaysInvalid": "Введіть ціле число днів від 0 до {max}.",
"modes": {
"open": {
"label": "Відкрита",
diff --git a/apps/web/messages/uk/invite.json b/apps/web/messages/uk/invite.json
index 40972dfd..e911e37d 100644
--- a/apps/web/messages/uk/invite.json
+++ b/apps/web/messages/uk/invite.json
@@ -3,14 +3,14 @@
"subtitle": "Прийміть запрошення, щоб почати роботу",
"notFoundTitle": "Запрошення не знайдено",
"notFoundSubtitle": "Це посилання недійсне або більше не активне",
- "notFoundMessage": "Це посилання-запрошення недійсне або було відкликане.",
"goToSignIn": "Перейти до входу",
"closedTitle": "Запрошення закрите",
"closedSubtitle": "Це запрошення вже {status, select, accepted {прийнято} rejected {відхилено} other {закрито}}",
+ "expiredTitle": "Термін запрошення минув",
+ "expiredSubtitle": "Попросіть того, хто вас запросив, надіслати нове",
"brandSubtitle": "Вас запросили до спільної роботи.",
"teamLabel": "Команда",
"projectLabel": "Проєкт",
- "alreadyHandled": "Це запрошення вже {status, select, accepted {прийнято} rejected {відхилено} other {закрито}}.",
"goToApp": "Перейти до застосунку",
"alreadyMember": "Ви вже учасник цього проєкту — приймати нічого.",
"goToProject": "Відкрити проєкт",
diff --git a/apps/web/messages/uk/members.json b/apps/web/messages/uk/members.json
index c152e06f..488471ef 100644
--- a/apps/web/messages/uk/members.json
+++ b/apps/web/messages/uk/members.json
@@ -60,15 +60,22 @@
"resendUnavailable": "Пошту не налаштовано. Скопіюйте посилання на запрошення.",
"resendEmail": "Надіслати лист",
"resendingEmail": "У чергу…",
+ "renew": "Оновити",
+ "renewing": "Оновлення…",
+ "renewed": "Запрошення оновлено: нове посилання надіслано поштою",
+ "renewedNoEmail": "Запрошення оновлено. Пошту не налаштовано: скопіюйте нове посилання, щоб поділитися ним.",
+ "renewedCopyLink": "Запрошення оновлено. Скопіюйте нове посилання, щоб поділитися ним.",
"revokeAction": "Відкликати запрошення",
"removeAction": "Прибрати запрошення",
"invitedBy": "Запросив {name} · ",
"createdAt": "створено {date}",
+ "expiredAt": "термін минув {date}",
"respondedAt": "{status, select, accepted {прийнято} rejected {відхилено} other {оновлено}} {date}",
"status": {
"pending": "В очікуванні",
"accepted": "Прийнято",
- "rejected": "Відхилено"
+ "rejected": "Відхилено",
+ "expired": "Термін минув"
},
"revokeTitle": "Відкликати запрошення для {email}",
"revokeConfirm": "Відкликати запрошення",
diff --git a/apps/web/messages/uk/teams.json b/apps/web/messages/uk/teams.json
index da8fec67..cc117b95 100644
--- a/apps/web/messages/uk/teams.json
+++ b/apps/web/messages/uk/teams.json
@@ -111,7 +111,10 @@
"revokeTitle": "Відкликати запрошення для {email}?",
"revokeConfirm": "Відкликати запрошення",
"revokeDescription": "Посилання перестане працювати. Запросити можна буде знову.",
- "pending": "Запрошено"
+ "pending": "Запрошено",
+ "expiredAt": "термін минув {date}",
+ "renew": "Оновити",
+ "renewing": "Оновлення…"
},
"manage": {
"label": "Керування командами",
diff --git a/apps/web/messages/zh-CN/auth.json b/apps/web/messages/zh-CN/auth.json
index c3522c9a..ec5d4f74 100644
--- a/apps/web/messages/zh-CN/auth.json
+++ b/apps/web/messages/zh-CN/auth.json
@@ -86,6 +86,7 @@
"passwordsDoNotMatch": "两次输入的密码不一致。",
"linkRefused": "此邮箱地址已有账户。请用它的密码登录并验证邮箱,然后重试。",
"signupDisabled": "此实例不接受新账户注册。",
+ "inviteExpired": "此地址的邀请已过期。请让邀请你的人重新发送。",
"emailNotFound": "登录提供方没有返回邮箱地址。请让管理员检查提供方的 scopes。",
"tokenExpired": "此验证链接已过期。请在下方登录以获取新链接。",
"invalidToken": "此验证链接无效。请在下方登录以获取新链接。",
diff --git a/apps/web/messages/zh-CN/god.json b/apps/web/messages/zh-CN/god.json
index fd6a8934..8d7b81c4 100644
--- a/apps/web/messages/zh-CN/god.json
+++ b/apps/web/messages/zh-CN/god.json
@@ -190,6 +190,9 @@
"saved": "身份验证设置已保存",
"registration": "注册",
"registrationHint": "设置哪些人可以创建此实例的账户。",
+ "inviteTtlDays": "邀请有效期(天)",
+ "inviteTtlDaysHint": "超过此期限后,邀请链接将失效;在仅限邀请注册时,也无法再用它注册。设为 0 则邀请永不过期。",
+ "inviteTtlDaysInvalid": "请输入 0 到 {max} 之间的整数天数。",
"modes": {
"open": {
"label": "开放注册",
diff --git a/apps/web/messages/zh-CN/invite.json b/apps/web/messages/zh-CN/invite.json
index 510c4538..3a80381d 100644
--- a/apps/web/messages/zh-CN/invite.json
+++ b/apps/web/messages/zh-CN/invite.json
@@ -3,14 +3,14 @@
"subtitle": "接受邀请即可开始协作",
"notFoundTitle": "找不到邀请",
"notFoundSubtitle": "此链接无效或已失效",
- "notFoundMessage": "此邀请链接无效或已撤销。",
"goToSignIn": "前往登录",
"closedTitle": "邀请已关闭",
"closedSubtitle": "此邀请已{status, select, accepted {接受} rejected {拒绝} other {关闭}}",
+ "expiredTitle": "邀请已过期",
+ "expiredSubtitle": "请让邀请你的人重新发送",
"brandSubtitle": "有人邀请你一起协作。",
"teamLabel": "团队",
"projectLabel": "项目",
- "alreadyHandled": "此邀请已{status, select, accepted {接受} rejected {拒绝} other {关闭}}。",
"goToApp": "打开应用",
"alreadyMember": "你已经是该项目的成员,无需接受。",
"goToProject": "打开项目",
diff --git a/apps/web/messages/zh-CN/members.json b/apps/web/messages/zh-CN/members.json
index 6c3e56d8..022e2ef6 100644
--- a/apps/web/messages/zh-CN/members.json
+++ b/apps/web/messages/zh-CN/members.json
@@ -60,15 +60,22 @@
"resendUnavailable": "邮件尚未配置。请复制邀请链接进行分享。",
"resendEmail": "发送邮件",
"resendingEmail": "正在加入队列…",
+ "renew": "续期",
+ "renewing": "正在续期…",
+ "renewed": "邀请已续期:新链接已通过邮件发送",
+ "renewedNoEmail": "邀请已续期。尚未配置邮件:请复制新链接进行分享。",
+ "renewedCopyLink": "邀请已续期。请复制新链接进行分享。",
"revokeAction": "撤销邀请",
"removeAction": "移除邀请",
"invitedBy": "由 {name} 邀请 · ",
"createdAt": "创建于 {date}",
+ "expiredAt": "已于 {date} 过期",
"respondedAt": "{status, select, accepted {已接受} rejected {已拒绝} other {已更新}} {date}",
"status": {
"pending": "待处理",
"accepted": "已接受",
- "rejected": "已拒绝"
+ "rejected": "已拒绝",
+ "expired": "已过期"
},
"revokeTitle": "撤销发送至 {email} 的邀请",
"revokeConfirm": "撤销邀请",
diff --git a/apps/web/messages/zh-CN/teams.json b/apps/web/messages/zh-CN/teams.json
index ab9f3dc9..08ef0e60 100644
--- a/apps/web/messages/zh-CN/teams.json
+++ b/apps/web/messages/zh-CN/teams.json
@@ -111,7 +111,10 @@
"revokeTitle": "撤销 {email} 的邀请?",
"revokeConfirm": "撤销邀请",
"revokeDescription": "链接将失效。之后可以重新邀请。",
- "pending": "已邀请"
+ "pending": "已邀请",
+ "expiredAt": "已于 {date} 过期",
+ "renew": "续期",
+ "renewing": "正在续期…"
},
"manage": {
"label": "管理团队",
diff --git a/apps/web/src/features/auth/hooks/useRedirectError.ts b/apps/web/src/features/auth/hooks/useRedirectError.ts
index 46a11e93..b34210c2 100644
--- a/apps/web/src/features/auth/hooks/useRedirectError.ts
+++ b/apps/web/src/features/auth/hooks/useRedirectError.ts
@@ -16,6 +16,7 @@ const MESSAGE_KEYS = {
unable_to_link_account: 'linkRefused',
account_not_linked: 'linkRefused',
signup_disabled: 'signupDisabled',
+ INVITE_EXPIRED: 'inviteExpired',
OIDC_DISABLED: 'ssoDisabled',
PASSWORD_AUTH_DISABLED: 'passwordDisabled',
ACCOUNT_DEACTIVATED: 'accountDeactivated',
diff --git a/apps/web/src/features/auth/services/auth.service.ts b/apps/web/src/features/auth/services/auth.service.ts
index 08535741..974593cd 100644
--- a/apps/web/src/features/auth/services/auth.service.ts
+++ b/apps/web/src/features/auth/services/auth.service.ts
@@ -90,7 +90,13 @@ export async function setNewPassword(input: {
// Sends a one-time sign-in link. Rejected by the API when the instance has magic
// links turned off.
export async function sendMagicLink(email: string): Promise<void> {
- const result = await signIn.magicLink({ email, callbackURL: appUrl('/') });
+ // A refused sign-up comes back to errorCallbackURL; on / it would be lost in the
+ // redirect to the sign-in page.
+ const result = await signIn.magicLink({
+ email,
+ callbackURL: appUrl('/'),
+ errorCallbackURL: appUrl('/login'),
+ });
if (result.error) throw new Error(result.error.message ?? '');
}
diff --git a/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx b/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx
index 8ea14140..f0b14c37 100644
--- a/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx
+++ b/apps/web/src/features/god/components/authentication/GodAuthenticationForm.tsx
@@ -7,10 +7,11 @@ import SettingsCard from '@/components/common/page/SettingsCard';
import SettingsSection from '@/components/common/page/SettingsSection';
import SettingsRow from '@/components/common/page/SettingsRow';
import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import GodSectionPage from '../GodSectionPage';
import RegistrationModePicker from './RegistrationModePicker';
-import { useGodPolicyForm } from '../../hooks/useGodPolicyForm';
+import { MAX_INVITE_TTL_DAYS, useGodPolicyForm } from '../../hooks/useGodPolicyForm';
// The registration policy and the sign-in options. The provider credentials live
// under Integrations (Email provider, Auth provider).
@@ -43,7 +44,11 @@ export default function GodAuthenticationForm({
<GodSectionPage
slug="authentication"
actions={
- <Button size="sm" onClick={() => void save()} disabled={!policy.dirty || policy.saving}>
+ <Button
+ size="sm"
+ onClick={() => void save()}
+ disabled={!policy.dirty || !policy.inviteTtlDaysValid || policy.saving}
+ >
{policy.saving ? tCommon('saving') : tCommon('save')}
</Button>
}
@@ -56,6 +61,30 @@ export default function GodAuthenticationForm({
disabled={policy.saving}
onChange={policy.setRegistration}
/>
+ <SettingsRow
+ title={t('inviteTtlDays')}
+ description={t('inviteTtlDaysHint')}
+ note={
+ policy.inviteTtlDaysValid
+ ? undefined
+ : t('inviteTtlDaysInvalid', { max: MAX_INVITE_TTL_DAYS })
+ }
+ control={
+ <Input
+ type="number"
+ min={0}
+ max={MAX_INVITE_TTL_DAYS}
+ step={1}
+ inputMode="numeric"
+ className="w-24"
+ aria-label={t('inviteTtlDays')}
+ aria-invalid={!policy.inviteTtlDaysValid}
+ value={policy.inviteTtlDays}
+ disabled={policy.saving}
+ onChange={(e) => policy.setInviteTtlDays(e.target.value)}
+ />
+ }
+ />
</SettingsCard>
</SettingsSection>
diff --git a/apps/web/src/features/god/hooks/useGodPolicyForm.test.tsx b/apps/web/src/features/god/hooks/useGodPolicyForm.test.tsx
new file mode 100644
index 00000000..7e2ddf66
--- /dev/null
+++ b/apps/web/src/features/god/hooks/useGodPolicyForm.test.tsx
@@ -0,0 +1,131 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { JSDOM } from 'jsdom';
+import type { InstanceAuthSettings, InstanceAuthSettingsPatch } from '@/lib/api/endpoints/god';
+
+// The invite lifetime is typed into the form as text: only a whole number of days, 0 or
+// more, can be saved, and it is saved with the rest of the page.
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'Node',
+ 'Element',
+ 'HTMLElement',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+
+let dom: JSDOM;
+let root: Root;
+let originals: Map<string, PropertyDescriptor | undefined>;
+let saved: InstanceAuthSettingsPatch[] = [];
+let form: import('./useGodPolicyForm').GodPolicyForm;
+let queryClient: QueryClient;
+let originalFetch: typeof fetch;
+
+const settings = {
+ registration: 'invite',
+ requireEmailVerification: false,
+ magicLink: false,
+ emailPassword: false,
+ trustProviderEmails: false,
+ personalWorkspaces: true,
+ inviteTtlDays: 7,
+ hasEmailProvider: true,
+ hasSsoProvider: true,
+} satisfies InstanceAuthSettings;
+
+async function render() {
+ const { useGodPolicyForm } = await import('./useGodPolicyForm');
+ function Probe() {
+ form = useGodPolicyForm(settings);
+ return null;
+ }
+ await act(async () =>
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <Probe />
+ </QueryClientProvider>,
+ ),
+ );
+}
+
+beforeEach(async () => {
+ originals = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'https://example.test/' });
+ for (const name of replacedGlobals) {
+ if (name in dom.window) {
+ Object.defineProperty(globalThis, name, {
+ configurable: true,
+ value: dom.window[name as keyof typeof dom.window],
+ });
+ }
+ }
+ Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
+ configurable: true,
+ value: true,
+ });
+ dom.window.__ITSAPLAN_ENV__ = { apiUrl: 'http://api.test', privacyUrl: '', termsUrl: '' };
+ saved = [];
+ originalFetch = globalThis.fetch;
+ globalThis.fetch = (async (input, init) => {
+ const url = new URL(String(input));
+ if (url.pathname === '/god/auth-settings' && init?.method === 'PUT') {
+ const patch = JSON.parse(String(init.body)) as InstanceAuthSettingsPatch;
+ saved.push(patch);
+ return Response.json({ ...settings, ...patch });
+ }
+ return Response.json(settings);
+ }) as typeof fetch;
+ queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.querySelector('#root')!);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ // React Query notifies on a timer; let it run while this window still exists.
+ await act(() => new Promise<void>((resolve) => setTimeout(resolve, 5)));
+ queryClient.clear();
+ globalThis.fetch = originalFetch;
+ dom.window.close();
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+describe('useGodPolicyForm invite lifetime', () => {
+ it('starts clean on the stored value', async () => {
+ await render();
+
+ assert.equal(form.inviteTtlDays, '7');
+ assert.equal(form.inviteTtlDaysValid, true);
+ assert.equal(form.dirty, false);
+ });
+
+ it('refuses a value that is not a whole number of days', async () => {
+ await render();
+
+ for (const value of ['2.5', '-1', '', 'abc', '3651']) {
+ await act(async () => form.setInviteTtlDays(value));
+ assert.equal(form.inviteTtlDaysValid, false, value);
+ }
+ });
+
+ it('saves a new lifetime as a number along with the rest of the page', async () => {
+ await render();
+
+ await act(async () => form.setInviteTtlDays('3'));
+ assert.equal(form.dirty, true);
+ await act(async () => form.save());
+
+ assert.equal(saved.length, 1);
+ assert.equal(saved[0].inviteTtlDays, 3);
+ });
+});
diff --git a/apps/web/src/features/god/hooks/useGodPolicyForm.ts b/apps/web/src/features/god/hooks/useGodPolicyForm.ts
index e814892a..d3eae913 100644
--- a/apps/web/src/features/god/hooks/useGodPolicyForm.ts
+++ b/apps/web/src/features/god/hooks/useGodPolicyForm.ts
@@ -4,6 +4,9 @@ import { useState } from 'react';
import type { InstanceAuthSettings, RegistrationMode } from '@/lib/api/endpoints/god';
import { useUpdateInstanceAuthSettings } from '../services/god.service';
+// The api's own limit on the invite lifetime.
+export const MAX_INVITE_TTL_DAYS = 3650;
+
export interface GodPolicyForm {
registration: RegistrationMode;
setRegistration: (v: RegistrationMode) => void;
@@ -15,6 +18,10 @@ export interface GodPolicyForm {
setEmailPassword: (v: boolean) => void;
trustProviderEmails: boolean;
setTrustProviderEmails: (v: boolean) => void;
+ // Kept as typed, so a half-written number can sit in the field without saving.
+ inviteTtlDays: string;
+ setInviteTtlDays: (v: string) => void;
+ inviteTtlDaysValid: boolean;
dirty: boolean;
saving: boolean;
save: () => Promise<void>;
@@ -32,21 +39,28 @@ export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyForm
const [magicLink, setMagicLink] = useState(settings.magicLink);
const [emailPassword, setEmailPassword] = useState(settings.emailPassword);
const [trustProviderEmails, setTrustProviderEmails] = useState(settings.trustProviderEmails);
+ const [inviteTtlDays, setInviteTtlDays] = useState(String(settings.inviteTtlDays));
+ const inviteTtlDaysValid =
+ /^\d+$/.test(inviteTtlDays.trim()) && Number(inviteTtlDays) <= MAX_INVITE_TTL_DAYS;
const dirty =
registration !== settings.registration ||
requireEmailVerification !== settings.requireEmailVerification ||
magicLink !== settings.magicLink ||
emailPassword !== settings.emailPassword ||
- trustProviderEmails !== settings.trustProviderEmails;
+ trustProviderEmails !== settings.trustProviderEmails ||
+ inviteTtlDays.trim() !== String(settings.inviteTtlDays);
async function save() {
+ // An empty field would be read as 0, which turns expiry off.
+ if (!inviteTtlDaysValid) return;
await update.mutateAsync({
registration,
requireEmailVerification,
magicLink,
emailPassword,
trustProviderEmails,
+ inviteTtlDays: Number(inviteTtlDays.trim()),
});
}
@@ -61,6 +75,9 @@ export function useGodPolicyForm(settings: InstanceAuthSettings): GodPolicyForm
setEmailPassword,
trustProviderEmails,
setTrustProviderEmails,
+ inviteTtlDays,
+ setInviteTtlDays,
+ inviteTtlDaysValid,
dirty,
saving: update.isPending,
save,
diff --git a/apps/web/src/features/invite/InviteAcceptPage.tsx b/apps/web/src/features/invite/InviteAcceptPage.tsx
index 379717c9..55997ed9 100644
--- a/apps/web/src/features/invite/InviteAcceptPage.tsx
+++ b/apps/web/src/features/invite/InviteAcceptPage.tsx
@@ -29,7 +29,7 @@ export default function InviteAcceptPage({ token }: { token: string }) {
title = t('notFoundTitle');
subtitle = t('notFoundSubtitle');
body = (
- <InviteNotice message={t('notFoundMessage')}>
+ <InviteNotice>
<Button asChild variant="outline">
<Link href="/login">{t('goToSignIn')}</Link>
</Button>
@@ -39,6 +39,9 @@ export default function InviteAcceptPage({ token }: { token: string }) {
if (invite.status !== 'pending') {
title = t('closedTitle');
subtitle = t('closedSubtitle', { status: invite.status });
+ } else if (invite.expired) {
+ title = t('expiredTitle');
+ subtitle = t('expiredSubtitle');
}
body = (
<div className="flex flex-col gap-6">
diff --git a/apps/web/src/features/invite/components/InviteNotice.tsx b/apps/web/src/features/invite/components/InviteNotice.tsx
index f56e4f2c..85109a0e 100644
--- a/apps/web/src/features/invite/components/InviteNotice.tsx
+++ b/apps/web/src/features/invite/components/InviteNotice.tsx
@@ -1,17 +1,18 @@
import type { ReactNode } from 'react';
-// A short status message on the invite screen (invite not found, no longer
-// pending, wrong account), with an optional action area below it.
+// A short status message on the invite screen (wrong account), with an optional
+// action area below it. Where the heading already names the state (not found,
+// closed, expired) it carries no message, so the screen does not say it twice.
export default function InviteNotice({
message,
children,
}: {
- message: ReactNode;
+ message?: ReactNode;
children?: ReactNode;
}) {
return (
<div className="flex flex-col items-center gap-4 text-center">
- <p className="text-sm text-muted-foreground">{message}</p>
+ {message && <p className="text-sm text-muted-foreground">{message}</p>}
{children}
</div>
);
diff --git a/apps/web/src/features/invite/components/InviteStep.tsx b/apps/web/src/features/invite/components/InviteStep.tsx
index 68922b69..4fc6ab1e 100644
--- a/apps/web/src/features/invite/components/InviteStep.tsx
+++ b/apps/web/src/features/invite/components/InviteStep.tsx
@@ -25,9 +25,9 @@ export default function InviteStep({ token, invite }: { token: string; invite: I
router.refresh();
}
- if (invite.status !== 'pending') {
+ if (invite.status !== 'pending' || invite.expired) {
return (
- <InviteNotice message={t('alreadyHandled', { status: invite.status })}>
+ <InviteNotice>
<Button asChild variant="outline">
<Link href="/">{t('goToApp')}</Link>
</Button>
diff --git a/apps/web/src/features/members/components/invites/InviteRow.test.tsx b/apps/web/src/features/members/components/invites/InviteRow.test.tsx
new file mode 100644
index 00000000..57d02c46
--- /dev/null
+++ b/apps/web/src/features/members/components/invites/InviteRow.test.tsx
@@ -0,0 +1,119 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import type { InviteRow as Invite } from '@/lib/api/endpoints/invites';
+import members from '../../../../../messages/en/members.json';
+import common from '../../../../../messages/en/common.json';
+
+// An expired invite has a dead link: the row offers a renewal instead of copying or
+// mailing it.
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'Node',
+ 'Element',
+ 'HTMLElement',
+ 'HTMLButtonElement',
+ 'Event',
+ 'MouseEvent',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+
+let dom: JSDOM;
+let root: Root;
+let originals: Map<string, PropertyDescriptor | undefined>;
+let renewed: number[] = [];
+
+const DAY = 24 * 60 * 60 * 1000;
+const invite = (expiresInDays: number): Invite => ({
+ id: 7,
+ token: 'tok',
+ email: '[email protected]',
+ teamRole: 'member',
+ projectKey: 'MKT',
+ projectName: 'Marketing',
+ role: 'member',
+ roleId: null,
+ roleName: null,
+ status: 'pending',
+ createdAt: new Date(Date.now() - 8 * DAY).toISOString(),
+ expiresAt: new Date(Date.now() + expiresInDays * DAY).toISOString(),
+ respondedAt: null,
+ invitedByName: null,
+ invitedByEmail: null,
+});
+
+async function render(row: Invite) {
+ const { default: InviteRow } = await import('./InviteRow');
+ await act(async () =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={{ members, common }} timeZone="UTC">
+ <InviteRow
+ invite={row}
+ onResend={() => {}}
+ onRenew={(i) => renewed.push(i.id)}
+ resending={false}
+ renewing={false}
+ />
+ </NextIntlClientProvider>,
+ ),
+ );
+}
+
+const button = (text: string) =>
+ [...document.querySelectorAll('button')].find((b) => b.textContent?.includes(text));
+
+beforeEach(async () => {
+ originals = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'https://example.test/' });
+ for (const name of replacedGlobals) {
+ if (name in dom.window) {
+ Object.defineProperty(globalThis, name, {
+ configurable: true,
+ value: dom.window[name as keyof typeof dom.window],
+ });
+ }
+ }
+ Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
+ configurable: true,
+ value: true,
+ });
+ renewed = [];
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.querySelector('#root')!);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ dom.window.close();
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+describe('InviteRow', () => {
+ it('offers to renew an expired invite, not to copy or mail its link', async () => {
+ await render(invite(-1));
+
+ assert.ok(document.body.textContent?.includes(members.invites.status.expired));
+ assert.equal(button(members.invites.copyLink), undefined);
+ assert.equal(button(members.invites.resendEmail), undefined);
+ await act(async () => button(members.invites.renew)!.click());
+ assert.deepEqual(renewed, [7]);
+ });
+
+ it('keeps the link and email actions for an invite still valid', async () => {
+ await render(invite(3));
+
+ assert.ok(button(members.invites.copyLink));
+ assert.ok(button(members.invites.resendEmail));
+ assert.equal(button(members.invites.renew), undefined);
+ });
+});
diff --git a/apps/web/src/features/members/components/invites/InviteRow.tsx b/apps/web/src/features/members/components/invites/InviteRow.tsx
index 541e3d49..5f10ed75 100644
--- a/apps/web/src/features/members/components/invites/InviteRow.tsx
+++ b/apps/web/src/features/members/components/invites/InviteRow.tsx
@@ -1,9 +1,10 @@
'use client';
import { useState } from 'react';
-import { Check, Copy, Mail, X } from 'lucide-react';
+import { Check, Copy, Mail, RefreshCw, X } from 'lucide-react';
import { useTranslations } from 'next-intl';
import type { InviteRow as Invite } from '@/lib/api/endpoints/invites';
+import { isInviteExpired } from '@/utils/invites';
import { inviteLink } from '@/utils/paths';
import { formatShortDate } from '@/utils/dates';
import { Badge } from '@/components/ui/badge';
@@ -14,30 +15,42 @@ const STATUS_VARIANT = { pending: 'secondary', accepted: 'default', rejected: 'o
// One invite row: the invited email and role, its status, who sent it, and — for
// a pending invite — email, copy-link, and revoke actions. Copy reads the link from
-// the current web origin so it works in any deployment.
+// the current web origin so it works in any deployment. An expired invite offers no
+// link to copy or mail, only a renewal, which sends a new one.
export default function InviteRow({
invite,
onResend,
+ onRenew,
onRevoke,
resending,
+ renewing,
}: {
invite: Invite;
onResend?: (invite: Invite) => void;
+ onRenew?: (invite: Invite) => void;
onRevoke?: (invite: Invite) => void;
resending: boolean;
+ renewing: boolean;
}) {
const t = useTranslations('members.invites');
const tCommon = useTranslations('common');
const [copied, setCopied] = useState(false);
- const pending = invite.status === 'pending';
+ const expired = invite.status === 'pending' && isInviteExpired(invite);
+ const pending = invite.status === 'pending' && !expired;
- // When the invite last changed: its creation for a pending one, otherwise the
- // moment it was accepted or rejected.
- const timestamp = pending
- ? t('createdAt', { date: formatShortDate(invite.createdAt) })
- : invite.respondedAt
- ? t('respondedAt', { status: invite.status, date: formatShortDate(invite.respondedAt) })
- : formatShortDate(invite.createdAt);
+ let timestamp: string;
+ if (expired) {
+ timestamp = t('expiredAt', { date: formatShortDate(invite.expiresAt!) });
+ } else if (pending) {
+ timestamp = t('createdAt', { date: formatShortDate(invite.createdAt) });
+ } else if (invite.respondedAt) {
+ timestamp = t('respondedAt', {
+ status: invite.status,
+ date: formatShortDate(invite.respondedAt),
+ });
+ } else {
+ timestamp = formatShortDate(invite.createdAt);
+ }
async function copy() {
const origin = typeof window === 'undefined' ? '' : window.location.origin;
@@ -76,10 +89,10 @@ export default function InviteRow({
{roleLabel}
</Badge>
<Badge
- variant={STATUS_VARIANT[invite.status]}
+ variant={expired ? 'destructive' : STATUS_VARIANT[invite.status]}
className="px-1.5 py-0 text-[10px] font-normal"
>
- {t(`status.${invite.status}`)}
+ {expired ? t('status.expired') : t(`status.${invite.status}`)}
</Badge>
</ItemTitle>
<span className="text-xs text-muted-foreground">
@@ -88,6 +101,18 @@ export default function InviteRow({
</span>
</ItemContent>
<ItemActions className="ms-auto w-full justify-end sm:w-auto">
+ {expired && onRenew && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 gap-1.5 text-xs text-muted-foreground hover:text-foreground"
+ disabled={renewing}
+ onClick={() => onRenew(invite)}
+ >
+ <RefreshCw className="size-3.5" />
+ {renewing ? t('renewing') : t('renew')}
+ </Button>
+ )}
{pending && onResend && (
<Button
variant="ghost"
@@ -116,7 +141,7 @@ export default function InviteRow({
variant="ghost"
size="icon"
className="size-7 text-muted-foreground hover:text-destructive"
- title={pending ? t('revokeAction') : t('removeAction')}
+ title={pending || expired ? t('revokeAction') : t('removeAction')}
onClick={revoke}
>
<X className="size-4" />
diff --git a/apps/web/src/features/members/components/invites/InvitesManager.tsx b/apps/web/src/features/members/components/invites/InvitesManager.tsx
index 318f4205..28b744c8 100644
--- a/apps/web/src/features/members/components/invites/InvitesManager.tsx
+++ b/apps/web/src/features/members/components/invites/InvitesManager.tsx
@@ -5,8 +5,15 @@ import { useTranslations } from 'next-intl';
import type { InviteRow as Invite } from '@/lib/api/endpoints/invites';
import ConfirmDialog from '@/components/common/overlay/ConfirmDialog';
import { ItemGroup } from '@/components/ui/item';
-import { useDeleteInvite, useInvitesQuery, useSendInviteEmail } from '@/services/members.service';
+import {
+ useDeleteInvite,
+ useInvitesQuery,
+ useRenewInvite,
+ useSendInviteEmail,
+} from '@/services/members.service';
import { usePermissions } from '@/hooks/usePermissions';
+import { useShell } from '@/context/shellContext';
+import { mayRenewInvite } from '@/utils/invites';
import InviteRow from './InviteRow';
// Invite panel shown above the members list: the invites that have not been accepted
@@ -15,13 +22,15 @@ import InviteRow from './InviteRow';
// standing of an owner or manager of the team — and renders nothing without it.
export default function InvitesManager({ projectKey }: { projectKey: string }) {
const t = useTranslations('members.invites');
- const { can, isAdmin } = usePermissions();
+ const { can, isAdmin, isOwner } = usePermissions();
+ const viewerTeamRole = useShell().project?.viewer?.teamRole ?? null;
const canRead = can('members_invite', 'read') || isAdmin;
const canCreate = can('members_invite', 'create') || isAdmin;
const canDelete = can('members_invite', 'delete') || isAdmin;
const invitesQuery = useInvitesQuery(projectKey, canRead);
const deleteInvite = useDeleteInvite(projectKey);
const sendEmail = useSendInviteEmail(projectKey);
+ const renew = useRenewInvite(projectKey);
const [target, setTarget] = useState<Invite | null>(null);
function resendInvite(invite: Invite) {
@@ -45,6 +54,13 @@ export default function InvitesManager({ projectKey }: { projectKey: string }) {
key={invite.id}
invite={invite}
onResend={canCreate ? resendInvite : undefined}
+ onRenew={
+ canCreate &&
+ mayRenewInvite(invite, { teamRole: viewerTeamRole, ownsProject: isOwner })
+ ? (expired) => renew.mutate(expired.id)
+ : undefined
+ }
+ renewing={renew.isPending && renew.variables === invite.id}
onRevoke={canDelete ? setTarget : undefined}
resending={sendEmail.isPending && sendEmail.variables === invite.id}
/>
diff --git a/apps/web/src/features/teams/components/members/TeamInviteRow.test.tsx b/apps/web/src/features/teams/components/members/TeamInviteRow.test.tsx
new file mode 100644
index 00000000..c56c895e
--- /dev/null
+++ b/apps/web/src/features/teams/components/members/TeamInviteRow.test.tsx
@@ -0,0 +1,124 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import type { InviteRow } from '@/lib/api/endpoints/invites';
+import teams from '../../../../../messages/en/teams.json';
+import common from '../../../../../messages/en/common.json';
+
+// A team's expired invite says so in place of "Invited" and offers a renewal instead of
+// its dead link; a valid one is mailed again or its link copied.
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'Node',
+ 'Element',
+ 'HTMLElement',
+ 'HTMLButtonElement',
+ 'Event',
+ 'MouseEvent',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+
+let dom: JSDOM;
+let root: Root;
+let originals: Map<string, PropertyDescriptor | undefined>;
+let renewed: number[] = [];
+
+const DAY = 24 * 60 * 60 * 1000;
+const invite = (expiresInDays: number): InviteRow => ({
+ id: 9,
+ token: 'tok',
+ email: '[email protected]',
+ teamRole: 'member',
+ projectKey: null,
+ projectName: null,
+ role: null,
+ roleId: null,
+ roleName: null,
+ status: 'pending',
+ createdAt: new Date(Date.now() - 8 * DAY).toISOString(),
+ expiresAt: new Date(Date.now() + expiresInDays * DAY).toISOString(),
+ respondedAt: null,
+ invitedByName: null,
+ invitedByEmail: null,
+});
+
+async function render(row: InviteRow, { mayRenew = true } = {}) {
+ const { default: TeamInviteRow } = await import('./TeamInviteRow');
+ await act(async () =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={{ teams, common }} timeZone="UTC">
+ <TeamInviteRow
+ invite={row}
+ onRevoke={() => {}}
+ onRenew={mayRenew ? (i) => renewed.push(i.id) : undefined}
+ renewing={false}
+ />
+ </NextIntlClientProvider>,
+ ),
+ );
+}
+
+const button = (text: string) =>
+ [...document.querySelectorAll('button')].find((b) => b.textContent?.includes(text));
+
+beforeEach(async () => {
+ originals = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'https://example.test/' });
+ for (const name of replacedGlobals) {
+ if (name in dom.window) {
+ Object.defineProperty(globalThis, name, {
+ configurable: true,
+ value: dom.window[name as keyof typeof dom.window],
+ });
+ }
+ }
+ Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
+ configurable: true,
+ value: true,
+ });
+ renewed = [];
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.querySelector('#root')!);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ dom.window.close();
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+describe('TeamInviteRow', () => {
+ it('marks an expired invite and renews it instead of copying its link', async () => {
+ await render(invite(-1));
+
+ assert.ok(document.body.textContent?.includes(teams.invite.expiredAt.split(' ')[0]));
+ assert.equal(button(teams.invite.copyLink), undefined);
+ await act(async () => button(teams.invite.renew)!.click());
+ assert.deepEqual(renewed, [9]);
+ });
+
+ it('offers no renewal to someone who may not renew the invite', async () => {
+ await render(invite(-1), { mayRenew: false });
+
+ assert.ok(document.body.textContent?.includes(teams.invite.expiredAt.split(' ')[0]));
+ assert.equal(button(teams.invite.renew), undefined);
+ });
+
+ it('shows a valid invite as invited, with its link', async () => {
+ await render(invite(3));
+
+ assert.ok(document.body.textContent?.includes(teams.invite.pending));
+ assert.ok(button(teams.invite.copyLink));
+ assert.equal(button(teams.invite.renew), undefined);
+ });
+});
diff --git a/apps/web/src/features/teams/components/members/TeamInviteRow.tsx b/apps/web/src/features/teams/components/members/TeamInviteRow.tsx
index 14de80a6..21a8af5d 100644
--- a/apps/web/src/features/teams/components/members/TeamInviteRow.tsx
+++ b/apps/web/src/features/teams/components/members/TeamInviteRow.tsx
@@ -1,26 +1,34 @@
'use client';
import { useState } from 'react';
-import { Check, Copy, Mail, X } from 'lucide-react';
+import { Check, Copy, RefreshCw, X } from 'lucide-react';
import { useTranslations } from 'next-intl';
import type { InviteRow } from '@/lib/api/endpoints/invites';
+import { isInviteExpired } from '@/utils/invites';
import { inviteLink } from '@/utils/paths';
+import { cn } from '@/lib/utils';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
-import { TableCell, TableRow } from '@/components/ui/table';
+import { formatShortDate } from '@/utils/dates';
-// One pending invite of the team: the invited address, what it grants — a rank in
-// the team, or a project it also joins — a copy-link button and a revoke action.
+// An expired invite's link no longer works, so it offers a renewal in place of copying
+// that link.
export default function TeamInviteRow({
invite,
onRevoke,
+ onRenew,
+ renewing,
}: {
invite: InviteRow;
onRevoke: (invite: InviteRow) => void;
+ // Left out when the viewer may not renew this invite: the API would refuse it.
+ onRenew?: (invite: InviteRow) => void;
+ renewing: boolean;
}) {
const t = useTranslations('teams.invite');
const tManage = useTranslations('teams.manage');
const [copied, setCopied] = useState(false);
+ const expired = isInviteExpired(invite);
async function copy() {
const origin = typeof window === 'undefined' ? '' : window.location.origin;
@@ -34,30 +42,35 @@ export default function TeamInviteRow({
}
return (
- <TableRow className="hover:bg-transparent">
- <TableCell className="px-3 py-3">
- <div className="flex min-w-0 items-center gap-2.5">
- <span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-muted">
- <Mail className="size-4 text-muted-foreground" />
- </span>
- <div className="min-w-0">
- <p className="truncate text-sm font-medium">{invite.email}</p>
- <p className="truncate text-xs text-muted-foreground">
- {invite.projectName
- ? t('joinsProject', { project: invite.projectName })
- : t('joinsTeam')}
- </p>
- </div>
- </div>
- </TableCell>
- <TableCell className="px-3 py-3">
- <Badge variant="outline" className="font-normal">
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-1 py-1.5">
+ <div className="flex min-w-0 flex-1 items-center gap-2">
+ <span className="truncate text-sm">
+ {invite.projectName ? t('joinsProject', { project: invite.projectName }) : t('joinsTeam')}
+ </span>
+ <Badge variant="outline" className="shrink-0 px-1.5 py-0 text-[10px] font-normal">
{tManage(`roles.${invite.teamRole}`)}
</Badge>
- </TableCell>
- <TableCell className="px-3 py-3 text-sm text-muted-foreground">{t('pending')}</TableCell>
- <TableCell className="px-3 py-2">
- <div className="flex items-center justify-end gap-1">
+ <span
+ className={cn('shrink-0 text-xs', expired ? 'text-destructive' : 'text-muted-foreground')}
+ >
+ {expired ? t('expiredAt', { date: formatShortDate(invite.expiresAt!) }) : t('pending')}
+ </span>
+ </div>
+ <div className="ms-auto flex items-center justify-end gap-1">
+ {expired ? (
+ onRenew && (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 gap-1.5 text-xs text-muted-foreground hover:text-foreground"
+ disabled={renewing}
+ onClick={() => onRenew(invite)}
+ >
+ <RefreshCw className="size-3.5" />
+ {renewing ? t('renewing') : t('renew')}
+ </Button>
+ )
+ ) : (
<Button
variant="ghost"
size="sm"
@@ -67,17 +80,17 @@ export default function TeamInviteRow({
{copied ? <Check className="size-3.5" /> : <Copy className="size-3.5" />}
{copied ? t('copied') : t('copyLink')}
</Button>
- <Button
- variant="ghost"
- size="icon"
- className="size-7 text-muted-foreground hover:text-destructive"
- title={t('revokeAction')}
- onClick={() => onRevoke(invite)}
- >
- <X className="size-4" />
- </Button>
- </div>
- </TableCell>
- </TableRow>
+ )}
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7 text-muted-foreground hover:text-destructive"
+ title={t('revokeAction')}
+ onClick={() => onRevoke(invite)}
+ >
+ <X className="size-4" />
+ </Button>
+ </div>
+ </div>
);
}
diff --git a/apps/web/src/features/teams/components/members/TeamInvitesList.test.tsx b/apps/web/src/features/teams/components/members/TeamInvitesList.test.tsx
new file mode 100644
index 00000000..a4f919d9
--- /dev/null
+++ b/apps/web/src/features/teams/components/members/TeamInvitesList.test.tsx
@@ -0,0 +1,119 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, describe, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM } from 'jsdom';
+import type { InviteRow } from '@/lib/api/endpoints/invites';
+import members from '../../../../../messages/en/members.json';
+import teams from '../../../../../messages/en/teams.json';
+import common from '../../../../../messages/en/common.json';
+
+// One address with several invites is listed once, with a line for each invite.
+const replacedGlobals = [
+ 'window',
+ 'document',
+ 'navigator',
+ 'Node',
+ 'Element',
+ 'HTMLElement',
+ 'HTMLButtonElement',
+ 'Event',
+ 'MouseEvent',
+ 'IS_REACT_ACT_ENVIRONMENT',
+] as const;
+
+let dom: JSDOM;
+let root: Root;
+let originals: Map<string, PropertyDescriptor | undefined>;
+
+const DAY = 24 * 60 * 60 * 1000;
+const invite = (
+ id: number,
+ email: string,
+ projectName: string | null,
+ expiresInDays = 3,
+): InviteRow => ({
+ id,
+ token: `tok-${id}`,
+ email,
+ teamRole: projectName ? 'member' : 'manager',
+ projectKey: projectName ? 'MKT' : null,
+ projectName,
+ role: null,
+ roleId: null,
+ roleName: null,
+ status: 'pending',
+ createdAt: new Date(Date.now() - 8 * DAY).toISOString(),
+ expiresAt: new Date(Date.now() + expiresInDays * DAY).toISOString(),
+ respondedAt: null,
+ invitedByName: null,
+ invitedByEmail: null,
+});
+
+async function render(rows: InviteRow[]) {
+ const { default: TeamInvitesList } = await import('./TeamInvitesList');
+ await act(async () =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={{ teams, members, common }} timeZone="UTC">
+ <TeamInvitesList
+ invites={rows}
+ onRevoke={() => {}}
+ onRenew={() => {}}
+ canRenew={() => true}
+ renewingId={null}
+ />
+ </NextIntlClientProvider>,
+ ),
+ );
+}
+
+const button = (text: string) =>
+ [...document.querySelectorAll('button')].find((b) => b.textContent?.includes(text));
+
+beforeEach(async () => {
+ originals = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ dom = new JSDOM('<!doctype html><div id="root"></div>', { url: 'https://example.test/' });
+ for (const name of replacedGlobals) {
+ if (name in dom.window) {
+ Object.defineProperty(globalThis, name, {
+ configurable: true,
+ value: dom.window[name as keyof typeof dom.window],
+ });
+ }
+ }
+ Object.defineProperty(globalThis, 'IS_REACT_ACT_ENVIRONMENT', {
+ configurable: true,
+ value: true,
+ });
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.querySelector('#root')!);
+});
+
+afterEach(async () => {
+ await act(async () => root.unmount());
+ dom.window.close();
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+describe('TeamInvitesList', () => {
+ it('lists an address once, with a line for each invite it holds', async () => {
+ await render([
+ invite(1, '[email protected]', null),
+ invite(2, '[email protected]', 'Marketing'),
+ invite(3, '[email protected]', null, -1),
+ ]);
+
+ const text = document.body.textContent ?? '';
+ assert.equal(text.split('[email protected]').length - 1, 1);
+ assert.ok(text.includes(teams.invite.joinsTeam));
+ assert.ok(text.includes(teams.invite.joinsProject.replace('{project}', 'Marketing')));
+ assert.ok(text.includes('3 pending invites'));
+ assert.ok(button(teams.invite.renew));
+ });
+});
diff --git a/apps/web/src/features/teams/components/members/TeamInvitesList.tsx b/apps/web/src/features/teams/components/members/TeamInvitesList.tsx
new file mode 100644
index 00000000..a0e35aa9
--- /dev/null
+++ b/apps/web/src/features/teams/components/members/TeamInvitesList.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { Mail } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import type { InviteRow } from '@/lib/api/endpoints/invites';
+import TeamInviteRow from './TeamInviteRow';
+
+// The team's open invites, apart from its members: an invite is nobody yet, and one
+// address can hold an invite into the team and others into its projects at once, so
+// each address is listed once with what every invite of it grants.
+export default function TeamInvitesList({
+ invites,
+ onRevoke,
+ onRenew,
+ canRenew,
+ renewingId,
+}: {
+ invites: InviteRow[];
+ onRevoke: (invite: InviteRow) => void;
+ onRenew: (invite: InviteRow) => void;
+ canRenew: (invite: InviteRow) => boolean;
+ renewingId: number | null;
+}) {
+ const tMembers = useTranslations('members.invites');
+ const byEmail = new Map<string, InviteRow[]>();
+ for (const invite of invites) {
+ const grants = byEmail.get(invite.email);
+ if (grants) grants.push(invite);
+ else byEmail.set(invite.email, [invite]);
+ }
+
+ return (
+ <div>
+ <div className="mb-1 border-b pb-1 text-xs font-medium text-muted-foreground">
+ {tMembers('pendingCount', { count: invites.length })}
+ </div>
+ <div className="divide-y divide-border">
+ {[...byEmail].map(([email, grants]) => (
+ <div key={email} className="flex gap-2.5 py-2">
+ <span className="mt-1 flex size-7 shrink-0 items-center justify-center rounded-full bg-muted">
+ <Mail className="size-3.5 text-muted-foreground" />
+ </span>
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-sm font-medium">{email}</p>
+ {grants.map((invite) => (
+ <TeamInviteRow
+ key={invite.id}
+ invite={invite}
+ onRevoke={onRevoke}
+ onRenew={canRenew(invite) ? onRenew : undefined}
+ renewing={renewingId === invite.id}
+ />
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/teams/components/members/TeamMembersSection.tsx b/apps/web/src/features/teams/components/members/TeamMembersSection.tsx
index 171c4a27..975b1e43 100644
--- a/apps/web/src/features/teams/components/members/TeamMembersSection.tsx
+++ b/apps/web/src/features/teams/components/members/TeamMembersSection.tsx
@@ -9,6 +9,7 @@ import type { MemberKind } from '@/lib/api/endpoints/members';
import type { TeamMember } from '@/lib/api/endpoints/teams';
import {
useDeleteTeamInvite,
+ useRenewTeamInvite,
useRemoveTeamMember,
useTeam,
useTeamInvitesQuery,
@@ -29,14 +30,15 @@ import { Button } from '@/components/ui/button';
import { Table, TableBody, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import TeamInviteDialog from './TeamInviteDialog';
-import TeamInviteRow from './TeamInviteRow';
+import TeamInvitesList from './TeamInvitesList';
+import { mayRenewInvite } from '@/utils/invites';
import TeamMemberRow from './TeamMemberRow';
// The team's members, a page at a time, with the invites that have not been answered
-// yet above them. People and agents work on one board, so both are listed and the tabs
-// tell them apart; selecting an agent opens the section that configures it. Owners and
-// managers run the list, so only they invite and see the pending invites; only an owner
-// removes a person from it.
+// yet listed apart above them. People and agents work on one board, so both are listed
+// and the tabs tell them apart; selecting an agent opens the section that configures it.
+// Owners and managers run the list, so only they invite and see the pending invites; only
+// an owner removes a person from it.
export default function TeamMembersSection({ teamId }: { teamId: number }) {
const t = useTranslations('teams');
const tMembers = useTranslations('members');
@@ -50,6 +52,7 @@ export default function TeamMembersSection({ teamId }: { teamId: number }) {
const canInvite = team != null && team.role !== 'member';
const invitesQuery = useTeamInvitesQuery(teamId, canInvite);
const deleteInvite = useDeleteTeamInvite(teamId);
+ const renewInvite = useRenewTeamInvite(teamId);
const removeMember = useRemoveTeamMember(teamId);
const [inviting, setInviting] = useState(false);
const [target, setTarget] = useState<InviteRow | null>(null);
@@ -59,12 +62,12 @@ export default function TeamMembersSection({ teamId }: { teamId: number }) {
const members = membersQuery.data?.items ?? [];
const total = membersQuery.data?.total ?? 0;
- // An invite is nobody yet, so it matches no tab and no search term: the rows only
- // stand above the first page of the plain list.
- const pending =
- paging.params.page === 1 && kind !== 'agent' && term === undefined
- ? (invitesQuery.data ?? []).filter((invite) => invite.status === 'pending')
- : [];
+ // The invites are not part of the paged member list, so tabs and pages leave them be;
+ // a search narrows them by address like it narrows the members.
+ const needle = term?.toLowerCase();
+ const pending = (invitesQuery.data ?? []).filter(
+ (invite) => invite.status === 'pending' && (!needle || invite.email.includes(needle)),
+ );
function onKindChange(next: string) {
setKind(next as MemberKind);
@@ -98,6 +101,18 @@ export default function TeamMembersSection({ teamId }: { teamId: number }) {
}
>
<div className="flex min-h-0 flex-1 flex-col gap-4">
+ {pending.length > 0 && (
+ <TeamInvitesList
+ invites={pending}
+ onRevoke={setTarget}
+ onRenew={(expired) => renewInvite.mutate(expired.id)}
+ canRenew={(invite) =>
+ mayRenewInvite(invite, { teamRole: team?.role ?? null, ownsProject: false })
+ }
+ renewingId={renewInvite.isPending ? (renewInvite.variables ?? null) : null}
+ />
+ )}
+
<Tabs value={kind} onValueChange={onKindChange}>
<div className="flex items-center justify-between gap-3">
<TabsList variant="line" className="w-auto border-b-0">
@@ -116,7 +131,7 @@ export default function TeamMembersSection({ teamId }: { teamId: number }) {
{membersQuery.isPending ? (
<ListSkeleton rows={4} rowClassName="h-12" />
- ) : members.length === 0 && pending.length === 0 ? (
+ ) : members.length === 0 ? (
<MembersEmptyState kind={kind} searching={term !== undefined} />
) : (
<div className="overflow-x-auto">
@@ -144,9 +159,6 @@ export default function TeamMembersSection({ teamId }: { teamId: number }) {
</TableRow>
</TableHeader>
<TableBody>
- {pending.map((invite) => (
- <TeamInviteRow key={invite.id} invite={invite} onRevoke={setTarget} />
- ))}
{members.map((member) => (
<TeamMemberRow
key={member.userId}
diff --git a/apps/web/src/lib/api/endpoints/god.ts b/apps/web/src/lib/api/endpoints/god.ts
index 77bfe872..b2b6b87b 100644
--- a/apps/web/src/lib/api/endpoints/god.ts
+++ b/apps/web/src/lib/api/endpoints/god.ts
@@ -23,6 +23,8 @@ export interface InstanceAuthSettings {
emailPassword: boolean;
trustProviderEmails: boolean;
personalWorkspaces: boolean;
+ // Days an invite link stays valid; 0 means invites never expire.
+ inviteTtlDays: number;
hasEmailProvider: boolean;
// Whether Google or the OIDC provider can run. Password sign-in may only be turned
// off while one of them can.
@@ -36,6 +38,7 @@ export interface InstanceAuthSettingsPatch {
emailPassword?: boolean;
trustProviderEmails?: boolean;
personalWorkspaces?: boolean;
+ inviteTtlDays?: number;
}
// The instance mail provider used for authentication email (password reset, address
diff --git a/apps/web/src/lib/api/endpoints/invites.ts b/apps/web/src/lib/api/endpoints/invites.ts
index ebaac3a5..eedf0531 100644
--- a/apps/web/src/lib/api/endpoints/invites.ts
+++ b/apps/web/src/lib/api/endpoints/invites.ts
@@ -26,6 +26,9 @@ export interface InviteRow {
roleName: string | null;
status: InviteStatus;
createdAt: string;
+ // When a pending invite stops working; null once it was answered or when invites
+ // never expire.
+ expiresAt: string | null;
respondedAt: string | null;
invitedByName: string | null;
invitedByEmail: string | null;
@@ -54,6 +57,7 @@ export interface InviteView {
roleName: string | null;
status: InviteStatus;
createdAt: string;
+ expired: boolean;
// Whether the invited email already has an account, so the accept screen can
// open in sign-in mode instead of registration.
hasAccount: boolean;
@@ -88,6 +92,12 @@ export const sendInviteEmail = (projectKey: string, inviteId: number) =>
method: 'POST',
});
+// A renewed invite is a new one under a new link; the expired one is gone.
+export const renewInvite = (projectKey: string, inviteId: number) =>
+ request<InviteCreateResult>(`/projects/${projectKey}/invites/${inviteId}/renew`, {
+ method: 'POST',
+ });
+
export const deleteInvite = (projectKey: string, inviteId: number) =>
request<void>(`/projects/${projectKey}/invites/${inviteId}`, { method: 'DELETE' });
@@ -99,6 +109,9 @@ export const createTeamInvite = (teamId: number, input: { email: string; role: I
body: JSON.stringify(input),
});
+export const renewTeamInvite = (teamId: number, inviteId: number) =>
+ request<InviteCreateResult>(`/teams/${teamId}/invites/${inviteId}/renew`, { method: 'POST' });
+
export const deleteTeamInvite = (teamId: number, inviteId: number) =>
request<void>(`/teams/${teamId}/invites/${inviteId}`, { method: 'DELETE' });
diff --git a/apps/web/src/services/members.service.ts b/apps/web/src/services/members.service.ts
index 9ead2b95..038ce4cd 100644
--- a/apps/web/src/services/members.service.ts
+++ b/apps/web/src/services/members.service.ts
@@ -5,6 +5,7 @@ import {
listInvites,
createInvite,
sendInviteEmail,
+ renewInvite,
deleteInvite,
} from '@/lib/api/endpoints/invites';
import {
@@ -146,6 +147,19 @@ export function useSendInviteEmail(projectKey: string) {
});
}
+export function useRenewInvite(projectKey: string) {
+ const t = useTranslations('members.invites');
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (inviteId: number) => renewInvite(projectKey, inviteId),
+ onSuccess: (result) => {
+ qc.invalidateQueries({ queryKey: qk.invites(projectKey) });
+ if (result.emailQueued) toast.success(t('renewed'));
+ else toast.info(t('renewedNoEmail'));
+ },
+ });
+}
+
export function useDeleteInvite(projectKey: string) {
const qc = useQueryClient();
return useMutation({
diff --git a/apps/web/src/services/teams.service.ts b/apps/web/src/services/teams.service.ts
index e6972b13..79475321 100644
--- a/apps/web/src/services/teams.service.ts
+++ b/apps/web/src/services/teams.service.ts
@@ -5,10 +5,13 @@ import {
useQuery,
useQueryClient,
} from '@tanstack/react-query';
+import { toast } from 'sonner';
+import { useTranslations } from 'next-intl';
import {
type InviteTeamRole,
listTeamInvites,
createTeamInvite,
+ renewTeamInvite,
deleteTeamInvite,
} from '@/lib/api/endpoints/invites';
import type { MemberKind, MemberListParams } from '@/lib/api/endpoints/members';
@@ -264,6 +267,21 @@ export function useCreateTeamInvite(teamId: number) {
});
}
+export function useRenewTeamInvite(teamId: number) {
+ const t = useTranslations('members.invites');
+ const qc = useQueryClient();
+ return useMutation({
+ mutationFn: (inviteId: number) => renewTeamInvite(teamId, inviteId),
+ onSuccess: (result) => {
+ qc.invalidateQueries({ queryKey: qk.teamInvites(teamId) });
+ if (result.emailQueued) toast.success(t('renewed'));
+ // A team invite has no email of its own; only a project one is mailed.
+ else if (result.projectName == null) toast.info(t('renewedCopyLink'));
+ else toast.info(t('renewedNoEmail'));
+ },
+ });
+}
+
export function useDeleteTeamInvite(teamId: number) {
const qc = useQueryClient();
return useMutation({
diff --git a/apps/web/src/utils/invites.test.ts b/apps/web/src/utils/invites.test.ts
new file mode 100644
index 00000000..a9962a6c
--- /dev/null
+++ b/apps/web/src/utils/invites.test.ts
@@ -0,0 +1,35 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { mayRenewInvite } from './invites';
+
+// The same rules as mayGrantInviteRanks on the API, which answers 403 to anyone else.
+describe('mayRenewInvite', () => {
+ const teamOwner = { teamRole: 'owner', ownsProject: false };
+ const manager = { teamRole: 'manager', ownsProject: false };
+ const projectOwner = { teamRole: 'member', ownsProject: true };
+ const member = { teamRole: 'member', ownsProject: false };
+
+ it('lets anyone who may invite renew an invite that grants no rank', () => {
+ const plain = { teamRole: 'member', role: 'member' } as const;
+ for (const viewer of [teamOwner, manager, projectOwner, member]) {
+ assert.equal(mayRenewInvite(plain, viewer), true);
+ }
+ });
+
+ it('leaves a team rank to the team owner', () => {
+ for (const teamRole of ['manager', 'owner'] as const) {
+ const rank = { teamRole, role: null };
+ assert.equal(mayRenewInvite(rank, teamOwner), true);
+ assert.equal(mayRenewInvite(rank, manager), false);
+ assert.equal(mayRenewInvite(rank, projectOwner), false);
+ }
+ });
+
+ it("leaves a project's ownership to whoever runs the team or owns the project", () => {
+ const ownership = { teamRole: 'member', role: 'owner' } as const;
+ assert.equal(mayRenewInvite(ownership, teamOwner), true);
+ assert.equal(mayRenewInvite(ownership, manager), true);
+ assert.equal(mayRenewInvite(ownership, projectOwner), true);
+ assert.equal(mayRenewInvite(ownership, member), false);
+ });
+});
diff --git a/apps/web/src/utils/invites.ts b/apps/web/src/utils/invites.ts
new file mode 100644
index 00000000..e2bedf40
--- /dev/null
+++ b/apps/web/src/utils/invites.ts
@@ -0,0 +1,17 @@
+import type { InviteRow } from '@/lib/api/endpoints/invites';
+
+export const isInviteExpired = (invite: Pick<InviteRow, 'expiresAt'>) =>
+ invite.expiresAt != null && new Date(invite.expiresAt) < new Date();
+
+// A renewal hands the grant out again, so the API (mayGrantInviteRanks) allows it only to
+// whoever could have sent it: a team rank is the team owner's to give, and a project's
+// ownership is for whoever runs the team or owns that project.
+export function mayRenewInvite(
+ invite: Pick<InviteRow, 'teamRole' | 'role'>,
+ viewer: { teamRole: string | null; ownsProject: boolean },
+): boolean {
+ const runsTeam = viewer.teamRole === 'owner' || viewer.teamRole === 'manager';
+ if (invite.teamRole !== 'member' && viewer.teamRole !== 'owner') return false;
+ if (invite.role === 'owner' && !runsTeam && !viewer.ownsProject) return false;
+ return true;
+}
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 32b353f7..fa71da46 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -85,8 +85,11 @@ nothing here needs a restart.
client secret back into the page. Name the sign-in button and turn the provider on.
The first sign-in creates the account, and the registration mode under **Authentication**
-decides whether it may: `open` creates it, `invite only` needs a pending project invite,
-`closed` refuses it. On a closed instance, provision people with SCIM.
+decides whether it may: `open` creates it, `invite only` needs a pending invite that has
+not expired, `closed` refuses it. Invites expire after the days set under **Authentication**
+(7 by default, 0 for never); an expired one is renewed from the member list under a new
+link, and a sign-in refused because the invite expired is told so. On a closed instance,
+provision people with SCIM.
A sign-in whose address already has an account joins that account instead of creating a
second one. That needs the provider to report the address as verified and the account to
diff --git a/packages/auth/AGENTS.md b/packages/auth/AGENTS.md
index 7f87a244..c272c6e8 100644
--- a/packages/auth/AGENTS.md
+++ b/packages/auth/AGENTS.md
@@ -43,12 +43,16 @@ The mail provider is read by the api and the worker as well, so its shape and re
live in `@repo/db` (`domains/instance-email.ts`); what is here is the write side god
mode drives.
-"Invite only" means the address has a pending `team_invite` (`hasPendingInvite`).
+"Invite only" means the address has a pending `team_invite` that has not expired
+(`hasPendingInvite`). An invite expires `inviteTtlDays` after it was created (7 by
+default, 0 for never, at most 3650; `inviteValidSince` gives the cutoff): it then neither gates
+registration nor can be accepted, and a new invite for the same address replaces it.
Invites are created and revoked inside a team, so there is no instance-level invite
-table and god mode has no invite section — do not add one.
+table and god mode has no invite section — do not add one; god mode only sets how long
+they last.
-`hooks.before` gates `/sign-up/email` (closed → 403, invite → no pending invite for
-that address → 403) and holds back `/sign-in/email` for an unconfirmed address while
+`hooks.before` gates `/sign-up/email` (closed → 403, invite → no pending, unexpired
+invite for that address → 403) and holds back `/sign-in/email` for an unconfirmed address while
verification is required. The requirement never outlives the mail provider: the api
refuses to turn it on without one, and `setEmailSettings` clears it when the provider
is removed, so the setting alone is what the gate, the sign-up endpoint and the
@@ -198,9 +202,14 @@ receive its real owner.
The registration gate (`assertRegistrationAllowed`) runs in
`databaseHooks.user.create.before`, which every account creation passes, and that is what
-applies closed/invite-only to a Google sign-up. Its `APIError`s carry a `code` because the
-social callback turns that into the `?error=` it redirects with; without one the callback
-fails the request instead. Agent bot users are written with a direct insert and never
+applies closed/invite-only to a Google, OIDC or magic-link sign-up. It refuses with
+`REGISTRATION_CLOSED` on a closed instance, `INVITE_ONLY` when the address has no pending
+invite, and `INVITE_EXPIRED` when its only invites have expired. That last one reveals that
+the address was invited, so it is given only where the address is proven (provider, magic
+link); the email form, open to anyone, gets `INVITE_ONLY`. Its `APIError`s carry a `code`
+because the provider callback and the magic link turn that into the `?error=` they redirect
+with; without one the callback fails the request instead (`invite-forms.test.ts` pins
+`INVITE_EXPIRED` and `INVITE_ONLY`). Agent bot users are written with a direct insert and never
reach the hook.
## API keys
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index 8a6f49c8..b6660780 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -17,6 +17,7 @@ import * as schema from '@repo/db/schema';
import {
getAuthSettings,
hasPendingInvite,
+ hasExpiredInvite,
getGoogleConfig,
isGoogleUsable,
getOidcConfig,
@@ -353,24 +354,33 @@ const PASSWORD_PATHS = new Set([
'/magic-link/verify',
]);
+const REGISTRATION_REFUSALS = {
+ REGISTRATION_CLOSED: 'Registration is closed on this instance',
+ INVITE_ONLY: 'This instance is invite-only. Ask a project owner to invite this address.',
+ INVITE_EXPIRED: 'The invite for this address has expired. Ask for a new one.',
+} as const;
+
+function refuseRegistration(code: keyof typeof REGISTRATION_REFUSALS): never {
+ throw new APIError('FORBIDDEN', { code, message: REGISTRATION_REFUSALS[code] });
+}
+
// The registration gate: who may create an account. Both sign-up paths run it — the
// email form checks it up front (below), and the user create hook catches every other
-// path, which is what stops a Google sign-up on a closed or invite-only instance.
-// Each refusal carries a `code`, which is what the social callback turns into the
-// ?error= it redirects with; without one the callback would fail the request instead.
-async function assertRegistrationAllowed(email: string): Promise<void> {
+// path, which is what stops a Google, OIDC or magic-link sign-up on a closed or
+// invite-only instance. Telling an expired invite apart reveals that the address was
+// invited, so it is said only once the address is proven (a provider or a magic link):
+// the email form, open to anyone, gets the plain invite-only refusal. Each refusal
+// carries a `code`, which is what the provider callback and the magic link turn into the
+// ?error= they redirect with; without one the callback would fail the request instead.
+async function assertRegistrationAllowed(
+ email: string,
+ { addressProven }: { addressProven: boolean },
+): Promise<void> {
const settings = await getAuthSettings();
- if (settings.registration === 'closed') {
- throw new APIError('FORBIDDEN', {
- code: 'REGISTRATION_CLOSED',
- message: 'Registration is closed on this instance',
- });
- }
+ if (settings.registration === 'closed') refuseRegistration('REGISTRATION_CLOSED');
if (settings.registration === 'invite' && !(await hasPendingInvite(email))) {
- throw new APIError('FORBIDDEN', {
- code: 'INVITE_ONLY',
- message: 'This instance is invite-only. Ask a project owner to invite this address.',
- });
+ const expired = addressProven && (await hasExpiredInvite(email));
+ refuseRegistration(expired ? 'INVITE_EXPIRED' : 'INVITE_ONLY');
}
}
@@ -625,7 +635,9 @@ export const auth = betterAuth({
}
if (ctx.path === '/sign-up/email') {
- await assertRegistrationAllowed((ctx.body as { email?: string } | undefined)?.email ?? '');
+ await assertRegistrationAllowed((ctx.body as { email?: string } | undefined)?.email ?? '', {
+ addressProven: false,
+ });
return;
}
@@ -729,7 +741,9 @@ export const auth = betterAuth({
// Assign the role before the row is inserted: first user ever → "god",
// everyone else → "user".
before: async (user) => {
- await assertRegistrationAllowed(user.email);
+ // The email form is refused up front unless its invite is valid, so a refusal
+ // here comes from a provider or a magic link, which prove the address.
+ await assertRegistrationAllowed(user.email, { addressProven: true });
const isFirstUser = (await db.$count(schema.user)) === 0;
// A sign-up that carried its own username has passed the plugin's own
// check against the other accounts by now, but not the one against the
@@ -955,6 +969,7 @@ export {
REGISTRATION_MODES,
getAuthSettings,
setAuthSettings,
+ inviteValidSince,
getEmailSettings,
setEmailSettings,
resolveEmailConfig,
diff --git a/packages/auth/src/instance.ts b/packages/auth/src/instance.ts
index b4a2b092..cebf0c80 100644
--- a/packages/auth/src/instance.ts
+++ b/packages/auth/src/instance.ts
@@ -12,7 +12,7 @@ import {
INSTANCE_EMAIL_SECRET_KEY,
type InstanceEmailConfig,
} from '@repo/db';
-import { and, eq } from 'drizzle-orm';
+import { and, eq, gte, lt } from 'drizzle-orm';
import { hasEmailProvider, type SmtpConfig } from '@repo/mailer';
// Authentication settings: who may register, whether email has to be confirmed,
@@ -62,6 +62,10 @@ export interface AuthSettings {
// Give every person a workspace of their own: created with the account, and offered
// to an account that has none. Off, only the instance owner has a workspace.
personalWorkspaces: boolean;
+ // How many days an invite link stays valid, counted from when it was created. A
+ // pending invite older than this neither gates registration nor can be accepted.
+ // 0 disables the limit (invites never expire).
+ inviteTtlDays: number;
}
function defaultAuthSettings(): AuthSettings {
@@ -72,6 +76,7 @@ function defaultAuthSettings(): AuthSettings {
emailPassword: true,
trustProviderEmails: false,
personalWorkspaces: true,
+ inviteTtlDays: 7,
};
}
@@ -81,6 +86,14 @@ export async function getAuthSettings(): Promise<AuthSettings> {
return { ...defaultAuthSettings(), ...(stored ?? {}) };
}
+// The cutoff an invite's createdAt must be at or after to still count, or null when
+// the instance has turned expiry off.
+export async function inviteValidSince(): Promise<Date | null> {
+ const days = (await getAuthSettings()).inviteTtlDays;
+ if (!days || days <= 0) return null;
+ return new Date(Date.now() - days * 24 * 60 * 60 * 1000);
+}
+
export async function setAuthSettings(patch: Partial<AuthSettings>): Promise<AuthSettings> {
const next = { ...(await getAuthSettings()), ...patch };
await setSetting(AUTH_SETTING_KEY, next);
@@ -489,20 +502,47 @@ export async function verifyScimToken(candidate: string): Promise<number | null>
// ── Invites ───────────────────────────────────────────────────────────────────
-// True when this address has a pending invite. That is what "invite only" means on
-// this instance: someone invites them to a team or to one of its projects, and that
-// invite is what lets them register at all. Invites are created and revoked inside a
-// team (team_invite), so there is nothing instance-level to manage.
+// True when this address has a pending, unexpired invite. That is what "invite only"
+// means on this instance: someone invites them to a team or to one of its projects, and
+// that invite is what lets them register at all. Invites are created and revoked inside
+// a team (team_invite), so there is nothing instance-level to manage.
//
// The invite itself is accepted after sign-up, on the /invite/:token screen — this
// only decides whether the account may be created, and leaves the invite pending.
export async function hasPendingInvite(email: string): Promise<boolean> {
const address = email.trim().toLowerCase();
if (!address) return false;
+ const since = await inviteValidSince();
+ const rows = await db
+ .select({ id: teamInvite.id })
+ .from(teamInvite)
+ .where(
+ and(
+ eq(teamInvite.email, address),
+ eq(teamInvite.status, 'pending'),
+ since ? gte(teamInvite.createdAt, since) : undefined,
+ ),
+ )
+ .limit(1);
+ return rows.length > 0;
+}
+
+// True when the address has a pending invite that has expired. Asked after
+// hasPendingInvite says no, so the person knows to ask for a new link.
+export async function hasExpiredInvite(email: string): Promise<boolean> {
+ const address = email.trim().toLowerCase();
+ const since = await inviteValidSince();
+ if (!address || !since) return false;
const rows = await db
.select({ id: teamInvite.id })
.from(teamInvite)
- .where(and(eq(teamInvite.email, address), eq(teamInvite.status, 'pending')))
+ .where(
+ and(
+ eq(teamInvite.email, address),
+ eq(teamInvite.status, 'pending'),
+ lt(teamInvite.createdAt, since),
+ ),
+ )
.limit(1);
return rows.length > 0;
}