@windrun-huaiin/backend-core 14.3.0 → 14.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@ require('../../../../prisma/prisma.js');
9
9
  require('../../../../services/database/credit.service.js');
10
10
  var transaction_service = require('../../../../services/database/transaction.service.js');
11
11
  require('@prisma/client');
12
- var authUtils = require('../../../../lib/auth-utils.js');
12
+ var authUtils = require('../../../../auth/auth-utils.js');
13
13
  var moneyPriceConfig = require('../../../../lib/money-price-config.js');
14
14
 
15
15
  // Request validation schema
@@ -7,7 +7,7 @@ import '../../../../prisma/prisma.mjs';
7
7
  import '../../../../services/database/credit.service.mjs';
8
8
  import { transactionService } from '../../../../services/database/transaction.service.mjs';
9
9
  import '@prisma/client';
10
- import { ApiAuthUtils } from '../../../../lib/auth-utils.mjs';
10
+ import { ApiAuthUtils } from '../../../../auth/auth-utils.mjs';
11
11
  import { getPriceConfig } from '../../../../lib/money-price-config.mjs';
12
12
 
13
13
  // Request validation schema
@@ -4,7 +4,7 @@ var tslib_es6 = require('../../../../node_modules/.pnpm/@rollup_plugin-typescrip
4
4
  var server = require('next/server');
5
5
  var zod = require('zod');
6
6
  var stripeConfig = require('../../../../lib/stripe-config.js');
7
- var authUtils = require('../../../../lib/auth-utils.js');
7
+ var authUtils = require('../../../../auth/auth-utils.js');
8
8
  require('../../../../prisma/prisma.js');
9
9
  var subscription_service = require('../../../../services/database/subscription.service.js');
10
10
  require('../../../../services/database/credit.service.js');
@@ -2,7 +2,7 @@ import { __awaiter } from '../../../../node_modules/.pnpm/@rollup_plugin-typescr
2
2
  import { NextResponse } from 'next/server';
3
3
  import { z } from 'zod';
4
4
  import { createOrGetCustomer, createCustomerPortalSession } from '../../../../lib/stripe-config.mjs';
5
- import { ApiAuthUtils } from '../../../../lib/auth-utils.mjs';
5
+ import { ApiAuthUtils } from '../../../../auth/auth-utils.mjs';
6
6
  import '../../../../prisma/prisma.mjs';
7
7
  import { subscriptionService } from '../../../../services/database/subscription.service.mjs';
8
8
  import '../../../../services/database/credit.service.mjs';
@@ -0,0 +1,13 @@
1
+ import type { ClerkMiddlewareAuth } from '@clerk/nextjs/server';
2
+ import { NextRequest, NextResponse } from 'next/server';
3
+ import { type ProviderIdentity } from './auth-shared';
4
+ export declare function buildProtectedPageRoutePatterns(protectedRoots: readonly string[], locales: readonly string[]): string[];
5
+ export interface AuthMiddlewareOptions {
6
+ protectedPageRoutes: (req: NextRequest) => boolean;
7
+ protectedApiRoutes: (req: NextRequest) => boolean;
8
+ publicApiRoutes: (req: NextRequest) => boolean;
9
+ intlMiddleware: (req: NextRequest) => ReturnType<typeof NextResponse.next> | Response | undefined;
10
+ }
11
+ export declare function buildAuthenticatedRequestHeaders(req: NextRequest, auth: ProviderIdentity): Headers;
12
+ export declare function handleAuthMiddleware(auth: ClerkMiddlewareAuth, req: NextRequest, options: AuthMiddlewareOptions): Promise<Response | null | undefined>;
13
+ //# sourceMappingURL=auth-middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-middleware.d.ts","sourceRoot":"","sources":["../../src/auth/auth-middleware.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACxD,OAAO,EAAgB,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEpE,wBAAgB,+BAA+B,CAC7C,cAAc,EAAE,SAAS,MAAM,EAAE,EACjC,OAAO,EAAE,SAAS,MAAM,EAAE,GACzB,MAAM,EAAE,CAsBV;AAED,MAAM,WAAW,qBAAqB;IACpC,mBAAmB,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC;IACnD,kBAAkB,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC;IAClD,eAAe,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,OAAO,CAAC;IAC/C,cAAc,EAAE,CAAC,GAAG,EAAE,WAAW,KAAK,UAAU,CAAC,OAAO,YAAY,CAAC,IAAI,CAAC,GAAG,QAAQ,GAAG,SAAS,CAAC;CACnG;AAcD,wBAAgB,gCAAgC,CAC9C,GAAG,EAAE,WAAW,EAChB,IAAI,EAAE,gBAAgB,GACrB,OAAO,CAKT;AAED,wBAAsB,oBAAoB,CACxC,IAAI,EAAE,mBAAmB,EACzB,GAAG,EAAE,WAAW,EAChB,OAAO,EAAE,qBAAqB,wCA6C/B"}
@@ -0,0 +1,86 @@
1
+ 'use strict';
2
+
3
+ var tslib_es6 = require('../node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.js');
4
+ var server = require('next/server');
5
+ var authShared = require('./auth-shared.js');
6
+
7
+ function buildProtectedPageRoutePatterns(protectedRoots, locales) {
8
+ const uniqueRoots = [...new Set(protectedRoots)]
9
+ .map((root) => root.trim())
10
+ .filter(Boolean)
11
+ .map((root) => (root.startsWith('/') ? root : `/${root}`))
12
+ .map((root) => root.replace(/\/+$/, ''));
13
+ const uniqueLocales = [...new Set(locales)]
14
+ .map((locale) => locale.trim())
15
+ .filter(Boolean);
16
+ const patterns = new Set();
17
+ for (const root of uniqueRoots) {
18
+ patterns.add(`${root}(.*)`);
19
+ for (const locale of uniqueLocales) {
20
+ patterns.add(`/${locale}${root}(.*)`);
21
+ }
22
+ }
23
+ return [...patterns];
24
+ }
25
+ function authenticateWithClerk(auth) {
26
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
27
+ const { userId } = yield auth();
28
+ if (!userId) {
29
+ return null;
30
+ }
31
+ return {
32
+ provider: 'clerk',
33
+ providerUserId: userId,
34
+ };
35
+ });
36
+ }
37
+ function buildAuthenticatedRequestHeaders(req, auth) {
38
+ const headers = new Headers(req.headers);
39
+ headers.set(authShared.AUTH_HEADERS.provider, auth.provider);
40
+ headers.set(authShared.AUTH_HEADERS.providerUserId, auth.providerUserId);
41
+ return headers;
42
+ }
43
+ function handleAuthMiddleware(auth, req, options) {
44
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
45
+ const { protectedPageRoutes, protectedApiRoutes, publicApiRoutes, intlMiddleware } = options;
46
+ if (protectedPageRoutes(req)) {
47
+ const identity = yield authenticateWithClerk(auth);
48
+ if (!identity) {
49
+ return (yield auth()).redirectToSignIn();
50
+ }
51
+ const requestHeaders = buildAuthenticatedRequestHeaders(req, identity);
52
+ console.log('Forward auth context for protected page:', identity.provider, identity.providerUserId);
53
+ return intlMiddleware(new server.NextRequest(req.url, {
54
+ headers: requestHeaders,
55
+ method: req.method,
56
+ body: req.body,
57
+ }));
58
+ }
59
+ if (protectedApiRoutes(req)) {
60
+ const identity = yield authenticateWithClerk(auth);
61
+ if (!identity) {
62
+ return (yield auth()).redirectToSignIn();
63
+ }
64
+ const requestHeaders = buildAuthenticatedRequestHeaders(req, identity);
65
+ console.log('Forward auth context for protected API:', identity.provider, identity.providerUserId);
66
+ return server.NextResponse.next({
67
+ request: {
68
+ headers: requestHeaders,
69
+ },
70
+ });
71
+ }
72
+ if (publicApiRoutes(req)) {
73
+ console.log('Public API route, no auth required:', req.nextUrl.pathname);
74
+ return server.NextResponse.next();
75
+ }
76
+ if (req.nextUrl.pathname.startsWith('/api/')) {
77
+ console.log('Other API route, no internationalization:', req.nextUrl.pathname);
78
+ return server.NextResponse.next();
79
+ }
80
+ return null;
81
+ });
82
+ }
83
+
84
+ exports.buildAuthenticatedRequestHeaders = buildAuthenticatedRequestHeaders;
85
+ exports.buildProtectedPageRoutePatterns = buildProtectedPageRoutePatterns;
86
+ exports.handleAuthMiddleware = handleAuthMiddleware;
@@ -0,0 +1,82 @@
1
+ import { __awaiter } from '../node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.mjs';
2
+ import { NextRequest, NextResponse } from 'next/server';
3
+ import { AUTH_HEADERS } from './auth-shared.mjs';
4
+
5
+ function buildProtectedPageRoutePatterns(protectedRoots, locales) {
6
+ const uniqueRoots = [...new Set(protectedRoots)]
7
+ .map((root) => root.trim())
8
+ .filter(Boolean)
9
+ .map((root) => (root.startsWith('/') ? root : `/${root}`))
10
+ .map((root) => root.replace(/\/+$/, ''));
11
+ const uniqueLocales = [...new Set(locales)]
12
+ .map((locale) => locale.trim())
13
+ .filter(Boolean);
14
+ const patterns = new Set();
15
+ for (const root of uniqueRoots) {
16
+ patterns.add(`${root}(.*)`);
17
+ for (const locale of uniqueLocales) {
18
+ patterns.add(`/${locale}${root}(.*)`);
19
+ }
20
+ }
21
+ return [...patterns];
22
+ }
23
+ function authenticateWithClerk(auth) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ const { userId } = yield auth();
26
+ if (!userId) {
27
+ return null;
28
+ }
29
+ return {
30
+ provider: 'clerk',
31
+ providerUserId: userId,
32
+ };
33
+ });
34
+ }
35
+ function buildAuthenticatedRequestHeaders(req, auth) {
36
+ const headers = new Headers(req.headers);
37
+ headers.set(AUTH_HEADERS.provider, auth.provider);
38
+ headers.set(AUTH_HEADERS.providerUserId, auth.providerUserId);
39
+ return headers;
40
+ }
41
+ function handleAuthMiddleware(auth, req, options) {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ const { protectedPageRoutes, protectedApiRoutes, publicApiRoutes, intlMiddleware } = options;
44
+ if (protectedPageRoutes(req)) {
45
+ const identity = yield authenticateWithClerk(auth);
46
+ if (!identity) {
47
+ return (yield auth()).redirectToSignIn();
48
+ }
49
+ const requestHeaders = buildAuthenticatedRequestHeaders(req, identity);
50
+ console.log('Forward auth context for protected page:', identity.provider, identity.providerUserId);
51
+ return intlMiddleware(new NextRequest(req.url, {
52
+ headers: requestHeaders,
53
+ method: req.method,
54
+ body: req.body,
55
+ }));
56
+ }
57
+ if (protectedApiRoutes(req)) {
58
+ const identity = yield authenticateWithClerk(auth);
59
+ if (!identity) {
60
+ return (yield auth()).redirectToSignIn();
61
+ }
62
+ const requestHeaders = buildAuthenticatedRequestHeaders(req, identity);
63
+ console.log('Forward auth context for protected API:', identity.provider, identity.providerUserId);
64
+ return NextResponse.next({
65
+ request: {
66
+ headers: requestHeaders,
67
+ },
68
+ });
69
+ }
70
+ if (publicApiRoutes(req)) {
71
+ console.log('Public API route, no auth required:', req.nextUrl.pathname);
72
+ return NextResponse.next();
73
+ }
74
+ if (req.nextUrl.pathname.startsWith('/api/')) {
75
+ console.log('Other API route, no internationalization:', req.nextUrl.pathname);
76
+ return NextResponse.next();
77
+ }
78
+ return null;
79
+ });
80
+ }
81
+
82
+ export { buildAuthenticatedRequestHeaders, buildProtectedPageRoutePatterns, handleAuthMiddleware };
@@ -0,0 +1,14 @@
1
+ export declare const AUTH_HEADERS: {
2
+ readonly provider: "x-auth-provider";
3
+ readonly providerUserId: "x-auth-provider-user-id";
4
+ };
5
+ export declare const AUTH_ERRORS: {
6
+ readonly unauthorized: "UNAUTHORIZED";
7
+ readonly userNotFound: "USER_NOT_FOUND";
8
+ };
9
+ export type AuthProvider = 'clerk';
10
+ export interface ProviderIdentity {
11
+ provider: AuthProvider;
12
+ providerUserId: string;
13
+ }
14
+ //# sourceMappingURL=auth-shared.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-shared.d.ts","sourceRoot":"","sources":["../../src/auth/auth-shared.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,YAAY;;;CAGf,CAAC;AAEX,eAAO,MAAM,WAAW;;;CAGd,CAAC;AAEX,MAAM,MAAM,YAAY,GAAG,OAAO,CAAC;AAEnC,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,EAAE,YAAY,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;CACxB"}
@@ -0,0 +1,13 @@
1
+ 'use strict';
2
+
3
+ const AUTH_HEADERS = {
4
+ provider: 'x-auth-provider',
5
+ providerUserId: 'x-auth-provider-user-id',
6
+ };
7
+ const AUTH_ERRORS = {
8
+ unauthorized: 'UNAUTHORIZED',
9
+ userNotFound: 'USER_NOT_FOUND',
10
+ };
11
+
12
+ exports.AUTH_ERRORS = AUTH_ERRORS;
13
+ exports.AUTH_HEADERS = AUTH_HEADERS;
@@ -0,0 +1,10 @@
1
+ const AUTH_HEADERS = {
2
+ provider: 'x-auth-provider',
3
+ providerUserId: 'x-auth-provider-user-id',
4
+ };
5
+ const AUTH_ERRORS = {
6
+ unauthorized: 'UNAUTHORIZED',
7
+ userNotFound: 'USER_NOT_FOUND',
8
+ };
9
+
10
+ export { AUTH_ERRORS, AUTH_HEADERS };
@@ -0,0 +1,48 @@
1
+ import { NextRequest } from 'next/server';
2
+ import { User } from '../services/database/prisma-model-type';
3
+ import { type AuthProvider } from './auth-shared';
4
+ /**
5
+ * 认证结果类型
6
+ */
7
+ export interface AuthResult {
8
+ userId: string;
9
+ user: User;
10
+ provider: AuthProvider;
11
+ providerUserId: string;
12
+ }
13
+ /**
14
+ * 从中间件设置的 Clerk ID 获取完整用户信息
15
+ */
16
+ export declare function getAuthenticatedUser(req: NextRequest): Promise<AuthResult>;
17
+ /**
18
+ * 要求用户必须已认证,返回用户ID
19
+ */
20
+ export declare function requireAuth(req: NextRequest): Promise<string>;
21
+ /**
22
+ * 要求用户必须已认证,返回完整用户信息
23
+ */
24
+ export declare function requireAuthWithUser(req: NextRequest): Promise<AuthResult>;
25
+ /**
26
+ * API Route版本的认证工具函数
27
+ */
28
+ export declare class ApiAuthUtils {
29
+ private req;
30
+ constructor(req: NextRequest);
31
+ /**
32
+ * 要求用户必须已认证,返回用户ID
33
+ */
34
+ requireAuth(): Promise<string>;
35
+ /**
36
+ * 要求用户必须已认证,返回完整用户信息
37
+ */
38
+ requireAuthWithUser(): Promise<AuthResult>;
39
+ /**
40
+ * 获取用户ID(如果已认证)
41
+ */
42
+ getUserId(): Promise<string | null>;
43
+ /**
44
+ * 获取完整用户信息(如果已认证)
45
+ */
46
+ getUser(): Promise<AuthResult | null>;
47
+ }
48
+ //# sourceMappingURL=auth-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-utils.d.ts","sourceRoot":"","sources":["../../src/auth/auth-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE1C,OAAO,EAAE,IAAI,EAAE,MAAM,wCAAwC,CAAC;AAC9D,OAAO,EAA6B,KAAK,YAAY,EAAE,MAAM,eAAe,CAAC;AAE7E;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,IAAI,CAAC;IACX,QAAQ,EAAE,YAAY,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;;GAEG;AACH,wBAAsB,oBAAoB,CAAC,GAAG,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAuBhF;AAED;;GAEG;AACH,wBAAsB,WAAW,CAAC,GAAG,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,CAAC,CAGnE;AAED;;GAEG;AACH,wBAAsB,mBAAmB,CAAC,GAAG,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC,CAE/E;AAED;;GAEG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,GAAG,CAAc;gBAEb,GAAG,EAAE,WAAW;IAI5B;;OAEG;IACG,WAAW,IAAI,OAAO,CAAC,MAAM,CAAC;IAIpC;;OAEG;IACG,mBAAmB,IAAI,OAAO,CAAC,UAAU,CAAC;IAIhD;;OAEG;IACG,SAAS,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IASzC;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;CAO5C"}
@@ -0,0 +1,110 @@
1
+ 'use strict';
2
+
3
+ var tslib_es6 = require('../node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.js');
4
+ var user_service = require('../services/database/user.service.js');
5
+ require('../prisma/prisma.js');
6
+ require('../services/database/credit.service.js');
7
+ require('@prisma/client');
8
+ var authShared = require('./auth-shared.js');
9
+
10
+ /**
11
+ * 从中间件设置的 Clerk ID 获取完整用户信息
12
+ */
13
+ function getAuthenticatedUser(req) {
14
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
15
+ try {
16
+ const provider = req.headers.get(authShared.AUTH_HEADERS.provider);
17
+ const providerUserId = req.headers.get(authShared.AUTH_HEADERS.providerUserId);
18
+ if (provider !== 'clerk' || !providerUserId) {
19
+ throw new Error(authShared.AUTH_ERRORS.unauthorized);
20
+ }
21
+ const user = yield user_service.userService.findByClerkUserId(providerUserId);
22
+ if (!user) {
23
+ throw new Error(authShared.AUTH_ERRORS.userNotFound);
24
+ }
25
+ return {
26
+ userId: user.userId,
27
+ user,
28
+ provider: 'clerk',
29
+ providerUserId,
30
+ };
31
+ }
32
+ catch (error) {
33
+ console.error('Error getting authenticated user:', error);
34
+ throw error;
35
+ }
36
+ });
37
+ }
38
+ /**
39
+ * 要求用户必须已认证,返回用户ID
40
+ */
41
+ function requireAuth(req) {
42
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
43
+ const auth = yield getAuthenticatedUser(req);
44
+ return auth.userId;
45
+ });
46
+ }
47
+ /**
48
+ * 要求用户必须已认证,返回完整用户信息
49
+ */
50
+ function requireAuthWithUser(req) {
51
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
52
+ return yield getAuthenticatedUser(req);
53
+ });
54
+ }
55
+ /**
56
+ * API Route版本的认证工具函数
57
+ */
58
+ class ApiAuthUtils {
59
+ constructor(req) {
60
+ this.req = req;
61
+ }
62
+ /**
63
+ * 要求用户必须已认证,返回用户ID
64
+ */
65
+ requireAuth() {
66
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
67
+ return yield requireAuth(this.req);
68
+ });
69
+ }
70
+ /**
71
+ * 要求用户必须已认证,返回完整用户信息
72
+ */
73
+ requireAuthWithUser() {
74
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
75
+ return yield requireAuthWithUser(this.req);
76
+ });
77
+ }
78
+ /**
79
+ * 获取用户ID(如果已认证)
80
+ */
81
+ getUserId() {
82
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
83
+ try {
84
+ const auth = yield getAuthenticatedUser(this.req);
85
+ return auth.userId;
86
+ }
87
+ catch (_a) {
88
+ return null;
89
+ }
90
+ });
91
+ }
92
+ /**
93
+ * 获取完整用户信息(如果已认证)
94
+ */
95
+ getUser() {
96
+ return tslib_es6.__awaiter(this, void 0, void 0, function* () {
97
+ try {
98
+ return yield getAuthenticatedUser(this.req);
99
+ }
100
+ catch (_a) {
101
+ return null;
102
+ }
103
+ });
104
+ }
105
+ }
106
+
107
+ exports.ApiAuthUtils = ApiAuthUtils;
108
+ exports.getAuthenticatedUser = getAuthenticatedUser;
109
+ exports.requireAuth = requireAuth;
110
+ exports.requireAuthWithUser = requireAuthWithUser;
@@ -0,0 +1,105 @@
1
+ import { __awaiter } from '../node_modules/.pnpm/@rollup_plugin-typescript@12.1.4_rollup@4.46.2_tslib@2.8.1_typescript@5.9.3/node_modules/tslib/tslib.es6.mjs';
2
+ import { userService } from '../services/database/user.service.mjs';
3
+ import '../prisma/prisma.mjs';
4
+ import '../services/database/credit.service.mjs';
5
+ import '@prisma/client';
6
+ import { AUTH_HEADERS, AUTH_ERRORS } from './auth-shared.mjs';
7
+
8
+ /**
9
+ * 从中间件设置的 Clerk ID 获取完整用户信息
10
+ */
11
+ function getAuthenticatedUser(req) {
12
+ return __awaiter(this, void 0, void 0, function* () {
13
+ try {
14
+ const provider = req.headers.get(AUTH_HEADERS.provider);
15
+ const providerUserId = req.headers.get(AUTH_HEADERS.providerUserId);
16
+ if (provider !== 'clerk' || !providerUserId) {
17
+ throw new Error(AUTH_ERRORS.unauthorized);
18
+ }
19
+ const user = yield userService.findByClerkUserId(providerUserId);
20
+ if (!user) {
21
+ throw new Error(AUTH_ERRORS.userNotFound);
22
+ }
23
+ return {
24
+ userId: user.userId,
25
+ user,
26
+ provider: 'clerk',
27
+ providerUserId,
28
+ };
29
+ }
30
+ catch (error) {
31
+ console.error('Error getting authenticated user:', error);
32
+ throw error;
33
+ }
34
+ });
35
+ }
36
+ /**
37
+ * 要求用户必须已认证,返回用户ID
38
+ */
39
+ function requireAuth(req) {
40
+ return __awaiter(this, void 0, void 0, function* () {
41
+ const auth = yield getAuthenticatedUser(req);
42
+ return auth.userId;
43
+ });
44
+ }
45
+ /**
46
+ * 要求用户必须已认证,返回完整用户信息
47
+ */
48
+ function requireAuthWithUser(req) {
49
+ return __awaiter(this, void 0, void 0, function* () {
50
+ return yield getAuthenticatedUser(req);
51
+ });
52
+ }
53
+ /**
54
+ * API Route版本的认证工具函数
55
+ */
56
+ class ApiAuthUtils {
57
+ constructor(req) {
58
+ this.req = req;
59
+ }
60
+ /**
61
+ * 要求用户必须已认证,返回用户ID
62
+ */
63
+ requireAuth() {
64
+ return __awaiter(this, void 0, void 0, function* () {
65
+ return yield requireAuth(this.req);
66
+ });
67
+ }
68
+ /**
69
+ * 要求用户必须已认证,返回完整用户信息
70
+ */
71
+ requireAuthWithUser() {
72
+ return __awaiter(this, void 0, void 0, function* () {
73
+ return yield requireAuthWithUser(this.req);
74
+ });
75
+ }
76
+ /**
77
+ * 获取用户ID(如果已认证)
78
+ */
79
+ getUserId() {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ try {
82
+ const auth = yield getAuthenticatedUser(this.req);
83
+ return auth.userId;
84
+ }
85
+ catch (_a) {
86
+ return null;
87
+ }
88
+ });
89
+ }
90
+ /**
91
+ * 获取完整用户信息(如果已认证)
92
+ */
93
+ getUser() {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ try {
96
+ return yield getAuthenticatedUser(this.req);
97
+ }
98
+ catch (_a) {
99
+ return null;
100
+ }
101
+ });
102
+ }
103
+ }
104
+
105
+ export { ApiAuthUtils, getAuthenticatedUser, requireAuth, requireAuthWithUser };
package/dist/index.js CHANGED
@@ -21,7 +21,6 @@ var moneyPriceHelper = require('./lib/money-price-helper.js');
21
21
  var fingerprintConfig = require('./lib/fingerprint-config.js');
