Ver Fonte

Keep published share behavior with protected H5 navigation

彭峰 há 4 dias atrás
pai
commit
64c8727af2

+ 9 - 3
common-page/pages/web-view/index.js

@@ -2,6 +2,7 @@
 const { requestedTarget, withQuery } = require('../../../utils/web-view-target');
 const Parse = getApp().Parse;
 const company = getApp().globalData.company;
+const { publicDestination, shareCard, isLegacyChatEntry } = require('./share');
 const DEBUG_WEBVIEW = false;
 const debugLog = (...args) => {
     if (DEBUG_WEBVIEW) {
@@ -34,7 +35,12 @@ Page({
     /**
      * 生命周期函数--监听页面加载
      */
-    onLoad: async function (options) {
+    onLoad: async function (options = {}) {
+        // Sharing is a public H5 landing. A fresh recipient has no native account.
+        if (options.fromShare === '1' || !options.path || isLegacyChatEntry()) {
+            this.setData({ path: publicDestination(options.path || options.url) });
+            return;
+        }
         debugLog('======= web-view 页面加载 =======');
         
         const destination = requestedTarget(options);
@@ -204,8 +210,8 @@ Page({
     /**
      * 用户点击右上角分享
      */
-    onShareAppMessage: function () {
-
+    onShareAppMessage: function (event = {}) {
+        return shareCard(event.webViewUrl || this.data.path);
     },
 
     /**

+ 1 - 1
common-page/pages/web-view/index.wxml

@@ -1,4 +1,4 @@
-<web-view src="{{path}}" bindmessage="handleMessage"></web-view>
+<web-view wx:if="{{path}}" src="{{path}}" bindmessage="handleMessage"></web-view>
 <payment
   id="miniPayComponent"
   show="{{miniPayVisible}}"

+ 74 - 0
common-page/pages/web-view/share.js

@@ -0,0 +1,74 @@
+const ORIGIN = 'https://www.yuban.co';
+const PAGE = 'common-page/pages/web-view/index';
+const HOME = ORIGIN + '/home';
+const ID = /^[a-zA-Z0-9_-]{1,128}$/;
+const REPORTS = {
+    '/ai-report': 'mental-health',
+    '/ai-life-attitude': 'life-attitude',
+    '/ai-emotion-changes': 'emotion-change',
+    '/ai-personality': 'personality',
+    '/ai-custom-analysis': 'custom-analysis',
+};
+
+function unpack(value) {
+    if (typeof value !== 'string') return '';
+    if (/^https?:\/\//i.test(value)) return value;
+    try { return decodeURIComponent(value); } catch (_) { return ''; }
+}
+
+// Use the Mini Program JS runtime's string primitives (URL is not available on all clients).
+// Rebuild the public destination from known route fields; a web-view URL can contain login data.
+function publicDestination(value) {
+    const match = /^https:\/\/www\.yuban\.co(\/[^?#]*)?(?:\?([^#]*))?(?:#.*)?$/i.exec(unpack(value));
+    if (!match) return HOME;
+    const path = (match[1] || '/').replace(/\/$/, '') || '/';
+    const query = Object.create(null);
+    for (const part of (match[2] || '').split('&')) {
+        const at = part.indexOf('=');
+        if (at < 1) continue;
+        try { query[decodeURIComponent(part.slice(0, at))] = decodeURIComponent(part.slice(at + 1)); }
+        catch (_) { /* Ignore malformed optional fields. */ }
+    }
+    if (path === '/community') return ORIGIN + path + (query.tab === 'topic' ? '?tab=topic' : '');
+    const detail = /^\/(story|article|topic|family-preview)\/([a-zA-Z0-9_-]{1,128})$/.exec(path);
+    let kind;
+    let id;
+    let report;
+    if (detail) {
+        kind = detail[1] === 'article' ? 'story' : detail[1];
+        id = detail[2];
+    } else if (Object.prototype.hasOwnProperty.call(REPORTS, path)) {
+        kind = 'ai-report';
+        id = query.articleId;
+        report = REPORTS[path];
+        if (path === '/ai-custom-analysis' && query.reportType === 'interview-outline') report = query.reportType;
+    } else if (path === '/' || path === '/startup') {
+        kind = query.shareType;
+        id = query.shareId;
+        report = query.reportType;
+    }
+    if (!['story', 'topic', 'family-preview', 'ai-report'].includes(kind) || !id || !ID.test(id)) return HOME;
+    const url = ORIGIN + '/?shareType=' + kind + '&shareId=' + id;
+    if (kind !== 'ai-report') return url;
+    const known = Object.values(REPORTS).includes(report) || report === 'interview-outline';
+    return url + '&reportType=' + (known ? report : 'mental-health');
+}
+
+function shareCard(currentUrl) {
+    const destination = publicDestination(currentUrl);
+    return {
+        title: destination === ORIGIN + '/community?tab=topic' ? '语伴 · 专题广场'
+            : destination === ORIGIN + '/community' ? '语伴 · 社区广场' : '自传语伴',
+        path: '/' + PAGE + '?path=' + encodeURIComponent(destination) + '&fromShare=1&skipAuth=true',
+    };
+}
+
+function isLegacyChatEntry() {
+    if (typeof wx.getEnterOptionsSync !== 'function' ||
+        typeof getCurrentPages !== 'function' || getCurrentPages().length !== 1) return false;
+    const entry = wx.getEnterOptionsSync() || {};
+    return String(entry.path || '').replace(/^\//, '') === PAGE &&
+        [1007, 1008, 1044, 1096].includes(Number(entry.scene));
+}
+
+module.exports = { publicDestination, shareCard, isLegacyChatEntry };

+ 2 - 1
project.config.json

@@ -65,6 +65,7 @@
   },
   "packOptions": {
     "ignore": [
+      { "value": "tests", "type": "folder" },
       {
         "value": "package-lock.json",
         "type": "file"
@@ -80,4 +81,4 @@
   "appid": "wx56914f69b1563869",
   "libVersion": "3.6.6",
   "simulatorPluginLibVersion": {}
-}
+}

+ 13 - 3
test/governance-smoke.test.cjs

@@ -45,14 +45,24 @@ test('通用业务页经已登记登录页恢复原目标,保留查询与片
   const wx = {
     getStorageSync:key=>storage.get(key),setStorageSync:(key,value)=>storage.set(key,value),
     redirectTo:({url})=>{const address=new URL(url,'https://local.invalid');assert.ok(routes.has(address.pathname.slice(1)));history.push(address);},
-    showToast(){},
+    showToast(){},getLaunchOptionsSync:()=>({scene:1001}),
   };
   const load = file => {
-    vm.runInNewContext(fs.readFileSync(path.join(root,file),'utf8'), {
+    const context = vm.createContext({
       wx,getApp:()=>app,getCurrentPages:()=>[currentPage],console:{log(){},debug(){},error(){},warn(){}},
-      require:name=>name.endsWith('web-view-target')?target:{},
+      require:name=>{
+        if (name.endsWith('web-view-target')) return target;
+        if (name==='./share') {
+          const module={exports:{}};
+          const code=fs.readFileSync(path.join(root,'common-page/pages/web-view/share.js'),'utf8');
+          vm.runInContext('(function(module,exports){'+code+'})',context)(module,module.exports);
+          return module.exports;
+        }
+        return {};
+      },
       Page:def=>{currentPage={...def,data:{...def.data},setData(value){Object.assign(this.data,value);}};},
     });
+    vm.runInContext(fs.readFileSync(path.join(root,file),'utf8'),context);
     return currentPage;
   };
   const original='https://www.yuban.co/user-profile/memory-cleanup?tab=people&label=a%26b#family';

+ 90 - 0
test/web-view-share.test.cjs

@@ -0,0 +1,90 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const config = require('../app.json');
+
+const origin = 'https://www.yuban.co';
+const container = '/common-page/pages/web-view/index';
+let definition;
+global.Page = page => { definition = page; };
+const app = { Parse: { User: { current: () => null } }, globalData: {}, checkAuth: async () => {} };
+global.getApp = () => app;
+global.wx = { getStorageSync: () => '', redirectTo: () => {} };
+require('../common-page/pages/web-view/index');
+function newPage() {
+  return { ...definition, data: { ...definition.data }, setData(update) { Object.assign(this.data, update); } };
+}
+function recipientOptions(path) {
+  assert.equal(path.split('?')[0], container);
+  assert.ok(config.subpackages.some(pkg => pkg.pages.some(page => '/' + pkg.root + '/' + page === container)));
+  return Object.fromEntries(path.split('?').slice(1).join('?').split('&').map(pair => {
+    const split = pair.indexOf('=');
+    return [pair.slice(0, split), pair.slice(split + 1)];
+  }));
+}
+
+for (const route of ['/home','/community','/community?tab=topic']) {
+  test('a new recipient opens '+route, async () => {
+    const sender = newPage();
+    sender.data.path = origin + '/home?token=sender-session';
+    const current = origin + route + (route.includes('?') ? '&' : '?') + 'token=secret&mobile=13800000001';
+    const card = sender.onShareAppMessage({ webViewUrl: current });
+    assert.ok(card?.path, 'native menu must return a usable path');
+    assert.doesNotMatch(decodeURIComponent(card.path), /token|secret|mobile|13800000001/);
+    const recipient = newPage();
+    recipient.checkUserLogin = () => assert.fail('sharing should open before native login');
+    await recipient.onLoad(recipientOptions(card.path));
+    assert.equal(recipient.data.path, origin + route);
+  });
+}
+
+test('an old card without parameters opens a usable homepage', async () => {
+  const page = newPage();
+  await page.onLoad({});
+  assert.equal(page.data.path, origin + '/home');
+});
+
+test('an old chat card with a URL opens the original public destination', async t => {
+  global.getCurrentPages = () => [{}];
+  wx.getEnterOptionsSync = () => ({ path: container, scene: 1008 });
+  t.after(() => { delete global.getCurrentPages; delete wx.getEnterOptionsSync; });
+  const page = newPage();
+  await page.onLoad({ path: encodeURIComponent(origin + '/community?tab=topic&userId=sender') });
+  assert.equal(page.data.path, origin + '/community?tab=topic');
+});
+
+test('cards preserve supported content IDs and discard other fields', async () => {
+  for (const [path, landing] of [
+    ['/topic/t123?token=secret', '/?shareType=topic&shareId=t123'],
+    ['/article/abc_123', '/?shareType=story&shareId=abc_123'],
+    ['/ai-personality?articleId=r123&mobile=123', '/?shareType=ai-report&shareId=r123&reportType=personality'],
+    ['/family-preview/f123', '/?shareType=family-preview&shareId=f123'],
+    ['/community?tab=mine', '/community'],
+  ]) {
+    const sender = newPage();
+    sender.data.path = origin + path;
+    const recipient = newPage();
+    await recipient.onLoad(recipientOptions(sender.onShareAppMessage().path));
+    assert.equal(recipient.data.path, origin + landing);
+  }
+});
+
+test('a missing or invalid destination recovers to home', async () => {
+  for (const path of ['', '%', 'https://www.yuban.co.example/home', origin + '/user-profile']) {
+    const page = newPage();
+    await page.onLoad({ path, fromShare: '1' });
+    assert.equal(page.data.path, origin + '/home');
+  }
+});
+
+test('ordinary in-app launches retain the original auth and carousel paths', async () => {
+  const gated = newPage();
+  let checked = false;
+  gated.checkUserLogin = async () => { checked = true; return false; };
+  await gated.onLoad({ path: encodeURIComponent(origin + '/user-profile') });
+  assert.ok(checked);
+  assert.equal(gated.data.path, '');
+  const carousel = newPage();
+  await carousel.onLoad({ path: encodeURIComponent(origin + '/home'), skipAuth: 'true' });
+  assert.ok(carousel.data.path.startsWith(origin + '/home?'));
+  assert.match(carousel.data.path, /fromStartup=1/);
+});