Files
RSSHub/lib/routes/zaker/utils.ts
T
dependabot[bot]andTony 417ab04f06 chore(deps-dev): bump eslint-plugin-unicorn from 66.0.0 to 68.0.0 (#22310)
* chore(deps-dev): bump eslint-plugin-unicorn from 66.0.0 to 68.0.0

Bumps [eslint-plugin-unicorn](https://github.com/sindresorhus/eslint-plugin-unicorn) from 66.0.0 to 68.0.0.
- [Release notes](https://github.com/sindresorhus/eslint-plugin-unicorn/releases)
- [Commits](https://github.com/sindresorhus/eslint-plugin-unicorn/compare/v66.0.0...v68.0.0)

---
updated-dependencies:
- dependency-name: eslint-plugin-unicorn
  dependency-version: 68.0.0
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* style: fix no-useless-coercion

* style: fix prefer-boolean-return

* style: fix no-useless-logical-operand

* style: fix prefer-single-replace

* style: fix consistent-conditional-object-spread

* style: fix no-useless-else

* style: fix prefer-unicode-code-point-escapes

* style: fix operator-assignment

* style: fix prefer-continue

* style: fix prefer-math-constants

* style: fix prefer-hoisting-branch-code

* style: fix prefer-array-slice

* style: fix consistent-class-member-order

* style: fix no-return-array-push

* style: fix prefer-promise-with-resolvers

* style: fix no-array-concat-in-loop

* style: fix no-loop-iterable-mutation

* style: fix no-invalid-argument-count

* style: fix no-duplicate-if-branches

* style: fix prefer-else-if

* style: fix no-unreadable-for-of-expression

* style: fix logical-assignment-operators

* style: fix default-export-style

* style: revert false positve in prefer-type-literal-last in #22274

* style: fix arrow-body-style

* style: add v68 recommended preset

* style: refactor GraphQL queries to use template literals for better readability

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Tony <TonyRL@users.noreply.github.com>
2026-06-20 23:11:27 +08:00

187 lines
5.7 KiB
TypeScript

import * as cheerio from 'cheerio';
import CryptoJS from 'crypto-js';
import { config } from '@/config';
import type { DataItem } from '@/types';
import cache from '@/utils/cache';
import logger from '@/utils/logger';
import ofetch from '@/utils/ofetch';
import { parseDate } from '@/utils/parse-date';
import timezone from '@/utils/timezone';
const hints = ['globalThis', 'headless', 'languages', 'permHook', 'vendor', 'webDriverValue', 'webdriver'];
export const baseUrl = 'https://www.myzaker.com';
const generateSalt = (input: string, targetZeros = 20) => {
for (let nonce = 0; nonce < 100_000_000; nonce++) {
const hash = CryptoJS.SHA256(input + nonce).toString();
let leadingZeros = 0;
for (const char of hash) {
if (char !== '0') {
leadingZeros += 4 - Number.parseInt(char, 16).toString(2).length;
break;
}
leadingZeros += 4;
}
if (leadingZeros >= targetZeros) {
return nonce;
}
}
return 0;
};
const padSeed = (seed: string) => {
const padding = '0'.repeat(16);
return CryptoJS.enc.Utf8.parse((seed + padding).slice(0, 16));
};
const encrypt = (data, seed: string) => {
const iv = CryptoJS.enc.Utf8.parse('1234567890123456');
return CryptoJS.AES.encrypt(JSON.stringify(data), padSeed(seed), {
iv,
padding: CryptoJS.pad.Pkcs7,
});
};
const encryptPayload = (data, seed: string) => encrypt(data, seed).ciphertext.toString();
export const getSafeLineCookieWithData = async (link): Promise<{ cookie: string; data: string }> => {
const cacheKey = 'zaker:cookie';
const cacheAge = 3600;
const cacheIn = await cache.get(cacheKey, false);
if (cacheIn) {
return JSON.parse(cacheIn);
}
const apiBaseUrl = 'https://challenge.rivers.chaitin.cn/captcha/api';
const headerResponse = await ofetch.raw(link);
const session = headerResponse.headers
.getSetCookie()
.find((e) => e.startsWith('sl-session'))
?.split(';', 1)[0]
.split('sl-session=', 2)[1];
const onceId = headerResponse._data.match(/once_id:\s*"(.*?)",/)?.[1];
logger.debug(`getSafeLineCookie: sl-session=${session}, onceId=${onceId}`);
if (!/window\.captcha/.test(headerResponse._data)) {
logger.debug('getSafeLineCookie: Failed to get once_id');
return {
cookie: headerResponse.headers
.getSetCookie()
.map((c) => c.split(';', 1)[0])
.join('; '),
data: headerResponse._data,
};
}
// await ofetch(`${apiBaseUrl}/index.html?${Math.random()}`);
// await ofetch('${apiBaseUrl}/sdk.js');
const seedResponse = await ofetch<{ req_id: string; seed: string }>(`${apiBaseUrl}/seed`, {
headers: {
Referer: `${baseUrl}/`,
},
query: {
once_id: onceId,
v: '1.0.0',
hints: hints.toSorted(() => Math.random() - 0.5).join(','),
},
});
const ua = config.ua;
const seed = seedResponse.seed;
const takeTime = Math.trunc(Math.random() * 2000 + 1000);
logger.debug(`getSafeLineCookie: ua=${ua}, seed=${seed}, takeTime=${takeTime}`);
const payload = encryptPayload(
{
resolution: '1920x1080',
languages: ['en-US'],
useragents: [ua, ua, ua],
hint: 0,
salt: String(generateSalt(seed, 16)),
taketime: takeTime,
},
seed
);
const inspectResponse = await ofetch<{ req_id: string; jwt: string; reason: string }>(`${apiBaseUrl}/inspect`, {
method: 'POST',
headers: {
Referer: `${baseUrl}/`,
'Content-Type': 'text/plain',
},
query: {
seed,
},
body: payload,
});
logger.debug(`getSafeLineCookie: inspectResponse=${JSON.stringify(inspectResponse)}`);
if (inspectResponse.reason) {
logger.error(`getSafeLineCookie: reason=${inspectResponse.reason}`);
return {
cookie: headerResponse.headers
.getSetCookie()
.map((c) => c.split(';', 1)[0])
.join('; '),
data: headerResponse._data,
};
}
const response = await ofetch.raw(link, {
headers: {
Cookie: `sl-session=${session}; sl_waf_recap=${inspectResponse.jwt}`,
},
});
const cookie = response.headers
.getSetCookie()
.map((c) => c.split(';', 1)[0])
.join('; ');
logger.debug(`getSafeLineCookie: ${cookie}`);
cache.set(cacheKey, JSON.stringify(cookie), cacheAge);
return {
cookie,
data: response._data,
};
};
export const parseList = ($: cheerio.CheerioAPI) => {
const winPageData = JSON.parse(
$('script:contains("window.WinPageData")')
.text()
.match(/window\.WinPageData\s*=\s*(\{.*\})/)?.[1] ?? '{}'
);
return winPageData.data.article.map((item) => ({
title: item.title,
description: item.desc,
link: 'https:' + item.url,
author: item.author_name,
pubDate: timezone(parseDate(item.date, 'MM月DD日'), 8),
category: item.tag.map((t) => t.tag),
image: item.thumbnail_mpic,
})) as DataItem[];
};
export const fetchItem = async (item: DataItem, cookie: string) => {
const response = await ofetch(item.link!, {
headers: {
Cookie: cookie as string,
},
});
const $ = cheerio.load(response);
const content = $('div.article_content div');
content.find('img').each((_, img) => {
const $img = $(img);
$img.attr('src', $img.attr('data-original'));
$img.removeAttr('data-original');
});
item.description = content.html();
return item;
};