22
22
  var creditInit = require('./lib/credit-init.js');
23
23
  var stripeConfig = require('./lib/stripe-config.js');
24
- var authUtils = require('./lib/auth-utils.js');
25
24
  var upstashConfig = require('./lib/upstash-config.js');
26
25
  var redisLock = require('./lib/upstash/redis-lock.js');
27
26
  var redisLike = require('./lib/upstash/redis-like.js');
@@ -91,10 +90,6 @@ exports.fetchPaymentId = stripeConfig.fetchPaymentId;
91
90
  exports.getStripe = stripeConfig.getStripe;
92
91
  exports.updateSubscription = stripeConfig.updateSubscription;
93
92
  exports.validateStripeWebhook = stripeConfig.validateStripeWebhook;
94
- exports.ApiAuthUtils = authUtils.ApiAuthUtils;
95
- exports.getAuthenticatedUser = authUtils.getAuthenticatedUser;
96
- exports.requireAuth = authUtils.requireAuth;
97
- exports.requireAuthWithUser = authUtils.requireAuthWithUser;
98
93
  exports.getQstash = upstashConfig.getQstash;
99
94
  exports.getRedis = upstashConfig.getRedis;
100
95
  exports.withQstash = upstashConfig.withQstash;
package/dist/index.mjs CHANGED
@@ -19,7 +19,6 @@ export { getMoneyPriceInitUserContext } from './lib/money-price-helper.mjs';
19
19
  export { fingerprintConfig } from './lib/fingerprint-config.mjs';
