Add OpenPGP public key server support
- Add VKS and HTTPS HKP lookup and publication with bounded, validated requests. - Add desktop key-server settings, lookup/import flow, and per-publication native confirmation. - Keep discovered keys untrusted and update architecture, encryption, and user documentation. - Add mocked server protocol and key-store tests. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,243 @@
|
||||
const openpgp = require('openpgp');
|
||||
|
||||
const MAX_KEY_LENGTH = 200000;
|
||||
const MAX_RESPONSE_BYTES = 600000;
|
||||
const REQUEST_TIMEOUT_MS = 15000;
|
||||
const MAX_CUSTOM_SERVERS = 10;
|
||||
|
||||
const BUILTIN_SERVERS = [
|
||||
{ id: 'openpgp-vks', name: 'keys.openpgp.org', url: 'https://keys.openpgp.org', protocol: 'vks', builtin: true },
|
||||
{ id: 'mailvelope-hkp', name: 'keys.mailvelope.com', url: 'https://keys.mailvelope.com', protocol: 'hkp', builtin: true }
|
||||
];
|
||||
|
||||
function normalizeBaseUrl(value) {
|
||||
const raw = String(value || '').trim();
|
||||
if (raw.length > 300) throw new Error('The key server URL is too long.');
|
||||
let url;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
throw new Error('Enter a valid HTTPS key server URL.');
|
||||
}
|
||||
if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
|
||||
throw new Error('Key server URLs must use HTTPS and cannot contain credentials, a query, or a fragment.');
|
||||
}
|
||||
url.pathname = `${url.pathname.replace(/\/+$/, '')}/`;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function normalizeCustomServer(input) {
|
||||
const name = String(input?.name || '').trim().slice(0, 60);
|
||||
const protocol = input?.protocol;
|
||||
if (!name) throw new Error('Enter a name for the key server.');
|
||||
if (!['hkp', 'vks'].includes(protocol)) throw new Error('Choose a supported HKP or VKS protocol.');
|
||||
return {
|
||||
id: String(input?.id || ''),
|
||||
name,
|
||||
url: normalizeBaseUrl(input?.url),
|
||||
protocol,
|
||||
builtin: false
|
||||
};
|
||||
}
|
||||
|
||||
function listServers(customServers = []) {
|
||||
return [
|
||||
...BUILTIN_SERVERS.map(server => ({ ...server })),
|
||||
...customServers.map(server => normalizeCustomServer(server))
|
||||
];
|
||||
}
|
||||
|
||||
function validateEmail(value) {
|
||||
const email = String(value || '').trim();
|
||||
if (!/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)) throw new Error('Enter a valid email address.');
|
||||
return email;
|
||||
}
|
||||
|
||||
function baseUrl(server) {
|
||||
return new URL(normalizeBaseUrl(server.url));
|
||||
}
|
||||
|
||||
function endpoint(server, path) {
|
||||
return new URL(path, baseUrl(server));
|
||||
}
|
||||
|
||||
async function readResponseText(response) {
|
||||
const declaredLength = Number(response.headers?.get?.('content-length') || 0);
|
||||
if (declaredLength > MAX_RESPONSE_BYTES) throw new Error('The key server response is too large.');
|
||||
if (!response.body) return '';
|
||||
const chunks = [];
|
||||
let length = 0;
|
||||
for await (const chunk of response.body) {
|
||||
const bytes = Buffer.from(chunk);
|
||||
length += bytes.length;
|
||||
if (length > MAX_RESPONSE_BYTES) {
|
||||
throw new Error('The key server response is too large.');
|
||||
}
|
||||
chunks.push(bytes);
|
||||
}
|
||||
return Buffer.concat(chunks, length).toString('utf8');
|
||||
}
|
||||
|
||||
function createKeyServerService({ fetchImpl = globalThis.fetch } = {}) {
|
||||
if (typeof fetchImpl !== 'function') throw new Error('Fetch is unavailable for key server requests.');
|
||||
|
||||
async function request(server, url, options = {}) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetchImpl(url, {
|
||||
...options,
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
||||
});
|
||||
} catch (error) {
|
||||
throw new Error(`Could not reach ${server.name}: ${error.message}`);
|
||||
}
|
||||
const text = await readResponseText(response);
|
||||
return { response, text };
|
||||
}
|
||||
|
||||
async function parsePublicKeys(armored, email) {
|
||||
if (typeof armored !== 'string' || armored.length > MAX_RESPONSE_BYTES) {
|
||||
throw new Error('The key server returned an invalid or oversized key response.');
|
||||
}
|
||||
const blocks = armored.match(/-----BEGIN PGP PUBLIC KEY BLOCK-----[\s\S]*?-----END PGP PUBLIC KEY BLOCK-----/g) || [];
|
||||
if (!blocks.length) {
|
||||
if (!armored.trim() || /no (matching )?keys|no results/i.test(armored)) return [];
|
||||
throw new Error('The key server response did not contain an OpenPGP public key.');
|
||||
}
|
||||
if (blocks.length > 10) throw new Error('The key server returned too many keys.');
|
||||
const keys = [];
|
||||
const seen = new Set();
|
||||
let validKeyCount = 0;
|
||||
for (const block of blocks) {
|
||||
if (block.length > MAX_KEY_LENGTH) continue;
|
||||
const key = await openpgp.readKey({ armoredKey: block }).catch(() => null);
|
||||
if (!key) continue;
|
||||
const fingerprint = key.getFingerprint().toUpperCase();
|
||||
if (seen.has(fingerprint)) continue;
|
||||
seen.add(fingerprint);
|
||||
const emails = [...new Set(key.getUserIDs()
|
||||
.map(id => (/<([^>]+)>/.exec(id)?.[1] || (id.includes('@') ? id : '')).trim().toLowerCase())
|
||||
.filter(Boolean))];
|
||||
const primary = await key.getPrimaryUser().catch(() => null);
|
||||
if (!primary) continue;
|
||||
validKeyCount += 1;
|
||||
if (email && !emails.includes(email.toLowerCase())) continue;
|
||||
keys.push({
|
||||
fingerprint,
|
||||
name: primary.user.userID?.name || '',
|
||||
emails,
|
||||
armoredKey: key.armor()
|
||||
});
|
||||
}
|
||||
if (!validKeyCount) throw new Error('The key server returned no valid public keys.');
|
||||
return keys;
|
||||
}
|
||||
|
||||
async function lookup(serverInput, emailInput) {
|
||||
const server = normalizeCustomServer(serverInput);
|
||||
const email = validateEmail(emailInput);
|
||||
let url;
|
||||
if (server.protocol === 'vks') {
|
||||
url = endpoint(server, `vks/v1/by-email/${encodeURIComponent(email)}`);
|
||||
} else {
|
||||
url = endpoint(server, 'pks/lookup');
|
||||
url.searchParams.set('op', 'get');
|
||||
url.searchParams.set('search', email);
|
||||
}
|
||||
const { response, text } = await request(server, url);
|
||||
if (response.status === 404) return [];
|
||||
if (!response.ok) throw new Error(`${server.name} returned HTTP ${response.status}.`);
|
||||
let armored = text;
|
||||
if (server.protocol === 'hkp' && /^\s*\{/.test(text)) {
|
||||
try {
|
||||
const data = JSON.parse(text);
|
||||
armored = data.publicKeyArmored || '';
|
||||
} catch {
|
||||
throw new Error(`${server.name} returned an invalid key response.`);
|
||||
}
|
||||
}
|
||||
return parsePublicKeys(armored, email);
|
||||
}
|
||||
|
||||
async function publishVks(server, email, armoredKey, expectedFingerprint) {
|
||||
const { response, text } = await request(server, endpoint(server, 'vks/v1/upload'), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
||||
body: JSON.stringify({ keytext: armoredKey })
|
||||
});
|
||||
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
|
||||
let result;
|
||||
try { result = JSON.parse(text); } catch { throw new Error(`${server.name} returned an invalid upload response.`); }
|
||||
if (String(result.key_fpr || '').toUpperCase() !== expectedFingerprint || !result.token || !result.status || typeof result.status !== 'object') {
|
||||
throw new Error(`${server.name} returned an incomplete or mismatched upload response.`);
|
||||
}
|
||||
const addressStatus = Object.entries(result.status).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
|
||||
if (addressStatus === 'published') return { uploaded: true, verification: 'published' };
|
||||
if (addressStatus === 'pending') return { uploaded: true, verification: 'pending' };
|
||||
if (addressStatus !== 'unpublished') {
|
||||
return { uploaded: true, verification: addressStatus || 'unknown' };
|
||||
}
|
||||
try {
|
||||
const verify = await request(server, endpoint(server, 'vks/v1/request-verify'), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
||||
body: JSON.stringify({ token: result.token, addresses: [email] })
|
||||
});
|
||||
if (!verify.response.ok) throw new Error(`HTTP ${verify.response.status}`);
|
||||
let verified;
|
||||
try { verified = JSON.parse(verify.text); } catch { throw new Error('invalid verification response'); }
|
||||
if (String(verified.key_fpr || '').toUpperCase() !== expectedFingerprint || !verified.status || typeof verified.status !== 'object') {
|
||||
throw new Error('verification response did not match the uploaded key');
|
||||
}
|
||||
const state = Object.entries(verified.status || {}).find(([address]) => address.toLowerCase() === email.toLowerCase())?.[1];
|
||||
return { uploaded: true, verification: state || 'requested' };
|
||||
} catch (error) {
|
||||
return { uploaded: true, verification: 'request-failed', warning: `The key was uploaded, but email verification could not be requested: ${error.message}` };
|
||||
}
|
||||
}
|
||||
|
||||
async function publishHkp(server, armoredKey) {
|
||||
const form = new URLSearchParams({ keytext: armoredKey });
|
||||
const { response, text } = await request(server, endpoint(server, 'pks/add'), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: form.toString()
|
||||
});
|
||||
if (!response.ok) throw new Error(`${server.name} rejected the key upload (HTTP ${response.status}).`);
|
||||
if (!/upload successful|successfully added|key added/i.test(text)) {
|
||||
throw new Error(`${server.name} did not confirm the key upload: ${text.trim().slice(0, 300) || 'empty response'}`);
|
||||
}
|
||||
return {
|
||||
uploaded: true,
|
||||
verification: server.id === 'mailvelope-hkp' ? 'check-email' : 'server-accepted',
|
||||
message: text.trim().slice(0, 500)
|
||||
};
|
||||
}
|
||||
|
||||
async function publish(serverInput, emailInput, armoredInput, expectedFingerprint) {
|
||||
const server = normalizeCustomServer(serverInput);
|
||||
const email = validateEmail(emailInput);
|
||||
const armoredKey = String(armoredInput || '').trim();
|
||||
if (!armoredKey || armoredKey.length > MAX_KEY_LENGTH || /BEGIN PGP PRIVATE KEY BLOCK/.test(armoredKey)) {
|
||||
throw new Error('Only a valid public key can be published.');
|
||||
}
|
||||
const keys = await parsePublicKeys(armoredKey, email);
|
||||
if (keys.length !== 1 || keys[0].fingerprint !== String(expectedFingerprint || '').toUpperCase()) {
|
||||
throw new Error('The selected public key does not match the key and email being published.');
|
||||
}
|
||||
if (server.protocol === 'vks') return publishVks(server, email, keys[0].armoredKey, keys[0].fingerprint);
|
||||
return publishHkp(server, keys[0].armoredKey);
|
||||
}
|
||||
|
||||
return { lookup, publish };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
BUILTIN_SERVERS,
|
||||
MAX_CUSTOM_SERVERS,
|
||||
createKeyServerService,
|
||||
listServers,
|
||||
normalizeBaseUrl,
|
||||
normalizeCustomServer
|
||||
};
|
||||
Reference in New Issue
Block a user