浏览代码

fix(mobile): 修复微信浏览器下载链路(Web 2.4.439 / server 1.0.627)

Co-authored-by: Cursor <cursoragent@cursor.com>
YY968XX 12 小时之前
父节点
当前提交
ffed8ca9c7

+ 1 - 1
Web/package.json

@@ -1,7 +1,7 @@
 {
 	"name": "admin.net",
 	"type": "module",
-	"version": "2.4.438",
+	"version": "2.4.439",
 	"packageManager": "pnpm@10.32.1",
 	"lastBuildTime": "2026.03.15",
 	"description": "Admin.NET 站在巨人肩膀上的 .NET 通用权限开发框架",

+ 2 - 1
Web/src/components/auth/auth.vue

@@ -6,6 +6,7 @@
 import { computed } from 'vue';
 import { storeToRefs } from 'pinia';
 import { useUserInfo } from '/@/stores/userInfo';
+import { hasAuthPermission } from '/@/utils/authPermission';
 
 // 定义父组件传过来的值
 const props = defineProps({
@@ -21,6 +22,6 @@ const { userInfos } = storeToRefs(stores);
 
 // 获取 pinia 中的用户权限
 const getUserAuthBtnList = computed(() => {
-	return userInfos.value.authBtnList.some((v: string) => v === props.value);
+	return hasAuthPermission(userInfos.value, props.value);
 });
 </script>

+ 2 - 2
Web/src/components/auth/authAll.vue

@@ -6,7 +6,7 @@
 import { computed } from 'vue';
 import { storeToRefs } from 'pinia';
 import { useUserInfo } from '/@/stores/userInfo';
-import { judgementSameArr } from '/@/utils/arrayOperation';
+import { hasAllAuthPermissions } from '/@/utils/authPermission';
 
 // 定义父组件传过来的值
 const props = defineProps({
@@ -22,6 +22,6 @@ const { userInfos } = storeToRefs(stores);
 
 // 获取 pinia 中的用户权限
 const getUserAuthBtnList = computed(() => {
-	return judgementSameArr(props.value, userInfos.value.authBtnList);
+	return hasAllAuthPermissions(userInfos.value, props.value as string[]);
 });
 </script>

+ 4 - 11
Web/src/directive/authDirective.ts

@@ -1,6 +1,6 @@
 import type { App } from 'vue';
 import { useUserInfo } from '/@/stores/userInfo';
-import { judgementSameArr } from '/@/utils/arrayOperation';
+import { hasAllAuthPermissions, hasAnyAuthPermission, hasAuthPermission } from '/@/utils/authPermission';
 
 /**
  * 用户权限指令
@@ -13,28 +13,21 @@ export function authDirective(app: App) {
 	app.directive('auth', {
 		mounted(el, binding) {
 			const stores = useUserInfo();
-			if (!stores.userInfos.authBtnList.some((v: string) => v === binding.value)) el.parentNode.removeChild(el);
+			if (!hasAuthPermission(stores.userInfos, binding.value)) el.parentNode.removeChild(el);
 		},
 	});
 	// 多个权限验证,满足一个则显示(v-auths="[xxx,xxx]")
 	app.directive('auths', {
 		mounted(el, binding) {
-			let flag = false;
 			const stores = useUserInfo();
-			stores.userInfos.authBtnList.map((val: string) => {
-				binding.value.map((v: string) => {
-					if (val === v) flag = true;
-				});
-			});
-			if (!flag) el.parentNode.removeChild(el);
+			if (!hasAnyAuthPermission(stores.userInfos, binding.value)) el.parentNode.removeChild(el);
 		},
 	});
 	// 多个权限验证,全部满足则显示(v-auth-all="[xxx,xxx]")
 	app.directive('auth-all', {
 		mounted(el, binding) {
 			const stores = useUserInfo();
-			const flag = judgementSameArr(binding.value, stores.userInfos.authBtnList);
-			if (!flag) el.parentNode.removeChild(el);
+			if (!hasAllAuthPermissions(stores.userInfos, binding.value)) el.parentNode.removeChild(el);
 		},
 	});
 }

+ 4 - 0
Web/src/router/index.ts

@@ -12,6 +12,10 @@ import { Session } from '/@/utils/storage';
 import { dynamicRoutes, staticRoutes, notFoundAndNoPower } from '/@/router/route';
 import { initFrontEndControlRoutes } from '/@/router/frontEnd';
 import { initBackEndControlRoutes } from '/@/router/backEnd';
+import { restoreAppDownloadHashEntry } from '/@/views/app/downloadEntry';
+
+// 微信转外部浏览器时会丢弃 URL fragment;保留 path/query 后在路由初始化前恢复内部 hash 路由。
+restoreAppDownloadHashEntry();
 
 /**
  * 1、前端控制路由时:isRequestRoutes 为 false,需要写 roles,需要走 setFilterRoute 方法。

+ 31 - 0
Web/src/utils/authPermission.spec.ts

@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+import { hasAllAuthPermissions, hasAnyAuthPermission, hasAuthPermission, isSuperAdmin } from './authPermission';
+
+describe('authPermission', () => {
+	it('lets a super administrator pass every UI permission gate', () => {
+		const user = { accountType: 999, authBtnList: [] };
+
+		expect(isSuperAdmin(user)).toBe(true);
+		expect(hasAuthPermission(user, 'sysAppRelease:upload')).toBe(true);
+		expect(hasAnyAuthPermission(user, ['sysAppRelease:upload', 'sysAppRelease:publish'])).toBe(true);
+		expect(hasAllAuthPermissions(user, ['sysAppRelease:upload', 'sysAppRelease:publish'])).toBe(true);
+	});
+
+	it('keeps ordinary users restricted to their explicit permissions', () => {
+		const user = { accountType: 777, authBtnList: ['sysAppRelease:view'] };
+
+		expect(isSuperAdmin(user)).toBe(false);
+		expect(hasAuthPermission(user, 'sysAppRelease:view')).toBe(true);
+		expect(hasAuthPermission(user, 'sysAppRelease:upload')).toBe(false);
+		expect(hasAnyAuthPermission(user, ['sysAppRelease:view', 'sysAppRelease:upload'])).toBe(true);
+		expect(hasAllAuthPermissions(user, ['sysAppRelease:view', 'sysAppRelease:upload'])).toBe(false);
+	});
+
+	it('fails closed when the permission list is missing', () => {
+		const user = { accountType: 777 };
+
+		expect(hasAuthPermission(user, 'sysAppRelease:upload')).toBe(false);
+		expect(hasAnyAuthPermission(user, ['sysAppRelease:upload'])).toBe(false);
+		expect(hasAllAuthPermissions(user, ['sysAppRelease:upload'])).toBe(false);
+	});
+});

+ 26 - 0
Web/src/utils/authPermission.ts

@@ -0,0 +1,26 @@
+export const SUPER_ADMIN_ACCOUNT_TYPE = 999;
+
+export interface AuthPermissionUser {
+	accountType?: number | string;
+	authBtnList?: unknown;
+}
+
+function permissionsOf(userInfos: AuthPermissionUser): string[] {
+	return Array.isArray(userInfos?.authBtnList) ? userInfos.authBtnList.filter((item): item is string => typeof item === 'string') : [];
+}
+
+export function isSuperAdmin(userInfos: AuthPermissionUser): boolean {
+	return Number(userInfos?.accountType) === SUPER_ADMIN_ACCOUNT_TYPE;
+}
+
+export function hasAuthPermission(userInfos: AuthPermissionUser, permission: string): boolean {
+	return isSuperAdmin(userInfos) || permissionsOf(userInfos).includes(permission);
+}
+
+export function hasAnyAuthPermission(userInfos: AuthPermissionUser, permissions: string[]): boolean {
+	return isSuperAdmin(userInfos) || permissions.some((permission) => permissionsOf(userInfos).includes(permission));
+}
+
+export function hasAllAuthPermissions(userInfos: AuthPermissionUser, permissions: string[]): boolean {
+	return isSuperAdmin(userInfos) || permissions.every((permission) => permissionsOf(userInfos).includes(permission));
+}

+ 2 - 4
Web/src/views/app/downloadDialog.vue

@@ -28,11 +28,10 @@
 <script setup lang="ts" name="appDownloadDialog">
 import { nextTick, ref } from 'vue';
 import { ElMessage } from 'element-plus';
-import { useRouter } from 'vue-router';
 import QRCode from 'qrcodejs2-fixes';
 import { createAppDownloadTicket, type AppDownloadTicket } from './api';
+import { buildAppDownloadPageUrl } from './downloadEntry';
 
-const router = useRouter();
 const visible = ref(false);
 const loading = ref(false);
 const errorMessage = ref('');
@@ -51,8 +50,7 @@ async function refresh() {
 	ticket.value = undefined;
 	try {
 		ticket.value = await createAppDownloadTicket();
-		const href = router.resolve({ name: 'appDownload', query: { t: ticket.value.ticket } }).href;
-		downloadPageUrl.value = new URL(href, window.location.origin).toString();
+		downloadPageUrl.value = buildAppDownloadPageUrl(window.location.origin, ticket.value.ticket);
 		await nextTick();
 		if (!qrRef.value) return;
 		qrRef.value.innerHTML = '';

+ 22 - 0
Web/src/views/app/downloadEntry.spec.ts

@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+import { buildAppDownloadPageUrl, resolveAppDownloadHashEntry } from './downloadEntry';
+
+describe('APP download browser handoff entry', () => {
+	it('builds a hash-free QR URL that external browsers preserve', () => {
+		expect(buildAppDownloadPageUrl('https://42.236.69.208/', 'a+b_c')).toBe(
+			'https://42.236.69.208/app/download?t=a%2Bb_c',
+		);
+	});
+
+	it('restores the internal hash route while preserving the outer path and ticket', () => {
+		expect(resolveAppDownloadHashEntry('/app/download', '?t=a%2Bb_c', '')).toBe(
+			'/app/download?t=a%2Bb_c#/app/download?t=a%2Bb_c',
+		);
+	});
+
+	it('does not rewrite unrelated or already-restored locations', () => {
+		expect(resolveAppDownloadHashEntry('/', '?t=token', '')).toBeNull();
+		expect(resolveAppDownloadHashEntry('/app/download', '?t=token', '#/app/download?t=token')).toBeNull();
+		expect(resolveAppDownloadHashEntry('/app/download', '', '')).toBeNull();
+	});
+});

+ 22 - 0
Web/src/views/app/downloadEntry.ts

@@ -0,0 +1,22 @@
+export const APP_DOWNLOAD_ENTRY_PATH = '/app/download';
+
+export function buildAppDownloadPageUrl(origin: string, ticket: string): string {
+	const url = new URL(APP_DOWNLOAD_ENTRY_PATH, origin);
+	url.searchParams.set('t', ticket);
+	return url.toString();
+}
+
+export function resolveAppDownloadHashEntry(pathname: string, search: string, hash: string): string | null {
+	if (pathname !== APP_DOWNLOAD_ENTRY_PATH || hash.startsWith('#/app/download')) return null;
+
+	const ticket = new URLSearchParams(search).get('t')?.trim();
+	if (!ticket) return null;
+
+	const hashQuery = new URLSearchParams({ t: ticket }).toString();
+	return `${pathname}${search}#/app/download?${hashQuery}`;
+}
+
+export function restoreAppDownloadHashEntry(): void {
+	const target = resolveAppDownloadHashEntry(window.location.pathname, window.location.search, window.location.hash);
+	if (target) window.history.replaceState(window.history.state, '', target);
+}

+ 55 - 0
docker/nginx/default.conf

@@ -8,10 +8,37 @@ server {
     gzip on;
     gzip_types text/plain text/css application/json application/javascript application/xml image/svg+xml;
 
+    location = /app/download {
+        access_log off;
+        add_header Cache-Control "no-store" always;
+        add_header X-Content-Type-Options "nosniff" always;
+        add_header Referrer-Policy "no-referrer" always;
+        try_files /index.html =404;
+    }
+
     location / {
         try_files $uri $uri/ /index.html;
     }
 
+    # 一次性 APP 下载票据不得进入访问日志;APK 响应直接流式转发。
+    location ^~ /prod-api/api/sysAppRelease/ {
+        access_log off;
+        add_header Cache-Control "no-store" always;
+        rewrite ^/prod-api/(.*)$ /$1 break;
+        proxy_pass http://api:5005;
+        proxy_http_version 1.1;
+        proxy_buffering off;
+        proxy_set_header Host $host;
+        proxy_set_header X-Real-IP $remote_addr;
+        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+        proxy_set_header X-Forwarded-Proto $scheme;
+        proxy_set_header X-Forwarded-Prefix /prod-api;
+        proxy_connect_timeout 60s;
+        proxy_send_timeout 300s;
+        proxy_read_timeout 300s;
+        client_max_body_size 320m;
+    }
+
     # 与 Web/.env.production 中 VITE_API_URL=/prod-api 一致
     location /prod-api/ {
         proxy_pass http://api:5005/;
@@ -41,10 +68,38 @@ server {
     gzip on;
     gzip_types text/plain text/css application/json application/javascript application/xml image/svg+xml;
 
+    location = /app/download {
+        access_log off;
+        add_header Cache-Control "no-store" always;
+        add_header Strict-Transport-Security "max-age=31536000" always;
+        add_header X-Content-Type-Options "nosniff" always;
+        add_header Referrer-Policy "no-referrer" always;
+        try_files /index.html =404;
+    }
+
     location / {
         try_files $uri $uri/ /index.html;
     }
 
+    # 一次性 APP 下载票据不得进入访问日志;APK 响应直接流式转发。
+    location ^~ /prod-api/api/sysAppRelease/ {
+        access_log off;
+        add_header Cache-Control "no-store" always;
+        rewrite ^/prod-api/(.*)$ /$1 break;
+        proxy_pass http://api:5005;
+        proxy_http_version 1.1;
+        proxy_buffering off;
+        proxy_set_header Host $host;
+        proxy_set_header X-Real-IP $remote_addr;
+        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+        proxy_set_header X-Forwarded-Proto $scheme;
+        proxy_set_header X-Forwarded-Prefix /prod-api;
+        proxy_connect_timeout 60s;
+        proxy_send_timeout 300s;
+        proxy_read_timeout 300s;
+        client_max_body_size 320m;
+    }
+
     location /prod-api/ {
         proxy_pass http://api:5005/;
         proxy_http_version 1.1;

+ 3 - 0
server/Admin.NET.Core/Service/AppVersion/SysAppReleaseService.cs

@@ -128,6 +128,7 @@ public sealed class SysAppReleaseService : IDynamicApiController, ITransient
     /// <summary>
     /// 当前登录用户创建一次性下载票据。
     /// </summary>
+    [SuppressMonitor]
     [ApiDescriptionSettings(Name = "CreateTicket"), HttpPost]
     [DisplayName("创建APP下载票据")]
     public async Task<AppDownloadTicketOutput> CreateTicket()
@@ -140,6 +141,7 @@ public sealed class SysAppReleaseService : IDynamicApiController, ITransient
     /// 匿名手机端凭票读取展示元数据,不消费票据。
     /// </summary>
     [AllowAnonymous]
+    [SuppressMonitor]
     [ApiDescriptionSettings(Name = "TicketInfo"), HttpGet]
     [DisplayName("查看APP下载票据信息")]
     public async Task<AppTicketInfoOutput> TicketInfo([FromQuery] string ticket)
@@ -164,6 +166,7 @@ public sealed class SysAppReleaseService : IDynamicApiController, ITransient
     /// 匿名手机端消费一次性票据并下载;OSS 返回短时重定向,本地/SSH 安全转发文件流。
     /// </summary>
     [AllowAnonymous]
+    [SuppressMonitor]
     [ApiDescriptionSettings(Name = "Download"), HttpGet]
     [DisplayName("凭票下载APP")]
     public async Task<IActionResult> Download([FromQuery] string ticket)

+ 38 - 0
server/Admin.NET.Test/Security/AppReleaseSecurityTests.cs

@@ -201,6 +201,44 @@ public class AppReleaseSecurityTests
         Assert.DoesNotContain("app_android_presigned", config);
     }
 
+    [Theory]
+    [InlineData(nameof(SysAppReleaseService.CreateTicket))]
+    [InlineData(nameof(SysAppReleaseService.TicketInfo))]
+    [InlineData(nameof(SysAppReleaseService.Download))]
+    public void TicketBearingEndpoints_AreExcludedFromStructuredRequestLogs(string methodName)
+    {
+        var method = typeof(SysAppReleaseService).GetMethod(methodName);
+
+        Assert.NotNull(method);
+        Assert.Contains(method!.GetCustomAttributes(inherit: true), attribute =>
+            attribute.GetType().Name == "SuppressMonitorAttribute");
+    }
+
+    [Fact]
+    public void DownloadProxy_StreamsWithoutBufferingTicketBearingRequests()
+    {
+        var root = FindRepositoryRoot();
+        var nginx = File.ReadAllText(Path.Combine(root, "docker", "nginx", "default.conf"));
+        var appReleaseLocations = nginx.Split("location ^~ /prod-api/api/sysAppRelease/ {", StringSplitOptions.None);
+        var downloadPageLocations = nginx.Split("location = /app/download {", StringSplitOptions.None);
+
+        Assert.True(appReleaseLocations.Length >= 3);
+        Assert.All(appReleaseLocations.Skip(1), location =>
+        {
+            var block = location.Split('}', 2)[0];
+            Assert.Contains("access_log off;", block);
+            Assert.Contains("proxy_buffering off;", block);
+        });
+        Assert.True(downloadPageLocations.Length >= 3);
+        Assert.All(downloadPageLocations.Skip(1), location =>
+        {
+            var block = location.Split('}', 2)[0];
+            Assert.Contains("access_log off;", block);
+            Assert.Contains("try_files /index.html =404;", block);
+            Assert.Contains("Referrer-Policy \"no-referrer\"", block);
+        });
+    }
+
     private static AppReleaseSnapshot CurrentRelease() => new()
     {
         FileId = 10,

+ 3 - 3
server/Admin.NET.Web.Entry/Admin.NET.Web.Entry.csproj

@@ -11,9 +11,9 @@
     <GenerateSatelliteAssembliesForCore>true</GenerateSatelliteAssembliesForCore>
     <Copyright>Admin.NET</Copyright>
     <Description>Admin.NET 通用权限开发平台</Description>
-    <AssemblyVersion>1.0.626</AssemblyVersion>
-    <FileVersion>1.0.626</FileVersion>
-    <Version>1.0.626</Version>
+    <AssemblyVersion>1.0.627</AssemblyVersion>
+    <FileVersion>1.0.627</FileVersion>
+    <Version>1.0.627</Version>
   </PropertyGroup>
 
   <ItemGroup>