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
14 changes: 14 additions & 0 deletions deploy/nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ map $biterstore_forwarded_proto $biterstore_hsts {
https "max-age=31536000; includeSubDomains";
}

map $http_origin $biterstore_cors_origin {
default "";
https://www.biterstore.top $http_origin;
https://store.young581.com $http_origin;
}

# Keep redirects on the hostname that the client used. The map avoids turning
# an untrusted Host header into an open redirect while allowing the campus
# entry point to coexist with the legacy public entry point.
Expand Down Expand Up @@ -185,6 +191,14 @@ server {
}

location /api/ {
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin $biterstore_cors_origin always;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Methods "GET, HEAD, POST, PATCH, PUT, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers $http_access_control_request_headers always;
add_header Access-Control-Max-Age 600 always;
return 204;
}
limit_req zone=biterstore_api_global burst=300 nodelay;
limit_req zone=biterstore_upload_global burst=30 nodelay;
limit_req zone=biterstore_recognition_global burst=5 nodelay;
Expand Down
2 changes: 2 additions & 0 deletions miniProgram/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ export default defineConfig<'webpack5'>(async (merge) => {
copy: {
patterns: [...assetPatterns, ...(!isWeapp ? [
{ from: 'src/hosting/_redirects', to: 'dist' },
{ from: 'src/hosting/robots.txt', to: 'dist/robots.txt' },
{ from: 'src/hosting/sitemap.xml', to: 'dist/sitemap.xml' },
{ from: path.resolve(__dirname, '../../web/public/sw.js'), to: 'dist/sw.js' }
] : [])],
options: {}
Expand Down
12 changes: 9 additions & 3 deletions miniProgram/nginx.h5.conf
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ server {
absolute_redirect off;
root /usr/share/nginx/html;

gzip on;
gzip_vary on;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_types text/plain text/css text/javascript application/javascript application/json application/manifest+json image/svg+xml;

# Browser-facing routes use query parameters because Taro's H5 router only
# registers static paths. Preserve older pretty links by canonicalizing them
# before the client bundle starts.
Expand Down Expand Up @@ -35,21 +41,21 @@ server {
try_files $uri =404;
add_header Cache-Control "no-cache";
}
location = /robots.txt { try_files $uri =404; default_type text/plain; }
location = /sitemap.xml { try_files $uri =404; default_type application/xml; }
location ~* \.(js|css)$ {
try_files $uri =404;
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
}
location ~* \.(png|jpg|jpeg|webp|svg|ico)$ {
try_files $uri =404;
expires 7d;
add_header Cache-Control "public, max-age=604800";
}

location / {
try_files $uri @app_not_found;
}
location @app_not_found {
return 302 /states?type=404;
return 404;
}
}
3 changes: 3 additions & 0 deletions miniProgram/src/hosting/robots.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
User-agent: *
Allow: /
Sitemap: https://www.biterstore.top/sitemap.xml
7 changes: 7 additions & 0 deletions miniProgram/src/hosting/sitemap.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>https://www.biterstore.top/</loc></url>
<url><loc>https://www.biterstore.top/welcome</loc></url>
<url><loc>https://www.biterstore.top/home</loc></url>
<url><loc>https://www.biterstore.top/search</loc></url>
</urlset>
6 changes: 5 additions & 1 deletion server/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ async function bootstrap() {
})
await app.register(cookie, { secret: accessTokenSecret() })
app.setGlobalPrefix('api/v1')
app.enableCors({ origin: (process.env.H5_ORIGIN || '').split(',').filter(Boolean), credentials: true })
app.enableCors({
origin: (process.env.H5_ORIGIN || '').split(',').filter(Boolean),
credentials: true,
methods: ['GET', 'HEAD', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS']
})
if (process.env.NODE_ENV !== 'production') {
const config = new DocumentBuilder().setTitle('梨苑儿 API').setVersion('1').addBearerAuth().build()
SwaggerModule.setup('docs', app, SwaggerModule.createDocument(app, config))
Expand Down
3 changes: 2 additions & 1 deletion server/src/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Body, Controller, Get, Headers, Post, Query, Req, Res, UseGuards } from '@nestjs/common'
import { Body, Controller, Get, Headers, HttpCode, Post, Query, Req, Res, UseGuards } from '@nestjs/common'
import type { FastifyReply, FastifyRequest } from 'fastify'
import { AuthGuard, CurrentUser, type AuthUser } from '../../common/auth.js'
import { AuthService } from './auth.service.js'
Expand Down Expand Up @@ -61,6 +61,7 @@ export class AuthController {
}

@Post('logout')
@HttpCode(204)
async logout(
@Body() body: unknown,
@Req() request: FastifyRequest,
Expand Down
3 changes: 2 additions & 1 deletion server/test/deployment-config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ describe('production gateway', () => {
expect(h5Nginx).toContain('return 302 /books?id=$1;')
expect(h5Nginx).toContain('return 302 /chat?id=$1;')
expect(h5Nginx).toContain('return 302 /notifications?type=$1;')
expect(h5Nginx).toContain('return 302 /states?type=404;')
expect(h5Nginx).toContain('location @app_not_found')
expect(h5Nginx).toContain('return 404;')
expect(h5Nginx).toContain('location = /sw.js')
})

Expand Down
19 changes: 12 additions & 7 deletions web/app/components/mobile-app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ const UI_ASSETS = [
'/assets/tobby-question.webp', '/assets/tobby-sad.webp', '/assets/tobby-search.webp',
'/assets/tobby-unavailable.webp',
] as const;
const UI_CRITICAL_ASSETS = UI_ASSETS.slice(0, 5);

const CurrentUserContext = createContext<User | undefined>(undefined);
function warmAccountSnapshots() { return Promise.allSettled([demoRepository.listFavorites(), demoRepository.listMyListings(), demoRepository.listThreads(), demoRepository.listNotifications()]); }
Expand Down Expand Up @@ -135,20 +136,20 @@ function profileToUser(profile: H5Profile): User {
};
}

async function warmUiAssetBundle(onProgress: (value: number) => void) {
async function warmUiAssetBundle(onProgress: (value: number) => void, assets: readonly string[] = UI_ASSETS) {
const workerReady = 'serviceWorker' in navigator
? navigator.serviceWorker.register('/sw.js', { scope: '/' }).then(() => navigator.serviceWorker.ready).catch(() => undefined)
: Promise.resolve(undefined);
let completed = 0;
await Promise.all(UI_ASSETS.map((src) => new Promise<void>((resolve) => {
await Promise.all(assets.map((src) => new Promise<void>((resolve) => {
const asset = new window.Image();
let settled = false;
const done = () => {
if (settled) return;
settled = true;
window.clearTimeout(timeout);
completed += 1;
onProgress(Math.round((completed / UI_ASSETS.length) * 100));
onProgress(Math.round((completed / assets.length) * 100));
resolve();
};
const timeout = window.setTimeout(done, 12000);
Expand Down Expand Up @@ -890,17 +891,21 @@ export function MobileApp({ initialPath }: { initialPath: string }) {
let active = true;
const cached = window.localStorage.getItem(UI_ASSET_BUNDLE_KEY) === UI_ASSET_BUNDLE_VERSION;
if (cached) {
void warmUiAssetBundle(() => undefined);
void warmUiAssetBundle(() => undefined, UI_CRITICAL_ASSETS);
return () => { active = false; };
}
const started = Date.now();
warmUiAssetBundle((value) => { if (active) setAssetProgress(value); }).then(async (complete) => {
if (complete) window.localStorage.setItem(UI_ASSET_BUNDLE_KEY, UI_ASSET_BUNDLE_VERSION);
warmUiAssetBundle((value) => { if (active) setAssetProgress(value); }, UI_CRITICAL_ASSETS).then(async () => {
const remaining = Math.max(0, 900 - (Date.now() - started));
if (remaining) await new Promise((resolve) => window.setTimeout(resolve, remaining));
if (active) { setAssetProgress(100); setAssetsReady(true); }
});
return () => { active = false; };
const deferred = window.setTimeout(() => {
void warmUiAssetBundle(() => undefined).then((complete) => {
if (complete) window.localStorage.setItem(UI_ASSET_BUNDLE_KEY, UI_ASSET_BUNDLE_VERSION);
});
}, 1500);
return () => { active = false; window.clearTimeout(deferred); };
}, []);
useEffect(() => {
let active = true;
Expand Down
Loading