1
0
mirror of https://gitcode.com/gh_mirrors/re/react-native-pushy.git synced 2025-09-18 00:46:10 +08:00
Code Issues Packages Projects Releases Wiki Activity GitHub Gitee

Compare commits

..

19 Commits

Author SHA1 Message Date
sunnylqm
7ab7dffb0f v9.1.5 2023-12-12 23:08:11 +08:00
sunnylqm
8622935bdf fix: zipslip 2023-12-12 23:07:11 +08:00
sunnylqm
b747b1f356 v9.1.4 2023-10-30 22:58:41 +08:00
sunnylqm
7752581470 chore: throttle switchversion 2023-10-30 22:58:09 +08:00
sunnylqm
33eb89d2a7 v9.1.3 2023-10-28 18:28:54 +08:00
sunnylqm
d111bf5a9c chore: rename onPushyEvents 2023-10-28 18:28:23 +08:00
sunnylqm
23346a5f1d v9.1.2 2023-10-28 17:26:19 +08:00
sunnylqm
5aca2104c2 fix: simpleUpdate for web 2023-10-28 17:25:54 +08:00
sunnylqm
fe0a05db3d v9.1.0 2023-10-28 17:01:54 +08:00
sunnylqm
2b287786ff chore: remove permissions 2023-10-28 14:37:26 +08:00
sunnylqm
7d128900cd feat: improve backup endpoints 2023-10-28 14:36:04 +08:00
sunnylqm
189e3ec78e v9.0.5 2023-09-24 21:18:11 +08:00
sunnylqm
821722165a v9.0.4 2023-09-15 16:16:48 +08:00
sunnylqm
6cb53ac655 fix: lastChecking 2023-09-15 16:16:13 +08:00
sunnylqm
7b9a24168a v9.0.3 2023-09-06 23:18:07 +08:00
sunnylqm
c6354bbedc fix: return type 2023-09-06 23:16:42 +08:00
sunnylqm
b53878c291 chore: cleanup 2023-09-06 22:56:41 +08:00
sunnylqm
ab01312f8d v9.0.2 2023-09-06 22:53:54 +08:00
sunnylqm
44784b6d3e feat: return cached result 2023-09-06 11:20:31 +08:00
12 changed files with 2630 additions and 218 deletions

View File

@@ -1,2 +1,3 @@
-keepnames class cn.reactnative.modules.update.DownloadTask { *; }
-keepnames class cn.reactnative.modules.update.UpdateModuleImpl { *; }
-keepnames class com.facebook.react.ReactInstanceManager { *; }

View File

@@ -1,9 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.reactnative.modules.update">
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application>
<meta-data android:name="pushy_build_time" android:value="@string/pushy_build_time" />
<provider

View File

@@ -237,19 +237,7 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
while (entries.hasMoreElements()) {
ZipEntry ze = entries.nextElement();
String fn = ze.getName();
File fmd = new File(param.unzipDirectory, fn);
if (UpdateContext.DEBUG) {
Log.d("RNUpdate", "Unzipping " + fn);
}
if (ze.isDirectory()) {
fmd.mkdirs();
continue;
}
zipFile.unzipToFile(ze, fmd);
zipFile.unzipToPath(ze, param.unzipDirectory);
}
zipFile.close();
@@ -324,8 +312,15 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
} else {
target = copyList.get((from));
}
target.add(new File(param.unzipDirectory, to));
//copyFromResource(from, new File(param.unzipDirectory, to));
File toFile = new File(param.unzipDirectory, to);
// Fixing a Zip Path Traversal Vulnerability
// https://support.google.com/faqs/answer/9294009
String canonicalPath = toFile.getCanonicalPath();
if (!canonicalPath.startsWith(param.unzipDirectory.getCanonicalPath() + File.separator)) {
throw new SecurityException("Illegal name: " + to);
}
target.add(toFile);
}
continue;
}
@@ -339,18 +334,9 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
fout.close();
continue;
}
File fmd = new File(param.unzipDirectory, fn);
if (UpdateContext.DEBUG) {
Log.d("RNUpdate", "Unzipping " + fn);
}
if (ze.isDirectory()) {
fmd.mkdirs();
continue;
}
zipFile.unzipToFile(ze, fmd);
zipFile.unzipToPath(ze, param.unzipDirectory);
}
zipFile.close();
@@ -419,18 +405,8 @@ class DownloadTask extends AsyncTask<DownloadTaskParams, long[], Void> {
fout.close();
continue;
}
File fmd = new File(param.unzipDirectory, fn);
if (UpdateContext.DEBUG) {
Log.d("RNUpdate", "Unzipping " + fn);
}
if (ze.isDirectory()) {
fmd.mkdirs();
continue;
}
zipFile.unzipToFile(ze, fmd);
zipFile.unzipToPath(ze, param.unzipDirectory);
}
zipFile.close();

