@windrun-huaiin/backend-core 31.0.0 → 31.0.1

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.
@@ -1,564 +1,17 @@
1
- import { __awaiter, __rest } from 'tslib';
2
- import { anonymousAggregateService } from '../../../../../services/aggregate/anonymous.aggregate.service.mjs';
1
+ import { __awaiter } from 'tslib';
3
2
  import { getOptionalServerAuthIdentity } from '../../../../../auth/auth-utils.mjs';
4
- import { extractFingerprintFromNextRequest } from '@windrun-huaiin/third-ui/fingerprint/server';
5
- import { NextResponse } from 'next/server';
6
- import { fetchUserContextByClerkUserId, fetchLatestUserContextByFingerprintId, mapSubscriptionToXSubscription, mapCreditToXCredit, mapUserToXUser } from '../../../../../services/context/user-context-service.mjs';
7
- import { finalizeUserContext } from '../../../../../services/context/user-context-finalizer.mjs';
3
+ import { handleFingerprintRequest } from './route-shared.mjs';
8
4
 
9
- /* eslint-disable @typescript-eslint/no-explicit-any */
10
- // Fix BigInt serialization issue
11
- BigInt.prototype.toJSON = function () {
12
- return this.toString();
13
- };
14
- // ==================== Utilities ====================
15
- /** Create a successful response payload */
16
- function createSuccessResponse(params) {
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);
18
- return finalizeUserContext(response);
19
- }
20
- /** Create an error response */
21
- function createErrorResponse(message, status = 400) {
22
- const errorResponse = { error: message };
23
- return NextResponse.json(errorResponse, { status });
24
- }
25
- const SOURCE_REF_MAX_LENGTH = 2048;
26
- const QUERY_PARAM_MAX_LENGTH = 512;
27
- const USER_AGENT_MAX_LENGTH = 1024;
28
- const FIRST_TOUCH_HEADER_MAX_LENGTH = 4096;
29
- const FIRST_TOUCH_HEADER_NAME = 'x-first-touch';
30
- function normalizeSourceRef(ref) {
31
- if (!ref) {
32
- return null;
33
- }
34
- const trimmed = ref.trim();
35
- if (!trimmed) {
36
- return null;
37
- }
38
- return trimmed.length > SOURCE_REF_MAX_LENGTH
39
- ? trimmed.slice(0, SOURCE_REF_MAX_LENGTH)
40
- : trimmed;
41
- }
42
- function normalizeQueryParam(value) {
43
- if (!value) {
44
- return null;
45
- }
46
- const trimmed = value.trim();
47
- if (!trimmed) {
48
- return null;
49
- }
50
- return trimmed.length > QUERY_PARAM_MAX_LENGTH
51
- ? trimmed.slice(0, QUERY_PARAM_MAX_LENGTH)
52
- : trimmed;
53
- }
54
- function decodeHeaderValue(value) {
55
- try {
56
- return decodeURIComponent(value);
57
- }
58
- catch (_a) {
59
- return null;
60
- }
61
- }
62
- function mergeSourceRef(target, source) {
63
- if (!source) {
64
- return;
65
- }
66
- const entries = Object.entries(source);
67
- for (const [key, value] of entries) {
68
- if (value === undefined || value === null) {
69
- continue;
70
- }
71
- if (target[key] === undefined) {
72
- target[key] = value;
73
- }
74
- }
75
- }
76
- function applySearchParams(sourceRef, params) {
77
- const setIfEmpty = (key, value) => {
78
- if (sourceRef[key] !== undefined) {
79
- return;
80
- }
81
- const normalized = normalizeQueryParam(value);
82
- if (normalized) {
83
- sourceRef[key] = normalized;
84
- }
85
- };
86
- setIfEmpty('utmSource', params.get('utm_source'));
87
- setIfEmpty('utmMedium', params.get('utm_medium'));
88
- setIfEmpty('utmCampaign', params.get('utm_campaign'));
89
- setIfEmpty('utmTerm', params.get('utm_term'));
90
- setIfEmpty('utmContent', params.get('utm_content'));
91
- setIfEmpty('utmId', params.get('utm_id'));
92
- setIfEmpty('ref', params.get('ref'));
93
- setIfEmpty('gclid', params.get('gclid'));
94
- setIfEmpty('fbclid', params.get('fbclid'));
95
- setIfEmpty('msclkid', params.get('msclkid'));
96
- setIfEmpty('ttclid', params.get('ttclid'));
97
- setIfEmpty('twclid', params.get('twclid'));
98
- setIfEmpty('liFatId', params.get('li_fat_id'));
99
- }
100
- function normalizeHost(host) {
101
- if (!host) {
102
- return null;
103
- }
104
- return host.trim().toLowerCase() || null;
105
- }
106
- function getRootDomain(host) {
107
- const normalizedHost = normalizeHost(host);
108
- if (!normalizedHost) {
109
- return null;
110
- }
111
- const hostname = normalizedHost.split(':')[0];
112
- if (hostname === 'localhost' || /^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) {
113
- return hostname;
114
- }
115
- const parts = hostname.split('.').filter(Boolean);
116
- if (parts.length <= 2) {
117
- return hostname;
118
- }
119
- return parts.slice(-2).join('.');
120
- }
121
- function isInternalReferer(landingHost, refererHost) {
122
- const normalizedLandingHost = normalizeHost(landingHost);
123
- const normalizedRefererHost = normalizeHost(refererHost);
124
- if (!normalizedLandingHost || !normalizedRefererHost) {
125
- return false;
126
- }
127
- if (normalizedLandingHost === normalizedRefererHost) {
128
- return true;
129
- }
130
- return normalizedLandingHost.endsWith(`.${normalizedRefererHost}`)
131
- || normalizedRefererHost.endsWith(`.${normalizedLandingHost}`);
132
- }
133
- function detectPlatform(value) {
134
- const normalized = value === null || value === void 0 ? void 0 : value.trim().toLowerCase();
135
- if (!normalized) {
136
- return null;
137
- }
138
- const matcherList = [
139
- { pattern: /chatgpt|chat-openai|openai/, platform: 'openai', channel: 'ai' },
140
- { pattern: /claude|anthropic/, platform: 'anthropic', channel: 'ai' },
141
- { pattern: /perplexity/, platform: 'perplexity', channel: 'ai' },
142
- { pattern: /gemini/, platform: 'gemini', channel: 'ai' },
143
- { pattern: /copilot/, platform: 'copilot', channel: 'ai' },
144
- { pattern: /google/, platform: 'google', channel: 'search' },
145
- { pattern: /bing/, platform: 'bing', channel: 'search' },
146
- { pattern: /baidu/, platform: 'baidu', channel: 'search' },
147
- { pattern: /yahoo/, platform: 'yahoo', channel: 'search' },
148
- { pattern: /duckduckgo/, platform: 'duckduckgo', channel: 'search' },
149
- { pattern: /facebook/, platform: 'facebook', channel: 'social' },
150
- { pattern: /instagram/, platform: 'instagram', channel: 'social' },
151
- { pattern: /x\.com|twitter/, platform: 'x', channel: 'social' },
152
- { pattern: /linkedin/, platform: 'linkedin', channel: 'social' },
153
- { pattern: /reddit/, platform: 'reddit', channel: 'social' },
154
- { pattern: /youtube/, platform: 'youtube', channel: 'social' },
155
- ];
156
- const matched = matcherList.find(({ pattern }) => pattern.test(normalized));
157
- if (!matched) {
158
- return null;
159
- }
160
- return matched.platform;
161
- }
162
- function detectChannelFromPlatform(platform) {
163
- switch (platform) {
164
- case 'openai':
165
- case 'anthropic':
166
- case 'perplexity':
167
- case 'gemini':
168
- case 'copilot':
169
- return 'ai';
170
- case 'google':
171
- case 'bing':
172
- case 'baidu':
173
- case 'yahoo':
174
- case 'duckduckgo':
175
- return 'search';
176
- case 'facebook':
177
- case 'instagram':
178
- case 'x':
179
- case 'linkedin':
180
- case 'reddit':
181
- case 'youtube':
182
- return 'social';
183
- default:
184
- return null;
185
- }
186
- }
187
- function detectChannelFromUtmMedium(value) {
188
- const normalized = value === null || value === void 0 ? void 0 : value.trim().toLowerCase();
189
- if (!normalized) {
190
- return null;
191
- }
192
- if (/^(cpc|ppc|paid|paid_search|display|banner|affiliate|email|newsletter|push|sms)$/.test(normalized)) {
193
- return 'campaign';
194
- }
195
- if (/^(social|social_paid|social-organic|social_organic)$/.test(normalized)) {
196
- return 'social';
197
- }
198
- if (/^(organic|seo|search)$/.test(normalized)) {
199
- return 'search';
200
- }
201
- if (/^(referral|partner)$/.test(normalized)) {
202
- return 'referral';
203
- }
204
- if (/^(ai|llm)$/.test(normalized)) {
205
- return 'ai';
206
- }
207
- return 'campaign';
208
- }
209
- function parseUserAgent(request) {
210
- var _a, _b, _c, _d, _e;
211
- const userAgentHeader = request.headers.get('user-agent');
212
- const secChUaMobile = (_a = normalizeQueryParam(request.headers.get('sec-ch-ua-mobile'))) !== null && _a !== void 0 ? _a : undefined;
213
- const secChUaPlatform = (_b = normalizeQueryParam(request.headers.get('sec-ch-ua-platform'))) !== null && _b !== void 0 ? _b : undefined;
214
- const userAgent = (_d = (_c = normalizeSourceRef(userAgentHeader)) === null || _c === void 0 ? void 0 : _c.slice(0, USER_AGENT_MAX_LENGTH)) !== null && _d !== void 0 ? _d : undefined;
215
- const ua = (_e = userAgent === null || userAgent === void 0 ? void 0 : userAgent.toLowerCase()) !== null && _e !== void 0 ? _e : '';
216
- let deviceType = 'desktop';
217
- if (!ua) {
218
- deviceType = 'unknown';
219
- }
220
- else if (/bot|spider|crawler|curl|wget|headless/.test(ua)) {
221
- deviceType = 'bot';
222
- }
223
- else if (/ipad|tablet/.test(ua)) {
224
- deviceType = 'tablet';
225
- }
226
- else if (/mobi|iphone|android/.test(ua) || secChUaMobile === '?1') {
227
- deviceType = 'mobile';
228
- }
229
- let os = 'Unknown';
230
- if (/iphone|ipad|ipod/.test(ua)) {
231
- os = 'iOS';
232
- }
233
- else if (/android/.test(ua)) {
234
- os = 'Android';
235
- }
236
- else if (/windows nt/.test(ua)) {
237
- os = 'Windows';
238
- }
239
- else if (/mac os x|macintosh/.test(ua)) {
240
- os = 'macOS';
241
- }
242
- else if (/cros/.test(ua)) {
243
- os = 'Chrome OS';
244
- }
245
- else if (/linux/.test(ua)) {
246
- os = 'Linux';
247
- }
248
- if (secChUaPlatform) {
249
- const normalizedPlatform = secChUaPlatform.replaceAll('"', '');
250
- if (normalizedPlatform && normalizedPlatform !== 'Unknown') {
251
- os = normalizedPlatform;
252
- }
253
- }
254
- let browser = 'Unknown';
255
- if (/edg\//.test(ua)) {
256
- browser = 'Edge';
257
- }
258
- else if (/opr\//.test(ua) || /opera/.test(ua)) {
259
- browser = 'Opera';
260
- }
261
- else if (/samsungbrowser\//.test(ua)) {
262
- browser = 'Samsung Internet';
263
- }
264
- else if (/crios\//.test(ua) || /chrome\//.test(ua)) {
265
- browser = 'Chrome';
266
- }
267
- else if (/firefox\//.test(ua)) {
268
- browser = 'Firefox';
269
- }
270
- else if (/safari\//.test(ua) && !/chrome\//.test(ua) && !/crios\//.test(ua)) {
271
- browser = 'Safari';
272
- }
273
- return {
274
- userAgent,
275
- deviceType,
276
- os,
277
- browser,
278
- secChUaMobile,
279
- secChUaPlatform,
280
- };
281
- }
282
- function parseFirstTouchHeader(request) {
283
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w;
284
- const rawHeader = request.headers.get(FIRST_TOUCH_HEADER_NAME);
285
- const normalizedHeader = (_a = normalizeSourceRef(rawHeader)) === null || _a === void 0 ? void 0 : _a.slice(0, FIRST_TOUCH_HEADER_MAX_LENGTH);
286
- if (!normalizedHeader) {
287
- return null;
288
- }
289
- const decodedHeader = decodeHeaderValue(normalizedHeader);
290
- if (!decodedHeader) {
291
- return null;
292
- }
293
- try {
294
- const parsed = JSON.parse(decodedHeader);
295
- const sourceRef = {};
296
- sourceRef.capturedAt = (_b = normalizeQueryParam(typeof parsed.capturedAt === 'string' ? parsed.capturedAt : null)) !== null && _b !== void 0 ? _b : undefined;
297
- sourceRef.landingUrl = (_c = normalizeSourceRef(typeof parsed.landingUrl === 'string' ? parsed.landingUrl : null)) !== null && _c !== void 0 ? _c : undefined;
298
- sourceRef.landingPath = (_d = normalizeSourceRef(typeof parsed.landingPath === 'string' ? parsed.landingPath : null)) !== null && _d !== void 0 ? _d : undefined;
299
- sourceRef.landingHost = (_e = normalizeHost(typeof parsed.landingHost === 'string' ? parsed.landingHost : null)) !== null && _e !== void 0 ? _e : undefined;
300
- sourceRef.ref = (_f = normalizeQueryParam(typeof parsed.ref === 'string' ? parsed.ref : null)) !== null && _f !== void 0 ? _f : undefined;
301
- sourceRef.utmSource = (_g = normalizeQueryParam(typeof parsed.utmSource === 'string' ? parsed.utmSource : null)) !== null && _g !== void 0 ? _g : undefined;
302
- sourceRef.utmMedium = (_h = normalizeQueryParam(typeof parsed.utmMedium === 'string' ? parsed.utmMedium : null)) !== null && _h !== void 0 ? _h : undefined;
303
- sourceRef.utmCampaign = (_j = normalizeQueryParam(typeof parsed.utmCampaign === 'string' ? parsed.utmCampaign : null)) !== null && _j !== void 0 ? _j : undefined;
304
- sourceRef.utmTerm = (_k = normalizeQueryParam(typeof parsed.utmTerm === 'string' ? parsed.utmTerm : null)) !== null && _k !== void 0 ? _k : undefined;
305
- sourceRef.utmContent = (_l = normalizeQueryParam(typeof parsed.utmContent === 'string' ? parsed.utmContent : null)) !== null && _l !== void 0 ? _l : undefined;
306
- sourceRef.utmId = (_m = normalizeQueryParam(typeof parsed.utmId === 'string' ? parsed.utmId : null)) !== null && _m !== void 0 ? _m : undefined;
307
- sourceRef.gclid = (_o = normalizeQueryParam(typeof parsed.gclid === 'string' ? parsed.gclid : null)) !== null && _o !== void 0 ? _o : undefined;
308
- sourceRef.fbclid = (_p = normalizeQueryParam(typeof parsed.fbclid === 'string' ? parsed.fbclid : null)) !== null && _p !== void 0 ? _p : undefined;
309
- sourceRef.msclkid = (_q = normalizeQueryParam(typeof parsed.msclkid === 'string' ? parsed.msclkid : null)) !== null && _q !== void 0 ? _q : undefined;
310
- sourceRef.ttclid = (_r = normalizeQueryParam(typeof parsed.ttclid === 'string' ? parsed.ttclid : null)) !== null && _r !== void 0 ? _r : undefined;
311
- sourceRef.twclid = (_s = normalizeQueryParam(typeof parsed.twclid === 'string' ? parsed.twclid : null)) !== null && _s !== void 0 ? _s : undefined;
312
- sourceRef.liFatId = (_t = normalizeQueryParam(typeof parsed.liFatId === 'string' ? parsed.liFatId : null)) !== null && _t !== void 0 ? _t : undefined;
313
- const externalReferrer = normalizeSourceRef(typeof parsed.externalReferrer === 'string' ? parsed.externalReferrer : null);
314
- if (externalReferrer) {
315
- sourceRef.httpRefer = externalReferrer;
316
- try {
317
- const refererUrl = new URL(externalReferrer);
318
- sourceRef.refererHost = (_u = normalizeHost(refererUrl.host)) !== null && _u !== void 0 ? _u : undefined;
319
- sourceRef.refererPath = (_v = normalizeSourceRef(refererUrl.pathname)) !== null && _v !== void 0 ? _v : undefined;
320
- sourceRef.refererDomain = (_w = getRootDomain(refererUrl.host)) !== null && _w !== void 0 ? _w : undefined;
321
- applySearchParams(sourceRef, refererUrl.searchParams);
322
- }
323
- catch (error) {
324
- console.warn('Failed to parse first-touch referrer url:', error);
325
- }
326
- }
327
- return Object.keys(sourceRef).length > 0 ? sourceRef : null;
328
- }
329
- catch (error) {
330
- console.warn('Failed to parse first-touch header:', error);
331
- return null;
332
- }
333
- }
334
- function finalizeAttribution(sourceRef) {
335
- var _a, _b, _c, _d, _e;
336
- const landingHost = normalizeHost(sourceRef.landingHost);
337
- const refererHost = normalizeHost(sourceRef.refererHost);
338
- const internal = isInternalReferer(landingHost, refererHost);
339
- const hasCampaignMarker = Boolean(sourceRef.utmSource
340
- || sourceRef.utmMedium
341
- || sourceRef.utmCampaign
342
- || sourceRef.utmTerm
343
- || sourceRef.utmContent
344
- || sourceRef.utmId
345
- || sourceRef.ref
346
- || sourceRef.gclid
347
- || sourceRef.fbclid
348
- || sourceRef.msclkid
349
- || sourceRef.ttclid
350
- || sourceRef.twclid
351
- || sourceRef.liFatId);
352
- if (internal) {
353
- sourceRef.isInternalReferer = true;
354
- }
355
- const utmPlatform = detectPlatform(sourceRef.utmSource) || detectPlatform(sourceRef.ref);
356
- if (utmPlatform) {
357
- sourceRef.sourcePlatform = utmPlatform;
358
- sourceRef.sourceChannel = (_c = (_b = (_a = detectChannelFromPlatform(utmPlatform)) !== null && _a !== void 0 ? _a : detectChannelFromUtmMedium(sourceRef.utmMedium)) !== null && _b !== void 0 ? _b : sourceRef.sourceChannel) !== null && _c !== void 0 ? _c : 'campaign';
359
- sourceRef.sourceType = 'campaign';
360
- return;
361
- }
362
- if (sourceRef.gclid) {
363
- sourceRef.sourcePlatform = 'google';
364
- sourceRef.sourceChannel = 'search';
365
- sourceRef.sourceType = 'campaign';
366
- return;
367
- }
368
- if (sourceRef.msclkid) {
369
- sourceRef.sourcePlatform = 'bing';
370
- sourceRef.sourceChannel = 'search';
371
- sourceRef.sourceType = 'campaign';
372
- return;
373
- }
374
- if (sourceRef.fbclid) {
375
- sourceRef.sourcePlatform = 'facebook';
376
- sourceRef.sourceChannel = 'social';
377
- sourceRef.sourceType = 'campaign';
378
- return;
379
- }
380
- if (sourceRef.ttclid) {
381
- sourceRef.sourcePlatform = 'tiktok';
382
- sourceRef.sourceChannel = 'social';
383
- sourceRef.sourceType = 'campaign';
384
- return;
385
- }
386
- if (sourceRef.twclid) {
387
- sourceRef.sourcePlatform = 'x';
388
- sourceRef.sourceChannel = 'social';
389
- sourceRef.sourceType = 'campaign';
390
- return;
391
- }
392
- if (sourceRef.liFatId) {
393
- sourceRef.sourcePlatform = 'linkedin';
394
- sourceRef.sourceChannel = 'social';
395
- sourceRef.sourceType = 'campaign';
396
- return;
397
- }
398
- if (hasCampaignMarker) {
399
- sourceRef.sourcePlatform = 'other';
400
- sourceRef.sourceChannel = (_d = detectChannelFromUtmMedium(sourceRef.utmMedium)) !== null && _d !== void 0 ? _d : 'campaign';
401
- sourceRef.sourceType = 'campaign';
402
- return;
403
- }
404
- if (!internal && refererHost) {
405
- const refererPlatform = detectPlatform(refererHost) || detectPlatform(sourceRef.httpRefer);
406
- sourceRef.sourcePlatform = refererPlatform !== null && refererPlatform !== void 0 ? refererPlatform : 'other';
407
- sourceRef.sourceChannel = (_e = detectChannelFromPlatform(refererPlatform)) !== null && _e !== void 0 ? _e : 'referral';
408
- sourceRef.sourceType = 'referer';
409
- return;
410
- }
411
- sourceRef.sourcePlatform = 'direct';
412
- sourceRef.sourceChannel = 'direct';
413
- sourceRef.sourceType = 'direct';
414
- }
415
- // Extract the user's first-touch attribution source.
416
- function extractSourceRef(request) {
417
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
418
- const headerRef = request.headers.get('referer') || request.headers.get('referrer');
419
- const customRef = request.headers.get('x-source-ref');
420
- const queryRef = request.nextUrl.searchParams.get('ref');
421
- const firstTouchRef = parseFirstTouchHeader(request);
422
- const sourceRef = Object.assign({}, parseUserAgent(request));
423
- mergeSourceRef(sourceRef, firstTouchRef);
424
- sourceRef.landingUrl = (_b = (_a = sourceRef.landingUrl) !== null && _a !== void 0 ? _a : normalizeSourceRef(request.nextUrl.toString())) !== null && _b !== void 0 ? _b : undefined;
425
- sourceRef.landingPath = (_d = (_c = sourceRef.landingPath) !== null && _c !== void 0 ? _c : normalizeSourceRef(request.nextUrl.pathname)) !== null && _d !== void 0 ? _d : undefined;
426
- sourceRef.landingHost = (_f = (_e = sourceRef.landingHost) !== null && _e !== void 0 ? _e : normalizeHost(request.nextUrl.host)) !== null && _f !== void 0 ? _f : undefined;
427
- sourceRef.ref = (_h = (_g = sourceRef.ref) !== null && _g !== void 0 ? _g : normalizeQueryParam(queryRef)) !== null && _h !== void 0 ? _h : undefined;
428
- let normalizedHttpRef = null;
429
- const candidates = [customRef, headerRef];
430
- for (const candidate of candidates) {
431
- const normalized = normalizeSourceRef(candidate);
432
- if (normalized) {
433
- normalizedHttpRef = normalized;
434
- sourceRef.httpRefer = (_j = sourceRef.httpRefer) !== null && _j !== void 0 ? _j : normalized;
435
- break;
436
- }
437
- }
438
- const searchParams = request.nextUrl.searchParams;
439
- applySearchParams(sourceRef, searchParams);
440
- if (normalizedHttpRef) {
441
- try {
442
- const refererUrl = new URL(normalizedHttpRef);
443
- sourceRef.refererHost = (_l = (_k = sourceRef.refererHost) !== null && _k !== void 0 ? _k : normalizeHost(refererUrl.host)) !== null && _l !== void 0 ? _l : undefined;
444
- sourceRef.refererPath = (_o = (_m = sourceRef.refererPath) !== null && _m !== void 0 ? _m : normalizeSourceRef(refererUrl.pathname)) !== null && _o !== void 0 ? _o : undefined;
445
- sourceRef.refererDomain = (_q = (_p = sourceRef.refererDomain) !== null && _p !== void 0 ? _p : getRootDomain(refererUrl.host)) !== null && _q !== void 0 ? _q : undefined;
446
- applySearchParams(sourceRef, refererUrl.searchParams);
447
- }
448
- catch (error) {
449
- console.warn('Failed to parse referer url for utm/ref:', error);
450
- }
451
- }
452
- finalizeAttribution(sourceRef);
453
- return Object.keys(sourceRef).length > 0 ? sourceRef : null;
454
- }
455
5
  /**
456
- * Query the user by Clerk user ID and return response data.
457
- */
458
- function getUserByClerkId(clerkUserId) {
459
- return __awaiter(this, void 0, void 0, function* () {
460
- const entities = yield fetchUserContextByClerkUserId(clerkUserId);
461
- if (!entities) {
462
- return null;
463
- }
464
- return createSuccessResponse({
465
- entities,
466
- isNewUser: false,
467
- });
468
- });
469
- }
470
- /**
471
- * Query the user by fingerprint ID and return response data.
472
- */
473
- function getUserByFingerprintId(fingerprintId) {
474
- return __awaiter(this, void 0, void 0, function* () {
475
- const result = yield fetchLatestUserContextByFingerprintId(fingerprintId);
476
- if (!result) {
477
- return null;
478
- }
479
- const { totalUsersOnDevice, hasAnonymousUser } = result, entities = __rest(result, ["totalUsersOnDevice", "hasAnonymousUser"]);
480
- return createSuccessResponse({
481
- entities,
482
- isNewUser: false,
483
- options: {
484
- totalUsersOnDevice,
485
- hasAnonymousUser,
486
- },
487
- });
488
- });
489
- }
490
- /**
491
- * Shared fingerprint request handling logic.
492
- */
493
- function handleFingerprintRequest(request_1) {
494
- return __awaiter(this, arguments, void 0, function* (request, options = {}) {
495
- var _a;
496
- // Extract the fingerprint ID from the request.
497
- const fingerprintId = extractFingerprintFromNextRequest(request);
498
- // Validate the fingerprint ID.
499
- if (!fingerprintId) {
500
- return createErrorResponse('Invalid or missing fingerprint ID');
501
- }
502
- console.log('Received fingerprintId:', fingerprintId);
503
- const authIdentity = yield getOptionalServerAuthIdentity();
504
- const clerkUserId = (_a = authIdentity === null || authIdentity === void 0 ? void 0 : authIdentity.providerUserId) !== null && _a !== void 0 ? _a : null;
505
- try {
506
- // Prefer Clerk user ID lookup when the user is authenticated.
507
- let existingUserResult = null;
508
- if (clerkUserId) {
509
- // Authenticated users are always resolved by clerkUserId.
510
- existingUserResult = yield getUserByClerkId(clerkUserId);
511
- if (existingUserResult && existingUserResult.xUser.fingerprintId !== fingerprintId) {
512
- // The authenticated user's fingerprint changed. Clerk still identifies the account as the same user.
513
- // Trust clerkUserId as the source of truth and keep resolving the user's own data by login identity.
514
- // A single fingerprint can be associated with multiple accounts, so no mutation is needed here.
515
- console.warn(`Current login user used diff fp_ids: ${clerkUserId}, db_fp_id=${existingUserResult.xUser.fingerprintId}, req_fp_id=${fingerprintId}`);
516
- }
517
- }
518
- else {
519
- // For anonymous requests, fall back to fingerprint lookup.
520
- existingUserResult = yield getUserByFingerprintId(fingerprintId);
521
- }
522
- if (existingUserResult) {
523
- return NextResponse.json(existingUserResult);
524
- }
525
- // If the user does not exist and creation is disabled, return 404.
526
- if (!options.createIfNotExists) {
527
- return createErrorResponse('User not found', 404);
528
- }
529
- const sourceRef = extractSourceRef(request);
530
- const anonymousInitResult = yield anonymousAggregateService.getOrCreateByFingerprintId(fingerprintId, { sourceRef: sourceRef !== null && sourceRef !== void 0 ? sourceRef : undefined });
531
- if (anonymousInitResult.isNewUser) {
532
- console.log(`Created new anonymous user ${anonymousInitResult.user.userId} with fingerprint ${fingerprintId}`);
533
- }
534
- // Return the created or existing context.
535
- const response = createSuccessResponse({
536
- entities: {
537
- user: anonymousInitResult.user,
538
- credit: anonymousInitResult.credit,
539
- subscription: anonymousInitResult.subscription,
540
- },
541
- isNewUser: anonymousInitResult.isNewUser,
542
- options: {
543
- totalUsersOnDevice: anonymousInitResult.totalUsersOnDevice,
544
- hasAnonymousUser: anonymousInitResult.hasAnonymousUser,
545
- },
546
- });
547
- return NextResponse.json(response);
548
- }
549
- catch (error) {
550
- console.error('Fingerprint request error:', error);
551
- return createErrorResponse('Internal server error', 500);
552
- }
553
- });
554
- }
555
- /**
556
- * Anonymous user initialization API.
6
+ * Clerk-aware anonymous user initialization API.
557
7
  * POST /api/user/anonymous/init
558
8
  */
