Files
RedditBot/extensions/reddit-session-exporter/session-export.js

57 lines
2.0 KiB
JavaScript

const REDDITBOT_SESSION_FILENAME = 'redditbot-session.json';
export const REDDIT_CHAT_URL = 'https://chat.reddit.com/';
export function normalizeRedditAccountId(accountId) {
const trimmed = String(accountId ?? '').trim();
const normalized = trimmed.startsWith('t2_') ? trimmed : `t2_${trimmed}`;
if (!/^t2_[a-z0-9]+$/i.test(normalized)) {
throw new Error('Reddit returned an invalid account ID.');
}
return normalized;
}
export function assertMatchingSessionIdentity(redditIdentity, matrixUserId) {
const accountId = normalizeRedditAccountId(redditIdentity?.accountId);
const username = String(redditIdentity?.username ?? '').trim();
if (!username) throw new Error('Reddit did not return an authenticated username.');
const expectedMatrixUserId = `@${accountId}:reddit.com`;
if (matrixUserId !== expectedMatrixUserId) {
throw new Error(
`Reddit is logged in as u/${username} (${accountId}), but Chat is authenticated as ${matrixUserId}. Reload Reddit Chat after switching accounts, then export again.`,
);
}
}
function isRedditDomain(domain) {
const normalised = domain.toLowerCase().replace(/^\./, '');
return normalised === 'reddit.com' || normalised.endsWith('.reddit.com');
}
function toExportCookie(cookie) {
return {
name: cookie.name,
value: cookie.value,
domain: cookie.domain,
path: cookie.path,
expires: cookie.expirationDate,
httpOnly: cookie.httpOnly,
secure: cookie.secure,
sameSite: cookie.sameSite,
};
}
export function createSessionExportDownload(cookies, matrix) {
if (!matrix?.homeserver || !matrix?.accessToken || !matrix?.userId) {
throw new Error('Open Reddit Chat before exporting so Matrix credentials can be captured.');
}
const exportFile = {
cookies: cookies.filter((cookie) => isRedditDomain(cookie.domain)).map(toExportCookie),
matrix,
};
return {
filename: REDDITBOT_SESSION_FILENAME,
url: `data:application/json;charset=utf-8,${encodeURIComponent(JSON.stringify(exportFile))}`,
};
}