@windrun-huaiin/backend-core 14.2.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.
Files changed (51) hide show
  1. package/dist/app/api/stripe/checkout/route.js +1 -1
  2. package/dist/app/api/stripe/checkout/route.mjs +1 -1
  3. package/dist/app/api/stripe/customer-portal/route.js +1 -1
  4. package/dist/app/api/stripe/customer-portal/route.mjs +1 -1
  5. package/dist/app/api/user/anonymous/init/route.d.ts.map +1 -1
  6. package/dist/app/api/user/anonymous/init/route.js +2 -1
  7. package/dist/app/api/user/anonymous/init/route.mjs +3 -2
  8. package/dist/auth/auth-middleware.d.ts +13 -0
  9. package/dist/auth/auth-middleware.d.ts.map +1 -0
  10. package/dist/auth/auth-middleware.js +86 -0
  11. package/dist/auth/auth-middleware.mjs +82 -0
  12. package/dist/auth/auth-shared.d.ts +14 -0
  13. package/dist/auth/auth-shared.d.ts.map +1 -0
  14. package/dist/auth/auth-shared.js +13 -0
  15. package/dist/auth/auth-shared.mjs +10 -0
  16. package/dist/auth/auth-utils.d.ts +48 -0
  17. package/dist/auth/auth-utils.d.ts.map +1 -0
  18. package/dist/auth/auth-utils.js +110 -0
  19. package/dist/auth/auth-utils.mjs +105 -0
  20. package/dist/index.js +2 -6
  21. package/dist/index.mjs +2 -2
  22. package/dist/lib/index.d.ts +0 -1
  23. package/dist/lib/index.d.ts.map +1 -1
  24. package/dist/lib/index.js +0 -5
  25. package/dist/lib/index.mjs +0 -1
  26. package/dist/lib/money-price-helper.js +2 -1
  27. package/dist/lib/money-price-helper.mjs +3 -2
  28. package/dist/services/context/index.d.ts +1 -0
  29. package/dist/services/context/index.d.ts.map +1 -1
  30. package/dist/services/context/index.js +2 -1
  31. package/dist/services/context/index.mjs +2 -1
  32. package/dist/services/context/user-context-finalizer.d.ts +13 -0
  33. package/dist/services/context/user-context-finalizer.d.ts.map +1 -0
  34. package/dist/services/context/user-context-finalizer.js +74 -0
  35. package/dist/services/context/user-context-finalizer.mjs +72 -0
  36. package/dist/services/context/user-context-service.d.ts +0 -6
  37. package/dist/services/context/user-context-service.d.ts.map +1 -1
  38. package/dist/services/context/user-context-service.js +0 -64
  39. package/dist/services/context/user-context-service.mjs +1 -64
  40. package/package.json +22 -7
  41. package/src/app/api/stripe/checkout/route.ts +1 -1
  42. package/src/app/api/stripe/customer-portal/route.ts +1 -1
  43. package/src/app/api/user/anonymous/init/route.ts +3 -2
  44. package/src/auth/auth-middleware.ts +109 -0
  45. package/src/auth/auth-shared.ts +16 -0
  46. package/src/{lib → auth}/auth-utils.ts +14 -10
  47. package/src/lib/index.ts +0 -1
  48. package/src/lib/money-price-helper.ts +3 -3
  49. package/src/services/context/index.ts +2 -1
  50. package/src/services/context/user-context-finalizer.ts +84 -0
  51. package/src/services/context/user-context-service.ts +0 -77