View File

@@ -1,5 +1,7 @@
package cn.reactnative.modules.update;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
@@ -10,12 +12,15 @@ import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class SafeZipFile extends ZipFile {
public SafeZipFile(File file) throws IOException {
super(file);
}
private static final int BUFFER_SIZE = 8192;
@Override
public Enumeration<? extends ZipEntry> entries() {
return new SafeZipEntryIterator(super.entries());
@@ -43,40 +48,46 @@ public class SafeZipFile extends ZipFile {
* avoid ZipperDown
*/
if (null != name && (name.contains("../") || name.contains("..\\"))) {
throw new SecurityException("illegal entry: " + entry.getName());
throw new SecurityException("illegal entry: " + name);
}
}
return entry;
}
}
public void unzipToFile(ZipEntry entry, File output) throws IOException {
InputStream inputStream = null;
try {
inputStream = getInputStream(entry);
writeOutInputStream(output, inputStream);
} finally {
if (inputStream != null) {
inputStream.close();
public void unzipToPath(ZipEntry ze, File targetPath) throws IOException {
String name = ze.getName();
File target = new File(targetPath, name);
// Fixing a Zip Path Traversal Vulnerability
// https://support.google.com/faqs/answer/9294009
String canonicalPath = target.getCanonicalPath();
if (!canonicalPath.startsWith(targetPath.getCanonicalPath() + File.separator)) {
throw new SecurityException("Illegal name: " + name);
}
if (UpdateContext.DEBUG) {
Log.d("RNUpdate", "Unzipping " + name);
}
if (ze.isDirectory()) {
target.mkdirs();
return;
}
unzipToFile(ze, target);
}
public void unzipToFile(ZipEntry ze, File target) throws IOException {
try (InputStream inputStream = getInputStream(ze)) {
try (BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(target));
BufferedInputStream input = new BufferedInputStream(inputStream)) {
byte[] buffer = new byte[BUFFER_SIZE];
int n;
while ((n = input.read(buffer, 0, BUFFER_SIZE)) >= 0) {
output.write(buffer, 0, n);
}
}
}
}
private void writeOutInputStream(File file, InputStream inputStream) throws IOException {
BufferedOutputStream output = null;
try {
output = new BufferedOutputStream(
new FileOutputStream(file));
BufferedInputStream input = new BufferedInputStream(inputStream);
byte b[] = new byte[8192];
int n;
while ((n = input.read(b, 0, 8192)) >= 0) {
output.write(b, 0, n);
}
} finally {
if (output != null) {
output.close();
}
}
}
}

View File

@@ -1,75 +1,26 @@
import { logger } from './utils';
let currentEndpoint = 'https://update.react-native.cn/api';
let backupEndpoints: string[] = ['https://update.reactnative.cn/api'];
let backupEndpointsQueryUrl: string | null = null;
function ping(url: string, rejectImmediate?: boolean) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = (e) => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
resolve(url);
} else {
rejectImmediate ? reject() : setTimeout(reject, 5000);
}
};
xhr.open('HEAD', url);
xhr.send();
xhr.timeout = 5000;
xhr.ontimeout = reject;
});
}
function logger(...args: any[]) {
console.log('Pushy: ', ...args);
}
let backupEndpoints: string[] = [];
let backupEndpointsQueryUrl: string | null =
'https://cdn.jsdelivr.net/gh/reactnativecn/react-native-pushy@master/endpoints.json';
export async function tryBackupEndpoints() {
if (!backupEndpoints.length && !backupEndpointsQueryUrl) {
return;
}
try {
await ping(getStatusUrl(), true);
logger('current endpoint ok', currentEndpoint);
return;
} catch (e) {
logger('current endpoint failed', currentEndpoint);
}
if (!backupEndpoints.length && backupEndpointsQueryUrl) {
export async function updateBackupEndpoints() {
if (backupEndpointsQueryUrl) {
try {
const resp = await fetch(backupEndpointsQueryUrl);
backupEndpoints = await resp.json();
logger('get remote endpoints:', backupEndpoints);
const remoteEndpoints = await resp.json();
if (Array.isArray(remoteEndpoints)) {
backupEndpoints = Array.from(
new Set([...backupEndpoints, ...remoteEndpoints]),
);
logger('fetch remote endpoints:', remoteEndpoints);
logger('merged backup endpoints:', backupEndpoints);
}
} catch (e) {
logger('get remote endpoints failed');
return;
logger('fetch remote endpoints failed');
}
}
await pickFatestAvailableEndpoint();
}
async function pickFatestAvailableEndpoint(endpoints = backupEndpoints) {
const fastestEndpoint = await Promise.race(
endpoints.map(pingAndReturnEndpoint),
);
if (typeof fastestEndpoint === 'string') {
logger(`pick endpoint: ${fastestEndpoint}`);
currentEndpoint = fastestEndpoint;
} else {
logger('all remote endpoints failed');
}
}
async function pingAndReturnEndpoint(endpoint = currentEndpoint) {
return ping(getStatusUrl(endpoint)).then(() => endpoint);
}
function getStatusUrl(endpoint = currentEndpoint) {
return `${endpoint}/status`;
return backupEndpoints;
}
export function getCheckUrl(APPKEY, endpoint = currentEndpoint) {
@@ -95,7 +46,6 @@ export function setCustomEndpoints({
backupEndpointsQueryUrl = null;
if (Array.isArray(backups) && backups.length > 0) {
backupEndpoints = backups;
pickFatestAvailableEndpoint();
}
if (typeof backupQueryUrl === 'string') {
backupEndpointsQueryUrl = backupQueryUrl;

View File

@@ -14,5 +14,5 @@ export const markSuccess = noop;
export const downloadAndInstallApk = noop;
export const setCustomEndpoints = noop;
export const getCurrentVersionInfo = noop;
export const simpleUpdate = noop;
export const onEvents = noop;
export const simpleUpdate = (app) => app;
export const onPushyEvents = noop;

View File

@@ -1,5 +1,5 @@
import {
tryBackupEndpoints,
updateBackupEndpoints,
getCheckUrl,
setCustomEndpoints,
} from './endpoint';
@@ -16,6 +16,7 @@ import {
UpdateAvailableResult,
UpdateEventsListener,
} from './type';
import { assertRelease, logger } from './utils';
export { setCustomEndpoints };
const {
version: v,
@@ -74,14 +75,10 @@ if (!uuid) {
PushyModule.setUuid(uuid);
}
function logger(...args: string[]) {
console.log('Pushy: ', ...args);
}
const noop = () => {};
let reporter: UpdateEventsListener = noop;
export function onEvents(customReporter: UpdateEventsListener) {
export function onPushyEvents(customReporter: UpdateEventsListener) {
reporter = customReporter;
if (isRolledBack) {
report({
@@ -125,19 +122,15 @@ export const cInfo = {
uuid,
};
function assertRelease() {
if (__DEV__) {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
}
}
let lastChecking = Date.now();
export async function checkUpdate(APPKEY: string, isRetry?: boolean) {
let lastChecking;
const empty = {};
let lastResult: CheckResult;
export async function checkUpdate(APPKEY: string) {
assertRelease();
const now = Date.now();
if (now - lastChecking < 1000 * 5) {
logger('repeated checking, ignored');
return;
if (lastResult && lastChecking && now - lastChecking < 1000 * 60) {
// logger('repeated checking, ignored');
return lastResult;
}
lastChecking = now;
if (blockUpdate && blockUpdate.until > Date.now() / 1000) {
@@ -147,36 +140,51 @@ export async function checkUpdate(APPKEY: string, isRetry?: boolean) {
blockUpdate.until * 1000,
).toLocaleString()}"之后重试。`,
});
return;
return lastResult || empty;
}
report({ type: 'checking' });
const fetchPayload = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
packageVersion,
hash: currentVersion,
buildTime,
cInfo,
}),
};
let resp;
try {
resp = await fetch(getCheckUrl(APPKEY), {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
packageVersion,
hash: currentVersion,
buildTime,
cInfo,
}),
});
resp = await fetch(getCheckUrl(APPKEY), fetchPayload);
} catch (e) {
if (isRetry) {
report({
type: 'errorChecking',
message: '无法连接更新服务器,请检查网络连接后重试',
});
return;
report({
type: 'errorChecking',
message: '无法连接主更新服务器,尝试备用节点',
});
const backupEndpoints = await updateBackupEndpoints();
if (backupEndpoints) {
try {
resp = await Promise.race(
backupEndpoints.map((endpoint) =>
fetch(getCheckUrl(APPKEY, endpoint), fetchPayload),
),
);
} catch {}
}
await tryBackupEndpoints();
return checkUpdate(APPKEY, true);
}
if (!resp) {
report({
type: 'errorChecking',
message: '无法连接更新服务器,请检查网络连接后重试',
});
return lastResult || empty;
}
const result: CheckResult = await resp.json();
lastResult = result;
// @ts-ignore
checkOperation(result.op);
@@ -186,7 +194,6 @@ export async function checkUpdate(APPKEY: string, isRetry?: boolean) {
//@ts-ignore
message: result.message,
});
return;
}
return result;
@@ -315,10 +322,12 @@ function assertHash(hash: string) {
return true;
}
let applyingUpdate = false;
export function switchVersion(hash: string) {
assertRelease();
if (assertHash(hash)) {
if (assertHash(hash) && !applyingUpdate) {
logger('switchVersion: ' + hash);
applyingUpdate = true;
PushyModule.reloadUpdate({ hash });
}
}

View File

@@ -16,20 +16,20 @@ import {
switchVersionLater,
markSuccess,
downloadAndInstallApk,
onEvents,
onPushyEvents,
} from './main';
import { UpdateEventsListener } from './type';
export function simpleUpdate(
WrappedComponent: ComponentType,
options: { appKey?: string; onEvents?: UpdateEventsListener } = {},
options: { appKey?: string; onPushyEvents?: UpdateEventsListener } = {},
) {
const { appKey, onEvents: eventListeners } = options;
const { appKey, onPushyEvents: eventListeners } = options;
if (!appKey) {
throw new Error('appKey is required for simpleUpdate()');
}
if (typeof eventListeners === 'function') {
onEvents(eventListeners);
onPushyEvents(eventListeners);
}
return __DEV__
? WrappedComponent

View File

@@ -26,7 +26,8 @@ export interface UpdateAvailableResult {
export type CheckResult =
| ExpiredResult
| UpTodateResult
| UpdateAvailableResult;
| UpdateAvailableResult
| {};
export interface ProgressData {
hash: string;

9
lib/utils.ts Normal file
View File

@@ -0,0 +1,9 @@
export function logger(...args: any[]) {
console.log('Pushy: ', ...args);
}
export function assertRelease() {
if (__DEV__) {
throw new Error('react-native-update 只能在 RELEASE 版本中运行.');
}
}

View File

@@ -1,6 +1,6 @@
{
"name": "react-native-update",
"version": "9.0.1",
"version": "9.1.5",
"description": "react-native hot update",
"main": "lib/index.ts",
"scripts": {
@@ -39,7 +39,7 @@
"url": "https://github.com/reactnativecn/react-native-pushy/issues"
},
"peerDependencies": {
"react-native": ">=0.27.0"
"react-native": ">=0.57.0"
},
"homepage": "https://github.com/reactnativecn/react-native-pushy#readme",
"dependencies": {
@@ -57,12 +57,15 @@
"devDependencies": {
"@types/fs-extra": "^9.0.13",
"@types/jest": "^29.2.1",
"@types/node": "^20.8.9",
"@types/react": "^18.2.33",
"detox": "^20.5.0",
"firebase-tools": "^11.24.1",
"fs-extra": "^9.1.0",
"jest": "^29.2.1",
"pod-install": "^0.1.37",
"react-native": "^0.72.6",
"ts-jest": "^29.0.3",
"typescript": "^4.1.3"
"typescript": "^5.2.2"
}
}

2527
yarn.lock

File diff suppressed because it is too large Load Diff