mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-11-25 23:06:59 +00:00
Parse Ctfile shares with the new url API and ALTCHA v2 (#303)
* Parse Ctfile shares with the new url API and ALTCHA v2 The legacy getfile.php and getdir.php endpoints now answer every share with Cloudflare Turnstile. Password-free files and folders use ALTCHA PBKDF2 instead: solve it off the event loop, reuse access_pass for the same owner, and fetch the direct link from POST /url/download. Password shares stay on Turnstile and are reported separately from missing links and wrong or missing passwords. Co-authored-by: qaiu <[email protected]> * Add Ctfile v4 login parsing for password-protected shares Password shares are blocked by Turnstile on the anonymous web API. When a refresh token or access token is configured, convert the share to an xtc link and use the official client list and fetch-url calls. Password-free shares still use ALTCHA. Tests use short synthetic fixtures only. Co-authored-by: qaiu <[email protected]> * Parse password-protected Ctfile shares with anonymous ALTCHA A password share's first response is often labeled Turnstile, but a fresh ALTCHA token plus the passcode returns the file. Try that before any login. Keep the v4 client only as a fallback when Turnstile remains and a token is configured. Live checks download the sample PDF and a directory zip. Co-authored-by: qaiu <[email protected]> --------- Co-authored-by: Cursor Agent <[email protected]>
This commit is contained in:
1 parent
feff1b88c1
commit
542d246aab
12 files changed
+2688
-566
No files matched your search
@@ -0,0 +1,96 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assert.fail;
|
||||
|
||||
public class AltchaV2SolverTest {
|
||||
|
||||
private static final String NONCE = "00112233445566778899aabbccddeeff";
|
||||
private static final String SALT = "0102030405060708090a0b0c0d0e0f10";
|
||||
|
||||
@Test
|
||||
public void pbkdf2MatchesAltchaVector() {
|
||||
byte[] password = password(NONCE, 7);
|
||||
byte[] derived = AltchaV2Solver.pbkdf2(password, AltchaV2Solver.decodeHex(SALT, "salt"), 100, 32);
|
||||
assertEquals("dce8b41d12bd8245a12f9fbca56d1d5db2924c1bfe02b924be69f6d89dc1721b",
|
||||
AltchaV2Solver.toHex(derived));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void productionCostMatchesCounterZero() {
|
||||
byte[] derived = AltchaV2Solver.pbkdf2(password(NONCE, 0),
|
||||
AltchaV2Solver.decodeHex(SALT, "salt"), 1200, 32);
|
||||
assertEquals("c24bb34595d0df8688c53e6be3b63e4a0fb0f2d9f732b5c4daebc46fba958bf7",
|
||||
AltchaV2Solver.toHex(derived));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void solverFindsPrefixedCounterAndBuildsPayload() {
|
||||
byte[] derived = AltchaV2Solver.pbkdf2(password(NONCE, 3),
|
||||
AltchaV2Solver.decodeHex(SALT, "salt"), 50, 32);
|
||||
String prefix = AltchaV2Solver.toHex(derived).substring(0, 8);
|
||||
JsonObject challenge = challenge(50, prefix, "sig-test");
|
||||
AltchaV2Solver.Solution solution = AltchaV2Solver.solve(challenge, 20, 5_000);
|
||||
assertEquals(3, solution.counter);
|
||||
assertTrue(solution.derivedKeyHex.startsWith(prefix));
|
||||
|
||||
JsonObject payload = new JsonObject(new String(Base64.getDecoder().decode(AltchaV2Solver.payload(challenge, solution))));
|
||||
assertEquals("sig-test", payload.getJsonObject("challenge").getString("signature"));
|
||||
assertEquals("PBKDF2/SHA-256", payload.getJsonObject("challenge").getJsonObject("parameters").getString("algorithm"));
|
||||
assertEquals(3, payload.getJsonObject("solution").getInteger("counter").intValue());
|
||||
assertEquals(solution.derivedKeyHex, payload.getJsonObject("solution").getString("derivedKey"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void impossiblePrefixStopsAtTheCounterCap() {
|
||||
byte[] beyondCap = AltchaV2Solver.pbkdf2(password(NONCE, 40),
|
||||
AltchaV2Solver.decodeHex(SALT, "salt"), 20, 32);
|
||||
JsonObject challenge = challenge(20, AltchaV2Solver.toHex(beyondCap).substring(0, 8), "sig");
|
||||
try {
|
||||
AltchaV2Solver.solve(challenge, 8, 5_000);
|
||||
fail("expected the search to stop");
|
||||
} catch (IllegalStateException e) {
|
||||
assertTrue(e.getMessage().contains("超时"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void rejectsCostAboveTheSafetyCap() {
|
||||
JsonObject challenge = challenge(AltchaV2Solver.MAX_COST + 1, "00", "sig");
|
||||
try {
|
||||
AltchaV2Solver.solve(challenge, 1, 1_000);
|
||||
fail("expected cost to be rejected");
|
||||
} catch (IllegalArgumentException e) {
|
||||
assertTrue(e.getMessage().contains("cost"));
|
||||
}
|
||||
}
|
||||
|
||||
private static JsonObject challenge(int cost, String keyPrefix, String signature) {
|
||||
return new JsonObject()
|
||||
.put("parameters", new JsonObject()
|
||||
.put("algorithm", "PBKDF2/SHA-256")
|
||||
.put("cost", cost)
|
||||
.put("keyLength", 32)
|
||||
.put("nonce", NONCE)
|
||||
.put("salt", SALT)
|
||||
.put("keyPrefix", keyPrefix))
|
||||
.put("signature", signature);
|
||||
}
|
||||
|
||||
private static byte[] password(String nonceHex, int counter) {
|
||||
byte[] nonce = AltchaV2Solver.decodeHex(nonceHex, "nonce");
|
||||
byte[] password = new byte[nonce.length + 4];
|
||||
System.arraycopy(nonce, 0, password, 0, nonce.length);
|
||||
password[nonce.length] = (byte) (counter >>> 24);
|
||||
password[nonce.length + 1] = (byte) (counter >>> 16);
|
||||
password[nonce.length + 2] = (byte) (counter >>> 8);
|
||||
password[nonce.length + 3] = (byte) counter;
|
||||
return password;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.ParserCreate;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.json.JsonArray;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.AfterClass;
|
||||
import org.junit.Assume;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
/**
|
||||
* 城通真实联调。默认不跑:
|
||||
* mvn -pl parser -DskipTests=false -Dctfile.live=true -Dtest=CtToolLiveTest test
|
||||
*/
|
||||
public class CtToolLiveTest {
|
||||
|
||||
private static final String FREE_FILE = "https://474b.com/file/4015376-131945810";
|
||||
private static final String PASSWORD_FILE =
|
||||
"https://url94.ctfile.com/f/64115194-17569800420720-06c697?p=7609";
|
||||
private static final String PASSWORD_FILE_WITHOUT_PASSWORD =
|
||||
"https://url94.ctfile.com/f/64115194-17569800420720-06c697";
|
||||
private static final String PASSWORD_DIR =
|
||||
"https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609";
|
||||
private static final String PASSWORD_FILE_WRONG =
|
||||
"https://url94.ctfile.com/f/64115194-17569800420720-06c697?p=0000";
|
||||
|
||||
private static Vertx vertx;
|
||||
|
||||
@AfterClass
|
||||
public static void tearDown() throws Exception {
|
||||
CtfileSession.clearCachedPasses();
|
||||
if (vertx != null) {
|
||||
CtTool.shutdownWorkerExecutor();
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(15, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void freeFileDownloadsRealPdfBytes() throws Exception {
|
||||
liveOnly();
|
||||
CtTool tool = tool(FREE_FILE);
|
||||
String url = tool.parse().toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
||||
FileInfo info = (FileInfo) tool.getShareLinkInfo().getOtherParam().get("fileInfo");
|
||||
assertNotNull(info);
|
||||
assertTrue(info.getFileName().endsWith(".pdf"));
|
||||
assertTrue(info.getSize() > 1000);
|
||||
assertTrue(url.startsWith("https://"));
|
||||
|
||||
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
|
||||
HttpResponse<byte[]> head = client.send(HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Range", "bytes=0-15")
|
||||
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
assertTrue("head status " + head.statusCode(), head.statusCode() == 206 || head.statusCode() == 200);
|
||||
String magic = new String(head.body(), 0, Math.min(5, head.body().length), StandardCharsets.ISO_8859_1);
|
||||
assertEquals("%PDF-", magic);
|
||||
String range = head.headers().firstValue("content-range").orElse("");
|
||||
String length = head.headers().firstValue("content-length").orElse("");
|
||||
assertTrue(range.endsWith("/" + info.getSize()) || length.equals(String.valueOf(info.getSize()))
|
||||
|| range.contains("/" + info.getSize()));
|
||||
|
||||
long size = info.getSize();
|
||||
HttpResponse<byte[]> tail = client.send(HttpRequest.newBuilder(URI.create(url))
|
||||
.timeout(Duration.ofSeconds(30))
|
||||
.header("Range", "bytes=" + Math.max(0, size - 20) + "-" + (size - 1))
|
||||
.GET().build(), HttpResponse.BodyHandlers.ofByteArray());
|
||||
String ending = new String(tail.body(), StandardCharsets.ISO_8859_1);
|
||||
assertTrue(ending.contains("%%EOF"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void sameSessionListsParentDirectory() throws Exception {
|
||||
liveOnly();
|
||||
ShareLinkInfo info = ParserCreate.fromShareUrl(FREE_FILE).getShareLinkInfo();
|
||||
try (CtfileSession session = CtfileSession.open(info)) {
|
||||
JsonObject resource = session.loadResource("file", info.getShareKey(),
|
||||
CtfileSession.ShareTarget.from(info), "", "");
|
||||
JsonObject file = CtfileSession.dataOf(resource).getJsonObject("file");
|
||||
String fileDir = file.getString("file_dir", "");
|
||||
int marker = fileDir.indexOf("/d/");
|
||||
assertTrue(fileDir, marker >= 0);
|
||||
String dirId = fileDir.substring(marker + 3);
|
||||
int query = dirId.indexOf('?');
|
||||
if (query >= 0) {
|
||||
dirId = dirId.substring(0, query);
|
||||
}
|
||||
JsonObject listing = session.listing("dir", dirId, new CtfileSession.ShareTarget("0", "", "0"),
|
||||
"", resource, 0, 20);
|
||||
JsonArray rows = CtfileSession.rowsOf(listing);
|
||||
assertTrue(rows.size() > 0);
|
||||
ShareLinkInfo directory = ShareLinkInfo.newBuilder()
|
||||
.type("ctd")
|
||||
.panName("城通网盘-目录")
|
||||
.shareKey(dirId)
|
||||
.shareUrl("https://474b.com/d/" + dirId)
|
||||
.build();
|
||||
directory.getOtherParam().put("domainName", "https://nfd.example");
|
||||
int named = 0;
|
||||
for (int i = 0; i < rows.size(); i++) {
|
||||
FileInfo item = CtTool.toFileInfo(rows.getJsonObject(i), directory);
|
||||
if (item != null && item.getFileName() != null && !item.getFileName().isBlank()) {
|
||||
named++;
|
||||
assertNotNull(item.getParserUrl());
|
||||
}
|
||||
}
|
||||
assertTrue(named > 0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void passwordFileDownloadsAnonymously() throws Exception {
|
||||
liveOnly();
|
||||
CtTool tool = tool(PASSWORD_FILE);
|
||||
String url = tool.parse().toCompletionStage().toCompletableFuture().get(120, TimeUnit.SECONDS);
|
||||
FileInfo info = (FileInfo) tool.getShareLinkInfo().getOtherParam().get("fileInfo");
|
||||
assertEquals("欢迎使用微盘.pdf", info.getFileName());
|
||||
assertEquals(Long.valueOf(4005749L), info.getSize());
|
||||
byte[] body = download(url);
|
||||
assertEquals(4005749, body.length);
|
||||
assertTrue(new String(body, 0, 5, StandardCharsets.ISO_8859_1).startsWith("%PDF-"));
|
||||
assertTrue(new String(body, body.length - 16, 16, StandardCharsets.ISO_8859_1).contains("%%EOF"));
|
||||
assertEquals("cce8357689762fd1acd1f73fcd7e83d62b4e9bcee6fccf0c9b8f46d26ee74902", sha256(body));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void passwordDirectoryListsAndDownloadsZipAnonymously() throws Exception {
|
||||
liveOnly();
|
||||
CtTool directory = tool(PASSWORD_DIR);
|
||||
List<FileInfo> files = directory.parseFileList().toCompletionStage().toCompletableFuture()
|
||||
.get(120, TimeUnit.SECONDS);
|
||||
assertEquals(3, files.size());
|
||||
FileInfo zip = null;
|
||||
for (FileInfo file : files) {
|
||||
assertNotNull(file.getParserUrl());
|
||||
assertTrue(file.getParserUrl().contains("pwd=7609") || decodedParam(file).getString("pwd").equals("7609"));
|
||||
if ("osm_model_20260602_153158.zip".equals(file.getFileName())) {
|
||||
zip = file;
|
||||
}
|
||||
}
|
||||
assertNotNull(zip);
|
||||
assertEquals(Long.valueOf(158842L), zip.getSize());
|
||||
ShareLinkInfo child = ShareLinkInfo.newBuilder()
|
||||
.type("ct")
|
||||
.panName("城通网盘")
|
||||
.shareKey("pending")
|
||||
.shareUrl("https://ctfile.com/file/pending")
|
||||
.build();
|
||||
child.getOtherParam().put("paramJson", decodedParam(zip));
|
||||
child.getOtherParam().put("domainName", "https://nfd.example");
|
||||
CtTool downloader = new CtTool(child);
|
||||
String url = downloader.parseById().toCompletionStage().toCompletableFuture().get(120, TimeUnit.SECONDS);
|
||||
byte[] body = download(url);
|
||||
assertEquals(158842, body.length);
|
||||
assertEquals('P', (char) body[0]);
|
||||
assertEquals('K', (char) body[1]);
|
||||
int entries = 0;
|
||||
try (ZipInputStream zipIn = new ZipInputStream(new ByteArrayInputStream(body))) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zipIn.getNextEntry()) != null) {
|
||||
byte[] ignored = zipIn.readAllBytes();
|
||||
assertTrue(entry.getName() != null);
|
||||
assertTrue(ignored.length >= 0);
|
||||
zipIn.closeEntry();
|
||||
entries++;
|
||||
}
|
||||
}
|
||||
assertTrue(entries > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingPasswordAndMissingShareStayDistinct() throws Exception {
|
||||
liveOnly();
|
||||
String withoutPassword = failure(tool(PASSWORD_FILE_WITHOUT_PASSWORD).parse());
|
||||
assertTrue(withoutPassword, withoutPassword.contains("需要访问密码"));
|
||||
assertFalse(withoutPassword, withoutPassword.contains("未配置城通账号"));
|
||||
|
||||
String wrongPassword = failure(tool(PASSWORD_FILE_WRONG).parse());
|
||||
assertTrue(wrongPassword, wrongPassword.contains("访问密码不正确"));
|
||||
assertFalse(wrongPassword, wrongPassword.contains("未配置城通账号"));
|
||||
|
||||
String missingFile = failure(tool("https://474b.com/file/4015376-1").parse());
|
||||
assertTrue(missingFile, missingFile.contains("不存在或已过期"));
|
||||
|
||||
String missingOwner = failure(tool("https://474b.com/file/0-0").parse());
|
||||
assertTrue(missingOwner, missingOwner.contains("不存在或已过期"));
|
||||
}
|
||||
|
||||
private static JsonObject decodedParam(FileInfo file) {
|
||||
String url = file.getParserUrl();
|
||||
return new JsonObject(decodeUrlBase64(url.substring(url.lastIndexOf('/') + 1)));
|
||||
}
|
||||
|
||||
private static String decodeUrlBase64(String value) {
|
||||
String padded = value;
|
||||
int mod = padded.length() % 4;
|
||||
if (mod != 0) {
|
||||
padded += "=".repeat(4 - mod);
|
||||
}
|
||||
return new String(java.util.Base64.getUrlDecoder().decode(padded), StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static byte[] download(String url) throws Exception {
|
||||
HttpResponse<byte[]> response = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(20))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build()
|
||||
.send(HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(120)).GET().build(),
|
||||
HttpResponse.BodyHandlers.ofByteArray());
|
||||
assertEquals(200, response.statusCode());
|
||||
return response.body();
|
||||
}
|
||||
|
||||
private static String sha256(byte[] body) throws Exception {
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256").digest(body);
|
||||
StringBuilder hex = new StringBuilder();
|
||||
for (byte value : digest) {
|
||||
hex.append(String.format("%02x", value));
|
||||
}
|
||||
return hex.toString();
|
||||
}
|
||||
|
||||
private static void liveOnly() {
|
||||
Assume.assumeTrue("set -Dctfile.live=true to call ctfile", Boolean.getBoolean("ctfile.live"));
|
||||
if (vertx == null) {
|
||||
vertx = Vertx.vertx();
|
||||
WebClientVertxInit.init(vertx);
|
||||
}
|
||||
}
|
||||
|
||||
private static CtTool tool(String url) {
|
||||
return (CtTool) ParserCreate.fromShareUrl(url).createTool();
|
||||
}
|
||||
|
||||
private static String failure(io.vertx.core.Future<?> future) throws Exception {
|
||||
try {
|
||||
future.toCompletionStage().toCompletableFuture().get(90, TimeUnit.SECONDS);
|
||||
return "";
|
||||
} catch (Exception e) {
|
||||
Throwable current = e;
|
||||
StringBuilder message = new StringBuilder();
|
||||
while (current != null) {
|
||||
if (current.getMessage() != null) {
|
||||
message.append(current.getMessage()).append('\n');
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
if (message.length() == 0) {
|
||||
throw e;
|
||||
}
|
||||
return message.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.impl.CtfileSession.Decision;
|
||||
import cn.qaiu.parser.impl.CtfileSession.Kind;
|
||||
import cn.qaiu.parser.impl.CtfileSession.ShareTarget;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CtfileResponseTest {
|
||||
|
||||
@Test
|
||||
public void classifiesNotFoundInvalidPasswordAndCaptcha() {
|
||||
Decision missing = CtfileSession.classify(json(404, null, "File was not found."), 404, "");
|
||||
assertEquals(Kind.NOT_FOUND, missing.kind);
|
||||
assertTrue(missing.message.contains("不存在或已过期"));
|
||||
assertFalse(missing.message.contains("密码"));
|
||||
|
||||
Decision unsigned = CtfileSession.classify(json(403, null, "Unsigned file link is not accepted."), 403, "");
|
||||
assertEquals(Kind.INVALID, unsigned.kind);
|
||||
|
||||
Decision needPassword = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"captcha_type\":\"turnstile\",\"capabilities\":{\"passcodeRequired\":true}},"
|
||||
+ "\"msg\":\"Share passcode is required.\"}"), 423, "");
|
||||
assertEquals(Kind.NEED_PASSWORD, needPassword.kind);
|
||||
assertTrue(needPassword.message.contains("需要访问密码"));
|
||||
|
||||
Decision wrong = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"error_type\":\"passcode_incorrect\",\"captcha_type\":\"turnstile\","
|
||||
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"incorrect\"}"), 423, "7609");
|
||||
assertEquals(Kind.BAD_PASSWORD, wrong.kind);
|
||||
|
||||
Decision turnstile = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"turnstile\","
|
||||
+ "\"capabilities\":{\"passcodeRequired\":true,\"ownerId\":64115194}},"
|
||||
+ "\"msg\":\"Share passcode needs a new human check.\"}"), 423, "7609");
|
||||
assertEquals(Kind.TURNSTILE, turnstile.kind);
|
||||
assertEquals("64115194", turnstile.ownerId);
|
||||
assertTrue(turnstile.message.contains("Turnstile"));
|
||||
assertFalse(turnstile.message.contains("密码"));
|
||||
|
||||
Decision altcha = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"altcha\","
|
||||
+ "\"capabilities\":{\"passcodeRequired\":false,\"ownerId\":4015376}},"
|
||||
+ "\"msg\":\"Share access needs a human check.\"}"), 423, "");
|
||||
assertEquals(Kind.ALTCHA, altcha.kind);
|
||||
assertEquals("4015376", altcha.ownerId);
|
||||
|
||||
Decision ok = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":200,\"data\":{\"access_pass\":\"v1.aaa.bbb\",\"capabilities\":{\"ownerId\":4015376}}}"), 200, "");
|
||||
assertEquals(Kind.OK, ok.kind);
|
||||
assertEquals("v1.aaa.bbb", ok.accessPass);
|
||||
|
||||
Decision labeledTurnstile = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"error_type\":\"captcha_required\",\"captcha_type\":\"turnstile\","
|
||||
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"Share passcode needs a new human check.\"}"),
|
||||
423, "pw");
|
||||
assertTrue(CtfileSession.shouldSolveAltcha(labeledTurnstile));
|
||||
assertFalse(CtfileSession.shouldSolveAltcha(needPassword));
|
||||
Decision wrongAfterAltcha = CtfileSession.classify(new JsonObject(
|
||||
"{\"code\":423,\"data\":{\"error_type\":\"passcode_incorrect\",\"captcha_type\":\"turnstile\","
|
||||
+ "\"capabilities\":{\"passcodeRequired\":true}},\"msg\":\"Share passcode is incorrect.\"}"),
|
||||
423, "0000");
|
||||
assertEquals(Kind.BAD_PASSWORD, wrongAfterAltcha.kind);
|
||||
assertFalse(CtfileSession.shouldSolveAltcha(wrongAfterAltcha));
|
||||
|
||||
ShareLinkInfo passwordShare = ShareLinkInfo.newBuilder()
|
||||
.type("ct")
|
||||
.shareKey("11-22-ab")
|
||||
.sharePassword("pw")
|
||||
.shareUrl("https://example.test/f/11-22-ab?p=pw")
|
||||
.build();
|
||||
assertFalse(CtTool.requiresV4(passwordShare));
|
||||
passwordShare.getOtherParam().put("ctV4FileId", "f22");
|
||||
assertTrue(CtTool.requiresV4(passwordShare));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void resourceQueryKeepsTokensAndEncodesThem() {
|
||||
Map<String, String> query = CtfileSession.resourceQuery("file", "4015376-131945810",
|
||||
new ShareTarget("0", "", "0"), "7609", "a+b/c=", "turn stile", "v1.aaa.bbb");
|
||||
String form = CtfileSession.form(query);
|
||||
assertTrue(form.contains("kind=file"));
|
||||
assertTrue(form.contains("passcode=7609"));
|
||||
assertTrue(form.contains("altcha_token=a%2Bb%2Fc%3D"));
|
||||
assertTrue(form.contains("turnstile_token=turn+stile") || form.contains("turnstile_token=turn%20stile"));
|
||||
assertTrue(form.contains("access_pass=v1.aaa.bbb"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listingRowBecomesFileAndFolderLinks() {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
||||
.type("ctd")
|
||||
.panName("城通网盘-目录")
|
||||
.shareKey("64115194-164803691-48508c")
|
||||
.sharePassword("7609")
|
||||
.shareUrl("https://url94.ctfile.com/d/64115194-164803691-48508c?p=7609")
|
||||
.build();
|
||||
info.getOtherParam().put("domainName", "https://nfd.example");
|
||||
|
||||
FileInfo folder = CtTool.toFileInfo(new JsonObject()
|
||||
.put("kind", "folder")
|
||||
.put("name", "2022")
|
||||
.put("folderId", 54597713)
|
||||
.put("folderKey", "bf0603")
|
||||
.put("date", "2023-02-22"), info);
|
||||
assertEquals("folder", folder.getFileType());
|
||||
assertTrue(folder.getParserUrl().contains("dirId="));
|
||||
assertTrue(folder.getParserUrl().contains("54597713"));
|
||||
assertTrue(folder.getParserUrl().contains("pwd=7609"));
|
||||
|
||||
FileInfo file = CtTool.toFileInfo(new JsonObject()
|
||||
.put("kind", "file")
|
||||
.put("name", "notes.pdf")
|
||||
.put("href", "#/f/t-token")
|
||||
.put("fileId", 415670738)
|
||||
.put("extension", "pdf")
|
||||
.put("size", "1 MB")
|
||||
.put("size_bytes", 1048576)
|
||||
.put("date", "2019-12-31"), info);
|
||||
assertEquals("t-token", fileId(file));
|
||||
assertEquals(Long.valueOf(1048576L), file.getSize());
|
||||
assertEquals("pdf", file.getFileType());
|
||||
assertTrue(file.getParserUrl().startsWith("https://nfd.example/v2/redirectUrl/ctd/"));
|
||||
}
|
||||
|
||||
private static JsonObject json(int code, JsonObject data, String message) {
|
||||
JsonObject body = new JsonObject().put("code", code).put("msg", message);
|
||||
if (data != null) {
|
||||
body.put("data", data);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
private static String fileId(FileInfo file) {
|
||||
String url = file.getParserUrl();
|
||||
String encoded = url.substring(url.lastIndexOf('/') + 1);
|
||||
return new JsonObject(decodeUrlBase64(encoded)).getString("id");
|
||||
}
|
||||
|
||||
private static String decodeUrlBase64(String value) {
|
||||
String padded = value;
|
||||
int mod = padded.length() % 4;
|
||||
if (mod != 0) {
|
||||
padded += "=".repeat(4 - mod);
|
||||
}
|
||||
byte[] bytes = java.util.Base64.getUrlDecoder().decode(padded);
|
||||
return new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package cn.qaiu.parser.impl;
|
||||
|
||||
import cn.qaiu.entity.FileInfo;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.impl.CtfileV4Client.V4CallException;
|
||||
import io.vertx.core.MultiMap;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class CtfileV4Test {
|
||||
|
||||
private static final String FILE_LINK = "xtc11-f22-ab-pw";
|
||||
private static final String DIR_LINK = "xtc11-d33-cd-pw";
|
||||
|
||||
@Test
|
||||
public void webShareBecomesXtlink() {
|
||||
assertEquals(FILE_LINK, CtfileXtlink.fromShare("11-22-ab", "pw", false));
|
||||
assertEquals(DIR_LINK, CtfileXtlink.fromShare("11-33-cd", "pw", true));
|
||||
assertEquals("xturl44-f55", CtfileXtlink.fromShare("44-55", "", false));
|
||||
assertEquals("xturl11-d33-cd", CtfileXtlink.fromShare("11-33-cd", null, true));
|
||||
assertEquals("xtc1-d2-ab-pw", CtfileXtlink.fromShare("xtc1-d2-ab-pw", "other", true));
|
||||
assertNull(CtfileXtlink.fromShare("t-signed", "pw", true));
|
||||
assertEquals("f22", CtfileXtlink.prefixedId("22", false));
|
||||
assertEquals("22", CtfileXtlink.bareId("f22"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void requestBodiesMatchTheClientProtocol() {
|
||||
JsonObject list = CtfileV4Client.listBody(DIR_LINK, "33", 1, 2);
|
||||
assertEquals(DIR_LINK, list.getString("xtlink"));
|
||||
assertEquals(33L, list.getLong("folder_id").longValue());
|
||||
assertEquals(1, list.getInteger("start").intValue());
|
||||
assertEquals(2, list.getInteger("pagesize").intValue());
|
||||
|
||||
JsonObject auth = CtfileV4Client.authBody(FILE_LINK, "f22");
|
||||
assertEquals("f22", auth.getString("ids"));
|
||||
|
||||
JsonObject fetch = CtfileV4Client.fetchBody(FILE_LINK, "22", "sig");
|
||||
assertEquals("22", fetch.getString("file_id"));
|
||||
assertEquals("sig", fetch.getString("download_sign"));
|
||||
assertEquals(0, fetch.getInteger("carrier").intValue());
|
||||
|
||||
assertFalse(CtfileV4Client.refreshBody("rt", false).containsKey("rotate_token"));
|
||||
assertTrue(CtfileV4Client.refreshBody("rt", true).getBoolean("rotate_token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void errorCodesStaySpecific() {
|
||||
assertTrue(CtfileV4Client.describeFailure(401, "无效或过期的refresh token", "api.auth.invalid_refresh_token")
|
||||
.contains("refresh_token 无效或已过期"));
|
||||
assertTrue(CtfileV4Client.describeFailure(401, "无效的令牌或账户已锁定", "").contains("登录令牌无效或账号已锁定"));
|
||||
assertEquals("城通账号已锁定", CtfileV4Client.describeFailure(401, "账户已锁定", ""));
|
||||
assertEquals("访问密码不正确", CtfileV4Client.describeFailure(403, "访问密码不正确", "api.passcode"));
|
||||
assertTrue(CtfileV4Client.describeFailure(404, "分享不存在", "").contains("不存在或已过期"));
|
||||
assertTrue(CtfileV4Client.describeFailure(401, "请扫码完成登录保护", "qr_required").contains("扫码"));
|
||||
V4CallException invalid = new V4CallException(401, "无效的令牌或账户已锁定", "");
|
||||
assertTrue(invalid.authenticationFailure());
|
||||
assertFalse(new V4CallException(403, "访问密码不正确", "passcode").authenticationFailure());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listRowBecomesDownloadParamWithXtlink() {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
||||
.type("ctd")
|
||||
.panName("城通网盘-目录")
|
||||
.shareKey("11-33-cd")
|
||||
.sharePassword("pw")
|
||||
.shareUrl("https://example.test/d/11-33-cd?p=pw")
|
||||
.build();
|
||||
info.getOtherParam().put("domainName", "https://nfd.example");
|
||||
FileInfo file = CtfileV4Client.toFileInfo(new JsonObject()
|
||||
.put("key", "f22")
|
||||
.put("name", "notes.pdf")
|
||||
.put("icon", "pdf")
|
||||
.put("size", 12)
|
||||
.put("date", "2024-01-02"), info, DIR_LINK);
|
||||
assertEquals("notes.pdf", file.getFileName());
|
||||
assertEquals(Long.valueOf(12L), file.getSize());
|
||||
assertTrue(file.getParserUrl().contains("/v2/redirectUrl/ctd/"));
|
||||
|
||||
JsonObject param = new JsonObject(decode(file.getParserUrl().substring(file.getParserUrl().lastIndexOf('/') + 1)));
|
||||
assertEquals("f22", param.getString("id"));
|
||||
assertEquals(DIR_LINK, param.getString("xtlink"));
|
||||
assertEquals("pw", param.getString("pwd"));
|
||||
|
||||
ShareLinkInfo download = ShareLinkInfo.newBuilder().type("ctd").sharePassword("").build();
|
||||
assertTrue(CtTool.applyFileParam(download, param));
|
||||
assertEquals("f22", download.getOtherParam().get("ctV4FileId"));
|
||||
assertEquals("11-33-cd", download.getShareKey());
|
||||
|
||||
FileInfo folder = CtfileV4Client.toFileInfo(new JsonObject()
|
||||
.put("fid", "d33")
|
||||
.put("name", "2022")
|
||||
.put("is_folder", true), info, DIR_LINK);
|
||||
assertEquals("folder", folder.getFileType());
|
||||
assertTrue(folder.getParserUrl().contains("dirId=33"));
|
||||
assertTrue(folder.getParserUrl().contains("pwd=pw"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void credentialsComeFromAuthsAndDoNotTreatSharePasswordAsLogin() {
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder()
|
||||
.type("ct")
|
||||
.shareKey("11-22-ab")
|
||||
.sharePassword("pw")
|
||||
.build();
|
||||
assertFalse(CtfileV4Client.hasCredentials(info));
|
||||
MultiMap auths = MultiMap.caseInsensitiveMultiMap();
|
||||
auths.set("refresh_token", "refresh-value");
|
||||
auths.set("authorization", "Bearer access-value");
|
||||
auths.set("_configId", "home");
|
||||
info.getOtherParam().put("auths", auths);
|
||||
CtfileV4Client.Credentials credentials = CtfileV4Client.credentials(info);
|
||||
assertEquals("refresh-value", credentials.refreshToken);
|
||||
assertEquals("access-value", credentials.accessToken);
|
||||
assertTrue(credentials.usable());
|
||||
assertTrue(CtfileV4Client.missingAccountMessage().contains("auths.ct.refresh_token"));
|
||||
}
|
||||
|
||||
private static String decode(String value) {
|
||||
String padded = value;
|
||||
int mod = padded.length() % 4;
|
||||
if (mod != 0) {
|
||||
padded += "=".repeat(4 - mod);
|
||||
}
|
||||
return new String(java.util.Base64.getUrlDecoder().decode(padded), java.nio.charset.StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user