20
20
  export { creditsConfig, freeAmount, freeExpiredDays, freeRegisterAmount, oneTimeExpiredDays } from './lib/credit-init.mjs';
21
21
  export { ActiveSubscriptionExistsError, cancelSubscription, createCheckoutSession, createCustomerPortalSession, createOrGetCustomer, fetchPaymentId, getStripe, updateSubscription, validateStripeWebhook } from './lib/stripe-config.mjs';
22
- export { ApiAuthUtils, getAuthenticatedUser, requireAuth, requireAuthWithUser } from './lib/auth-utils.mjs';
23
22
  export { getQstash, getRedis, withQstash, withRedis } from './lib/upstash-config.mjs';
24
23
  export { acquireLock, releaseLock, withLock } from './lib/upstash/redis-lock.mjs';
25
24
  export { getTargetLikeCount, getUserLikedTargets, isTargetLiked, likeTarget, unlikeTarget } from './lib/upstash/redis-like.mjs';
@@ -3,7 +3,6 @@ export * from './money-price-helper';
3
3
  export * from './fingerprint-config';
4
4
  export * from './credit-init';
5
5
  export * from './stripe-config';
6
- export * from './auth-utils';
7
6
  export * from './upstash-config';
8
7
  export * from './upstash';
9
8
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,kBAAkB,CAAC;AACjC,cAAc,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/lib/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC;AACjC,cAAc,WAAW,CAAC"}
package/dist/lib/index.js CHANGED
@@ -5,7 +5,6 @@ var moneyPriceHelper = require('./money-price-helper.js');
5
5
  var fingerprintConfig = require('./fingerprint-config.js');
