fix(settings): validate git identity emails only on the request path

A stored identity email that failed the stricter rule made every settings
read fall back to defaults, and the next save persisted that reset.

- the stored preferences schema accepts any email string again
- PATCH /api/settings rejects an invalid gitIdentity or gitIdentities email
  with a field path, and saves the trimmed address
- the rule accepts local hosts such as root@localhost
This commit is contained in:
Chris Scott committed 2026-10-23 15:45:36 -04:00
1 parent d089dde466
commit 0c4c024dcc
4 files changed
+157 -17

No files matched your search

+31 -1
View File
@@ -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<string
return { output, timedOut: false }
}
const trimGitIdentityEmail = <T extends { email: string }>(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),
+71 -10
View File
@@ -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', '<agent>@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<string | number>; 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<string | number>; 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()
})
})
+53
View File
@@ -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' })
})
})
+2 -6
View File
@@ -124,12 +124,8 @@ export const GitCredentialSchema = z.object({
export type GitCredential = z.infer<typeof GitCredentialSchema>;
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<typeof GitIdentitySchema>;