fix(auth): harden WeChat login and explicit identity switching

This commit is contained in:
xsl
2026-10-12 10:07:54 +08:00
parent 0ec5e5dc32
commit d68f841f0e
16 changed files with 1484 additions and 735 deletions
+9 -5
View File
@@ -1,8 +1,9 @@
/* Browser identity is a random credential, never a fingerprint or a report. */
window.AccountClient = (function () {
'use strict';
var key = 'juzi.identity.v1', user = null;
function read() { try { return localStorage.getItem(key); } catch (_) { return null; } }
var key = 'juzi.identity.v1', kindKey = 'juzi.auth.kind.v1', user = null;
function read(name) { try { return localStorage.getItem(name || key); } catch (_) { return null; } }
function rememberKind() { try { if (user) localStorage.setItem(kindKey, user.kind); } catch (_) {} }
function request(url, data) {
return fetch(url, { credentials: 'same-origin', method: data ? 'POST' : 'GET',
headers: data ? { 'Content-Type': 'application/json' } : {},
@@ -13,13 +14,16 @@ window.AccountClient = (function () {
function browser(consent) {
return request('api/auth/browser', { consent: consent, token: read() }).then(function (v) {
try { localStorage.setItem(key, v.token); } catch (_) { /* session cookie still works */ }
user = v.user; return v;
user = v.user; rememberKind(); return v;
});
}
function init() {
function init(options) {
return request('api/auth/session').then(function (v) {
user = v.user;
if (!user && read()) return browser(true).catch(function (e) {
rememberKind();
// A missing WeChat session is not permission to switch to a browser account.
// OAuth returns must also stay explicit when its cookie was not retained.
if (!user && !(options && options.restoreBrowser === false) && read(kindKey) !== 'wechat' && read()) return browser(true).catch(function (e) {
// Do not replace an existing credential on a transient server/network error.
if (/身份已失效/.test(e.message)) { try { localStorage.removeItem(key); } catch (_) {} }
throw e;