559
9
  function POST(request) {
560
10
  return __awaiter(this, void 0, void 0, function* () {
561
- return handleFingerprintRequest(request, { createIfNotExists: true });
11
+ return handleFingerprintRequest(request, {
12
+ createIfNotExists: true,
13
+ getAuthIdentity: getOptionalServerAuthIdentity,
14
+ });
562
15
  });
563
16
  }
564
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@windrun-huaiin/backend-core",
3
- "version": "31.0.0",
3
+ "version": "31.0.1",
4
4
  "description": "Shared backend primitives: Prisma schema/client, database services, routing helpers",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -107,6 +107,11 @@
107
107
  "import": "./dist/app/api/user/anonymous/init/route.mjs",
108
108
  "require": "./dist/app/api/user/anonymous/init/route.js"
109
109
  },
110
+ "./app/api/user/anonymous/init/fingerprint-only-route": {
111
+ "types": "./dist/app/api/user/anonymous/init/fingerprint-only-route.d.ts",
112
+ "import": "./dist/app/api/user/anonymous/init/fingerprint-only-route.mjs",
113
+ "require": "./dist/app/api/user/anonymous/init/fingerprint-only-route.js"
114
+ },
110
115
  "./app/api/user/credit-overview/route": {
111
116
  "types": "./dist/app/api/user/credit-overview/route.d.ts",
112
117
  "import": "./dist/app/api/user/credit-overview/route.mjs",
@@ -148,9 +153,9 @@
148
153
  "svix": "^1.86.0",
149
154
  "tslib": "^2.8.1",
150
155
  "zod": "^4.3.6",
151
- "@windrun-huaiin/lib": "^31.0.0",
152
- "@windrun-huaiin/third-ui": "^31.0.0",
153
- "@windrun-huaiin/contracts": "^31.0.0"
156
+ "@windrun-huaiin/lib": "^31.0.2",
157
+ "@windrun-huaiin/contracts": "^31.0.0",
158
+ "@windrun-huaiin/third-ui": "^31.3.1"
154
159
  },
155
160
  "devDependencies": {
156
161
  "@rollup/plugin-alias": "^5.1.1",
@@ -0,0 +1,14 @@
1
+ import { handleFingerprintRequest } from './route-shared';
2
+ import type { NextRequest } from 'next/server';
3
+
4
+ /**
5
+ * Fingerprint-only anonymous user initialization API.
6
+ * Use this route in apps that do not install or configure Clerk.
7
+ * POST /api/user/anonymous/init
8
+ */
9
+ export async function POST(request: NextRequest) {
10
+ return handleFingerprintRequest(request, {
11
+ createIfNotExists: true,
12
+ getAuthIdentity: async () => null,
13
+ });
14
+ }