6
6
  var creditInit = require('./credit-init.js');
7
7
  var stripeConfig = require('./stripe-config.js');
8
- var authUtils = require('./auth-utils.js');
9
8
  var upstashConfig = require('./upstash-config.js');
10
9
  var redisLock = require('./upstash/redis-lock.js');
11
10
  var redisLike = require('./upstash/redis-like.js');
@@ -36,10 +35,6 @@ exports.fetchPaymentId = stripeConfig.fetchPaymentId;
36
35
  exports.getStripe = stripeConfig.getStripe;
37
36
  exports.updateSubscription = stripeConfig.updateSubscription;
38
37
  exports.validateStripeWebhook = stripeConfig.validateStripeWebhook;
39
- exports.ApiAuthUtils = authUtils.ApiAuthUtils;
40
- exports.getAuthenticatedUser = authUtils.getAuthenticatedUser;
41
- exports.requireAuth = authUtils.requireAuth;
42
- exports.requireAuthWithUser = authUtils.requireAuthWithUser;
43
38
  exports.getQstash = upstashConfig.getQstash;
44
39
  exports.getRedis = upstashConfig.getRedis;
45
40
  exports.withQstash = upstashConfig.withQstash;
@@ -3,7 +3,6 @@ export { getMoneyPriceInitUserContext } from './money-price-helper.mjs';
3
3
  export { fingerprintConfig } from './fingerprint-config.mjs';