@@ -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';
@@ -1 +1 @@
1
- {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../../../../src/app/api/user/anonymous/init/route.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA2rBxD;;;GAGG;AACH,wBAAsB,IAAI,CAAC,OAAO,EAAE,WAAW,kCAE9C"}
1
+ {"version":3,"file":"route.d.ts","sourceRoot":"","sources":["../../../../../../src/app/api/user/anonymous/init/route.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA4rBxD;;;GAGG;AACH,wBAAsB,IAAI,CAAC,OAAO,EAAE,WAAW,kCAE9C"}
@@ -6,6 +6,7 @@ var server = require('@windrun-huaiin/third-ui/fingerprint/server');
6
6
  var server$1 = require('@clerk/nextjs/server');
7
7
  var server$2 = require('next/server');
8
8
  var userContextService = require('../../../../../services/context/user-context-service.js');
9
+ var userContextFinalizer = require('../../../../../services/context/user-context-finalizer.js');
9
10
 
10
11
  /* eslint-disable @typescript-eslint/no-explicit-any */
11
12
  // Fix BigInt serialization issue
@@ -16,7 +17,7 @@ BigInt.prototype.toJSON = function () {
16
17
  /** 创建成功响应对象 */
17
18
  function createSuccessResponse(params) {
18
19
  const response = Object.assign({ success: true, xUser: userContextService.mapUserToXUser(params.entities.user), xCredit: params.entities.credit ? userContextService.mapCreditToXCredit(params.entities.credit) : null, xSubscription: userContextService.mapSubscriptionToXSubscription(params.entities.subscription), isNewUser: params.isNewUser }, params.options);
19
- return userContextService.applyUserMockContext(response);
20
+ return userContextFinalizer.finalizeUserContext(response);
20
21
  }
21
22
  /** 创建错误响应 */
22
23
  function createErrorResponse(message, status = 400) {
@@ -3,7 +3,8 @@ import { anonymousAggregateService } from '../../../../../services/aggregate/ano
3
3
  import { extractFingerprintFromNextRequest } from '@windrun-huaiin/third-ui/fingerprint/server';
4
4
  import { auth } from '@clerk/nextjs/server';
5
5
  import { NextResponse } from 'next/server';
6
- import { fetchUserContextByClerkUserId, fetchLatestUserContextByFingerprintId, mapSubscriptionToXSubscription, mapCreditToXCredit, mapUserToXUser, applyUserMockContext } from '../../../../../services/context/user-context-service.mjs';
6
+ import { fetchUserContextByClerkUserId, fetchLatestUserContextByFingerprintId, mapSubscriptionToXSubscription, mapCreditToXCredit, mapUserToXUser } from '../../../../../services/context/user-context-service.mjs';
7
+ import { finalizeUserContext } from '../../../../../services/context/user-context-finalizer.mjs';
7
8
 
8
9
  /* eslint-disable @typescript-eslint/no-explicit-any */
9
10
  // Fix BigInt serialization issue
@@ -14,7 +15,7 @@ BigInt.prototype.toJSON = function () {
14
15
  /** 创建成功响应对象 */
15
16
  function createSuccessResponse(params) {
16
17
  const response = Object.assign({ success: true, xUser: mapUserToXUser(params.entities.user), xCredit: params.entities.credit ? mapCreditToXCredit(params.entities.credit) : null, xSubscription: mapSubscriptionToXSubscription(params.entities.subscription), isNewUser: params.isNewUser }, params.options);
17
- return applyUserMockContext(response);
18
+ return finalizeUserContext(response);
18
19
  }
19
20
  /** 创建错误响应 */
20
21
  function createErrorResponse(message, status = 400) {
@@ -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
@@ -14,13 +14,13 @@ var user_aggregate_service = require('./services/aggregate/user.aggregate.servic
14
14
  var billing_aggregate_service = require('./services/aggregate/billing.aggregate.service.js');
15
15
  var anonymous_aggregate_service = require('./services/aggregate/anonymous.aggregate.service.js');
16
16
  var userContextService = require('./services/context/user-context-service.js');
17
+ var userContextFinalizer = require('./services/context/user-context-finalizer.js');
17
18
  var webhookHandler = require('./services/stripe/webhook-handler.js');
18
19
  var moneyPriceConfig = require('./lib/money-price-config.js');
19
20
  var moneyPriceHelper = require('./lib/money-price-helper.js');
20
21
  var fingerprintConfig = require('./lib/fingerprint-config.js');
21
22
  var creditInit = require('./lib/credit-init.js');
22
23
  var stripeConfig = require('./lib/stripe-config.js');
23
- var authUtils = require('./lib/auth-utils.js');
24
24
  var upstashConfig = require('./lib/upstash-config.js');
25
25
  var redisLock = require('./lib/upstash/redis-lock.js');
26
26
  var redisLike = require('./lib/upstash/redis-like.js');
@@ -62,13 +62,13 @@ exports.isValidUserStatus = constants.isValidUserStatus;
62
62
  exports.userAggregateService = user_aggregate_service.userAggregateService;
63
63
  exports.billingAggregateService = billing_aggregate_service.billingAggregateService;
64
64
  exports.anonymousAggregateService = anonymous_aggregate_service.anonymousAggregateService;
65
- exports.applyUserMockContext = userContextService.applyUserMockContext;
66
65
  exports.buildInitUserContextFromEntities = userContextService.buildInitUserContextFromEntities;
67
66
  exports.fetchLatestUserContextByFingerprintId = userContextService.fetchLatestUserContextByFingerprintId;
68
67
  exports.fetchUserContextByClerkUserId = userContextService.fetchUserContextByClerkUserId;
69
68
  exports.mapCreditToXCredit = userContextService.mapCreditToXCredit;
70
69
  exports.mapSubscriptionToXSubscription = userContextService.mapSubscriptionToXSubscription;
71
70
  exports.mapUserToXUser = userContextService.mapUserToXUser;
71
+ exports.finalizeUserContext = userContextFinalizer.finalizeUserContext;
72
72
  exports.handleStripeEvent = webhookHandler.handleStripeEvent;
73
73
  exports.getActiveProviderConfig = moneyPriceConfig.getActiveProviderConfig;
74
74
  exports.getCreditsFromPriceId = moneyPriceConfig.getCreditsFromPriceId;
@@ -90,10 +90,6 @@ exports.fetchPaymentId = stripeConfig.fetchPaymentId;
90
90
  exports.getStripe = stripeConfig.getStripe;
91
91
  exports.updateSubscription = stripeConfig.updateSubscription;
92
92
  exports.validateStripeWebhook = stripeConfig.validateStripeWebhook;
93
- exports.ApiAuthUtils = authUtils.ApiAuthUtils;
94
- exports.getAuthenticatedUser = authUtils.getAuthenticatedUser;
95
- exports.requireAuth = authUtils.requireAuth;
96
- exports.requireAuthWithUser = authUtils.requireAuthWithUser;
97
93
  exports.getQstash = upstashConfig.getQstash;
98
94
  exports.getRedis = upstashConfig.getRedis;
99
95
  exports.withQstash = upstashConfig.withQstash;
package/dist/index.mjs CHANGED
@@ -11,14 +11,14 @@ export { BillingReason, CreditType, OperationType, OrderStatus, PaySupplier, Pay
11
11
  export { userAggregateService } from './services/aggregate/user.aggregate.service.mjs';
12
12
  export { billingAggregateService } from './services/aggregate/billing.aggregate.service.mjs';
13
13
  export { anonymousAggregateService } from './services/aggregate/anonymous.aggregate.service.mjs';
14
- export { applyUserMockContext, buildInitUserContextFromEntities, fetchLatestUserContextByFingerprintId, fetchUserContextByClerkUserId, mapCreditToXCredit, mapSubscriptionToXSubscription, mapUserToXUser } from './services/context/user-context-service.mjs';
14
+ export { buildInitUserContextFromEntities, fetchLatestUserContextByFingerprintId, fetchUserContextByClerkUserId, mapCreditToXCredit, mapSubscriptionToXSubscription, mapUserToXUser } from './services/context/user-context-service.mjs';
15
+ export { finalizeUserContext } from './services/context/user-context-finalizer.mjs';
15
16
  export { handleStripeEvent } from './services/stripe/webhook-handler.mjs';
16
17
  export { getActiveProviderConfig, getCreditsFromPriceId, getPriceConfig, moneyPriceConfig } from './lib/money-price-config.mjs';
17
18
  export { getMoneyPriceInitUserContext } from './lib/money-price-helper.mjs';
18
19
  export { fingerprintConfig } from './lib/fingerprint-config.mjs';
19
20
  export { creditsConfig, freeAmount, freeExpiredDays, freeRegisterAmount, oneTimeExpiredDays } from './lib/credit-init.mjs';
20
21
  export { ActiveSubscriptionExistsError, cancelSubscription, createCheckoutSession, createCustomerPortalSession, createOrGetCustomer, fetchPaymentId, getStripe, updateSubscription, validateStripeWebhook } from './lib/stripe-config.mjs';
21
- export { ApiAuthUtils, getAuthenticatedUser, requireAuth, requireAuthWithUser } from './lib/auth-utils.mjs';
22
22
  export { getQstash, getRedis, withQstash, withRedis } from './lib/upstash-config.mjs';
23
23
  export { acquireLock, releaseLock, withLock } from './lib/upstash/redis-lock.mjs';
24
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