Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added
- Added privacy-scoped setup wizard funnel and Docker startup-failure telemetry with deployment identity handoff, Node.js 20.20.0 support, and cross-platform end-to-end test coverage. [#1653](https://github.com/sourcebot-dev/sourcebot/pull/1653)
- Added an admin-configurable Markdown message with access instructions and links on sign-in and sign-up pages. [#1668](https://github.com/sourcebot-dev/sourcebot/pull/1668)

## [5.1.13] - 2026-09-12

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Org" ADD COLUMN "loginMessage" TEXT;
3 changes: 3 additions & 0 deletions packages/db/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,9 @@ model Org {
/// in shared/src/utils.ts
isEmailCodeLoginEnabled Boolean @default(false)

/// Markdown message displayed before sign-in; null means no message.
Comment thread
brendan-kellam marked this conversation as resolved.
Resolved
Comment thread
brendan-kellam marked this conversation as resolved.
Resolved
loginMessage String?
Comment thread
brendan-kellam marked this conversation as resolved.
Resolved

/// @deprecated This property can be overriden by the environment
/// variable `FORCE_ENABLE_ANONYMOUS_ACCESS`, as well as the org's
/// available entitlements. Use the helper function `isAnonymousAccessEnabled`
Expand Down
1 change: 1 addition & 0 deletions packages/web/src/__mocks__/prisma.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export const MOCK_ORG: Org = {
memberApprovalRequired: false,
isCredentialsLoginEnabled: true,
isEmailCodeLoginEnabled: false,
loginMessage: null,
isAnonymousAccessEnabled: false,
inviteLinkEnabled: false,
inviteLinkId: null,
Expand Down
93 changes: 93 additions & 0 deletions packages/web/src/app/(app)/settings/security/actions.test.ts
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);
});
});
27 changes: 26 additions & 1 deletion packages/web/src/app/(app)/settings/security/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The validation error hard-codes 5,000 while the limit comes from LOGIN_MESSAGE_MAX_LENGTH. Build the message from the constant so future limit changes remain accurate.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/web/src/app/(app)/settings/security/actions.ts, line 18:

<comment>The validation error hard-codes `5,000` while the limit comes from `LOGIN_MESSAGE_MAX_LENGTH`. Build the message from the constant so future limit changes remain accurate.</comment>

<file context>
@@ -4,13 +4,38 @@ import { getProviders } from "@/auth";
+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.")
+    .nullable()
+    .transform(message => message?.trim() ? message : null);
</file context>
Suggested change
.max(LOGIN_MESSAGE_MAX_LENGTH, "Login message must be 5,000 characters or fewer.")
.max(LOGIN_MESSAGE_MAX_LENGTH, `Login message must be ${LOGIN_MESSAGE_MAX_LENGTH.toLocaleString()} characters or fewer.`)

.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 }) =>
Expand Down
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,
Comment thread
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 () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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 draft.length > LOGIN_MESSAGE_MAX_LENGTH and renders 'Failed to save the login message. Please try again.' when setLoginMessage rejects, but no test exercises either; only the service-error { errorCode, ... } path is covered. Add a test that verifies the Save button stays disabled above 5,000 characters (count is user-visible) and one where the action rejects (mocks.save.mockRejectedValueOnce) asserting the catch branch's alert text.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/web/src/app/(app)/settings/security/components/loginMessageSettingsCard.test.tsx, line 18:

<comment>The character-limit and failure paths the PR explicitly highlights are untested. The component disables Save once `draft.length > LOGIN_MESSAGE_MAX_LENGTH` and renders `'Failed to save the login message. Please try again.'` when `setLoginMessage` rejects, but no test exercises either; only the service-error `{ errorCode, ... }` path is covered. Add a test that verifies the Save button stays disabled above 5,000 characters (count is user-visible) and one where the action rejects (mocks.save.mockRejectedValueOnce) asserting the catch branch's alert text.</comment>

<file context>
@@ -0,0 +1,58 @@
+});
+afterEach(cleanup);
+
+test('saves Markdown only after editing and marks a successful save as unchanged', async () => {
+    render(<LoginMessageSettingsCard loginMessage="Old message" />);
+    const save = screen.getByRole('button', { name: 'Save changes' }) as HTMLButtonElement;
</file context>

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>

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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
Check if this issue is valid — if so, understand the root cause and fix it. At packages/web/src/app/(app)/settings/security/components/loginMessageSettingsCard.tsx, line 74:

<comment>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.</comment>

<file context>
@@ -0,0 +1,84 @@
+            </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>
+            </div>
+            {error && <p role="alert" className="mt-3 text-sm text-destructive">{error}</p>}
</file context>
Suggested change
<span id={`${id}-count`} className="shrink-0">{draft.length.toLocaleString()} / {LOGIN_MESSAGE_MAX_LENGTH.toLocaleString()}</span>
<span id={`${id}-count`} className="shrink-0">{draft.length.toLocaleString("en-US")} / {LOGIN_MESSAGE_MAX_LENGTH.toLocaleString("en-US")}</span>

</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>
);
}
11 changes: 10 additions & 1 deletion packages/web/src/app/(app)/settings/security/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { IdentityProviderUpsellCard } from "./components/identityProviderUpsellC
import { ScimProvisioningSettings } from "./components/scimProvisioningSettings";
import { ScimEnabledSettingsCard } from "./components/scimEnabledSettingsCard";
import { ScimUpsellCard } from "./components/scimUpsellCard";
import { LoginMessageSettingsCard } from "./components/loginMessageSettingsCard";
import { getScimTokens } from "@/ee/features/scim/actions";
import { UpgradeBadge } from "@/app/(app)/@sidebar/components/upgradeBadge";
import { getProviders, IdentityProvider } from "@/auth";
Expand Down Expand Up @@ -154,6 +155,14 @@ export default authenticatedPage(async ({ org }) => {
)}
</>
)}

<section aria-labelledby="login-message-heading" className="space-y-4">
<div>
<h3 id="login-message-heading" className="text-md font-medium">Login message</h3>
<p className="text-sm text-muted-foreground">Show access instructions or a registration link on your sign-in and sign-up pages.</p>
</div>
<LoginMessageSettingsCard loginMessage={org.loginMessage} />
</section>
</div>
</div>
)
Expand All @@ -167,4 +176,4 @@ const getConfiguredIdentityProviders = async (): Promise<IdentityProvider[]> =>
return providers.filter((provider) =>
provider.purpose === "sso" && !["credentials", "nodemailer"].includes(provider.type)
);
}
}
4 changes: 2 additions & 2 deletions packages/web/src/app/login/components/credentialsForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export const CredentialsForm = ({ callbackUrl, context }: CredentialsFormProps)
control={form.control}
name="password"
render={({ field }) => (
<FormItem className="mb-8">
<FormItem className="mb-4">
<FormLabel>Password</FormLabel>
<FormControl>
<Input
Expand All @@ -93,4 +93,4 @@ export const CredentialsForm = ({ callbackUrl, context }: CredentialsFormProps)
</form>
</Form>
);
}
}
22 changes: 22 additions & 0 deletions packages/web/src/app/login/components/loginForm.test.tsx
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();
});
Loading
Loading