Repository navigation
feat(web): add configurable login message #1668
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| -- AlterTable | ||
| ALTER TABLE "Org" ADD COLUMN "loginMessage" TEXT; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| import { beforeEach, describe, expect, test, vi } from 'vitest'; | ||
| import { ErrorCode } from '@/lib/errorCodes'; | ||
|
|
||
| const mocks = vi.hoisted(() => ({ | ||
| authenticated: true, | ||
| role: 'OWNER' as 'OWNER' | 'MEMBER', | ||
| update: vi.fn(), | ||
| captureException: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock('@/auth', () => ({ getProviders: vi.fn() })); | ||
| vi.mock('@/lib/entitlements', () => ({ isAnonymousAccessAvailable: vi.fn() })); | ||
| vi.mock('@sourcebot/shared', () => ({ | ||
| env: {}, | ||
| createLogger: () => ({ error: vi.fn() }), | ||
| })); | ||
| vi.mock('@sentry/nextjs', () => ({ captureException: mocks.captureException })); | ||
| vi.mock('@/middleware/withAuth', () => ({ | ||
| withAuth: async (fn: (context: unknown) => unknown) => { | ||
| if (!mocks.authenticated) { | ||
| return { statusCode: 401, errorCode: 'NOT_AUTHENTICATED', message: 'Not authenticated' }; | ||
| } | ||
| return fn({ org: { id: 42 }, role: mocks.role, prisma: { org: { update: mocks.update } } }); | ||
| }, | ||
| })); | ||
|
|
||
| const { setLoginMessage } = await import('./actions'); | ||
|
|
||
| beforeEach(() => { | ||
| vi.resetAllMocks(); | ||
| mocks.authenticated = true; | ||
| mocks.role = 'OWNER'; | ||
| mocks.update.mockResolvedValue({}); | ||
| }); | ||
|
|
||
| describe('setLoginMessage', () => { | ||
| test('stores raw Markdown on the authenticated organization, preserving meaningful whitespace', async () => { | ||
| const message = ' Indented code\n\n[Request access](https://example.com/access) \nContact **IT**.'; | ||
| await expect(setLoginMessage(message)).resolves.toEqual({ success: true }); | ||
| expect(mocks.update).toHaveBeenCalledWith({ | ||
| where: { id: 42 }, | ||
| data: { loginMessage: message }, | ||
| }); | ||
| }); | ||
|
|
||
| test.each([null, '', ' \n\t '])('clears the message for %j', async (message) => { | ||
| await expect(setLoginMessage(message)).resolves.toEqual({ success: true }); | ||
| expect(mocks.update).toHaveBeenCalledWith({ where: { id: 42 }, data: { loginMessage: null } }); | ||
| }); | ||
|
|
||
| test('accepts exactly 5,000 characters', async () => { | ||
| await expect(setLoginMessage('x'.repeat(5000))).resolves.toEqual({ success: true }); | ||
| }); | ||
|
|
||
| test('rejects messages over 5,000 characters without writing', async () => { | ||
| await expect(setLoginMessage('x'.repeat(5001))).resolves.toMatchObject({ | ||
| statusCode: 400, errorCode: ErrorCode.INVALID_REQUEST_BODY, | ||
| }); | ||
| expect(mocks.update).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test.each([[undefined], [42], [{}], [[]]])('rejects invalid input %j without writing', async (message) => { | ||
| await expect(setLoginMessage(message as string)).resolves.toMatchObject({ | ||
| statusCode: 400, errorCode: ErrorCode.INVALID_REQUEST_BODY, | ||
| }); | ||
| expect(mocks.update).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('denies organization members through the owner role check', async () => { | ||
| mocks.role = 'MEMBER'; | ||
| await expect(setLoginMessage('Unauthorized edit')).resolves.toMatchObject({ | ||
| statusCode: 403, errorCode: ErrorCode.INSUFFICIENT_PERMISSIONS, | ||
| }); | ||
| expect(mocks.update).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('requires authentication', async () => { | ||
| mocks.authenticated = false; | ||
| await expect(setLoginMessage('Unauthorized edit')).resolves.toMatchObject({ | ||
| statusCode: 401, errorCode: ErrorCode.NOT_AUTHENTICATED, | ||
| }); | ||
| expect(mocks.update).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('returns a service error when persistence fails', async () => { | ||
| const error = new Error('Database unavailable'); | ||
| mocks.update.mockRejectedValue(error); | ||
| await expect(setLoginMessage('Message')).resolves.toMatchObject({ | ||
| statusCode: 500, errorCode: ErrorCode.UNEXPECTED_ERROR, | ||
| }); | ||
| expect(mocks.captureException).toHaveBeenCalledWith(error); | ||
| }); | ||
| }); |
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -4,13 +4,38 @@ import { getProviders } from "@/auth"; | |||||
| import { SOURCEBOT_SUPPORT_EMAIL } from "@/lib/constants"; | ||||||
| import { isAnonymousAccessAvailable } from "@/lib/entitlements"; | ||||||
| import { ErrorCode } from "@/lib/errorCodes"; | ||||||
| import { ServiceError } from "@/lib/serviceError"; | ||||||
| import { requestBodySchemaValidationError, ServiceError } from "@/lib/serviceError"; | ||||||
| import { sew } from "@/middleware/sew"; | ||||||
| import { withAuth } from "@/middleware/withAuth"; | ||||||
| import { withMinimumOrgRole } from "@/middleware/withMinimumOrgRole"; | ||||||
| import { OrgRole } from "@sourcebot/db"; | ||||||
| import { env } from "@sourcebot/shared"; | ||||||
| import { StatusCodes } from "http-status-codes"; | ||||||
| import { z } from "zod"; | ||||||
| import { LOGIN_MESSAGE_MAX_LENGTH } from "@/features/auth/constants"; | ||||||
|
|
||||||
| const loginMessageSchema = z.string() | ||||||
| .max(LOGIN_MESSAGE_MAX_LENGTH, "Login message must be 5,000 characters or fewer.") | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P3: The validation error hard-codes Prompt for AI agents
Suggested change
|
||||||
| .nullable() | ||||||
| .transform(message => message?.trim() ? message : null); | ||||||
|
|
||||||
| export const setLoginMessage = async (message: string | null): Promise<{ success: boolean } | ServiceError> => sew(async () => | ||||||
| withAuth(async ({ org, role, prisma }) => | ||||||
| withMinimumOrgRole(role, OrgRole.OWNER, async () => { | ||||||
| const parsed = loginMessageSchema.safeParse(message); | ||||||
| if (!parsed.success) { | ||||||
| return requestBodySchemaValidationError(parsed.error); | ||||||
| } | ||||||
|
|
||||||
| await prisma.org.update({ | ||||||
| where: { id: org.id }, | ||||||
| data: { loginMessage: parsed.data }, | ||||||
| }); | ||||||
|
|
||||||
| return { success: true }; | ||||||
| }) | ||||||
| ) | ||||||
| ); | ||||||
|
|
||||||
| export const setMemberApprovalRequired = async (required: boolean): Promise<{ success: boolean } | ServiceError> => sew(async () => | ||||||
| withAuth(async ({ org, role, prisma }) => | ||||||
|
|
||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; | ||
| import { afterEach, beforeEach, expect, test, vi } from 'vitest'; | ||
|
|
||
| const mocks = vi.hoisted(() => ({ save: vi.fn(), toast: vi.fn() })); | ||
| vi.mock('../actions', () => ({ setLoginMessage: mocks.save })); | ||
| vi.mock('@/components/hooks/use-toast', () => ({ useToast: () => ({ toast: mocks.toast }) })); | ||
| vi.mock('@/lib/utils', () => ({ | ||
| cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '), | ||
| isServiceError: (value: unknown) => !!value && typeof value === 'object' && 'errorCode' in value, | ||
|
brendan-kellam marked this conversation as resolved.
Resolved
|
||
| })); | ||
| const { LoginMessageSettingsCard } = await import('./loginMessageSettingsCard'); | ||
| beforeEach(() => { | ||
| vi.resetAllMocks(); | ||
| mocks.save.mockResolvedValue({ success: true }); | ||
| }); | ||
| afterEach(cleanup); | ||
|
|
||
| test('saves Markdown only after editing and marks a successful save as unchanged', async () => { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2: The character-limit and failure paths the PR explicitly highlights are untested. The component disables Save once Prompt for AI agents |
||
| render(<LoginMessageSettingsCard loginMessage="Old message" />); | ||
| const save = screen.getByRole('button', { name: 'Save changes' }) as HTMLButtonElement; | ||
| expect(save.disabled).toBe(true); | ||
| const message = ' Code\n\n[Request access](https://example.com) \nThanks'; | ||
| fireEvent.change(screen.getByRole('textbox', { name: 'Login message' }), { target: { value: message } }); | ||
| expect(save.disabled).toBe(false); | ||
| fireEvent.click(save); | ||
| await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith({ description: 'Login message saved.' })); | ||
| expect(mocks.save).toHaveBeenCalledWith(message); | ||
| expect(save.disabled).toBe(true); | ||
| }); | ||
|
|
||
| test('previews the draft with the same rendered links used on the login page', () => { | ||
| render(<LoginMessageSettingsCard loginMessage={null} />); | ||
| fireEvent.change(screen.getByRole('textbox'), { target: { value: '[Request access](https://example.com/access)' } }); | ||
| fireEvent.keyDown(screen.getByRole('tab', { name: 'Preview' }), { key: 'Enter' }); | ||
| expect(screen.getByRole('link', { name: 'Request access' }).getAttribute('href')).toBe('https://example.com/access'); | ||
| expect(mocks.save).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| test('clearing a saved message sends null', async () => { | ||
| render(<LoginMessageSettingsCard loginMessage="Old message" />); | ||
| fireEvent.change(screen.getByRole('textbox'), { target: { value: ' \n ' } }); | ||
| fireEvent.click(screen.getByRole('button', { name: 'Save changes' })); | ||
| await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith({ description: 'Login message removed.' })); | ||
| expect(mocks.save).toHaveBeenCalledWith(null); | ||
| expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(''); | ||
| }); | ||
|
|
||
| test('preserves the draft and permits retrying after a failed save', async () => { | ||
| mocks.save.mockResolvedValueOnce({ errorCode: 'UNEXPECTED_ERROR', statusCode: 500, message: 'Could not save' }); | ||
| render(<LoginMessageSettingsCard loginMessage={null} />); | ||
| fireEvent.change(screen.getByRole('textbox'), { target: { value: 'New message' } }); | ||
| fireEvent.click(screen.getByRole('button', { name: 'Save changes' })); | ||
| await waitFor(() => expect(screen.getByRole('alert').textContent).toBe('Could not save')); | ||
| expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe('New message'); | ||
| expect(mocks.toast).not.toHaveBeenCalled(); | ||
| fireEvent.click(screen.getByRole('button', { name: 'Save changes' })); | ||
| await waitFor(() => expect(mocks.toast).toHaveBeenCalledWith({ description: 'Login message saved.' })); | ||
| }); | ||
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,84 @@ | ||||||
| "use client"; | ||||||
|
|
||||||
| import { useId, useState } from "react"; | ||||||
| import { SettingsCard } from "../../components/settingsCard"; | ||||||
| import { setLoginMessage } from "../actions"; | ||||||
| import { Textarea } from "@/components/ui/textarea"; | ||||||
| import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; | ||||||
| import { LoadingButton } from "@/components/ui/loading-button"; | ||||||
| import { useToast } from "@/components/hooks/use-toast"; | ||||||
| import { isServiceError } from "@/lib/utils"; | ||||||
| import { LoginMessage } from "@/features/auth/components/loginMessage"; | ||||||
| import { LOGIN_MESSAGE_MAX_LENGTH } from "@/features/auth/constants"; | ||||||
|
|
||||||
| export function LoginMessageSettingsCard({ loginMessage }: { loginMessage: string | null }) { | ||||||
| const [draft, setDraft] = useState(loginMessage ?? ""); | ||||||
| const [savedMessage, setSavedMessage] = useState(loginMessage ?? ""); | ||||||
| const [isSaving, setIsSaving] = useState(false); | ||||||
| const [error, setError] = useState<string | null>(null); | ||||||
| const id = useId(); | ||||||
| const { toast } = useToast(); | ||||||
| const message = draft.trim() ? draft : ""; | ||||||
|
|
||||||
| const handleSave = async () => { | ||||||
| setIsSaving(true); | ||||||
| setError(null); | ||||||
| try { | ||||||
| const result = await setLoginMessage(message || null); | ||||||
| if (isServiceError(result)) { | ||||||
| setError(result.message); | ||||||
| return; | ||||||
| } | ||||||
| setSavedMessage(message); | ||||||
| setDraft(message); | ||||||
| toast({ description: message ? "Login message saved." : "Login message removed." }); | ||||||
| } catch { | ||||||
| setError("Failed to save the login message. Please try again."); | ||||||
| } finally { | ||||||
| setIsSaving(false); | ||||||
| } | ||||||
| }; | ||||||
|
|
||||||
| return ( | ||||||
| <SettingsCard> | ||||||
| <Tabs defaultValue="write"> | ||||||
| <TabsList aria-label="Login message editor"> | ||||||
| <TabsTrigger value="write">Write</TabsTrigger> | ||||||
| <TabsTrigger value="preview">Preview</TabsTrigger> | ||||||
| </TabsList> | ||||||
| <TabsContent value="write"> | ||||||
| <label htmlFor={id} className="sr-only">Login message</label> | ||||||
| <Textarea | ||||||
| id={id} | ||||||
| aria-describedby={`${id}-hint ${id}-count`} | ||||||
| value={draft} | ||||||
| onChange={(event) => { | ||||||
| setDraft(event.target.value); | ||||||
| setError(null); | ||||||
| }} | ||||||
| disabled={isSaving} | ||||||
| maxLength={LOGIN_MESSAGE_MAX_LENGTH} | ||||||
| rows={7} | ||||||
| className="font-mono text-sm" | ||||||
| placeholder="Need access? [Request access](https://example.com/access) before signing in." | ||||||
| /> | ||||||
| </TabsContent> | ||||||
| <TabsContent value="preview" className="min-h-40"> | ||||||
| {message ? <LoginMessage message={message} /> : ( | ||||||
| <p className="py-6 text-sm text-muted-foreground">No message will be shown.</p> | ||||||
| )} | ||||||
| </TabsContent> | ||||||
| </Tabs> | ||||||
| <div className="mt-3 flex items-start justify-between gap-4 text-xs text-muted-foreground"> | ||||||
| <p id={`${id}-hint`}>Use Markdown for formatting and links. Leave empty to hide the message.</p> | ||||||
| <span id={`${id}-count`} className="shrink-0">{draft.length.toLocaleString()} / {LOGIN_MESSAGE_MAX_LENGTH.toLocaleString()}</span> | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P3: When an admin uses a non-English browser, this locale-dependent count can differ from the server-rendered text and trigger a hydration mismatch. Use a fixed locale for both values, consistent with the app's English document language. Prompt for AI agents
Suggested change
|
||||||
| </div> | ||||||
| {error && <p role="alert" className="mt-3 text-sm text-destructive">{error}</p>} | ||||||
| <div className="mt-4 flex justify-end"> | ||||||
| <LoadingButton onClick={handleSave} loading={isSaving} disabled={message === savedMessage || draft.length > LOGIN_MESSAGE_MAX_LENGTH}> | ||||||
| Save changes | ||||||
| </LoadingButton> | ||||||
| </div> | ||||||
| </SettingsCard> | ||||||
| ); | ||||||
| } | ||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| import { cleanup, render, screen } from '@testing-library/react'; | ||
| import { afterEach, expect, test, vi } from 'vitest'; | ||
|
|
||
| vi.mock('@/hooks/useCaptureEvent', () => ({ default: () => vi.fn() })); | ||
| vi.mock('@/features/auth/useIdentityProviders', () => ({ useIdentityProviders: () => [] })); | ||
| vi.mock('@/app/components/sourcebotLogo', () => ({ SourcebotLogo: () => null })); | ||
| vi.mock('@/app/components/authMethodSelector', () => ({ AuthMethodSelector: () => <div data-testid="sign-in-options">Sign-in options</div> })); | ||
| vi.mock('@/lib/utils', () => ({ cn: (...classes: unknown[]) => classes.filter(Boolean).join(' ') })); | ||
| const { LoginForm } = await import('./loginForm'); | ||
| afterEach(cleanup); | ||
|
|
||
| test.each(['login', 'signup'] as const)('shows the message above authentication options in %s', (context) => { | ||
| render(<LoginForm context={context} loginMessage="[Request access](https://example.com/access)" />); | ||
| const link = screen.getByRole('link', { name: 'Request access' }); | ||
| expect(link.compareDocumentPosition(screen.getByTestId('sign-in-options')) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); | ||
| }); | ||
|
|
||
| test('renders sign-in options when no message is configured', () => { | ||
| render(<LoginForm context="login" loginMessage={null} />); | ||
| expect(screen.getByTestId('sign-in-options')).toBeTruthy(); | ||
| expect(screen.queryByRole('link', { name: 'Request access' })).toBeNull(); | ||
| }); |
Uh oh!
There was an error while loading. Please reload this page.