313 lines
13 KiB
JavaScript
313 lines
13 KiB
JavaScript
const MAX_DEPTH = 20;
|
|
const MAX_VALUES = 25_000;
|
|
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': [null, {
|
|
email: str(320), password: str(4096), displayName: str(80), imapHost: str(253), smtpHost: str(253),
|
|
authMethod: { type: 'enum', values: ['password', 'oauth2'] },
|
|
oauthProvider: { type: 'enum', values: ['google', 'microsoft'] },
|
|
reauthorizeOAuth: bool(),
|
|
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),
|
|
authMethod: { type: 'enum', values: ['password', 'oauth2'] },
|
|
oauthProvider: { type: 'enum', values: ['google', 'microsoft'] },
|
|
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': [],
|
|
'mail:list-accounts': [],
|
|
'mail:list-oauth-providers': [],
|
|
'mail:select-account': ['string'],
|
|
'mail:remove-account': ['string'],
|
|
'mail:update-account': ['string', 'object'],
|
|
'mail:connect': ['object'],
|
|
'mail:sync-folder': ['string', 'number?', 'object?'],
|
|
'mail:list-folders': [],
|
|
'mail:create-folder': ['object'],
|
|
'mail:list-drafts': [],
|
|
'mail:save-draft': ['object'],
|
|
'mail:delete-draft': ['string'],
|
|
'mail:set-snooze': ['object'],
|
|
'mail:update-message': ['object'],
|
|
'mail:save-attachment': ['object'],
|
|
'mail:preview-attachment': ['object'],
|
|
'mail:send': ['object'],
|
|
'mail:open-external': ['string'],
|
|
'mail:sync-inbox': [],
|
|
'mail:disconnect': ['string?'],
|
|
'pgp:list': [],
|
|
'pgp:generate': ['object'],
|
|
'pgp:import': ['object'],
|
|
'pgp:export-public': ['string'],
|
|
'pgp:export-private': ['string', 'string'],
|
|
'pgp:change-passphrase': ['object'],
|
|
'pgp:export-revocation': ['string', 'string'],
|
|
'pgp:delete': ['string', 'string'],
|
|
'pgp:decrypt-message': ['object'],
|
|
'pgp:check-send': ['object'],
|
|
'pgp:contacts': [],
|
|
'pgp:add-contact': ['object'],
|
|
'pgp:set-trust': ['string', 'string'],
|
|
'pgp:remove-contact': ['string'],
|
|
'pgp:export-contact': ['string'],
|
|
'pgp:get-settings': [],
|
|
'pgp:set-settings': ['object'],
|
|
'pgp:key-servers': [],
|
|
'pgp:set-key-server-enabled': ['object'],
|
|
'pgp:add-key-server': ['object'],
|
|
'pgp:remove-key-server': ['string'],
|
|
'pgp:find-key': ['object'],
|
|
'pgp:publish-key': ['object'],
|
|
'pgp:forget-passphrases': [],
|
|
'dav:list': [],
|
|
'dav:connect': ['object'],
|
|
'dav:activate': ['object'],
|
|
'dav:remove': ['object'],
|
|
'dav:sync': ['enum:caldav,carddav'],
|
|
'dav:save-event': ['object'],
|
|
'dav:delete-event': ['object'],
|
|
'dav:save-contact': ['object'],
|
|
'dav:delete-contact': ['object']
|
|
};
|
|
|
|
function isRecord(value) {
|
|
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
|
|
const prototype = Object.getPrototypeOf(value);
|
|
return prototype === Object.prototype || prototype === null;
|
|
}
|
|
|
|
function validateTree(value, channel) {
|
|
let values = 0;
|
|
const ancestors = new WeakSet();
|
|
|
|
function visit(current, depth, key = '') {
|
|
values += 1;
|
|
if (values > MAX_VALUES) throw new Error(`Too many values in IPC request for ${channel}.`);
|
|
if (depth > MAX_DEPTH) throw new Error(`IPC request for ${channel} is nested too deeply.`);
|
|
if (current === null || current === undefined || typeof current === 'boolean') return;
|
|
if (typeof current === 'number') {
|
|
if (!Number.isFinite(current)) throw new Error(`Invalid number in IPC request for ${channel}.`);
|
|
return;
|
|
}
|
|
if (typeof current === 'string') {
|
|
const limit = key === 'armoredKey' ? MAX_ARMORED_KEY_LENGTH :
|
|
['contentBase64', 'rawBase64'].includes(key) ? Infinity : MAX_STRING_LENGTH;
|
|
if (current.length > limit) throw new Error(`String value is too large in IPC request for ${channel}.`);
|
|
return;
|
|
}
|
|
if (typeof current !== 'object' || (!Array.isArray(current) && !isRecord(current))) {
|
|
throw new Error(`Unsupported value in IPC request for ${channel}.`);
|
|
}
|
|
if (ancestors.has(current)) throw new Error(`Cyclic value in IPC request for ${channel}.`);
|
|
ancestors.add(current);
|
|
if (Array.isArray(current)) {
|
|
if (current.length > MAX_COLLECTION_ITEMS) throw new Error(`Too many items in IPC request for ${channel}.`);
|
|
for (const item of current) visit(item, depth + 1);
|
|
} else {
|
|
const entries = Object.entries(current);
|
|
if (entries.length > MAX_COLLECTION_ITEMS) throw new Error(`Too many fields in IPC request for ${channel}.`);
|
|
for (const [childKey, child] of entries) {
|
|
if (['__proto__', 'prototype', 'constructor'].includes(childKey)) {
|
|
throw new Error(`Unsafe field in IPC request for ${channel}.`);
|
|
}
|
|
visit(child, depth + 1, childKey);
|
|
}
|
|
}
|
|
ancestors.delete(current);
|
|
}
|
|
|
|
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}.`);
|
|
if (!Array.isArray(args)) throw new TypeError('IPC arguments must be an array.');
|
|
const required = schema.filter(type => !type.endsWith('?')).length;
|
|
if (args.length < required || args.length > schema.length) {
|
|
throw new Error(`Invalid argument count for IPC channel ${channel}.`);
|
|
}
|
|
for (let index = 0; index < args.length; index += 1) {
|
|
const expected = schema[index].replace(/\?$/, '');
|
|
const value = args[index];
|
|
if (value === undefined && schema[index].endsWith('?')) continue;
|
|
const isEnum = expected.startsWith('enum:');
|
|
const typeIsValid = expected === 'object'
|
|
? isRecord(value)
|
|
: isEnum
|
|
? expected.slice('enum:'.length).split(',').includes(value)
|
|
: typeof value === expected;
|
|
if (!typeIsValid) {
|
|
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}.`);
|
|
}
|
|
}
|
|
|
|
function hasIpcSchema(channel) {
|
|
return Object.hasOwn(schemas, channel);
|
|
}
|
|
|
|
module.exports = { hasIpcSchema, validateIpcArguments };
|