4
4
  export { creditsConfig, freeAmount, freeExpiredDays, freeRegisterAmount, oneTimeExpiredDays } from './credit-init.mjs';
5
5
  export { ActiveSubscriptionExistsError, cancelSubscription, createCheckoutSession, createCustomerPortalSession, createOrGetCustomer, fetchPaymentId, getStripe, updateSubscription, validateStripeWebhook } from './stripe-config.mjs';
6
- export { ApiAuthUtils, getAuthenticatedUser, requireAuth, requireAuthWithUser } from './auth-utils.mjs';
7
6
  export { getQstash, getRedis, withQstash, withRedis } from './upstash-config.mjs';
8
7
  export { acquireLock, releaseLock, withLock } from './upstash/redis-lock.mjs';
9
8
  export { getTargetLikeCount, getUserLikedTargets, isTargetLiked, likeTarget, unlikeTarget } from './upstash/redis-like.mjs';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windrun-huaiin/backend-core",
3
- "version": "14.3.0",
3
+ "version": "14.4.0",
4
4
  "description": "Shared backend primitives: Prisma schema/client, database services, routing helpers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -47,6 +47,21 @@
47
47
  "import": "./dist/lib/index.mjs",
48
48
  "require": "./dist/lib/index.js"
49
49
  },
50
+ "./auth/server": {
51
+ "types": "./dist/auth/auth-utils.d.ts",
52
+ "import": "./dist/auth/auth-utils.mjs",
53
+ "require": "./dist/auth/auth-utils.js"
54
+ },
55
+ "./auth/shared": {
56
+ "types": "./dist/auth/auth-shared.d.ts",
57
+ "import": "./dist/auth/auth-shared.mjs",
58
+ "require": "./dist/auth/auth-shared.js"
59
+ },
60
+ "./auth/middleware": {
61
+ "types": "./dist/auth/auth-middleware.d.ts",
62
+ "import": "./dist/auth/auth-middleware.mjs",
63
+ "require": "./dist/auth/auth-middleware.js"
64
+ },
50
65
  "./app/api/webhook/stripe/route": {
51
66
  "types": "./dist/app/api/webhook/stripe/route.d.ts",
52
67
  "import": "./dist/app/api/webhook/stripe/route.mjs",
@@ -95,7 +110,7 @@
95
110
  "svix": "^1.86.0",
96
111
  "zod": "^4.3.6",
97
112
  "@windrun-huaiin/lib": "^14.0.1",
98
- "@windrun-huaiin/third-ui": "^14.2.0"
113
+ "@windrun-huaiin/third-ui": "^14.4.3"
99
114
  },
