Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion android/assets/i18n/java-ar.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-en.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-es.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-fr.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-id.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-ja.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-ko.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-ru.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion android/assets/i18n/java-zh-Hant.json

Large diffs are not rendered by default.

135 changes: 121 additions & 14 deletions android/java/cc/codroid/Consent.java
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ static boolean persistable(Context c) {
*/
static void grant(Context c, String name, String value) {
synchronized (LOCK) {
if (verifiedGrant != null && verifiedGrant.name.equals(name)) verifiedGrant = null;
MEM.put(name, value);
// 旧签名先作废:值变了(读屏 自动 → 常开)不能让旧的那份还验得过
dropSaved(c, name);
Expand All @@ -138,6 +139,7 @@ static void grant(Context c, String name, String value) {
/** 关掉:内存、存档、钥匙一起清。不用验证 */
static void revoke(Context c, String name) {
synchronized (LOCK) {
if (verifiedGrant != null && verifiedGrant.name.equals(name)) verifiedGrant = null;
MEM.remove(name);
PENDING.removeIf((x) -> x[0].equals(name));
dropSaved(c, name);
Expand Down Expand Up @@ -176,6 +178,123 @@ private static String label(String name, String value) {

// ── 签名(主线程,MainActivity 收到 ACTION_CONSENT 时调)──
private static boolean running;
private static final class VerifiedGrant {
final String name, value;
final java.util.function.BooleanSupplier current;
final java.util.function.Consumer<Boolean> complete;
boolean finished;

VerifiedGrant(String name, String value, java.util.function.BooleanSupplier current, java.util.function.Consumer<Boolean> complete) {
this.name = name;
this.value = value;
this.current = current;
this.complete = complete;
}
}
private static VerifiedGrant verifiedGrant;

/** Renewal publishes neither an in-memory grant nor a stored grant until authentication succeeds. */
static void grantAfterVerification(Activity a, String name, String value, java.util.function.BooleanSupplier current,
java.util.function.Consumer<Boolean> complete) {
VerifiedGrant request = new VerifiedGrant(name, value, current, complete);
synchronized (LOCK) {
if (running || !PENDING.isEmpty() || !persistable(a) || !current.getAsBoolean() || MEM.containsKey(name)) {
complete.accept(false);
return;
}
verifiedGrant = request;
running = true;
}
new Thread(() -> {
try {
// Keep KeyStore / attestation verification off the UI thread and outside LOCK.
if (get(a, name) != null) {
a.runOnUiThread(() -> finishVerifiedGrant(a, request, false));
return;
}
Signature signature = signing(a, name, value);
a.runOnUiThread(() -> verifyGrant(a, request, signature));
} catch (Exception e) {
Log.w(TAG, "无法准备续期验证", e);
a.runOnUiThread(() -> finishVerifiedGrant(a, request, false));
}
}, "consent-renewal").start();
}

private static void verifyGrant(Activity a, VerifiedGrant request, Signature signature) {
synchronized (LOCK) {
if (signature == null || verifiedGrant != request || !request.current.getAsBoolean() || a.isFinishing() || a.isDestroyed()) {
finishVerifiedGrant(a, request, false);
return;
}
}
try {
BiometricPrompt prompt = new BiometricPrompt.Builder(a)
.setTitle(Tr.t("用锁屏验证保存这项设置"))
.setSubtitle(label(request.name, request.value))
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG | BiometricManager.Authenticators.DEVICE_CREDENTIAL)
.build();
prompt.authenticate(new BiometricPrompt.CryptoObject(signature), new CancellationSignal(), a.getMainExecutor(),
new BiometricPrompt.AuthenticationCallback() {
@Override public void onAuthenticationSucceeded(BiometricPrompt.AuthenticationResult r) {
boolean saved = false;
try {
Signature signer = r.getCryptoObject().getSignature();
signer.update(msg(a, request.name, request.value));
String sig = Base64.encodeToString(signer.sign(), Base64.NO_WRAP);
synchronized (LOCK) {
if (verifiedGrant == request && request.current.getAsBoolean() && !a.isFinishing() && !a.isDestroyed()) {
saved = sp(a).edit().putString("v." + request.name, request.value).putString("s." + request.name, sig).commit();
if (saved) {
BAD_SIG.remove(request.name);
MEM.put(request.name, request.value);
}
else sp(a).edit().remove("v." + request.name).remove("s." + request.name).commit();
}
}
} catch (Exception e) { Log.w(TAG, "续期签名保存失败", e); }
finishVerifiedGrant(a, request, saved);
}
@Override public void onAuthenticationError(int code, CharSequence message) {
finishVerifiedGrant(a, request, false);
}
});
} catch (RuntimeException e) {
Log.w(TAG, "无法显示续期验证", e);
finishVerifiedGrant(a, request, false);
}
}

private static void finishVerifiedGrant(Activity a, VerifiedGrant request, boolean saved) {
synchronized (LOCK) {
if (request.finished) return;
request.finished = true;
verifiedGrant = null;
running = false;
}
request.complete.accept(saved);
runNext(a);
}

private static Signature signing(Context c, String name, String value) throws Exception {
KeyPairGenerator g = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
g.initialize(new KeyGenParameterSpec.Builder(ALIAS + name, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
.setDigests(KeyProperties.DIGEST_SHA256)
.setUserAuthenticationRequired(true)
.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG | KeyProperties.AUTH_DEVICE_CREDENTIAL)
.setInvalidatedByBiometricEnrollment(false)
.setAttestationChallenge(challenge(c, name, value))
.build());
PrivateKey k = g.generateKeyPair().getPrivate();
KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); ks.load(null);
if (attested(c, ks, name, value) == null) {
try { ks.deleteEntry(ALIAS + name); } catch (Exception ignored) {}
return null;
}
Signature signature = Signature.getInstance("SHA256withECDSA");
signature.initSign(k);
return signature;
}
static void runNext(Activity a) {
try { runNext0(a); }
catch (Throwable t) { // 主线程上:任何意外都别把应用带崩(DeepSeek 复核 11-03),这一项只在这次运行有效
Expand All @@ -200,23 +319,11 @@ private static void runNext0(Activity a) {
new Thread(() -> {
final Signature s;
try {
KeyPairGenerator g = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");
g.initialize(new KeyGenParameterSpec.Builder(ALIAS + name, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY)
.setDigests(KeyProperties.DIGEST_SHA256)
.setUserAuthenticationRequired(true)
.setUserAuthenticationParameters(0, KeyProperties.AUTH_BIOMETRIC_STRONG | KeyProperties.AUTH_DEVICE_CREDENTIAL)
.setInvalidatedByBiometricEnrollment(false)
.setAttestationChallenge(challenge(a, name, value))
.build());
PrivateKey k = g.generateKeyPair().getPrivate();
KeyStore ks = KeyStore.getInstance("AndroidKeyStore"); ks.load(null);
if (attested(a, ks, name, value) == null) {
try { ks.deleteEntry(ALIAS + name); } catch (Exception ignored) {}
s = signing(a, name, value);
if (s == null) {
a.runOnUiThread(() -> done(a, Tr.f("这台设备做不了硬件密钥认证,「{0}」只在这次运行有效", label(name, value))));
return;
}
s = Signature.getInstance("SHA256withECDSA");
s.initSign(k);
} catch (Exception e) {
Log.w(TAG, "生成签名钥匙失败", e);
a.runOnUiThread(() -> done(a, Tr.f("没能保存「{0}」,只在这次运行有效:", label(name, value)) + e.getMessage()));
Expand Down
80 changes: 73 additions & 7 deletions android/java/cc/codroid/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -615,21 +615,87 @@ private void confirmPriv(String id, String cmd, String who, boolean trustable, b
.setNegativeButton(Tr.t("拒绝"), (x, w) -> { said[0] = true; Priv.answer(id, 0); });
// 这个会话后面的都允许(Claude 发来的才有):勾上再点「允许」。只在内存里,应用重启就失效
final android.widget.CheckBox all = sess && !clipGet && !clipSet && !openUrl ? new android.widget.CheckBox(this) : null;
if (all != null) {
all.setText(Tr.t("这个会话后面的特权命令都允许,不再逐条问(应用重启后失效)"));
int pad = (int) (20 * getResources().getDisplayMetrics().density);
android.widget.FrameLayout box = new android.widget.FrameLayout(this);
box.setPadding(pad, pad / 2, pad, 0);
box.addView(all);
boolean canRenew = Priv.renewalDuration(id) > 0;
int[] durations = canRenew ? NoAskDuration.options() : new int[0];
android.widget.Spinner duration = canRenew ? new android.widget.Spinner(this) : null;
if (all != null || canRenew) {
android.widget.LinearLayout box = new android.widget.LinearLayout(this);
box.setOrientation(android.widget.LinearLayout.VERTICAL);
box.setPadding(dp(24), dp(12), dp(24), canRenew ? dp(16) : 0);
if (all != null) {
all.setText(Tr.t("这个会话后面的特权命令都允许,不再逐条问(应用重启后失效)"));
box.addView(all);
}
if (canRenew) {
String label = Tr.t("放行所有特权指令(指定期限)");
android.widget.TextView heading = new android.widget.TextView(this);
heading.setText(label);
android.widget.LinearLayout.LayoutParams headingLayout = new android.widget.LinearLayout.LayoutParams(-1, -2);
if (all != null) headingLayout.topMargin = dp(12);
box.addView(heading, headingLayout);
String[] labels = new String[durations.length + 1];
labels[0] = Tr.t("关闭");
for (int i = 0; i < durations.length; i++) labels[i + 1] = Priv.noAskDurationLabel(durations[i]);
duration.setContentDescription(label);
duration.setMinimumHeight(dp(48));
android.widget.ArrayAdapter<String> options = new android.widget.ArrayAdapter<>(this, android.R.layout.simple_spinner_item, labels);
options.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
duration.setAdapter(options);
duration.setSelection(0);
android.widget.LinearLayout.LayoutParams pickerLayout = new android.widget.LinearLayout.LayoutParams(-1, -2);
pickerLayout.topMargin = dp(6);
box.addView(duration, pickerLayout);
android.widget.TextView note = new android.widget.TextView(this);
note.setText(Tr.t("选定时长后,点「允许」并验证。授权对所有会话和终端生效,后台也一样。涉及应用自身、Shizuku / Sui 的命令仍需确认。"));
android.widget.LinearLayout.LayoutParams noteLayout = new android.widget.LinearLayout.LayoutParams(-1, -2);
noteLayout.topMargin = dp(8);
box.addView(note, noteLayout);
}
b.setView(box);
}
b.setPositiveButton(openUrl ? Tr.t("打开") : Tr.t("允许"), (x, w) -> { said[0] = true; Priv.answer(id, all != null && all.isChecked() ? 3 : 1); });
Runnable allow = () -> { said[0] = true; Priv.answer(id, all != null && all.isChecked() ? 3 : 1); };
b.setPositiveButton(openUrl ? Tr.t("打开") : Tr.t("允许"), (x, w) -> allow.run());
if (canRenew) b.setNegativeButton(Tr.t("取消"), (x, w) -> { said[0] = true; Priv.answer(id, 0); });
// 命令里引用了文件的,不给「不再问」:信任的是文字,文件内容随时能换(见 Priv.trustable)
if (trustable) b.setNeutralButton(Tr.t("允许,这条命令 10 分钟内不再问"), (x, w) -> { said[0] = true; Priv.answer(id, 2); });
android.app.AlertDialog d = b.create();
d.setOnDismissListener((x) -> { PRIV_DLG.remove(id); if (!said[0]) Priv.answer(id, 0); });
PRIV_DLG.put(id, d);
if (!guard(d, android.content.DialogInterface.BUTTON_POSITIVE, android.content.DialogInterface.BUTTON_NEUTRAL)) { PRIV_DLG.remove(id); Priv.answer(id, 0); }
else if (canRenew) {
android.widget.Button action = d.getButton(android.content.DialogInterface.BUTTON_POSITIVE);
android.widget.Button limited = d.getButton(android.content.DialogInterface.BUTTON_NEUTRAL);
duration.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
@Override public void onItemSelected(android.widget.AdapterView<?> parent, View view, int position, long rowId) {
if (all != null) all.setEnabled(position == 0);
if (limited != null) limited.setVisibility(position == 0 ? View.VISIBLE : View.GONE);
}
@Override public void onNothingSelected(android.widget.AdapterView<?> parent) {}
});
action.setOnClickListener(v -> {
int position = duration.getSelectedItemPosition();
if (position <= 0) {
allow.run();
d.dismiss();
return;
}
if (position > durations.length) return;
action.setEnabled(false);
duration.setEnabled(false);
Priv.renewAndAllow(this, id, durations[position - 1], saved -> {
if (PRIV_DLG.get(id) != d || !d.isShowing()) return;
if (saved) {
said[0] = true;
d.dismiss();
} else {
duration.setSelection(0);
duration.setEnabled(true);
action.setEnabled(true);
android.widget.Toast.makeText(this, Tr.t("没有续期,仍可单独确认这条命令"), android.widget.Toast.LENGTH_SHORT).show();
}
});
});
}
}
private static final java.util.Map<String, android.app.Dialog> PRIV_DLG = new java.util.concurrent.ConcurrentHashMap<>();
/** Priv.ask 等不到回答(超时)时收起对话框:别留一个点了也没用的「允许」在屏幕上 */
Expand Down
32 changes: 32 additions & 0 deletions android/java/cc/codroid/NoAskDuration.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package cc.codroid;

/** Fixed durations shared by the settings page and the renewal dialog. */
final class NoAskDuration {
static final int DEFAULT = 24 * 60;
private static final int[] DURATIONS = { 60, 240, 1440, 4320, 10080 };

static int[] options() { return DURATIONS.clone(); }

static boolean supports(int minutes) {
for (int option : DURATIONS) if (option == minutes) return true;
return false;
}

static String value(int minutes, long now) { return (now + minutes * 60000L) + ":" + minutes; }

static long until(String value) {
if (value == null) return 0;
int split = value.indexOf(':');
try { return Long.parseLong(split < 0 ? value : value.substring(0, split)); }
catch (NumberFormatException e) { return 0; }
}

static int minutes(String value) {
int split = value == null ? -1 : value.indexOf(':');
if (split < 0) return 0; // Legacy signed values contain only the deadline.
try {
int minutes = Integer.parseInt(value.substring(split + 1));
return supports(minutes) ? minutes : 0;
} catch (NumberFormatException e) { return 0; }
}
}
Loading
Loading