Skip to content

Commit

Permalink
main: improve login and cookie handling
Browse files Browse the repository at this point in the history
  • Loading branch information
rocka committed Jul 13, 2023
1 parent 226893a commit c2f0379
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 60 deletions.
74 changes: 19 additions & 55 deletions src/main/api/httpClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,18 @@ export default class HttpClient {

initCookieJar() {
this.cookieJar = new CookieJar();
this.cookieJar.setCookies([
'appver=8.10.20',
'mobilename=linux',
'os=android',
'osver=10.0.0',
], '.music.163.com', '/');
}

/**
* clear all cookies, and set cookie as given arguments
* @param {string | string[] | Record<string, string>} [arg='']
* @param {Record<string, string>} [arg]
*/
updateCookie(arg = '') {
updateCookie(arg = {}) {
this.initCookieJar();
if (typeof arg === 'string' || Array.isArray(arg)) {
this.cookieJar.setCookies(arg);
return;
}
const cookies = Object.entries(arg).map(([k, v]) => `${k}=${v}`);
const ignoredMobileCookie = ['os', 'osver', 'appver', 'mobilename'];
const cookies = Object.entries(arg)
.filter(([k]) => !ignoredMobileCookie.includes(k))
.map(([k, v]) => `${k}=${v}`);
this.cookieJar.setCookies(cookies);
}

Expand All @@ -62,16 +55,11 @@ export default class HttpClient {
cookies.forEach(c => result[c.name] = c.value);
return result;
}
const c = cookies.find(c => c.name === key) || { value: '' };
return c.value;
return cookies.find(c => c.name === key)?.value ?? '';
}

getCookieString(excludeMobile = false) {
getCookieString() {
const cookies = this.cookieJar.getCookies(CookieAccessInfo.All);
if (excludeMobile) {
const excluded = ['appver', 'mobilename', 'os', 'osver'];
return cookies.filter(c => !excluded.includes(c.name)).map(c => c.toValueString()).join('; ');
}
return cookies.map(c => c.toValueString()).join('; ');
}

Expand All @@ -89,20 +77,6 @@ export default class HttpClient {
return hd;
}

/**
* merge provided header key-value maps with pre-defined headers, excluding mobile client headers
* @param {...any} headers headers to append
*/
mergeHeadersWeb(...headers) {
let hd = Object.assign({}, this.clientHeaders, ...headers);
if (hd.Cookie) {
hd.Cookie += ('; ' + this.getCookieString(true));
} else {
hd.Cookie = this.getCookieString(true);
}
return hd;
}

/**
* update cookiejar with 'set-cookie' headers
* @param {import('electron-fetch').Response} res electron-fetch's `Response` object
Expand Down Expand Up @@ -157,22 +131,12 @@ export default class HttpClient {
* wrapper of electron-fetch function
* @param {string} url
* @param {import('electron-fetch').RequestInit} init
* @param {boolean} excludeMobile
*/
async post(url, init, excludeMobile = false) {
let headers;
if (excludeMobile) {
headers = this.mergeHeadersWeb({
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(init.body)
}, init.headers);
} else {
headers = this.mergeHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(init.body)
}, init.headers);
}
init.headers = headers;
async post(url, init) {
init.headers = this.mergeHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(init.body)
}, init.headers);

const res = await fetch(url, init);
this.handleResponse(res);
Expand Down Expand Up @@ -200,7 +164,7 @@ export default class HttpClient {
body.csrf_token = __csrf;
}
init.body = qs.stringify(encodeWeb(body));
return this.post(url, init, true);
return this.post(url, init);
}

/**
Expand Down Expand Up @@ -240,10 +204,10 @@ export default class HttpClient {
}
// default eapi cookies
body.header = Object.assign({
os: 'pc',
osver: 'linux',
appver: '2.0.3.131777',
channel: 'netease'
os: 'android',
osver: '10.0.0',
appver: '8.10.20',
mobilename: 'linux'
}, this.getCookie());
/** @type {import('electron-fetch').RequestInit} */
let init = {
Expand All @@ -254,7 +218,7 @@ export default class HttpClient {
// encrypt request payload
init.body = qs.stringify(encodeEApi(new URL(url).pathname, body));
init.headers = this.mergeHeaders({
'Cookie': 'os=pc; osver=linux; appver=2.0.3.131777; channel=netease',
'Cookie': 'os=android; osver=10.0.0; appver=2.0.3.131777; mobilename=linux',
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(init.body)
});
Expand Down
2 changes: 1 addition & 1 deletion src/main/api/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const downloader = new Downloader(musicCache);

/**
* clear all cookies, and set cookie as given arguments
* @param {string | string[] | Record<string, string>} [cookie]
* @param {Record<string, string>} [cookie]
*/
export function updateCookie(cookie) {
client.updateCookie(cookie);
Expand Down
7 changes: 3 additions & 4 deletions src/main/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,17 +208,17 @@ ipcMain.on('showLoginWindow', () => {
});
loginWindow.loadURL(LoginURL);
const { session } = loginWindow.webContents;
session.webRequest.onHeadersReceived({ urls: [`${LoginURL}/*`] }, (details, callback) => {
session.webRequest.onCompleted({ urls: [`${LoginURL}/*`] }, (details) => {
const values = Object.entries(details.responseHeaders)
.filter(header => header[0].toLocaleLowerCase() === 'set-cookie')
.map(header => header[1])
.flat();
if (values.length <= 0 || values.every(v => !v.includes('MUSIC_U='))) {
// no `set-cookie: MUSIC_U=...`, skip this response
return callback({ cancel: false });
return;
}
// remove webRequest listener
session.webRequest.onHeadersReceived(null);
session.webRequest.onCompleted(null);
ipcMain.handleOnce('getLoginCookie', async () => {
const cookies = await session.cookies.get({ url: LoginURL });
session.clearCache();
Expand All @@ -228,7 +228,6 @@ ipcMain.on('showLoginWindow', () => {
const cookie = Object.fromEntries(cookies.map(ck => [ck.name, ck.value]));
return cookie;
});
callback({ cancel: false });
loginWindow.close();
});
});
Expand Down

0 comments on commit c2f0379

Please sign in to comment.