Selaa lähdekoodia

fix(miniprogram): keep native credentials out of H5 navigation

彭峰 6 päivää sitten
vanhempi
commit
ba2c639e92

+ 7 - 16
common-page/pages/web-view/index.js

@@ -46,27 +46,14 @@ Page({
         const homeStartup = isHome && options.skipAuth === 'true';
         if (!homeStartup && !await this.checkUserLogin(options)) return;
 
-        let user = Parse.User.current();
-        if (homeStartup && !user) {
-            const saved = wx.getStorageSync('sessionToken');
-            if (saved) {
-                try { user = await Parse.User.become(saved); }
-                catch (_) { wx.removeStorageSync('sessionToken'); wx.removeStorageSync('userLogin'); }
-            }
-        }
         const params = homeStartup ? {fromStartup:'1',source:'wechat-miniprogram'} : {};
-        if (user) {
-            params.token = user.getSessionToken();
-            params.userId = user.id;
-            params.mobile = user.get('mobile');
-        }
         this.setData({ path: withQuery(destination, params) });
         if (homeStartup) return;
 
         const passedStoreName = options.storeName ? decodeURIComponent(options.storeName) : '';
         const passedStoreId = options.storeId || '';
         // /home 场景下默认不需要门店标题:跳过 ShopStore 的 Parse 查询以提速。
-        // 这里根据 H5 path 判断:例如 https://www.yuban.co/home?token=...&skipAuth=true...
+        // 这里根据 H5 path 判断:例如 https://www.yuban.co/home?fromStartup=1
 
         if (passedStoreName) {
             this.setNavigationTitle(passedStoreName);
@@ -353,7 +340,8 @@ Page({
         // 若 H5 传入 callbackUrl,则通过刷新 web-view URL 回传支付结果。
         if (!ctx.callbackUrl) return;
         try {
-            const separator = ctx.callbackUrl.includes('?') ? '&' : '?';
+            const callback = requestedTarget({path:ctx.callbackUrl});
+            if (!callback) return;
             const query = [
                 'miniPayResult=1',
                 `success=${result.payload.success ? 1 : 0}`,
@@ -362,7 +350,10 @@ Page({
                 `cancelled=${result.payload.cancelled ? 1 : 0}`,
                 `errMsg=${encodeURIComponent(result.payload.errMsg || '')}`
             ].join('&');
-            const callbackPath = `${ctx.callbackUrl}${separator}${query}`;
+            const hashAt = callback.indexOf('#');
+            const base = hashAt < 0 ? callback : callback.slice(0,hashAt);
+            const hash = hashAt < 0 ? '' : callback.slice(hashAt);
+            const callbackPath = base + (base.includes('?') ? '&' : '?') + query + hash;
             this.setData({ path: callbackPath });
         } catch (error) {
             console.error('❌ 回传支付结果失败:', error);

+ 2 - 2
components/app-auth/index.js

@@ -1,4 +1,4 @@
-const { readTarget } = require('../../utils/web-view-target');
+const { requestedTarget } = require('../../utils/web-view-target');
 let Parse = getApp().Parse;
 let company = getApp().globalData.company
 const request = require("../../utils/request");
@@ -505,7 +505,7 @@ Page({
     
     // 检查是否有 returnUrl 参数(从 H5 页面传递过来)
     const currentPage = pages[pages.length - 1];
-    const target = readTarget(currentPage?.options?.returnUrl);
+    const target = requestedTarget({path:currentPage?.options?.returnUrl});
     if (target) {
       wx.redirectTo({
         url: '/common-page/pages/web-view/index?path=' + encodeURIComponent(target),

+ 19 - 37
index.js

@@ -1288,26 +1288,20 @@ Page({
       if (partnerId) console.log('合作伙伴 ID:', partnerId);
       console.log('===========================================');
       
-      const currentUser = Parse.User.current();
-      const token = currentUser ? currentUser.getSessionToken() : null;
       
       // 构建产品详情的 H5 URL(不要在这里编码,后面统一编码)
-      let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/products?storeId=${storeId}`;
+      let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/products?storeId=${encodeURIComponent(storeId)}`;
       
       // 如果有 token,添加到 URL
-      if (token) {
-        h5Url += `&token=${token}`;
-      } else {
-        // 如果没有 token,使用游客模式
-        h5Url += `&guestMode=true`;
-      }
+      // This legacy H5 already supports guestMode. Its session is independent.
+      h5Url += '&guestMode=true';
       
       // 添加产品ID(不要在这里编码,避免双重编码)
-      h5Url += `&productId=${productId}`;
+      h5Url += `&productId=${encodeURIComponent(productId)}`;
       
       // 如果有合作伙伴ID,也添加到URL中
       if (partnerId) {
-        h5Url += `&partnerId=${partnerId}`;
+        h5Url += `&partnerId=${encodeURIComponent(partnerId)}`;
       }
       
       console.log('🌐 H5 URL:', h5Url);
@@ -1316,7 +1310,7 @@ Page({
       const encodedUrl = encodeURIComponent(h5Url);
       
       // 构建 web-view 页面路径
-      let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
+      let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${encodeURIComponent(storeId)}`;
       
       console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
       console.log('===========================================');
@@ -1357,26 +1351,20 @@ Page({
       if (partnerId) console.log('合作伙伴 ID:', partnerId);
       console.log('===========================================');
       
-      const currentUser = Parse.User.current();
-      const token = currentUser ? currentUser.getSessionToken() : null;
       
       // 构建案例详情的 H5 URL(不要在这里编码,后面统一编码)
-      let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/cases?storeId=${storeId}`;
+      let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/cases?storeId=${encodeURIComponent(storeId)}`;
       
       // 如果有 token,添加到 URL
-      if (token) {
-        h5Url += `&token=${token}`;
-      } else {
-        // 如果没有 token,使用游客模式
-        h5Url += `&guestMode=true`;
-      }
+      // This legacy H5 already supports guestMode. Its session is independent.
+      h5Url += '&guestMode=true';
       
       // 添加案例ID(不要在这里编码,避免双重编码)
-      h5Url += `&caseId=${caseId}`;
+      h5Url += `&caseId=${encodeURIComponent(caseId)}`;
       
       // 如果有合作伙伴ID,也添加到URL中
       if (partnerId) {
-        h5Url += `&partnerId=${partnerId}`;
+        h5Url += `&partnerId=${encodeURIComponent(partnerId)}`;
       }
       
       console.log('🌐 H5 URL:', h5Url);
@@ -1385,7 +1373,7 @@ Page({
       const encodedUrl = encodeURIComponent(h5Url);
       
       // 构建 web-view 页面路径
-      let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
+      let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${encodeURIComponent(storeId)}`;
       
       console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
       console.log('===========================================');
@@ -1428,31 +1416,25 @@ Page({
       if (partnerId) console.log('合作伙伴 ID:', partnerId);
       console.log('===========================================');
       
-      const currentUser = Parse.User.current();
-      const token = currentUser ? currentUser.getSessionToken() : null;
       
       // 构建门店首页的 H5 URL,带上方案ID
-      let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/home?storeId=${storeId}`;
+      let h5Url = `https://app.fmode.cn/dev/pobingfeng/owner/nav/home?storeId=${encodeURIComponent(storeId)}`;
       
       // 如果有 token,添加到 URL
-      if (token) {
-        h5Url += `&token=${token}`;
-      } else {
-        // 如果没有 token,使用游客模式
-        h5Url += `&guestMode=true`;
-      }
+      // This legacy H5 already supports guestMode. Its session is independent.
+      h5Url += '&guestMode=true';
       
       // 添加方案ID(使用planId参数名)
-      h5Url += `&planId=${planId}`;
+      h5Url += `&planId=${encodeURIComponent(planId)}`;
       
       // 如果有分享用户ID,也添加到URL中
       if (shareUserId) {
-        h5Url += `&shareUserId=${shareUserId}`;
+        h5Url += `&shareUserId=${encodeURIComponent(shareUserId)}`;
       }
       
       // 如果有合作伙伴ID,也添加到URL中
       if (partnerId) {
-        h5Url += `&partnerId=${partnerId}`;
+        h5Url += `&partnerId=${encodeURIComponent(partnerId)}`;
       }
       
       console.log('🌐 H5 URL:', h5Url);
@@ -1461,7 +1443,7 @@ Page({
       const encodedUrl = encodeURIComponent(h5Url);
       
       // 构建 web-view 页面路径
-      let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${storeId}`;
+      let webViewPath = `/common-page/pages/web-view/index?path=${encodedUrl}&storeId=${encodeURIComponent(storeId)}`;
       
       console.log('📄 web-view 页面路径:', webViewPath.substring(0, 100) + '...');
       console.log('===========================================');

+ 32 - 2
test/governance-smoke.test.cjs

@@ -74,17 +74,47 @@ test('通用业务页经已登记登录页恢复原目标,保留查询与片
   const final=new URL(resumed.data.path);
   assert.equal(final.pathname,'/user-profile/memory-cleanup');assert.equal(final.hash,'#family');
   assert.equal(final.searchParams.get('label'),'a&b');assert.equal(final.searchParams.get('source'),'mini');
-  assert.equal(final.searchParams.get('token'),'fixture-session');assert.deepEqual(final.searchParams.getAll('userId'),['fixture-member']);
+  assert.equal(final.searchParams.has('token'),false);assert.equal(final.searchParams.has('userId'),false);assert.equal(final.searchParams.has('mobile'),false);
 });
 
 test('引导页会话信息与已有受控业务路径兼容', () => {
   const {readTarget,requestedTarget,withQuery}=require('../utils/web-view-target');
   const path='https://www.yuban.co/home?fromStartup=1&source=wechat-miniprogram#start';
-  const url=new URL(withQuery(requestedTarget({path:encodeURIComponent(path),skipAuth:'true'}),{token:'fixture-current'}));
+  const url=new URL(requestedTarget({path:encodeURIComponent(path),skipAuth:'true',sessionToken:'fixture-session',mobile:'fixture-mobile'}));
+  assert.equal(url.searchParams.has('sessionToken'),false);assert.equal(url.searchParams.has('mobile'),false);
   assert.equal(url.hash,'#start');assert.equal(url.searchParams.getAll('source').length,1);assert.equal(url.searchParams.has('skipAuth'),false);
   assert.equal(readTarget('%broken'),'');
   for(const name of ['products','cases','home']) {
     const legacy='https://app.fmode.cn/dev/pobingfeng/owner/nav/'+name+'?storeId=sample';
     assert.equal(readTarget(encodeURIComponent(legacy)),legacy);
+    assert.equal(requestedTarget({path:legacy+'&token=sample-token&mobile=sample-mobile',source:'mini'}),legacy+'&source=mini');
   }
 });
+
+test('语伴引导与三条旧商城导航只传业务参数,保留 H5 支付回调', async () => {
+  const vm=require('node:vm');
+  const {requestedTarget}=require('../utils/web-view-target');
+  let home,index,navigation;
+  const wx={getStorageSync(){throw Error('Home must not read native identity');},redirectTo:options=>{navigation=options.url;}};
+  vm.runInNewContext(fs.readFileSync(path.join(root,'yuban/components/home/index.js'),'utf8'),{Component:def=>{home=def.methods;},wx});
+  function target(route) {
+    const target=new URL(new URL(route,'https://local.invalid').searchParams.get('path'));
+    for(const key of ['userId','mobile','token','sessionToken'])assert.equal(target.searchParams.has(key),false);
+    return target;
+  }
+  const launch=target(home.buildWebViewPath.call(home));
+  assert.equal(launch.pathname,'/home');assert.deepEqual([...launch.searchParams.keys()],['fromStartup','source']);
+  wx.getStorageSync=()=>null;
+  vm.runInNewContext(fs.readFileSync(path.join(root,'index.js'),'utf8'),{
+    Page:def=>{index=def;},wx,require:()=>({default:{}}),requirePlugin:()=>({}),
+    console:{log(){},error(){}},
+  });
+  for(const [method,itemKey,route] of [['redirectToProductDetail','productId','products'],['redirectToCaseDetail','caseId','cases'],['redirectToStoreWithPlan','planId','home']]){
+    navigation=null;await index[method]('s&1','item?42','synthetic');
+    const dest=target(navigation);assert.equal(dest.pathname,'/dev/pobingfeng/owner/nav/'+route);
+    assert.equal(dest.searchParams.get(itemKey),'item?42');assert.equal(dest.searchParams.get('storeId'),'s&1');assert.equal(dest.searchParams.get('guestMode'),'true');
+  }
+  const pay='https://www.yuban.co/user-profile/membership-renewal?code=payment-code&state=payment-state&invite=keep';
+  assert.equal(requestedTarget({path:pay+'&token=fixture'}),pay);
+  assert.equal(requestedTarget({path:'https://www.yuban.co/home?sessionToken=fixture&invite=keep&code=old#part'}),'https://www.yuban.co/home?invite=keep#part');
+});

+ 16 - 5
utils/web-view-target.js

@@ -17,17 +17,28 @@ function queryKey(part) {
   try { return decodeURIComponent(part.split('=')[0]); } catch (_) { return ''; }
 }
 
-function withQuery(target, values = {}, removeIdentity = false) {
+const identityKeys = new Set(['token','sessiontoken','accesstoken','access_token','refreshtoken','refresh_token','authorization','userid','mobile','openid','unionid']);
+function isIdentity(key) { return identityKeys.has(String(key).toLowerCase()); }
+
+function withQuery(target, values = {}, clean = false) {
+  // Existing payment callbacks own their OAuth code and state.
+  const payment = /^https:\/\/www\.yuban\.co\/user-profile\/(?:account-recharge|membership-renewal)\/?(?:[?#]|$)/.test(target);
+  const omit = key => clean && (isIdentity(key) || (!payment && ['code','state'].includes(key)));
   const hashAt = target.indexOf('#');
   const url = hashAt < 0 ? target : target.slice(0, hashAt);
-  const hash = hashAt < 0 ? '' : target.slice(hashAt);
+  let hash = hashAt < 0 ? '' : target.slice(hashAt);
+  if (clean && hash.includes('?')) {
+    const separator = hash.indexOf('?');
+    const params = hash.slice(separator+1).split('&').filter(part => part && !omit(queryKey(part)));
+    hash = hash.slice(0,separator) + (params.length ? '?' + params.join('&') : '');
+  }
   const index = url.indexOf('?');
   const base = index < 0 ? url : url.slice(0, index);
   let parts = index < 0 ? [] : url.slice(index + 1).split('&').filter(Boolean);
-  if (removeIdentity) parts = parts.filter(part => !['token','userId','mobile'].includes(queryKey(part)));
+  if (clean) parts = parts.filter(part => !omit(queryKey(part)));
   const keys = new Set(parts.map(queryKey));
   for (const [key,value] of Object.entries(values)) {
-    if (keys.has(key) || value === '' || value == null) continue;
+    if (omit(key) || keys.has(key) || value === '' || value == null) continue;
     parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(String(value)));
   }
   return base + (parts.length ? '?' + parts.join('&') : '') + hash;
@@ -38,7 +49,7 @@ function requestedTarget(options = {}) {
   if (!target) return '';
   const values = {};
   for (const [key,value] of Object.entries(options)) {
-    if (!['path','url','skipAuth','token','userId','mobile','__proto__','constructor','prototype'].includes(key) && typeof value === 'string') values[key] = value;
+    if (!['path','url','skipAuth','__proto__','constructor','prototype'].includes(key) && typeof value === 'string') values[key] = value;
   }
   return withQuery(target, values, true);
 }

+ 2 - 36
yuban/components/home/index.js

@@ -66,42 +66,8 @@ Component({
     },
 
     buildWebViewPath() {
-      let token = null;
-      let userId = null;
-      let mobile = null;
-      try {
-        const app = getApp();
-        if (app && app.Parse) {
-          const currentUser = app.Parse.User.current();
-          if (currentUser) {
-            token = currentUser.getSessionToken() || null;
-            userId = currentUser.id || null;
-            mobile = currentUser.get('mobile') || null;
-          }
-        }
-      } catch (e) {
-        // Parse 不可用时直接游客模式进入 H5
-      }
-
-      // 兜底:storage 里可能已有登录态
-      try {
-        if (!token) token = wx.getStorageSync('sessionToken') || null;
-        if (!userId) userId = wx.getStorageSync('userLogin') || null;
-        if (!mobile) {
-          const userInfo = wx.getStorageSync('userInfo') || {};
-          mobile = userInfo.mobile || null;
-        }
-      } catch (e) {
-        // ignore
-      }
-
-      // 约定:直达 /home,勿进 /startup;fromStartup=1 触发 H5 欢迎语桥接
-      const h5Url = this.appendQuery(H5_BASE, {
-        ...STARTUP_SOURCE_PARAMS,
-        token,
-        userId,
-        mobile,
-      });
+      // H5 maintains its own SMS session. Native account data stays in the mini program.
+      const h5Url = this.appendQuery(H5_BASE, STARTUP_SOURCE_PARAMS);
       const encodedUrl = encodeURIComponent(h5Url);
       return `/common-page/pages/web-view/index?path=${encodedUrl}&skipAuth=true`;
     },