Refractoring Stage 5 Completed channel-specific IPC validation

This commit is contained in:
2026-10-16 17:26:51 +03:00
parent 88a8729f4f
commit 928e6dd62a
6 changed files with 205 additions and 6 deletions
+2 -2
View File
@@ -88,7 +88,7 @@ This is a gradual destination, not a requirement to move everything at once. IPC
- [x] Restrict navigation to the exact app document URL; reject arbitrary `file:` navigation.
- [x] Validate channel names, argument counts/types, and nested payload complexity (`desktop/security/ipc-arguments.cjs`).
- [x] Bind DAV object updates/deletes to the selected account, server collection, server-returned resource, and current ETag (`desktop/dav/remote-reference.cjs`).
- [ ] Finish channel-specific validation for remaining nested fields and sensitive values.
- [x] Validate channel-specific fields and limits; reject renderer-supplied raw SMTP payload fields.
- [ ] Register handlers by feature and keep `preload.cjs` as the narrow renderer API.
- [ ] Return deliberate DTOs rather than internal store objects.
@@ -130,5 +130,5 @@ This is a gradual destination, not a requirement to move everything at once. IPC
- Step 5 also aligned `will-navigate` with the same exact-document policy; `npm test` passes 96 tests.
- Step 5 added request schemas for all 54 registered channels, plus depth/collection/string bounds. Base64 attachment payloads remain uncapped to preserve the existing no-total-size-cap behavior.
- Step 5 also binds DAV updates/deletes to the configured account, same-origin collection, a server-listed resource, and a current ETag; DAV IDs are constrained against line injection and path traversal.
- The current IPC/DAV validation changes pass the full suite: 106 tests.
- The current IPC/DAV validation changes pass the full suite: 108 tests.
- While work continued, `package.json` and `package-lock.json` reflected a version bump to `0.4.6`; those changes were preserved.
+9 -1
View File
@@ -983,7 +983,15 @@ registerIpcHandler('mail:send', async (event, message) => {
const account = await readAccount();
if (!account) throw new Error('Add a mail account before sending.');
const pgpOptions = message?.pgp && (message.pgp.encrypt || message.pgp.sign) ? message.pgp : null;
const queuedMessage = { ...message, messageId: message?.messageId || `<${randomUUID()}@ep-mail.local>` };
const queuedMessage = {
to: message.to,
cc: message.cc,
subject: message.subject,
text: message.text,
displayName: message.displayName,
messageId: message.messageId || `<${randomUUID()}@ep-mail.local>`,
attachments: message.attachments
};
const attachments = normalizeOutgoingAttachments(message?.attachments);
queuedMessage.attachments = serializeOutgoingAttachments(attachments);
delete queuedMessage.pgp;
+164
View File
@@ -4,6 +4,114 @@ const MAX_COLLECTION_ITEMS = 5_000;
const MAX_STRING_LENGTH = 1_000_000;
const MAX_ARMORED_KEY_LENGTH = 200_000;
const str = (max = MAX_STRING_LENGTH, options = {}) => ({ type: 'string', max, ...options });
const num = options => ({ type: 'number', ...options });
const bool = () => ({ type: 'boolean' });
const record = (fields, options = {}) => ({ type: 'object', fields, ...options });
const array = (item, maxItems = MAX_COLLECTION_ITEMS) => ({ type: 'array', item, maxItems });
const attachmentFields = {
filename: str(255),
contentType: str(200),
contentBase64: str(Infinity, { required: true })
};
const ruleFields = {
id: str(100),
senderContains: str(200),
subjectContains: str(200),
action: { type: 'enum', values: ['archive', 'move', 'label', 'flag'] },
value: str(200)
};
const davRemoteFields = {
accountId: str(256),
collectionUrl: str(4096),
objectUrl: str(4096),
etag: str(1024, { nullable: true }),
uid: str(255, { nullable: true })
};
const objectFieldSchemas = {
'mail:update-account': [{
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
signature: str(5000), notificationsEnabled: bool(), syncIntervalMinutes: num(),
rules: array(record(ruleFields), 50)
}],
'mail:connect': [{
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
signature: str(5000), notificationsEnabled: bool(), syncIntervalMinutes: num(),
rules: array(record(ruleFields), 50)
}],
'mail:sync-folder': [null, null, {
folder: str(256), query: str(2000), sender: str(1000), subject: str(1000),
after: str(20), before: str(20), hasAttachments: bool()
}],
'mail:create-folder': [{ name: str(100) }],
'mail:save-draft': [{
id: str(256), to: str(4000), cc: str(4000), subject: str(998), text: str(500_000),
attachments: array(record(attachmentFields))
}],
'mail:set-snooze': [{
uid: num({ integer: true, min: 1 }), folder: str(256), sourceFolder: str(256),
dueAt: num({ nullable: true }), subject: str(200)
}],
'mail:update-message': [{
uid: num({ integer: true, min: 1 }), folder: str(256),
action: { type: 'enum', values: ['star', 'unread', 'archive', 'delete', 'inbox'] }, enabled: bool()
}],
'mail:save-attachment': [{ uid: num({ integer: true, min: 1 }), folder: str(256), filename: str(1000) }],
'mail:preview-attachment': [{ uid: num({ integer: true, min: 1 }), folder: str(256), filename: str(1000) }],
'mail:send': [{
to: str(4000), cc: str(4000), subject: str(998), text: str(500_000), displayName: str(80),
messageId: str(998), attachments: array(record(attachmentFields)),
pgp: record({ encrypt: bool(), sign: bool(), passphrase: str(4096, { nullable: true }) }, { nullable: true })
}],
'pgp:generate': [{ name: str(200), email: str(320), passphrase: str(4096), accountId: str(256, { nullable: true }) }],
'pgp:import': [{ armoredKey: str(MAX_ARMORED_KEY_LENGTH), passphrase: str(4096), accountId: str(256, { nullable: true }) }],
'pgp:change-passphrase': [{ fingerprint: str(64), currentPassphrase: str(4096), newPassphrase: str(4096) }],
'pgp:decrypt-message': [{ folder: str(256), uid: num({ integer: true, min: 1 }), passphrase: str(4096, { nullable: true }) }],
'pgp:check-send': [{ to: str(4000), cc: str(4000), sign: bool() }],
'pgp:add-contact': [{ armoredKey: str(MAX_ARMORED_KEY_LENGTH), passphrase: str(4096), source: { type: 'enum', values: ['import', 'message', 'paste', 'keyserver'] } }],
'pgp:set-settings': [{ cacheMinutes: num({ min: 0, max: 1440 }) }],
'pgp:set-key-server-enabled': [{ serverId: str(256), enabled: bool() }],
'pgp:add-key-server': [{ name: str(60), url: str(300), protocol: { type: 'enum', values: ['hkp', 'vks'] } }],
'pgp:find-key': [{ email: str(320) }],
'pgp:publish-key': [{ fingerprint: str(64), serverId: str(256) }],
'dav:connect': [{ type: { type: 'enum', values: ['caldav', 'carddav'] }, serverUrl: str(2048), username: str(1024), password: str(4096) }],
'dav:activate': [{ type: { type: 'enum', values: ['caldav', 'carddav'] }, id: str(256) }],
'dav:remove': [{ type: { type: 'enum', values: ['caldav', 'carddav'] }, id: str(256) }],
'dav:save-event': [{
title: str(120), date: str(20), time: str(20), with: str(4000), place: str(1000), notes: str(5000),
_dav: record(davRemoteFields, { nullable: true })
}],
'dav:delete-event': [davRemoteFields],
'dav:save-contact': [{
name: str(100), email: str(320), note: str(5000),
_dav: record(davRemoteFields, { nullable: true })
}],
'dav:delete-contact': [davRemoteFields]
};
const positionalEnums = {
'pgp:set-trust': { 1: ['unknown', 'trusted', 'verified'] }
};
const positionalFieldSchemas = {
'mail:select-account': { 0: str(256) },
'mail:remove-account': { 0: str(256) },
'mail:delete-draft': { 0: str(256) },
'mail:disconnect': { 0: str(256) },
'mail:open-external': { 0: str(2048) },
'pgp:export-public': { 0: str(64) },
'pgp:export-private': { 0: str(64), 1: str(4096) },
'pgp:export-revocation': { 0: str(64), 1: str(4096) },
'pgp:delete': { 0: str(64), 1: str(4096) },
'pgp:set-trust': { 0: str(64) },
'pgp:remove-contact': { 0: str(64) },
'pgp:export-contact': { 0: str(64) },
'pgp:remove-key-server': { 0: str(256) }
};
const sendMessageFields = new Set(['to', 'cc', 'subject', 'text', 'displayName', 'messageId', 'attachments', 'pgp']);
const schemas = {
'app:get-version': [],
'mail:get-account': [],
@@ -110,6 +218,52 @@ function validateTree(value, channel) {
visit(value, 0);
}
function validateField(value, field, channel, fieldPath) {
if (value === undefined) {
if (field.required) throw new Error(`Missing ${fieldPath} in IPC request for ${channel}.`);
return;
}
if (value === null && field.nullable) return;
if (field.type === 'string') {
if (typeof value !== 'string') throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
if (value.length > field.max) throw new Error(`The ${fieldPath} value is too large in IPC request for ${channel}.`);
return;
}
if (field.type === 'number') {
if (typeof value !== 'number' || !Number.isFinite(value) ||
(field.integer && !Number.isInteger(value)) ||
(field.min !== undefined && value < field.min) ||
(field.max !== undefined && value > field.max)) {
throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
}
return;
}
if (field.type === 'boolean') {
if (typeof value !== 'boolean') throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
return;
}
if (field.type === 'enum') {
if (!field.values.includes(value)) throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
return;
}
if (field.type === 'array') {
if (!Array.isArray(value) || value.length > field.maxItems) {
throw new Error(`Invalid ${fieldPath} list in IPC request for ${channel}.`);
}
value.forEach((item, index) => validateField(item, field.item, channel, `${fieldPath}[${index}]`));
return;
}
if (field.type === 'object') {
if (!isRecord(value)) throw new Error(`Invalid ${fieldPath} in IPC request for ${channel}.`);
for (const [name, childField] of Object.entries(field.fields || {})) {
validateField(value[name], childField, channel, `${fieldPath}.${name}`);
}
return;
}
throw new Error(`Unsupported validation rule for ${channel}.${fieldPath}.`);
}
function validateIpcArguments(channel, args) {
const schema = schemas[channel];
if (!schema) throw new Error(`Unknown IPC channel: ${channel}.`);
@@ -132,6 +286,16 @@ function validateIpcArguments(channel, args) {
throw new Error(`Invalid ${expected} argument ${index + 1} for IPC channel ${channel}.`);
}
validateTree(value, channel);
const fieldSchema = objectFieldSchemas[channel]?.[index];
if (fieldSchema) validateField(value, { type: 'object', fields: fieldSchema }, channel, `argument ${index + 1}`);
const enumValues = positionalEnums[channel]?.[index];
if (enumValues && !enumValues.includes(value)) throw new Error(`Invalid argument ${index + 1} for IPC channel ${channel}.`);
const positionalField = positionalFieldSchemas[channel]?.[index];
if (positionalField) validateField(value, positionalField, channel, `argument ${index + 1}`);
}
if (channel === 'mail:send') {
const unknown = Object.keys(args[0]).find(key => !sendMessageFields.has(key));
if (unknown) throw new Error(`Unsupported message field for IPC channel ${channel}.`);
}
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "ep-mail",
"version": "0.4.8",
"version": "0.4.10",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "ep-mail",
"version": "0.4.8",
"version": "0.4.10",
"dependencies": {
"@capacitor/android": "^8.5.2",
"@capacitor/core": "^8.5.2",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "ep-mail",
"version": "0.4.8",
"version": "0.4.10",
"private": true,
"description": "Eternity Project mail client",
"homepage": "https://git.eternityproject.fi/thuttu/ep-mail-client",
+27
View File
@@ -16,6 +16,8 @@ test('validates supported IPC channels and their positional argument types', ()
assert.throws(() => validateIpcArguments('mail:list-accounts', ['unexpected']), /Invalid argument count/);
assert.doesNotThrow(() => validateIpcArguments('dav:sync', ['carddav']));
assert.throws(() => validateIpcArguments('dav:sync', ['contacts']), /Invalid enum/);
assert.throws(() => validateIpcArguments('mail:open-external', [`https://example.test/${'x'.repeat(2048)}`]), /too large/);
assert.throws(() => validateIpcArguments('pgp:export-public', ['A'.repeat(65)]), /too large/);
assert.throws(() => validateIpcArguments('unknown:channel', []), /Unknown IPC channel/);
});
@@ -42,6 +44,31 @@ test('rejects non-finite numbers, cycles, and prototype-sensitive fields', () =>
assert.throws(() => validateIpcArguments('mail:save-draft', [unsafe]), /Unsafe field/);
});
test('validates channel-specific field shapes, limits, and enums', () => {
assert.doesNotThrow(() => validateIpcArguments('mail:connect', [{
email: 'user@example.test', password: 'secret', displayName: 'User',
imapHost: 'imap.example.test', smtpHost: 'smtp.example.test',
rules: [{ senderContains: 'alerts', action: 'flag', value: '' }]
}]));
assert.throws(() => validateIpcArguments('mail:connect', [{ rules: Array(51).fill({ action: 'flag' }) }]), /Invalid argument 1/);
assert.throws(() => validateIpcArguments('mail:update-message', [{ uid: '4', action: 'star' }]), /uid/);
assert.throws(() => validateIpcArguments('mail:update-message', [{ uid: 4, action: 'delete-anything' }]), /action/);
assert.throws(() => validateIpcArguments('pgp:add-key-server', [{ name: 'Keys', url: 'https://keys.example.test', protocol: 'ftp' }]), /protocol/);
assert.throws(() => validateIpcArguments('dav:save-event', [{ title: 'Event', _dav: { etag: 42 } }]), /_dav.etag/);
});
test('prevents renderer-supplied raw SMTP messages while accepting standard compose fields', () => {
assert.doesNotThrow(() => validateIpcArguments('mail:send', [{
to: 'friend@example.test', cc: '', subject: 'Hello', text: 'Body',
attachments: [{ filename: 'note.txt', contentBase64: 'aGVsbG8=' }],
pgp: { encrypt: true, sign: false, passphrase: null }
}]));
assert.doesNotThrow(() => validateIpcArguments('pgp:decrypt-message', [{ folder: 'Inbox', uid: 4, passphrase: null }]));
assert.throws(() => validateIpcArguments('mail:send', [{ rawBase64: 'YWJj', envelope: { to: ['victim@example.test'] } }]), /Unsupported message field/);
assert.throws(() => validateIpcArguments('mail:send', [{ pgp: { encrypt: 'true' } }]), /pgp.encrypt/);
assert.throws(() => validateIpcArguments('mail:send', [{ attachments: [{ contentBase64: 123 }] }]), /contentBase64/);
});
test('every registered main-process IPC handler has a request schema', () => {
const mainPath = path.resolve(__dirname, '..', 'desktop', 'main.cjs');
const source = fs.readFileSync(mainPath, 'utf8');