23 lines
2.3 KiB
JavaScript
23 lines
2.3 KiB
JavaScript
// Browser session data stays in memory and is sent only to the local native host.
|
|
export const SESSION_PERMISSION = { permissions: ["cookies"], origins: ["https://*.youtube.com/*"] };
|
|
export const isYouTubeDomain = domain => /^(?:[a-z0-9-]+\.)*youtube\.com$/i.test(String(domain || "").replace(/^\./, ""));
|
|
const loginCookie = /^(?:SAPISID|SID|LOGIN_INFO|__Secure-(?:1P|3P)(?:SID|APISID))$/;
|
|
|
|
export async function readSession(tabId = null, includeCookies = false) {
|
|
const { youtubeSession = false } = await chrome.storage.local.get("youtubeSession");
|
|
if (!youtubeSession) return { status: "disabled", message: "Открытые ролики скачиваются без входа. При необходимости можно подключить текущий профиль браузера." };
|
|
if (!await chrome.permissions.contains(SESSION_PERMISSION)) return { status: "permission_required", message: "Разрешите расширению использовать вход в YouTube." };
|
|
const stores = Number.isInteger(tabId) ? await chrome.cookies.getAllCookieStores() : [];
|
|
const storeId = stores.find(store => store.tabIds.includes(tabId))?.id;
|
|
if (Number.isInteger(tabId) && !storeId) throw new Error("Не удалось определить профиль вкладки YouTube. Откройте меню заново.");
|
|
const cookies = (await chrome.cookies.getAll({ domain: "youtube.com", ...(storeId ? { storeId } : {}) }))
|
|
.filter(cookie => isYouTubeDomain(cookie.domain) && !cookie.partitionKey && cookie.value
|
|
&& (!cookie.expirationDate || cookie.expirationDate > Date.now() / 1000))
|
|
.map(({ name, value, domain, path, secure, httpOnly, hostOnly, expirationDate }) =>
|
|
({ name, value, domain, path, secure, httpOnly, hostOnly, ...(expirationDate ? { expirationDate } : {}) }));
|
|
const connected = cookies.some(cookie => loginCookie.test(cookie.name));
|
|
return { status: connected ? "connected" : "signed_out", message: connected
|
|
? "Вход браузера передаётся локальному помощнику при каждой загрузке."
|
|
: "В этом профиле вход не найден. Войдите на YouTube и нажмите «Проверить вход».", ...(includeCookies ? { cookies } : {}) };
|
|
}
|