Files

291 lines
7.6 KiB
JavaScript

import forge from 'node-forge';
// Discourse user-api-key authorization. This is not OAuth2: the client sends a
// public key, the user approves on the forum, and Discourse redirects back with
// an RSA-encrypted payload.
export const DISCOURSE_AUTH_SCOPES = 'notifications,session_info';
export function normalizeDiscourseUrl(input) {
let url = (input ?? '').trim();
if (!url) {
return null;
}
if (!url.startsWith('http://') && !url.startsWith('https://')) {
url = 'https://' + url;
}
return url;
}
// Selects the pending Discourse integration that the authorization payload
// belongs to. `decrypt(candidate)` should return the decrypted payload object
// for that candidate or throw if the candidate's key cannot decrypt it.
//
// Matching on the nonce (echoed back inside the encrypted payload) prevents a
// key from being stored against the wrong forum when several authorizations
// are pending at once.
export function selectDecryptedIntegration(candidates, decrypt) {
for (const candidate of candidates) {
let apiData;
try {
apiData = decrypt(candidate);
} catch {
continue;
}
if (!apiData?.key) {
continue;
}
if (
apiData.nonce &&
candidate.data?.nonce &&
apiData.nonce !== candidate.data.nonce
) {
continue;
}
return { candidate, apiData };
}
return null;
}
function generateKeyPair() {
return window.crypto.subtle.generateKey(
{
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: 'SHA-256',
},
true,
['encrypt', 'decrypt']
);
}
async function exportPublicKeyToPem(publicKey) {
const exported = await window.crypto.subtle.exportKey('spki', publicKey);
const base64 = btoa(String.fromCharCode(...new Uint8Array(exported)));
return `-----BEGIN PUBLIC KEY-----\n${base64.match(/.{1,64}/g).join('\n')}\n-----END PUBLIC KEY-----`;
}
async function publicKeyPemFromPrivateKey(privateKeyBase64) {
const privateKeyData = Uint8Array.from(atob(privateKeyBase64), (char) =>
char.charCodeAt(0)
);
const privateKey = await window.crypto.subtle.importKey(
'pkcs8',
privateKeyData,
{ name: 'RSA-OAEP', hash: 'SHA-1' },
true,
['decrypt']
);
const jwk = await window.crypto.subtle.exportKey('jwk', privateKey);
const publicKey = await window.crypto.subtle.importKey(
'jwk',
{ kty: jwk.kty, n: jwk.n, e: jwk.e },
{ name: 'RSA-OAEP', hash: 'SHA-1' },
true,
['encrypt']
);
return exportPublicKeyToPem(publicKey);
}
async function findPendingIntegration(storage, origin) {
const keys = await storage.keys('integrations');
const records = await Promise.all(
keys
.filter((key) => key.startsWith('discourse-'))
.map(async (key) => ({
key,
data: await storage.get('integrations', key),
}))
);
return records.find(
({ data }) => data && data.status === 'pending' && data.url === origin
);
}
async function storePendingIntegration(
storage,
{ clientId, origin, privateKey, nonce, redirectUrl }
) {
const exportedPrivateKey = await window.crypto.subtle.exportKey(
'pkcs8',
privateKey
);
const privateKeyBase64 = btoa(
String.fromCharCode(...new Uint8Array(exportedPrivateKey))
);
await storage.set('integrations', `discourse-${clientId}`, {
type: 'discourse',
status: 'pending',
clientId,
nonce,
url: origin,
redirectUrl,
privateKey: privateKeyBase64,
createdAt: Date.now(),
});
}
async function discourseIntegrations(storage) {
const keys = await storage.keys('integrations');
const integrations = await Promise.all(
keys
.filter((key) => key.startsWith('discourse-'))
.map(async (key) => ({
key,
data: await storage.get('integrations', key),
}))
);
return integrations.filter(({ data }) => Boolean(data));
}
function decodePayload(payload) {
const clean = payload.replace(/\s/g, '');
let base64 = clean.replace(/-/g, '+').replace(/_/g, '/');
while (base64.length % 4) {
base64 += '=';
}
try {
return forge.util.decode64(base64);
} catch {
return null;
}
}
function importPrivateKey(privateKeyBase64) {
const bytes = Uint8Array.from(atob(privateKeyBase64), (char) =>
char.charCodeAt(0)
);
const der = forge.util.createBuffer(bytes);
const asn1 = forge.asn1.fromDer(der);
return forge.pki.privateKeyFromAsn1(asn1);
}
async function activate(candidate, apiData, integrations, storage) {
const active = {
...candidate.data,
status: 'active',
apiKey: apiData.key,
oneTimePassword: apiData.one_time_password,
activatedAt: Date.now(),
};
delete active.privateKey;
await storage.set('integrations', candidate.key, active);
// Drop superseded records for the same forum: leftover pending records or a
// previous active record replaced by a reconnect.
await Promise.all(
integrations
.filter(
({ key, data }) =>
key !== candidate.key && data?.url === candidate.data.url
)
.map(({ key }) => storage.remove('integrations', key))
);
return active;
}
// Generates/reuses a pending integration for the forum and returns the URL the
// user must visit to authorize Dashtab.
async function prepare({ inputUrl, redirectUri, storage }) {
const url = normalizeDiscourseUrl(inputUrl);
if (!url) {
throw new Error('Please enter a Discourse URL');
}
const urlObj = new URL(url);
let clientId;
let nonce;
let publicKeyPem;
const existing = await findPendingIntegration(storage, urlObj.origin);
if (existing) {
clientId = existing.data.clientId;
nonce = existing.data.nonce;
publicKeyPem = await publicKeyPemFromPrivateKey(existing.data.privateKey);
} else {
const { publicKey, privateKey } = await generateKeyPair();
clientId = crypto.randomUUID();
nonce = crypto.randomUUID();
publicKeyPem = await exportPublicKeyToPem(publicKey);
await storePendingIntegration(storage, {
clientId,
origin: urlObj.origin,
privateKey,
nonce,
redirectUrl: redirectUri,
});
}
const authUrl = new URL('/user-api-key/new', urlObj);
authUrl.search = new URLSearchParams({
application_name: 'Dashtab',
client_id: clientId,
nonce,
scopes: DISCOURSE_AUTH_SCOPES,
auth_redirect: redirectUri,
public_key: publicKeyPem,
}).toString();
return authUrl.toString();
}
// Decrypts the payload returned by Discourse and stores the activated
// integration. `resultUrl` is the full redirect URL containing `?payload=`.
async function complete({ resultUrl, storage }) {
const payload = new URL(resultUrl).searchParams.get('payload');
if (!payload) {
throw new Error('No payload received from Discourse');
}
const encryptedData = decodePayload(payload);
if (!encryptedData) {
throw new Error('Invalid payload format from Discourse');
}
const integrations = await discourseIntegrations(storage);
const pending = integrations.filter(
({ data }) => data && data.status === 'pending'
);
if (pending.length === 0) {
throw new Error('No pending integration found');
}
const match = selectDecryptedIntegration(pending, (candidate) => {
const privateKey = importPrivateKey(candidate.data.privateKey);
const decrypted = privateKey.decrypt(encryptedData, 'RSAES-PKCS1-V1_5');
return JSON.parse(decrypted);
});
if (!match) {
throw new Error(
'Failed to decrypt response from Discourse. The key or encryption format may be incompatible.'
);
}
return activate(match.candidate, match.apiData, integrations, storage);
}
export const discourseProvider = {
id: 'discourse',
webCallbackPath: '/auth/discourse/callback',
prepare,
complete,
};