-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
2453 lines (2209 loc) · 97.8 KB
/
api.js
File metadata and controls
2453 lines (2209 loc) · 97.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import "dotenv/config";
import crypto from "crypto";
import express from "express";
import compression from "compression";
import helmet from "helmet";
import rateLimit from "express-rate-limit";
import swaggerUi from "swagger-ui-express";
import { swaggerSpec } from "./lib/swagger.js";
import { getAccessToken, invalidateToken, searchActive, searchSold, getEbayUsageToday, DAILY_CAP } from "./lib/sources/ebay.js";
import { searchSnkrdunk } from "./lib/sources/snkrdunk.js";
import { searchMagi } from "./lib/sources/magi.js";
import { searchYahooAuctions } from "./lib/sources/yahooauctions.js";
import { getPsaGradingSignal } from "./lib/grading/psa.js";
import { gradeImage, medianGrade } from "./lib/grading/grading.js";
import { parseListingLanguagesFromInput, filterByCondition, detectCondition, flagPriceOutliers, filterRelevantResults, isGradedCard } from "./lib/search/filters.js";
import { buildEbaySearchQuery } from "./lib/search/listingQuery.js";
import { EBAY_CATEGORY_TCG_SINGLE_CARDS_US } from "./lib/search/ebayCategories.js";
import { saveGradeLog, getGradeLogs, getGradeLogsByUser, getGradeLog, deleteGradeLog, saveDrop, getDrops, getDrop, saveWebhook, getWebhooks, deleteWebhook, getFirestoreStatus, saveAlert, getActiveAlerts, updateAlert, getAlertsByEmail, saveErrorLog, getErrorLogs, clearErrorLogs, getPortfolio, addToPortfolio, removeFromPortfolio, updatePortfolioCard, savePortfolioSnapshot, getPortfolioSnapshots, listPortfolioUserIds, trackSearchFrequency, getTopSearchedCards, recordMilestone, getFunnelStats } from "./lib/data/firestore.js";
import { getDemoSearchResult, getDemoResult, listDemoCards, findDemoByNumber } from "./lib/cards/demo.js";
import { csvEscape, csvRow } from "./lib/data/csv.js";
import { createApiKey, listApiKeys, listAllKeys, listKeysByOwner, getApiKey, updateApiKey, deleteApiKey, rotateApiKey, validateApiKey } from "./lib/auth/api-keys.js";
import { recordSoldPrices, getPriceHistory, computePriceTrend } from "./lib/cards/price-history.js";
import { sendAlertEmail } from "./lib/data/email.js";
import { logRequest, getAnalytics, getAnalyticsByUser } from "./lib/data/analytics.js";
import { saveGradedImages } from "./lib/cards/grading-dataset.js";
import { verifyGoogleToken, generateJwt, verifyJwt } from "./lib/auth/auth.js";
import { seedFromTCGPlayer } from "./lib/sources/tcgplayer.js";
import { getOrCreateCard, findCardByQuery, parseCardIdentity, resolveCardIdToQuery, SET_NAME_MAP } from "./lib/cards/card-identity.js";
import { initCardDatabase, searchCards, refreshCardDatabase, getAllSets, getSetWithCards, findCardByCardId } from "./lib/cards/card-database.js";
import { raspMiddleware, getSecurityEvents } from "./lib/security/rasp.js";
import { fileURLToPath } from "url";
import path from "path";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
app.set("trust proxy", 1);
app.use(helmet({
contentSecurityPolicy: false,
crossOriginEmbedderPolicy: false,
}));
app.use(compression());
app.use(express.json({ limit: "100kb" }));
app.use(raspMiddleware({ mode: process.env.RASP_MODE || "monitor" }));
app.use((req, res, next) => {
req.requestId = req.requestId || crypto.randomUUID().slice(0, 8);
res.setHeader("X-Request-Id", req.requestId);
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
if (req.method === "OPTIONS") return res.sendStatus(204);
next();
});
app.use(express.static(path.join(__dirname, "public")));
app.use("/logos", express.static(path.join(__dirname, "logos")));
app.get("/docs/spec.json", (req, res) => res.json(swaggerSpec));
app.use("/docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));
function getRequestToken(req) {
const auth = req.headers.authorization;
const query = req.query.key;
return auth?.startsWith("Bearer ") ? auth.slice(7) : query || "";
}
function isOwnerKey(req) {
const key = process.env.CASECOMP_API_KEY;
if (!key) return true;
return getRequestToken(req) === key;
}
function cachePrefix() {
return "";
}
const apiLimiter = rateLimit({
windowMs: 60_000,
max: 60,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Too many requests, please try again later" },
});
const demoLimiter = rateLimit({
windowMs: 60_000,
max: 360,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Too many requests, please try again later" },
});
const sandboxLimiter = rateLimit({
windowMs: 60_000,
max: 5,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Sandbox rate limit: 5 requests per minute" },
});
function isSandboxKey(req) {
const token = getRequestToken(req);
return token && token === process.env.CASECOMP_SANDBOX_KEY;
}
const keyRateCounters = new Map();
function checkKeyRateLimit(keyId, limit) {
const now = Date.now();
const windowMs = 60_000;
let entry = keyRateCounters.get(keyId);
if (!entry || now - entry.windowStart > windowMs) {
entry = { windowStart: now, count: 0 };
keyRateCounters.set(keyId, entry);
}
entry.count++;
return entry.count <= limit;
}
const isLocal = !process.env.K_SERVICE;
app.use("/api", (req, res, next) => {
if (isLocal || req.path === "/health") return next();
if (req.query.demo === "true") return demoLimiter(req, res, next);
if (isSandboxKey(req)) return sandboxLimiter(req, res, next);
return apiLimiter(req, res, next);
});
if (!isLocal) app.use("/v1", apiLimiter);
function classifyTier(req) {
const token = getRequestToken(req);
if (!token) return req.query.demo === "true" ? "demo" : "public";
if (token === process.env.CASECOMP_API_KEY) return "owner";
if (token === process.env.CASECOMP_SANDBOX_KEY) return "sandbox";
if (req.query.demo === "true") return "demo";
return "developer";
}
function hashIp(ip) {
return crypto.createHash("sha256").update(ip || "unknown").digest("hex").slice(0, 8);
}
if (!isLocal) {
app.use("/api", (req, res, next) => {
if (req.path === "/health") return next();
const start = Date.now();
res.on("finish", () => {
logRequest({
path: req.path,
method: req.method,
status: res.statusCode,
latencyMs: Date.now() - start,
tier: classifyTier(req),
userId: portfolioUserId(req),
ipHash: hashIp(req.ip),
userAgent: (req.headers["user-agent"] || "").substring(0, 200),
requestId: req.requestId,
query: req.query.q || null,
ts: new Date().toISOString(),
}).catch(() => {});
});
next();
});
}
function safeErrorMessage(e) {
const msg = e.message || String(e);
if (/ECONNREFUSED|ETIMEDOUT|ENOTFOUND/.test(msg)) return "Upstream service unavailable";
if (/api[_-]?key|token|secret|credential/i.test(msg)) return "Authentication error";
if (/firestore|grpc|google/i.test(msg)) return "Internal storage error";
if (msg.length > 200) return msg.slice(0, 200);
return msg;
}
async function logError(type, message, detail = "", requestId = "") {
console.error(`[ERROR] [${requestId}] ${type}: ${message}`);
try { await saveErrorLog({ type, message, detail, requestId, ts: new Date().toISOString() }); } catch {}
}
const clientId = process.env.EBAY_CLIENT_ID;
const clientSecret = process.env.EBAY_CLIENT_SECRET;
async function getToken() { return getAccessToken(clientId, clientSecret); }
async function on401() { invalidateToken(); }
function validateQuery(q, res) {
if (!q) { res.status(400).json({ error: "Missing required parameter: q" }); return false; }
if (q.length > 200) { res.status(400).json({ error: "Query too long (max 200 characters)" }); return false; }
return true;
}
function buildConfig(q) {
const config = {
language: "any",
languages: [],
deliveryCountries: ["US", "IN"],
deliveryPincodes: { US: "19701", IN: "600028" },
resultsPerCard: 5,
soldListingsLimit: 5,
soldBrowser: false,
tcgBrowseCategoryIds: EBAY_CATEGORY_TCG_SINGLE_CARDS_US,
listingFormat: "raw",
rawSearchSuffix: "",
slab: { provider: "PSA", grade: "10" },
aiGrading: {
enabled: false,
mode: "llm",
llm: { provider: "claude", model: "claude-opus-4-7", maxTokens: 500 },
site: { provider: "local" },
minGradeToReport: 0,
cacheGrades: true,
},
};
if (q.lang) {
config.languages = parseListingLanguagesFromInput(q.lang);
config.language = config.languages.length ? config.languages.join("+") : "any";
}
if (q.countries) config.deliveryCountries = q.countries.split(",").map(s => s.trim().toUpperCase()).filter(Boolean);
if (q.results) config.resultsPerCard = Math.max(1, Number(q.results));
if (q.sold) config.soldListingsLimit = Math.max(1, Number(q.sold));
if (q.format === "slab") config.listingFormat = "slab";
if (q.slab_provider) config.slab.provider = q.slab_provider;
if (q.slab_grade) config.slab.grade = q.slab_grade;
if (q.condition) config.condition = q.condition.toUpperCase();
if (q.source) config.source = q.source.toLowerCase();
if (q.grade === "true" || q.grade === true) {
config.aiGrading.enabled = true;
if (q.provider) config.aiGrading.llm.provider = q.provider;
if (q.model) config.aiGrading.llm.model = q.model;
}
return config;
}
async function storeGradeLog(record) {
await saveGradeLog(record);
}
async function gradeItems(items, config, cardName, source) {
return Promise.all(items.map(async (row) => {
try {
const extraImages = row.additionalImages || [];
const g = await gradeImage(row.imageUrl, config, extraImages);
if (g && !g.error) {
await storeGradeLog({
ts: new Date().toISOString(),
cardName,
source,
listingId: row.itemId,
imageUrl: row.imageUrl,
extraImages: extraImages.map(e => e.imageUrl || e),
provider: config.aiGrading.llm.provider,
model: config.aiGrading.llm.model,
grade: g,
listingPrice: row.price,
condition: row.condition,
});
}
return { ...row, grade: g };
} catch (e) {
return { ...row, grade: { error: safeErrorMessage(e) } };
}
}));
}
// GET /api/demo — list available demo cards
app.get("/api/demo", (req, res) => {
res.json({ cards: listDemoCards(), hint: "Use any of these with /api/search?q=...&demo=true" });
});
// GET /api/search
app.get("/api/search", apiAuthMiddleware, (req, res, next) => { req._errorType = "search"; next(); }, async (req, res) => {
const { q } = req.query;
if (!validateQuery(q, res)) return;
const wantDemo = req.query.demo === "true" || (!clientId && !clientSecret);
if (wantDemo) {
const demoResult = getDemoSearchResult(q, { source: req.query.source, condition: req.query.condition });
for (const country of Object.keys(demoResult.activeByCountry || {})) {
demoResult.activeByCountry[country] = flagPriceOutliers(demoResult.activeByCountry[country].map(item => ({
...item, detectedCondition: item.detectedCondition || detectCondition(item),
})));
}
const demoIdentity = parseCardIdentity(q);
if (demoResult.sold?.length) recordSoldPrices(q, demoResult.sold, demoResult.source, { cardId: demoIdentity.cardId }).catch(() => {});
if (demoIdentity.cardId) {
demoResult.cardId = demoIdentity.cardId;
demoResult.cardIdentity = { name: demoIdentity.name, setCode: demoIdentity.setCode, rarity: demoIdentity.rarity, setName: SET_NAME_MAP[demoIdentity.setCode] || null };
}
return res.json(demoResult);
}
try {
const config = buildConfig(req.query);
const source = config.source || "ebay";
let result;
if (source === "snkrdunk") {
result = await searchSnkrdunk(q, config);
} else if (source === "magi") {
result = await searchMagi(q, config);
} else if (source === "yahoo") {
result = await searchYahooAuctions(q, config);
for (const country of Object.keys(result.activeByCountry || {})) {
result.activeByCountry[country] = filterRelevantResults(result.activeByCountry[country], result.ebaySearchQuery || q).filtered;
}
if (result.sold?.length) result.sold = filterRelevantResults(result.sold, result.ebaySearchQuery || q).filtered;
result.counts = { activeTotal: Object.values(result.activeByCountry || {}).reduce((n, arr) => n + arr.length, 0), sold: result.sold?.length || 0 };
} else {
const ebayQuery = buildEbaySearchQuery(q, config);
const cp = cachePrefix(req);
config._cachePrefix = cp;
const activeRes = await searchActive({ query: ebayQuery, relevanceQuery: q, deliveryCountries: config.deliveryCountries, languages: config.languages, config, refresh: false, noEbay: false, getToken, on401 });
const filteredByCountry = {};
for (const [country, items] of Object.entries(activeRes.itemsByCountry || {})) {
filteredByCountry[country] = filterRelevantResults(items, q).filtered;
}
searchSold({ query: ebayQuery, relevanceQuery: q, languages: config.languages, config, refresh: false, noEbay: false, getToken, on401, soldBrowser: false }).catch(() => {});
getPsaGradingSignal(q, { _cachePrefix: cp }).catch(() => null);
result = {
query: q,
source: "ebay",
listingFormat: config.listingFormat,
activeByCountry: filteredByCountry,
sold: [],
soldSource: "pending",
psaSignal: null,
counts: {
activeTotal: Object.values(filteredByCountry).reduce((n, arr) => n + arr.length, 0),
sold: 0,
},
};
}
const identity = parseCardIdentity(q);
if (identity.cardId) {
result.cardId = identity.cardId;
result.cardIdentity = { name: identity.name, setCode: identity.setCode, rarity: identity.rarity, setName: SET_NAME_MAP[identity.setCode] || null };
}
if (config.aiGrading.enabled) {
const allItems = [];
for (const items of Object.values(result.activeByCountry || {})) allItems.push(...items);
const graded = await gradeItems(allItems, config, q, source);
const gradedMap = new Map(graded.map(g => [g.itemId, g]));
for (const country of Object.keys(result.activeByCountry || {})) {
result.activeByCountry[country] = result.activeByCountry[country].map(item => gradedMap.get(item.itemId) || item);
}
}
// Add detected condition + flag outliers
for (const country of Object.keys(result.activeByCountry || {})) {
result.activeByCountry[country] = flagPriceOutliers(result.activeByCountry[country].map(item => ({
...item,
detectedCondition: item.detectedCondition || detectCondition(item),
})));
}
// Filter by condition if requested
if (config.condition && result.activeByCountry) {
for (const country of Object.keys(result.activeByCountry)) {
result.activeByCountry[country] = filterByCondition(result.activeByCountry[country], config.condition);
}
result.counts.activeTotal = Object.values(result.activeByCountry).reduce((n, arr) => n + arr.length, 0);
}
if (result.sold?.length) {
recordSoldPrices(q, result.sold, result.source, { cardId: identity.cardId }).catch(() => {});
saveGradedImages(result.sold, result.source).catch(() => {});
}
getOrCreateCard(q, { source: result.source, lang: config.language }).catch(() => {});
trackSearchFrequency(q).catch(() => {});
if (req.userId) recordMilestone(req.userId, "firstSearch").catch(() => {});
res.json(result);
} catch (e) {
logError(req._errorType || "api", e.message, req.originalUrl, req.requestId);
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/sold
app.get("/api/sold", apiAuthMiddleware, (req, res, next) => { req._errorType = "sold"; next(); }, async (req, res) => {
const { q } = req.query;
if (!validateQuery(q, res)) return;
const wantSoldDemo = req.query.demo === "true" || (!clientId && !clientSecret);
if (wantSoldDemo) {
const d = getDemoSearchResult(q);
return res.json({ query: q, sold: d.sold, soldSource: d.soldSource || "demo", counts: { sold: d.sold.length }, _demo: true });
}
try {
const config = buildConfig(req.query);
const source = config.source || "ebay";
let sold = [], soldSource = source;
if (source === "snkrdunk") {
const r = await searchSnkrdunk(q, config);
sold = r.sold;
} else if (source === "magi") {
const r = await searchMagi(q, config);
sold = r.sold;
soldSource = r.soldSource;
} else if (source === "yahoo") {
const r = await searchYahooAuctions(q, config);
sold = filterRelevantResults(r.sold || [], r.ebaySearchQuery || q).filtered;
soldSource = r.soldSource;
} else {
const ebayQuery = buildEbaySearchQuery(q, config);
config._cachePrefix = cachePrefix(req);
const soldRes = await Promise.race([
searchSold({ query: ebayQuery, relevanceQuery: q, languages: config.languages, config, refresh: false, noEbay: false, getToken, on401, soldBrowser: false }),
new Promise(r => setTimeout(() => r({ items: [], source: "timeout" }), 30000)),
]);
sold = soldRes.items || [];
soldSource = soldRes.source;
}
if (sold.length) saveGradedImages(sold, soldSource).catch(() => {});
res.json({ query: q, sold, soldSource, counts: { sold: sold.length } });
} catch (e) {
logError(req._errorType || "api", e.message, req.originalUrl, req.requestId);
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/psa
app.get("/api/psa", apiAuthMiddleware, (req, res, next) => { req._errorType = "psa"; next(); }, async (req, res) => {
const { q } = req.query;
if (!validateQuery(q, res)) return;
try {
if (req.query.demo === "true") {
const demo = getDemoSearchResult(q, {});
return res.json({ query: q, signal: demo.psaSignal || null, _demo: true });
}
const signal = await getPsaGradingSignal(q);
res.json({ query: q, signal });
} catch (e) {
logError(req._errorType || "api", e.message, req.originalUrl, req.requestId);
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// POST /api/grade
app.post("/api/grade", authMiddleware, (req, res, next) => { req._errorType = "grade"; next(); }, async (req, res) => {
const { imageUrl, extraImages, provider, model, cardName, cardId, source, listingId, listingPrice, condition, centeringHint, passes: rawPasses } = req.body;
if (!imageUrl) return res.status(400).json({ error: "Missing required field: imageUrl" });
const passes = Math.min(3, Math.max(1, Number(rawPasses) || 1));
try {
const extras = (extraImages || []).map(u => ({ imageUrl: u }));
let grade;
if (passes > 1) {
const results = [];
for (let i = 0; i < passes; i++) {
const config = {
aiGrading: {
enabled: true,
mode: "llm",
llm: { provider: provider || "claude", model: model || "claude-opus-4-7", maxTokens: 500 },
cacheGrades: false,
},
};
const r = await gradeImage(imageUrl, config, extras, centeringHint);
if (r && !r.error) results.push(r);
}
grade = results.length ? medianGrade(results) : { error: "All passes failed" };
} else {
const config = {
aiGrading: {
enabled: true,
mode: "llm",
llm: { provider: provider || "claude", model: model || "claude-opus-4-7", maxTokens: 500 },
cacheGrades: true,
},
};
grade = await gradeImage(imageUrl, config, extras, centeringHint);
}
let gradeId = null;
if (grade && !grade.error) {
const userId = portfolioUserId(req);
gradeId = await storeGradeLog({
ts: new Date().toISOString(),
userId: userId || null,
cardId: cardId || null,
cardName: cardName || "unknown",
source: source || "api",
listingId: listingId || null,
imageUrl,
extraImages: extraImages || [],
provider: (provider || "claude"),
model: (model || "claude-opus-4-7"),
grade,
listingPrice: listingPrice || null,
condition: condition || null,
});
if (passes === 1) {
const { cacheGrade } = await import("./lib/grading/grading.js");
const cacheConfig = { aiGrading: { mode: "llm", llm: { provider: provider || "claude", model: model || "claude-opus-4-7" }, cacheGrades: true } };
await cacheGrade(imageUrl, cacheConfig, grade).catch(() => {});
}
}
if (req.userId && grade && !grade.error) recordMilestone(req.userId, "firstGrade").catch(() => {});
res.json({ grade, gradeId, stored: !!(grade && !grade.error) });
} catch (e) {
logError(req._errorType || "api", e.message, req.originalUrl, req.requestId);
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/grade/report/:id — shareable grade report as PNG
app.get("/api/grade/report/:id", async (req, res) => {
try {
const records = await getGradeLogs({ limit: 1, query: req.params.id });
const record = records.find(r => r.id === req.params.id);
if (!record?.grade || record.grade.error) return res.status(404).json({ error: "Grade not found" });
const { default: sharp } = await import("sharp");
const grade = record.grade;
const overall = grade.overall || "?";
const conf = Math.round((grade.confidence || 0) * 100);
const dist = grade.gradeDistribution || {};
const limiter = grade.notes || "";
const scores = [
["Centering", grade.centering],
["Corners", grade.corners],
["Edges", grade.edges],
["Surface", grade.surface],
];
const distLines = Object.entries(dist)
.sort((a, b) => b[1] - a[1])
.slice(0, 3)
.map(([g, p]) => `PSA ${g}: ${p}%`)
.join(" · ");
const barsSvg = scores.map(([name, score], i) => {
const y = 180 + i * 48;
const barW = Math.round(((score || 0) / 10) * 260);
const color = score >= 9 ? "#7ce0a8" : score >= 7 ? "#d9b676" : "#ff5d5d";
return `
<text x="30" y="${y}" fill="rgba(255,255,255,0.5)" font-size="14" font-family="sans-serif">${name}</text>
<text x="320" y="${y}" fill="white" font-size="14" font-family="monospace" text-anchor="end">${score || "?"}</text>
<rect x="30" y="${y + 6}" width="${barW}" height="4" rx="2" fill="${color}"/>
<rect x="30" y="${y + 6}" width="260" height="4" rx="2" fill="rgba(255,255,255,0.05)"/>
<rect x="30" y="${y + 6}" width="${barW}" height="4" rx="2" fill="${color}"/>`;
}).join("");
const svg = `<svg width="400" height="500" xmlns="http://www.w3.org/2000/svg">
<rect width="400" height="500" fill="#07070a"/>
<rect x="15" y="15" width="370" height="470" rx="12" fill="#0c0d12" stroke="rgba(255,255,255,0.08)" stroke-width="1"/>
<text x="200" y="50" fill="#d9b676" font-size="12" font-family="sans-serif" text-anchor="middle" letter-spacing="2">CASECOMP AI GRADE</text>
<text x="200" y="110" fill="white" font-size="56" font-family="sans-serif" font-weight="bold" text-anchor="middle">${overall}</text>
<text x="200" y="135" fill="rgba(255,255,255,0.4)" font-size="12" font-family="sans-serif" text-anchor="middle">${conf}% confidence</text>
<text x="200" y="158" fill="rgba(255,255,255,0.3)" font-size="11" font-family="monospace" text-anchor="middle">${distLines}</text>
${barsSvg}
<text x="30" y="400" fill="rgba(255,255,255,0.25)" font-size="11" font-family="sans-serif">${limiter.substring(0, 60)}</text>
<text x="200" y="460" fill="rgba(255,255,255,0.15)" font-size="10" font-family="sans-serif" text-anchor="middle">casecomp.xyz</text>
</svg>`;
const png = await sharp(Buffer.from(svg)).png().toBuffer();
res.setHeader("Content-Type", "image/png");
res.setHeader("Cache-Control", "public, max-age=86400");
res.send(png);
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/grades/mine — user's grade history
app.get("/api/grades/mine", authMiddleware, async (req, res) => {
try {
const userId = portfolioUserId(req);
if (!userId) return res.status(401).json({ error: "Sign in required" });
const limit = Math.min(100, Math.max(1, Number(req.query.limit) || 50));
const grades = await getGradeLogsByUser(userId, { limit });
res.json({ grades, count: grades.length });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// DELETE /api/grades/:id — delete your grade
app.delete("/api/grades/:id", authMiddleware, async (req, res) => {
try {
const userId = portfolioUserId(req);
if (!userId) return res.status(401).json({ error: "Sign in required" });
const record = await getGradeLog(req.params.id);
if (!record) return res.status(404).json({ error: "Grade not found" });
if (record.userId !== userId && !isAdminUser(req)) return res.status(403).json({ error: "Not your grade" });
await deleteGradeLog(req.params.id);
res.json({ ok: true });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/grades
app.get("/api/grades", authMiddleware, async (req, res) => {
const limit = Math.min(1000, Math.max(1, Number(req.query.limit) || 100));
try {
const records = await getGradeLogs({ limit, query: req.query.q, source: req.query.source });
res.json(records);
} catch (e) {
logError(req._errorType || "api", e.message, req.originalUrl, req.requestId);
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/errors
app.get("/api/errors", authMiddleware, async (req, res) => {
const limit = Math.min(100, Math.max(1, Number(req.query.limit) || 20));
const type = req.query.type || undefined;
try {
const errors = await getErrorLogs({ limit, type });
res.json({ errors, count: errors.length });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// DELETE /api/errors — clear all error logs (owner only)
app.delete("/api/errors", ownerOnly, async (req, res) => {
try {
const cleared = await clearErrorLogs();
res.json({ ok: true, cleared });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/analytics
app.get("/api/analytics", ownerOnly, async (req, res) => {
const days = Math.min(30, Math.max(1, Number(req.query.days) || 7));
try {
const stats = await getAnalytics({ days });
res.json(stats);
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/funnel
app.get("/api/funnel", ownerOnly, async (req, res) => {
try {
const stats = await getFunnelStats();
res.json(stats);
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/grading-dataset/stats
app.get("/api/grading-dataset/stats", ownerOnly, async (req, res) => {
try {
const { getDatasetStats } = await import("./lib/cards/grading-dataset.js");
const stats = await getDatasetStats();
res.json(stats);
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
app.get("/api/security/events", ownerOnly, async (req, res) => {
const days = Math.min(30, Math.max(1, Number(req.query.days) || 7));
const category = req.query.category || null;
try {
const events = await getSecurityEvents({ days, limit: 200, category });
res.json({ events, count: events.length, days });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/health
app.get("/api/health", async (req, res) => {
const firestoreStatus = await getFirestoreStatus();
let ebayUsage = null;
try { ebayUsage = await getEbayUsageToday(); } catch {}
const isOwner = getRequestToken(req) === process.env.CASECOMP_API_KEY;
const cardDbLoaded = getAllSets().length > 0;
const mem = process.memoryUsage();
const secrets = {
anthropic: !!process.env.ANTHROPIC_API_KEY,
ebay: !!(clientId && clientSecret),
jwt: !!process.env.CASECOMP_JWT_SECRET,
together: !!(process.env.TOGETHER_API_KEY && process.env.TOGETHER_API_KEY.length > 20),
};
res.json({
status: "ok",
uptime: Math.floor(process.uptime()),
firestore: firestoreStatus,
cardDatabase: cardDbLoaded,
secrets,
ebay: { configured: secrets.ebay, ...(isOwner ? { usageToday: ebayUsage, dailyCap: DAILY_CAP } : {}) },
...(isOwner ? { memory: { rss: Math.round(mem.rss / 1048576), heap: Math.round(mem.heapUsed / 1048576) } } : {}),
});
});
// POST /auth/google
const authLimiter = rateLimit({ windowMs: 60_000, max: 10, standardHeaders: true, legacyHeaders: false, message: { error: "Too many auth attempts, try again later" } });
app.post("/auth/google", authLimiter, async (req, res) => {
const { idToken } = req.body || {};
if (!idToken) return res.status(400).json({ error: "idToken required" });
try {
const gUser = await verifyGoogleToken(idToken);
const jwt = generateJwt(gUser);
let apiKey = null;
const existingKeys = await listKeysByOwner(gUser.sub).catch(() => []);
if (existingKeys.length === 0) {
const newKey = await createApiKey({ label: `${gUser.name || gUser.email}'s key`, ownerId: gUser.sub }).catch(() => null);
if (newKey) apiKey = { key: newKey.key, keyPrefix: newKey.keyPrefix, id: newKey.id, isNew: true };
} else {
apiKey = { keyPrefix: existingKeys[0].keyPrefix, id: existingKeys[0].id, isNew: false };
}
const isAdmin = gUser.sub === process.env.CASECOMP_ADMIN_SUB;
recordMilestone(gUser.sub, "signup").catch(() => {});
res.json({ jwt, apiKey, isAdmin, user: { id: gUser.sub, email: gUser.email, name: gUser.name, picture: gUser.picture } });
} catch (e) {
res.status(401).json({ error: "Invalid Google token" });
}
});
// POST /api/upload-url — generate signed GCS upload URL
app.post("/api/upload-url", authMiddleware, async (req, res) => {
const { filename, contentType } = req.body || {};
if (!filename || !contentType) return res.status(400).json({ error: "filename and contentType required" });
if (!/^image\/(jpeg|png|webp)$/.test(contentType)) return res.status(400).json({ error: "Only JPEG, PNG, or WebP images allowed" });
try {
const { Storage } = await import("@google-cloud/storage");
const storage = new Storage();
const bucket = storage.bucket("casecomp-uploads");
const userId = portfolioUserId(req);
const key = `${userId}/${Date.now()}-${filename.replace(/[^a-zA-Z0-9._-]/g, "_")}`;
const file = bucket.file(key);
const [url] = await file.getSignedUrl({
version: "v4",
action: "write",
expires: Date.now() + 15 * 60 * 1000,
contentType,
});
const publicUrl = `https://storage.googleapis.com/casecomp-uploads/${key}`;
res.json({ uploadUrl: url, imageUrl: publicUrl, key });
} catch (e) {
logError("upload", e.message, req.originalUrl, req.requestId);
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
function isAdminUser(req) {
const adminSub = process.env.CASECOMP_ADMIN_SUB;
if (!adminSub) return isOwnerKey(req);
const jwtPayload = verifyJwt(getRequestToken(req));
return jwtPayload?.sub === adminSub || isOwnerKey(req);
}
// ── Developer self-serve ─────────────────────────────────────
// GET /api/developer/keys — list your API keys
app.get("/api/developer/keys", authMiddleware, async (req, res) => {
try {
const userId = portfolioUserId(req);
if (!userId) return res.status(401).json({ error: "Sign in required" });
const keys = await listKeysByOwner(userId);
res.json({ keys, count: keys.length });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// POST /api/developer/keys — create a new API key (max 3 per user)
app.post("/api/developer/keys", authMiddleware, async (req, res) => {
try {
const userId = portfolioUserId(req);
if (!userId) return res.status(401).json({ error: "Sign in required" });
const existing = await listKeysByOwner(userId);
if (existing.length >= 3) return res.status(400).json({ error: "Maximum 3 keys per account" });
const { label } = req.body || {};
const key = await createApiKey({ label: label || "My key", ownerId: userId });
res.status(201).json({ id: key.id, key: key.key, keyPrefix: key.keyPrefix, label: key.label, rateLimit: key.rateLimit });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// DELETE /api/developer/keys/:id — revoke your API key
app.delete("/api/developer/keys/:id", authMiddleware, async (req, res) => {
try {
const userId = portfolioUserId(req);
if (!userId) return res.status(401).json({ error: "Sign in required" });
const key = await getApiKey(req.params.id);
if (!key || key.ownerId !== userId) return res.status(404).json({ error: "Key not found" });
await deleteApiKey(req.params.id);
res.json({ ok: true });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// POST /api/developer/keys/:id/rotate — rotate your key
app.post("/api/developer/keys/:id/rotate", authMiddleware, async (req, res) => {
try {
const userId = portfolioUserId(req);
if (!userId) return res.status(401).json({ error: "Sign in required" });
const key = await getApiKey(req.params.id);
if (!key || key.ownerId !== userId) return res.status(404).json({ error: "Key not found" });
const rotated = await rotateApiKey(req.params.id);
res.json({ id: rotated.id, key: rotated.key, keyPrefix: rotated.keyPrefix });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/developer/stats — your usage stats
app.get("/api/developer/stats", authMiddleware, async (req, res) => {
try {
const userId = portfolioUserId(req);
if (!userId) return res.status(401).json({ error: "Sign in required" });
const days = Math.min(30, Math.max(1, Number(req.query.days) || 7));
const [keys, usage] = await Promise.all([
listKeysByOwner(userId),
getAnalyticsByUser(userId, { days }),
]);
const totalRequests = keys.reduce((sum, k) => sum + (k.requestCount || 0), 0);
res.json({ keys: keys.length, totalRequests, usage });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// ── Admin key management (admin only) ────────────────────────
// GET /api/admin/keys — list ALL developer keys
app.get("/api/admin/keys", authMiddleware, async (req, res) => {
if (!isAdminUser(req)) return res.status(403).json({ error: "Admin access required" });
try {
const keys = await listAllKeys();
res.json({ keys, count: keys.length });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// PATCH /api/admin/keys/:id — update any key (toggle active, change rate limit)
app.patch("/api/admin/keys/:id", authMiddleware, async (req, res) => {
if (!isAdminUser(req)) return res.status(403).json({ error: "Admin access required" });
try {
const { active, rateLimit, label } = req.body || {};
const updated = await updateApiKey(req.params.id, { active, rateLimit, label });
if (!updated) return res.status(404).json({ error: "Key not found" });
res.json(updated);
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// DELETE /api/admin/keys/:id — delete any key
app.delete("/api/admin/keys/:id", authMiddleware, async (req, res) => {
if (!isAdminUser(req)) return res.status(403).json({ error: "Admin access required" });
try {
const deleted = await deleteApiKey(req.params.id);
if (!deleted) return res.status(404).json({ error: "Key not found" });
res.json({ ok: true });
} catch (e) {
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /api/autocomplete
app.get("/api/autocomplete", (req, res) => {
const q = (req.query.q || "").trim();
if (!q || q.length < 2) return res.status(400).json({ error: "Query must be at least 2 characters" });
if (q.length > 100) return res.status(400).json({ error: "Query too long (max 100 characters)" });
const limit = Math.min(20, Math.max(1, Number(req.query.limit) || 8));
const results = searchCards(q, limit);
res.json({ results, count: results.length, query: q });
});
// GET /api/sets
app.get("/api/sets", (req, res) => {
const sets = getAllSets();
const era = req.query.era;
const filtered = era ? sets.filter(s => s.era === era) : sets;
res.json({ sets: filtered, count: filtered.length });
});
// GET /api/sets/:setCode
app.get("/api/sets/:setCode", (req, res) => {
const result = getSetWithCards(req.params.setCode);
if (!result) return res.status(404).json({ error: "Set not found" });
res.json(result);
});
// ============ V1 API — Drop Intelligence ============
async function authMiddleware(req, res, next) {
if (isLocal) return next();
const ownerKey = process.env.CASECOMP_API_KEY;
const sandboxKey = process.env.CASECOMP_SANDBOX_KEY;
if (!ownerKey) return next();
const token = getRequestToken(req);
if (!token) return res.status(401).json({ error: "Invalid or missing API key" });
if (token === ownerKey || token === sandboxKey) return next();
const jwtPayload = verifyJwt(token);
if (jwtPayload) return next();
const devKey = await validateApiKey(token);
if (devKey) {
if (!devKey.active) return res.status(403).json({ error: "API key has been deactivated" });
if (!checkKeyRateLimit(devKey.id, devKey.rateLimit || 60)) {
return res.status(429).json({ error: `Rate limit exceeded (${devKey.rateLimit || 60} req/min)` });
}
req._devKey = devKey;
return next();
}
return res.status(401).json({ error: "Invalid or missing API key" });
}
function ownerOnly(req, res, next) {
if (isLocal) return next();
const token = getRequestToken(req);
if (token !== process.env.CASECOMP_API_KEY) {
return res.status(403).json({ error: "Owner key required" });
}
next();
}
function apiAuthMiddleware(req, res, next) {
if (req.query.demo === "true") return next();
return authMiddleware(req, res, next);
}
const v1 = express.Router();
v1.use(authMiddleware);
// GET /v1/drops — list recent drop events
v1.get("/drops", async (req, res) => {
const limit = Math.min(100, Math.max(1, Number(req.query.limit) || 20));
try {
const records = await getDrops({ limit, site: req.query.site, status: req.query.status });
res.json({ drops: records, count: records.length, limit });
} catch (e) {
logError(req._errorType || "api", e.message, req.originalUrl, req.requestId);
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /v1/drops/:id — single drop with queue metrics
v1.get("/drops/:id", async (req, res) => {
try {
const record = await getDrop(req.params.id);
if (!record) return res.status(404).json({ error: "Drop not found" });
res.json(record);
} catch (e) {
logError(req._errorType || "api", e.message, req.originalUrl, req.requestId);
res.status(500).json({ error: safeErrorMessage(e), requestId: req.requestId });
}
});
// GET /v1/comps — sold and listed prices
v1.get("/comps", async (req, res) => {
const { sku, q } = req.query;
const query = sku || q;
if (!query) return res.status(400).json({ error: "Missing required parameter: sku or q" });
try {
const config = buildConfig(req.query);
const source = config.source || "ebay";
let active = [], sold = [];
if (source === "snkrdunk") {
const r = await searchSnkrdunk(query, config);
active = r.items || r.active || [];
sold = r.sold || [];
} else if (source === "magi") {
const r = await searchMagi(query, config);
active = r.items || r.active || [];
sold = r.sold || [];
} else if (source === "yahoo") {
const r = await searchYahooAuctions(query, config);
active = filterRelevantResults(r.items || r.active || Object.values(r.activeByCountry || {}).flat(), r.ebaySearchQuery || query).filtered;
sold = filterRelevantResults(r.sold || [], r.ebaySearchQuery || query).filtered;
} else {
const ebayQuery = buildEbaySearchQuery(query, config);
config._cachePrefix = cachePrefix(req);
const activeRes = await searchActive({ query: ebayQuery, relevanceQuery: query, deliveryCountries: config.deliveryCountries, languages: config.languages, config, refresh: false, noEbay: false, getToken, on401 });
const soldRes = await searchSold({ query: ebayQuery, relevanceQuery: query, languages: config.languages, config, refresh: false, noEbay: false, getToken, on401, soldBrowser: false });
for (const items of Object.values(activeRes.itemsByCountry || {})) active.push(...items);
sold = soldRes.items || [];
}
res.json({
query,
source,
active: { items: active, count: active.length },