100
115
  "devDependencies": {
101
116
  "@rollup/plugin-alias": "^5.1.1",
@@ -12,7 +12,7 @@ import {
12
12
  PaySupplier,
13
13
  PaymentStatus
14
14
  } from '@/db/index';
15
- import { ApiAuthUtils } from '@/lib/auth-utils';
15
+ import { ApiAuthUtils } from '@/auth/auth-utils';
16
16
  import { getPriceConfig } from '@/lib/money-price-config';
17
17
 
18
18
  // Request validation schema
@@ -4,7 +4,7 @@ import {
4
4
  createCustomerPortalSession,
5
5
  createOrGetCustomer,
6
6
  } from '@/lib/stripe-config';
7
- import { ApiAuthUtils } from '@/lib/auth-utils';
7
+ import { ApiAuthUtils } from '@/auth/auth-utils';
8
8
  import { subscriptionService } from '@/db/index';
9
9
 
10
10
  const createCustomerPortalSchema = z
@@ -0,0 +1,109 @@
1
+ import type { ClerkMiddlewareAuth } from '@clerk/nextjs/server';
2
+ import { NextRequest, NextResponse } from 'next/server';
3
+ import { AUTH_HEADERS, type ProviderIdentity } from './auth-shared';
4
+
5
+ export function buildProtectedPageRoutePatterns(
6
+ protectedRoots: readonly string[],
7
+ locales: readonly string[]
8
+ ): string[] {
9
+ const uniqueRoots = [...new Set(protectedRoots)]
10
+ .map((root) => root.trim())
11
+ .filter(Boolean)
12
+ .map((root) => (root.startsWith('/') ? root : `/${root}`))
13
+ .map((root) => root.replace(/\/+$/, ''));
14
+
15
+ const uniqueLocales = [...new Set(locales)]
16
+ .map((locale) => locale.trim())
17
+ .filter(Boolean);
18
+
19
+ const patterns = new Set<string>();
20
+
21
+ for (const root of uniqueRoots) {
22
+ patterns.add(`${root}(.*)`);
23
+
24
+ for (const locale of uniqueLocales) {
25
+ patterns.add(`/${locale}${root}(.*)`);
26
+ }
27
+ }
28
+
29
+ return [...patterns];
30
+ }
31
+
32
+ export interface AuthMiddlewareOptions {
33
+ protectedPageRoutes: (req: NextRequest) => boolean;
34
+ protectedApiRoutes: (req: NextRequest) => boolean;
35
+ publicApiRoutes: (req: NextRequest) => boolean;
36
+ intlMiddleware: (req: NextRequest) => ReturnType<typeof NextResponse.next> | Response | undefined;
37
+ }
38
+
39
+ async function authenticateWithClerk(auth: ClerkMiddlewareAuth): Promise<ProviderIdentity | null> {
40
+ const { userId } = await auth();
41
+ if (!userId) {
42
+ return null;
43
+ }
44
+
45
+ return {
46
+ provider: 'clerk',
47
+ providerUserId: userId,
48
+ };
49
+ }
50
+
51
+ export function buildAuthenticatedRequestHeaders(
52
+ req: NextRequest,
53
+ auth: ProviderIdentity
54
+ ): Headers {
55
+ const headers = new Headers(req.headers);
56
+ headers.set(AUTH_HEADERS.provider, auth.provider);
57
+ headers.set(AUTH_HEADERS.providerUserId, auth.providerUserId);
58
+ return headers;
59
+ }
60
+
61
+ export async function handleAuthMiddleware(
62
+ auth: ClerkMiddlewareAuth,
63
+ req: NextRequest,
64
+ options: AuthMiddlewareOptions
65
+ ) {
66
+ const { protectedPageRoutes, protectedApiRoutes, publicApiRoutes, intlMiddleware } = options;
67
+
68
+ if (protectedPageRoutes(req)) {
69
+ const identity = await authenticateWithClerk(auth);
70
+ if (!identity) {
71
+ return (await auth()).redirectToSignIn();
72
+ }
73
+ const requestHeaders = buildAuthenticatedRequestHeaders(req, identity);
74
+ console.log('Forward auth context for protected page:', identity.provider, identity.providerUserId);
75
+ return intlMiddleware(
76
+ new NextRequest(req.url, {
77
+ headers: requestHeaders,
78
+ method: req.method,
79
+ body: req.body,
80
+ })
81
+ );
82
+ }
83
+
84
+ if (protectedApiRoutes(req)) {
85
+ const identity = await authenticateWithClerk(auth);
86
+ if (!identity) {
87
+ return (await auth()).redirectToSignIn();
88
+ }
89
+ const requestHeaders = buildAuthenticatedRequestHeaders(req, identity);
90
+ console.log('Forward auth context for protected API:', identity.provider, identity.providerUserId);
91
+ return NextResponse.next({
92
+ request: {
93
+ headers: requestHeaders,
94
+ },
95
+ });
96
+ }
97
+
98
+ if (publicApiRoutes(req)) {
99
+ console.log('Public API route, no auth required:', req.nextUrl.pathname);
100
+ return NextResponse.next();
101
+ }
102
+
103
+ if (req.nextUrl.pathname.startsWith('/api/')) {
104
+ console.log('Other API route, no internationalization:', req.nextUrl.pathname);
105
+ return NextResponse.next();
106
+ }
107
+
108
+ return null;
109
+ }
@@ -0,0 +1,16 @@
1
+ export const AUTH_HEADERS = {
2
+ provider: 'x-auth-provider',
3
+ providerUserId: 'x-auth-provider-user-id',
4
+ } as const;
5
+
6
+ export const AUTH_ERRORS = {
7
+ unauthorized: 'UNAUTHORIZED',
8
+ userNotFound: 'USER_NOT_FOUND',
9
+ } as const;
10
+
11
+ export type AuthProvider = 'clerk';
12
+
13
+ export interface ProviderIdentity {
14
+ provider: AuthProvider;
15
+ providerUserId: string;
16
+ }
@@ -1,6 +1,7 @@
1
1
  import { NextRequest } from 'next/server';
2
2
  import { userService } from '../services/database/index';
3
3
  import { User } from '../services/database/prisma-model-type';
4
+ import { AUTH_ERRORS, AUTH_HEADERS, type AuthProvider } from './auth-shared';
4
5
 
5
6
  /**
6
7
  * 认证结果类型
@@ -8,7 +9,8 @@ import { User } from '../services/database/prisma-model-type';
8
9
  export interface AuthResult {
9
10
  userId: string;
10
11
  user: User;
11
- clerkUserId: string;
12
+ provider: AuthProvider;
13
+ providerUserId: string;
12
14
  }
13
15
 
14
16
  /**
@@ -16,20 +18,22 @@ export interface AuthResult {
16
18
  */
17
19
  export async function getAuthenticatedUser(req: NextRequest): Promise<AuthResult> {
18
20
  try {
19
- const clerkUserId = req.headers.get('x-clerk-user-id');
20
- if (!clerkUserId) {
21
- throw new Error('Authentication required');
21
+ const provider = req.headers.get(AUTH_HEADERS.provider);
22
+ const providerUserId = req.headers.get(AUTH_HEADERS.providerUserId);
23
+ if (provider !== 'clerk' || !providerUserId) {
24
+ throw new Error(AUTH_ERRORS.unauthorized);
22
25
  }
23
-
24
- const user = await userService.findByClerkUserId(clerkUserId);
26
+
27
+ const user = await userService.findByClerkUserId(providerUserId);
25
28
  if (!user) {
26
- throw new Error('User not found in database');
29
+ throw new Error(AUTH_ERRORS.userNotFound);
27
30
  }
28
-
31
+
29
32
  return {
30
33
  userId: user.userId,
31
34
  user,
32
- clerkUserId
35
+ provider: 'clerk',
36
+ providerUserId,
33
37
  };
34
38
  } catch (error) {
35
39
  console.error('Error getting authenticated user:', error);
@@ -98,4 +102,4 @@ export class ApiAuthUtils {
98
102
  return null;
99
103
  }
100
104
  }
101
- }
105
+ }
package/src/lib/index.ts CHANGED
@@ -3,6 +3,5 @@ export * from './money-price-helper';
3
3
  export * from './fingerprint-config';
4
4
  export * from './credit-init';
5
5
  export * from './stripe-config';
6
- export * from './auth-utils';
7
6
  export * from './upstash-config';
8
7
  export * from './upstash';