diff --git a/backend/src/routes/settings.ts b/backend/src/routes/settings.ts index e9309fbb..3ba3af2c 100644 --- a/backend/src/routes/settings.ts +++ b/backend/src/routes/settings.ts @@ -12,6 +12,7 @@ import type { OpenCodeClient } from '../services/opencode/client' import { getAgentsMdPath } from '@opencode-manager/shared/config/env' import { UserPreferencesSchema, + isValidGitIdentityEmail, type SandboxPreferences, type UserPreferences, } from '../types/settings' @@ -299,9 +300,38 @@ function spawnWithTimeout(args: string[], timeoutMs: number, env?: Record(identity: T): T => ({ + ...identity, + email: identity.email.trim(), +}) + const UpdateSettingsSchema = z.object({ preferences: UserPreferencesSchema.partial(), -}) +}).superRefine(({ preferences }, ctx) => { + if (preferences.gitIdentity && !isValidGitIdentityEmail(preferences.gitIdentity.email)) { + ctx.addIssue({ + code: 'custom', + path: ['preferences', 'gitIdentity', 'email'], + message: 'Invalid email address', + }) + } + + preferences.gitIdentities?.forEach((identity, index) => { + if (!isValidGitIdentityEmail(identity.email)) { + ctx.addIssue({ + code: 'custom', + path: ['preferences', 'gitIdentities', index, 'email'], + message: 'Invalid email address', + }) + } + }) +}).transform(({ preferences }) => ({ + preferences: { + ...preferences, + ...(preferences.gitIdentity ? { gitIdentity: trimGitIdentityEmail(preferences.gitIdentity) } : {}), + ...(preferences.gitIdentities ? { gitIdentities: preferences.gitIdentities.map(trimGitIdentityEmail) } : {}), + }, +})) const CreateCustomCommandSchema = z.object({ name: z.string().min(1).max(255), diff --git a/backend/test/routes/settings.test.ts b/backend/test/routes/settings.test.ts index 38e05daa..66f87fc6 100644 --- a/backend/test/routes/settings.test.ts +++ b/backend/test/routes/settings.test.ts @@ -1555,7 +1555,7 @@ describe('Settings Routes - OpenCode Upgrade', () => { }) describe('PATCH / - git identity validation', () => { - it.each(['not-an-email', 'missing@tld', 'two words@example.com'])('rejects the email %s with 400', async (email) => { + it.each(['not-an-email', 'two words@example.com', '@example.com'])('rejects the email %s with 400', async (email) => { const res = await settingsApp.fetch(new Request('http://localhost/', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, @@ -1568,29 +1568,85 @@ describe('Settings Routes - OpenCode Upgrade', () => { expect(mockUpdateSettings).not.toHaveBeenCalled() }) - it('accepts an empty email and a valid email', async () => { + it('reports the rejected field path for the default identity email', async () => { + const res = await settingsApp.fetch(new Request('http://localhost/', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ preferences: { gitIdentity: { name: 'Agent', email: 'bad' } } }), + })) + const json = await res.json() as { details: Array<{ path: Array; message: string }> } + + expect(res.status).toBe(400) + expect(json.details).toContainEqual(expect.objectContaining({ + path: ['preferences', 'gitIdentity', 'email'], + message: 'Invalid email address', + })) + expect(mockUpdateSettings).not.toHaveBeenCalled() + }) + + it.each(['', 'agent@example.com', 'root@localhost', 'root@box'])('accepts the email %s', async (email) => { mockGetSettings.mockReturnValue({ preferences: { gitIdentity: { name: 'Agent', email: '' } }, updatedAt: 1, }) mockUpdateSettings.mockReturnValue({ - preferences: { gitIdentity: { name: 'Agent', email: 'agent@example.com' } }, + preferences: { gitIdentity: { name: 'Agent', email } }, updatedAt: 2, }) - const emptyRes = await settingsApp.fetch(new Request('http://localhost/', { + const res = await settingsApp.fetch(new Request('http://localhost/', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ preferences: { gitIdentity: { name: 'Agent', email: '' } } }), + body: JSON.stringify({ preferences: { gitIdentity: { name: 'Agent', email } } }), })) - expect(emptyRes.status).toBe(200) - const validRes = await settingsApp.fetch(new Request('http://localhost/', { + expect(res.status).toBe(200) + expect(mockUpdateSettings).toHaveBeenCalledWith({ gitIdentity: { name: 'Agent', email } }, 'default') + }) + + it('trims identity emails before saving', async () => { + mockGetSettings.mockReturnValue({ + preferences: { gitIdentity: { name: 'Agent', email: '' }, gitIdentities: [] }, + updatedAt: 1, + }) + mockUpdateSettings.mockReturnValue({ + preferences: { + gitIdentity: { name: 'Root', email: 'root@box' }, + gitIdentities: [{ id: 'work', name: 'Work', email: 'agent@example.com' }], + }, + updatedAt: 2, + }) + + const res = await settingsApp.fetch(new Request('http://localhost/', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ preferences: { gitIdentity: { name: 'Agent', email: 'agent@example.com' } } }), + body: JSON.stringify({ + preferences: { + gitIdentity: { name: 'Root', email: ' root@box ' }, + gitIdentities: [{ id: 'work', name: 'Work', email: ' agent@example.com ' }], + }, + }), })) - expect(validRes.status).toBe(200) + + expect(res.status).toBe(200) + expect(mockUpdateSettings).toHaveBeenCalledWith({ + gitIdentity: { name: 'Root', email: 'root@box' }, + gitIdentities: [{ id: 'work', name: 'Work', email: 'agent@example.com' }], + }, 'default') + }) + + it('passes preferences through unchanged when no identity fields are present', async () => { + mockGetSettings.mockReturnValue({ preferences: { theme: 'dark', mode: 'build' }, updatedAt: 1 }) + mockUpdateSettings.mockReturnValue({ preferences: { theme: 'light', mode: 'plan' }, updatedAt: 2 }) + + const res = await settingsApp.fetch(new Request('http://localhost/', { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ preferences: { theme: 'light', mode: 'plan' } }), + })) + + expect(res.status).toBe(200) + expect(mockUpdateSettings).toHaveBeenCalledWith({ theme: 'light', mode: 'plan' }, 'default') }) it('rejects an invalid email in a saved identity profile', async () => { @@ -1598,11 +1654,16 @@ describe('Settings Routes - OpenCode Upgrade', () => { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ - preferences: { gitIdentities: [{ id: 'a', name: 'Alpha', email: 'not-an-email' }] }, + preferences: { gitIdentities: [{ id: 'a', name: 'Alpha', email: 'bad' }] }, }), })) + const json = await res.json() as { details: Array<{ path: Array; message: string }> } expect(res.status).toBe(400) + expect(json.details).toContainEqual(expect.objectContaining({ + path: ['preferences', 'gitIdentities', 0, 'email'], + message: 'Invalid email address', + })) expect(mockUpdateSettings).not.toHaveBeenCalled() }) }) diff --git a/backend/test/services/settings.test.ts b/backend/test/services/settings.test.ts index ca25e2da..a3810d51 100644 --- a/backend/test/services/settings.test.ts +++ b/backend/test/services/settings.test.ts @@ -26,4 +26,57 @@ describe('SettingsService', () => { expect(settings.preferences.activityWindowMinutes).toBe(DEFAULT_ACTIVITY_WINDOW_MINUTES) expect(settings.preferences.autoScroll).toBe(false) }) + + it('reads a stored git identity email that the request pattern rejects', () => { + db.prepare( + `INSERT INTO user_preferences (user_id, preferences, updated_at) + VALUES (?, ?, ?)` + ).run( + 'default', + JSON.stringify({ mode: 'plan', gitIdentity: { name: 'Root', email: 'root@box' } }), + Date.now() + ) + + const settings = settingsService.getSettings() + + expect(settings.preferences.mode).toBe('plan') + expect(settings.preferences.gitIdentity).toEqual({ name: 'Root', email: 'root@box' }) + }) + + it('keeps a stored git identity and other preferences when an unrelated field is updated', () => { + db.prepare( + `INSERT INTO user_preferences (user_id, preferences, updated_at) + VALUES (?, ?, ?)` + ).run( + 'default', + JSON.stringify({ mode: 'plan', gitIdentity: { name: 'Root', email: 'root@box' } }), + Date.now() + ) + + const settings = settingsService.updateSettings({ theme: 'light' }) + + expect(settings.preferences.theme).toBe('light') + expect(settings.preferences.mode).toBe('plan') + expect(settings.preferences.gitIdentity).toEqual({ name: 'Root', email: 'root@box' }) + }) + + it('keeps a stored legacy identity email that no current pattern accepts', () => { + db.prepare( + `INSERT INTO user_preferences (user_id, preferences, updated_at) + VALUES (?, ?, ?)` + ).run( + 'default', + JSON.stringify({ mode: 'plan', gitIdentity: { name: 'Root', email: 'not an email' } }), + Date.now() + ) + + const settings = settingsService.getSettings() + const updated = settingsService.updateSettings({ autoScroll: false }) + + expect(settings.preferences.mode).toBe('plan') + expect(settings.preferences.gitIdentity).toEqual({ name: 'Root', email: 'not an email' }) + expect(updated.preferences.autoScroll).toBe(false) + expect(updated.preferences.mode).toBe('plan') + expect(updated.preferences.gitIdentity).toEqual({ name: 'Root', email: 'not an email' }) + }) }) diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index a23d64c0..e1ea3496 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -124,12 +124,8 @@ export const GitCredentialSchema = z.object({ export type GitCredential = z.infer; -const GIT_IDENTITY_EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; +const GIT_IDENTITY_EMAIL_PATTERN = /^[^\s@<>]+@[^\s@<>]+$/; -/** - * A git identity email is valid when it is blank or a plain `local@domain` address. Blank is allowed because the - * default identity starts without an email. - */ export function isValidGitIdentityEmail(email: string): boolean { const trimmed = email.trim(); return trimmed === "" || GIT_IDENTITY_EMAIL_PATTERN.test(trimmed); @@ -137,7 +133,7 @@ export function isValidGitIdentityEmail(email: string): boolean { export const GitIdentitySchema = z.object({ name: z.string(), - email: z.string().trim().refine(isValidGitIdentityEmail, "Invalid email address"), + email: z.string(), }); export type GitIdentity = z.infer;