@usethink/cf-core 0.3.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 (169) hide show
  1. package/README.md +88 -0
  2. package/dist/features/anti-abuse/index.d.ts +62 -0
  3. package/dist/features/anti-abuse/index.d.ts.map +1 -0
  4. package/dist/features/anti-abuse/index.js +139 -0
  5. package/dist/features/anti-abuse/index.js.map +1 -0
  6. package/dist/features/email/index.d.ts +68 -0
  7. package/dist/features/email/index.d.ts.map +1 -0
  8. package/dist/features/email/index.js +120 -0
  9. package/dist/features/email/index.js.map +1 -0
  10. package/dist/features/payment/fetch-utils.d.ts +17 -0
  11. package/dist/features/payment/fetch-utils.d.ts.map +1 -0
  12. package/dist/features/payment/fetch-utils.js +56 -0
  13. package/dist/features/payment/fetch-utils.js.map +1 -0
  14. package/dist/features/payment/index.d.ts +20 -0
  15. package/dist/features/payment/index.d.ts.map +1 -0
  16. package/dist/features/payment/index.js +21 -0
  17. package/dist/features/payment/index.js.map +1 -0
  18. package/dist/features/payment/providers/alipay.d.ts +30 -0
  19. package/dist/features/payment/providers/alipay.d.ts.map +1 -0
  20. package/dist/features/payment/providers/alipay.js +149 -0
  21. package/dist/features/payment/providers/alipay.js.map +1 -0
  22. package/dist/features/payment/providers/stripe.d.ts +34 -0
  23. package/dist/features/payment/providers/stripe.d.ts.map +1 -0
  24. package/dist/features/payment/providers/stripe.js +168 -0
  25. package/dist/features/payment/providers/stripe.js.map +1 -0
  26. package/dist/features/payment/providers/trc20.d.ts +24 -0
  27. package/dist/features/payment/providers/trc20.d.ts.map +1 -0
  28. package/dist/features/payment/providers/trc20.js +96 -0
  29. package/dist/features/payment/providers/trc20.js.map +1 -0
  30. package/dist/features/payment/registry.d.ts +43 -0
  31. package/dist/features/payment/registry.d.ts.map +1 -0
  32. package/dist/features/payment/registry.js +65 -0
  33. package/dist/features/payment/registry.js.map +1 -0
  34. package/dist/features/payment/types.d.ts +72 -0
  35. package/dist/features/payment/types.d.ts.map +1 -0
  36. package/dist/features/payment/types.js +8 -0
  37. package/dist/features/payment/types.js.map +1 -0
  38. package/dist/features/thompson-router/index.d.ts +101 -0
  39. package/dist/features/thompson-router/index.d.ts.map +1 -0
  40. package/dist/features/thompson-router/index.js +186 -0
  41. package/dist/features/thompson-router/index.js.map +1 -0
  42. package/dist/features/webhook/index.d.ts +76 -0
  43. package/dist/features/webhook/index.d.ts.map +1 -0
  44. package/dist/features/webhook/index.js +127 -0
  45. package/dist/features/webhook/index.js.map +1 -0
  46. package/dist/src/audit.d.ts +45 -0
  47. package/dist/src/audit.d.ts.map +1 -0
  48. package/dist/src/audit.js +40 -0
  49. package/dist/src/audit.js.map +1 -0
  50. package/dist/src/auth/jwt.d.ts +33 -0
  51. package/dist/src/auth/jwt.d.ts.map +1 -0
  52. package/dist/src/auth/jwt.js +87 -0
  53. package/dist/src/auth/jwt.js.map +1 -0
  54. package/dist/src/auth/password.d.ts +26 -0
  55. package/dist/src/auth/password.d.ts.map +1 -0
  56. package/dist/src/auth/password.js +52 -0
  57. package/dist/src/auth/password.js.map +1 -0
  58. package/dist/src/bootstrap.d.ts +74 -0
  59. package/dist/src/bootstrap.d.ts.map +1 -0
  60. package/dist/src/bootstrap.js +231 -0
  61. package/dist/src/bootstrap.js.map +1 -0
  62. package/dist/src/cache.d.ts +52 -0
  63. package/dist/src/cache.d.ts.map +1 -0
  64. package/dist/src/cache.js +76 -0
  65. package/dist/src/cache.js.map +1 -0
  66. package/dist/src/config.d.ts +83 -0
  67. package/dist/src/config.d.ts.map +1 -0
  68. package/dist/src/config.js +96 -0
  69. package/dist/src/config.js.map +1 -0
  70. package/dist/src/crypto.d.ts +33 -0
  71. package/dist/src/crypto.d.ts.map +1 -0
  72. package/dist/src/crypto.js +87 -0
  73. package/dist/src/crypto.js.map +1 -0
  74. package/dist/src/db/connection.d.ts +53 -0
  75. package/dist/src/db/connection.d.ts.map +1 -0
  76. package/dist/src/db/connection.js +104 -0
  77. package/dist/src/db/connection.js.map +1 -0
  78. package/dist/src/db/index.d.ts +6 -0
  79. package/dist/src/db/index.d.ts.map +1 -0
  80. package/dist/src/db/index.js +6 -0
  81. package/dist/src/db/index.js.map +1 -0
  82. package/dist/src/db/schema.d.ts +649 -0
  83. package/dist/src/db/schema.d.ts.map +1 -0
  84. package/dist/src/db/schema.js +76 -0
  85. package/dist/src/db/schema.js.map +1 -0
  86. package/dist/src/error.d.ts +47 -0
  87. package/dist/src/error.d.ts.map +1 -0
  88. package/dist/src/error.js +94 -0
  89. package/dist/src/error.js.map +1 -0
  90. package/dist/src/http.d.ts +83 -0
  91. package/dist/src/http.d.ts.map +1 -0
  92. package/dist/src/http.js +116 -0
  93. package/dist/src/http.js.map +1 -0
  94. package/dist/src/idempotency.d.ts +78 -0
  95. package/dist/src/idempotency.d.ts.map +1 -0
  96. package/dist/src/idempotency.js +84 -0
  97. package/dist/src/idempotency.js.map +1 -0
  98. package/dist/src/index.d.ts +31 -0
  99. package/dist/src/index.d.ts.map +1 -0
  100. package/dist/src/index.js +45 -0
  101. package/dist/src/index.js.map +1 -0
  102. package/dist/src/logger.d.ts +31 -0
  103. package/dist/src/logger.d.ts.map +1 -0
  104. package/dist/src/logger.js +45 -0
  105. package/dist/src/logger.js.map +1 -0
  106. package/dist/src/middleware/admin-auth.d.ts +38 -0
  107. package/dist/src/middleware/admin-auth.d.ts.map +1 -0
  108. package/dist/src/middleware/admin-auth.js +55 -0
  109. package/dist/src/middleware/admin-auth.js.map +1 -0
  110. package/dist/src/middleware/api-key-auth.d.ts +42 -0
  111. package/dist/src/middleware/api-key-auth.d.ts.map +1 -0
  112. package/dist/src/middleware/api-key-auth.js +104 -0
  113. package/dist/src/middleware/api-key-auth.js.map +1 -0
  114. package/dist/src/middleware/index.d.ts +3 -0
  115. package/dist/src/middleware/index.d.ts.map +1 -0
  116. package/dist/src/middleware/index.js +3 -0
  117. package/dist/src/middleware/index.js.map +1 -0
  118. package/dist/src/rate-limit.d.ts +54 -0
  119. package/dist/src/rate-limit.d.ts.map +1 -0
  120. package/dist/src/rate-limit.js +134 -0
  121. package/dist/src/rate-limit.js.map +1 -0
  122. package/dist/src/security.d.ts +78 -0
  123. package/dist/src/security.d.ts.map +1 -0
  124. package/dist/src/security.js +175 -0
  125. package/dist/src/security.js.map +1 -0
  126. package/dist/src/types.d.ts +64 -0
  127. package/dist/src/types.d.ts.map +1 -0
  128. package/dist/src/types.js +8 -0
  129. package/dist/src/types.js.map +1 -0
  130. package/features/anti-abuse/index.ts +180 -0
  131. package/features/anti-abuse/tests/index.test.ts +50 -0
  132. package/features/email/index.ts +172 -0
  133. package/features/email/tests/index.test.ts +44 -0
  134. package/features/payment/fetch-utils.ts +65 -0
  135. package/features/payment/index.ts +39 -0
  136. package/features/payment/providers/alipay.ts +171 -0
  137. package/features/payment/providers/stripe.ts +192 -0
  138. package/features/payment/providers/trc20.ts +115 -0
  139. package/features/payment/registry.ts +87 -0
  140. package/features/payment/tests/index.test.ts +506 -0
  141. package/features/payment/types.ts +93 -0
  142. package/features/telegram-miniapp/index.ts +109 -0
  143. package/features/telegram-miniapp/tests/index.test.ts +11 -0
  144. package/features/thompson-router/index.ts +243 -0
  145. package/features/thompson-router/tests/index.test.ts +93 -0
  146. package/features/webhook/index.ts +183 -0
  147. package/features/webhook/tests/index.test.ts +21 -0
  148. package/package.json +202 -0
  149. package/src/audit.ts +70 -0
  150. package/src/auth/jwt.ts +114 -0
  151. package/src/auth/password.ts +75 -0
  152. package/src/bootstrap.ts +322 -0
  153. package/src/cache.ts +78 -0
  154. package/src/config.ts +134 -0
  155. package/src/crypto.ts +106 -0
  156. package/src/db/connection.ts +127 -0
  157. package/src/db/index.ts +6 -0
  158. package/src/db/schema.ts +90 -0
  159. package/src/error.ts +125 -0
  160. package/src/http.ts +150 -0
  161. package/src/idempotency.ts +127 -0
  162. package/src/index.ts +85 -0
  163. package/src/logger.ts +63 -0
  164. package/src/middleware/admin-auth.ts +71 -0
  165. package/src/middleware/api-key-auth.ts +164 -0
  166. package/src/middleware/index.ts +2 -0
  167. package/src/rate-limit.ts +167 -0
  168. package/src/security.ts +219 -0
  169. package/src/types.ts +70 -0
package/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # @usethink/cf-core
2
+
3
+ Cloudflare Workers 共享内核 — Hono + Turso + Drizzle 标准化基础设施。
4
+
5
+ 从 eshop / xtools / vcode 三个项目中提取的公共代码,为批量产品复制提供统一基础。
6
+
7
+ ## 快速开始
8
+
9
+ ```bash
10
+ # 安装
11
+ cd packages/cf-core && npm install
12
+
13
+ # 类型检查
14
+ npm run type-check
15
+
16
+ # 测试
17
+ npm test
18
+ ```
19
+
20
+ ## 在项目中使用
21
+
22
+ ### 方式 1:子路径导入(推荐)
23
+
24
+ ```ts
25
+ import { ok, fail, maskContact } from "@usethink/cf-core/http";
26
+ import { sha256, verifyTurnstile, getIpHash } from "@usethink/cf-core/security";
27
+ import { initDatabase } from "@usethink/cf-core/db";
28
+ import { createAdminAuth } from "@usethink/cf-core/middleware";
29
+ import { bootstrap } from "@usethink/cf-core/bootstrap";
30
+ ```
31
+
32
+ ### 方式 2:根导入
33
+
34
+ ```ts
35
+ import { ok, fail, sha256, initDatabase, bootstrap } from "@usethink/cf-core";
36
+ ```
37
+
38
+ ## 模块清单
39
+
40
+ | 模块 | 子路径 | 功能 |
41
+ |------|--------|------|
42
+ | **http** | `/http` | ok/fail 响应、maskContact、csvEscape、toCsv |
43
+ | **security** | `/security` | sha256、constantTimeEqual、getIpHash、verifyTurnstile、buildSecurityHeaders |
44
+ | **db** | `/db` | initDatabase(Isolate 级连接复用)、公共 Schema |
45
+ | **db/schema** | `/db/schema` | systemConfig、adminAuditLogs、rateLimitWindows、idempotencyKeys、apiKeys |
46
+ | **rate-limit** | `/rate-limit` | MemoryRateLimiter / KvRateLimiter / DbRateLimiter |
47
+ | **cache** | `/cache` | Workers Cache API 封装(Free 套餐不计入请求配额) |
48
+ | **idempotency** | `/idempotency` | 原子 UPSERT + 哨兵值幂等保护 |
49
+ | **audit** | `/audit` | fire-and-forget 审计日志 |
50
+ | **config** | `/config` | SystemConfig 类(运行时 KV 配置,热生效) |
51
+ | **bootstrap** | `/bootstrap` | Worker 入口工厂(DB 中间件 + 安全头 + 路由分流) |
52
+ | **auth/jwt** | `/auth/jwt` | JWT 签发/验证(HMAC-SHA256,纯 Web Crypto) |
53
+ | **auth/password** | `/auth/password` | PBKDF2 密码哈希 |
54
+ | **middleware** | `/middleware` | createAdminAuth / createApiKeyAuth |
55
+ | **error** | `/error` | classifyError + retryWithBackoff |
56
+ | **logger** | `/logger` | 结构化 JSON 日志 |
57
+ | **crypto** | `/crypto` | AES-256-GCM 加解密、generateUUID |
58
+
59
+ ## 新项目模板使用
60
+
61
+ ```ts
62
+ // src/index.ts
63
+ import * as schema from "./db/schema";
64
+ import { bootstrap } from "@usethink/cf-core/bootstrap";
65
+ import { createAdminAuth } from "@usethink/cf-core/middleware";
66
+ import { productRoutes } from "./routes/products";
67
+ import { orderRoutes } from "./routes/orders";
68
+
69
+ export default bootstrap({
70
+ schema,
71
+ securityHeaders: { allowTelegram: true },
72
+ registerRoutes: (api) => {
73
+ api.route("/products", productRoutes);
74
+ api.route("/orders", orderRoutes);
75
+ api.route("/admin", new Hono().use("*", createAdminAuth()).route("/", adminRoutes));
76
+ },
77
+ pageRoutes: { "/admin": "/admin.html" },
78
+ spaRoutes: { fallback: "/_app/index.html", paths: ["/shop", "/order"] },
79
+ immutablePrefixes: ["/_app/assets/"],
80
+ });
81
+ ```
82
+
83
+ ## 设计原则
84
+
85
+ 1. **泛型优先** — 所有函数使用泛型 `Context<E>` 而非特定 `AppEnv`,兼容任意项目
86
+ 2. **零耦合** — 模块间仅通过导入引用,不依赖全局状态
87
+ 3. **Web Crypto** — 所有加密操作使用 Workers 原生 API,零外部依赖
88
+ 4. **Free 友好** — Cache API 优先、Isolate 级缓存、惰性清理
@@ -0,0 +1,62 @@
1
+ /**
2
+ * anti-abuse — 防刷检测插件
3
+ *
4
+ * 提供 API 级别的异常行为检测:
5
+ * - 多 IP 访问同一资源
6
+ * - 高频请求检测
7
+ * - 凭证扫描检测(顺序遍历 ID)
8
+ * - 快速连续操作检测
9
+ *
10
+ * 纯内存实现(Workers 实例级别),无需外部存储。
11
+ *
12
+ * 来源:vcode src/services/anti-abuse.ts
13
+ */
14
+ export type AbuseType = "multi_ip_access" | "high_frequency" | "token_scan" | "rapid_fire";
15
+ export interface AbuseEvent {
16
+ type: AbuseType;
17
+ resourceId: string;
18
+ ipHash: string;
19
+ timestamp: number;
20
+ detail: string;
21
+ }
22
+ export interface AntiAbuseConfig {
23
+ /** 同一资源允许的最大不同 IP 数(默认 5) */
24
+ maxIpsPerResource?: number;
25
+ /** 同一 IP 在窗口内允许的最大请求数(默认 30) */
26
+ maxRequestsPerIp?: number;
27
+ /** 请求频率窗口(毫秒,默认 60000) */
28
+ windowMs?: number;
29
+ /** 连续 ID 差值阈值(检测扫描,默认 3) */
30
+ scanThreshold?: number;
31
+ /** 快速连续操作最小间隔(毫秒,默认 500) */
32
+ rapidFireIntervalMs?: number;
33
+ }
34
+ export declare class AntiAbuseService {
35
+ readonly name = "anti-abuse";
36
+ readonly version = "0.1.0";
37
+ private config;
38
+ private resourceIps;
39
+ private ipRequests;
40
+ private lastAccessByIp;
41
+ private lastResourceIdByIp;
42
+ private events;
43
+ constructor(config?: AntiAbuseConfig);
44
+ /**
45
+ * 记录一次资源访问,返回检测到的异常事件列表
46
+ */
47
+ record(resourceId: string, ipHash: string): AbuseEvent[];
48
+ /**
49
+ * 获取最近的异常事件
50
+ */
51
+ getEvents(limit?: number): AbuseEvent[];
52
+ /**
53
+ * 检查某个 IP 是否可疑
54
+ */
55
+ isSuspicious(ipHash: string): boolean;
56
+ /**
57
+ * 清理过期数据
58
+ */
59
+ cleanup(): void;
60
+ private parseNumericId;
61
+ }
62
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../features/anti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 /**
2
+ * anti-abuse — 防刷检测插件
3
+ *
4
+ * 提供 API 级别的异常行为检测:
5
+ * - 多 IP 访问同一资源
6
+ * - 高频请求检测
7
+ * - 凭证扫描检测(顺序遍历 ID)
8
+ * - 快速连续操作检测
9
+ *
10
+ * 纯内存实现(Workers 实例级别),无需外部存储。
11
+ *
12
+ * 来源:vcode src/services/anti-abuse.ts
13
+ */
14
+ // ═══════════════════════════════════════════════════════════════════════════════
15
+ // AntiAbuseService
16
+ // ═══════════════════════════════════════════════════════════════════════════════
17
+ export class AntiAbuseService {
18
+ name = "anti-abuse";
19
+ version = "0.1.0";
20
+ config;
21
+ // 内存存储
22
+ resourceIps = new Map();
23
+ ipRequests = new Map();
24
+ lastAccessByIp = new Map();
25
+ lastResourceIdByIp = new Map();
26
+ events = [];
27
+ constructor(config = {}) {
28
+ this.config = {
29
+ maxIpsPerResource: config.maxIpsPerResource ?? 5,
30
+ maxRequestsPerIp: config.maxRequestsPerIp ?? 30,
31
+ windowMs: config.windowMs ?? 60_000,
32
+ scanThreshold: config.scanThreshold ?? 3,
33
+ rapidFireIntervalMs: config.rapidFireIntervalMs ?? 500,
34
+ };
35
+ }
36
+ /**
37
+ * 记录一次资源访问,返回检测到的异常事件列表
38
+ */
39
+ record(resourceId, ipHash) {
40
+ const now = Date.now();
41
+ const detected = [];
42
+ // 1. 多 IP 访问检测
43
+ if (!this.resourceIps.has(resourceId)) {
44
+ this.resourceIps.set(resourceId, new Set());
45
+ }
46
+ const ips = this.resourceIps.get(resourceId);
47
+ ips.add(ipHash);
48
+ if (ips.size > this.config.maxIpsPerResource) {
49
+ detected.push({
50
+ type: "multi_ip_access",
51
+ resourceId,
52
+ ipHash,
53
+ timestamp: now,
54
+ detail: `${ips.size} different IPs accessed this resource (limit: ${this.config.maxIpsPerResource})`,
55
+ });
56
+ }
57
+ // 2. 高频请求检测
58
+ if (!this.ipRequests.has(ipHash)) {
59
+ this.ipRequests.set(ipHash, []);
60
+ }
61
+ const timestamps = this.ipRequests.get(ipHash);
62
+ const windowStart = now - this.config.windowMs;
63
+ const validTimestamps = timestamps.filter((ts) => ts > windowStart);
64
+ validTimestamps.push(now);
65
+ this.ipRequests.set(ipHash, validTimestamps);
66
+ if (validTimestamps.length > this.config.maxRequestsPerIp) {
67
+ detected.push({
68
+ type: "high_frequency",
69
+ resourceId,
70
+ ipHash,
71
+ timestamp: now,
72
+ detail: `${validTimestamps.length} requests in ${this.config.windowMs}ms (limit: ${this.config.maxRequestsPerIp})`,
73
+ });
74
+ }
75
+ // 3. 凭证扫描检测
76
+ const lastId = this.lastResourceIdByIp.get(ipHash);
77
+ if (lastId) {
78
+ const idDiff = this.parseNumericId(resourceId) - this.parseNumericId(lastId);
79
+ if (idDiff > 0 && idDiff <= this.config.scanThreshold) {
80
+ detected.push({
81
+ type: "token_scan",
82
+ resourceId,
83
+ ipHash,
84
+ timestamp: now,
85
+ detail: `Sequential ID access: ${lastId} → ${resourceId} (diff: ${idDiff})`,
86
+ });
87
+ }
88
+ }
89
+ this.lastResourceIdByIp.set(ipHash, resourceId);
90
+ // 4. 快速连续操作检测
91
+ const lastAccess = this.lastAccessByIp.get(ipHash);
92
+ if (lastAccess && now - lastAccess < this.config.rapidFireIntervalMs) {
93
+ detected.push({
94
+ type: "rapid_fire",
95
+ resourceId,
96
+ ipHash,
97
+ timestamp: now,
98
+ detail: `Rapid access: ${now - lastAccess}ms (min: ${this.config.rapidFireIntervalMs}ms)`,
99
+ });
100
+ }
101
+ this.lastAccessByIp.set(ipHash, now);
102
+ // 记录事件
103
+ for (const event of detected) {
104
+ this.events.push(event);
105
+ }
106
+ return detected;
107
+ }
108
+ /**
109
+ * 获取最近的异常事件
110
+ */
111
+ getEvents(limit = 50) {
112
+ return this.events.slice(-limit);
113
+ }
114
+ /**
115
+ * 检查某个 IP 是否可疑
116
+ */
117
+ isSuspicious(ipHash) {
118
+ return this.events.some((e) => e.ipHash === ipHash);
119
+ }
120
+ /**
121
+ * 清理过期数据
122
+ */
123
+ cleanup() {
124
+ const cutoff = Date.now() - this.config.windowMs * 2;
125
+ for (const [ip, timestamps] of this.ipRequests) {
126
+ const valid = timestamps.filter((ts) => ts > cutoff);
127
+ if (valid.length === 0)
128
+ this.ipRequests.delete(ip);
129
+ else
130
+ this.ipRequests.set(ip, valid);
131
+ }
132
+ this.events = this.events.filter((e) => e.timestamp > cutoff);
133
+ }
134
+ parseNumericId(id) {
135
+ const match = id.match(/(\d+)$/);
136
+ return match ? parseInt(match[1]) : 0;
137
+ }
138
+ }
139
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../features/anti-abuse/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AA6BH,kFAAkF;AAClF,mBAAmB;AACnB,kFAAkF;AAElF,MAAM,OAAO,gBAAgB;IAClB,IAAI,GAAG,YAAY,CAAC;IACpB,OAAO,GAAG,OAAO,CAAC;IAEnB,MAAM,CAA4B;IAE1C,OAAO;IACC,WAAW,GAAG,IAAI,GAAG,EAAuB,CAAC;IAC7C,UAAU,GAAG,IAAI,GAAG,EAAoB,CAAC;IACzC,cAAc,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC3C,kBAAkB,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC/C,MAAM,GAAiB,EAAE,CAAC;IAElC,YAAY,SAA0B,EAAE;QACtC,IAAI,CAAC,MAAM,GAAG;YACZ,iBAAiB,EAAE,MAAM,CAAC,iBAAiB,IAAI,CAAC;YAChD,gBAAgB,EAAE,MAAM,CAAC,gBAAgB,IAAI,EAAE;YAC/C,QAAQ,EAAE,MAAM,CAAC,QAAQ,IAAI,MAAM;YACnC,aAAa,EAAE,MAAM,CAAC,aAAa,IAAI,CAAC;YACxC,mBAAmB,EAAE,MAAM,CAAC,mBAAmB,IAAI,GAAG;SACvD,CAAC;IACJ,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,UAAkB,EAAE,MAAc;QACvC,MAAM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IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,SAAS,GAAG,MAAM,CAAC,CAAC;IAChE,CAAC;IAEO,cAAc,CAAC,EAAU;QAC/B,MAAM,KAAK,GAAG,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QACjC,OAAO,KAAK,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACxC,CAAC;CACF"}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * email-resend — Resend 邮件发送插件
3
+ *
4
+ * 通过 Resend API 发送事务邮件,支持:
5
+ * - 模板插值({{变量}})+ HTML 转义
6
+ * - 3 次重试(指数退避)
7
+ * - 邮件日志记录(可选,需传入 Drizzle DB 实例)
8
+ *
9
+ * 来源:eshop src/services/email-service.ts
10
+ */
11
+ export declare function escapeHtml(s: string): string;
12
+ export declare function interpolate(template: string, data: Record<string, string>): string;
13
+ export interface EmailTemplate {
14
+ subject: string;
15
+ html: string;
16
+ }
17
+ export interface ResendConfig {
18
+ apiKey: string;
19
+ from?: string;
20
+ defaultFrom?: string;
21
+ }
22
+ export interface SendEmailOptions {
23
+ to: string;
24
+ subject: string;
25
+ html: string;
26
+ from?: string;
27
+ }
28
+ export interface SendResult {
29
+ ok: boolean;
30
+ messageId?: string;
31
+ error?: string;
32
+ }
33
+ /**
34
+ * Resend 邮件发送服务
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * import { EmailService } from "@usethink/cf-core/plugins/email-resend";
39
+ *
40
+ * const email = new EmailService({ apiKey: env.RESEND_API_KEY, from: "noreply@example.com" });
41
+ * const result = await email.send({
42
+ * to: "buyer@example.com",
43
+ * subject: "订单确认",
44
+ * html: "<h1>您的订单已确认</h1>",
45
+ * });
46
+ * ```
47
+ */
48
+ export declare class EmailService {
49
+ readonly name = "email-resend";
50
+ readonly version = "0.1.0";
51
+ private config;
52
+ constructor(config: ResendConfig);
53
+ /**
54
+ * 发送邮件
55
+ */
56
+ send(opts: SendEmailOptions): Promise<SendResult>;
57
+ /**
58
+ * 使用模板发送邮件
59
+ */
60
+ sendWithTemplate(to: string, template: EmailTemplate, data: Record<string, string>, opts?: {
61
+ from?: string;
62
+ }): Promise<SendResult>;
63
+ /**
64
+ * 健康检查 — 验证 API Key 是否有效
65
+ */
66
+ healthCheck(): Promise<boolean>;
67
+ }
68
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../features/email/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAMH,wBAAgB,UAAU,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,CAI5C;AAED,wBAAgB,WAAW,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAMlF;AAMD,MAAM,WAAW,aAAa;IAC5B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,UAAU;IACzB,EAAE,EAAE,OAAO,CAAC;IACZ,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;;;;;GAcG;AACH,qBAAa,YAAY;IACvB,QAAQ,CAAC,IAAI,kBAAkB;IAC/B,QAAQ,CAAC,OAAO,WAAW;IAE3B,OAAO,CAAC,MAAM,CAAe;gBAEjB,MAAM,EAAE,YAAY;IAIhC;;OAEG;IACG,IAAI,CAAC,IAAI,EAAE,gBAAgB,GAAG,OAAO,CAAC,UAAU,CAAC;IAqDvD;;OAEG;IACG,gBAAgB,CACpB,EAAE,EAAE,MAAM,EACV,QAAQ,EAAE,aAAa,EACvB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC5B,IAAI,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,GACvB,OAAO,CAAC,UAAU,CAAC;IAMtB;;OAEG;IACG,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;CAgBtC"}
@@ -0,0 +1,120 @@
1
+ /**
2
+ * email-resend — Resend 邮件发送插件
3
+ *
4
+ * 通过 Resend API 发送事务邮件,支持:
5
+ * - 模板插值({{变量}})+ HTML 转义
6
+ * - 3 次重试(指数退避)
7
+ * - 邮件日志记录(可选,需传入 Drizzle DB 实例)
8
+ *
9
+ * 来源:eshop src/services/email-service.ts
10
+ */
11
+ // ═══════════════════════════════════════════════════════════════════════════════
12
+ // 模板引擎
13
+ // ═══════════════════════════════════════════════════════════════════════════════
14
+ export function escapeHtml(s) {
15
+ return s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c] ?? c));
16
+ }
17
+ export function interpolate(template, data) {
18
+ return template
19
+ .replace(/\{\{(\w+)\}\}/g, (_, key) => escapeHtml(String(data[key] ?? "")))
20
+ .replace(/\{\{#if (\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g, (_, key, content) => data[key] ? content : "");
21
+ }
22
+ /**
23
+ * Resend 邮件发送服务
24
+ *
25
+ * @example
26
+ * ```ts
27
+ * import { EmailService } from "@usethink/cf-core/plugins/email-resend";
28
+ *
29
+ * const email = new EmailService({ apiKey: env.RESEND_API_KEY, from: "noreply@example.com" });
30
+ * const result = await email.send({
31
+ * to: "buyer@example.com",
32
+ * subject: "订单确认",
33
+ * html: "<h1>您的订单已确认</h1>",
34
+ * });
35
+ * ```
36
+ */
37
+ export class EmailService {
38
+ name = "email-resend";
39
+ version = "0.1.0";
40
+ config;
41
+ constructor(config) {
42
+ this.config = config;
43
+ }
44
+ /**
45
+ * 发送邮件
46
+ */
47
+ async send(opts) {
48
+ const { to, subject, html } = opts;
49
+ const from = opts.from || this.config.from || this.config.defaultFrom || "noreply@example.com";
50
+ if (!to || !to.includes("@")) {
51
+ return { ok: false, error: "无效的收件人邮箱" };
52
+ }
53
+ const MAX_RETRIES = 3;
54
+ const RETRY_DELAYS = [500, 1000, 2000];
55
+ let lastError = "";
56
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
57
+ try {
58
+ const res = await fetch("https://api.resend.com/emails", {
59
+ method: "POST",
60
+ headers: {
61
+ Authorization: `Bearer ${this.config.apiKey}`,
62
+ "Content-Type": "application/json",
63
+ },
64
+ body: JSON.stringify({ from, to, subject, html }),
65
+ });
66
+ const data = (await res.json());
67
+ if (res.ok) {
68
+ return { ok: true, messageId: data.id };
69
+ }
70
+ if (res.status >= 400 && res.status < 500) {
71
+ return { ok: false, error: data.message || `HTTP ${res.status}` };
72
+ }
73
+ lastError = data.message || `HTTP ${res.status}`;
74
+ if (attempt < MAX_RETRIES) {
75
+ await new Promise((r) => setTimeout(r, RETRY_DELAYS[attempt - 1]));
76
+ continue;
77
+ }
78
+ return { ok: false, error: lastError };
79
+ }
80
+ catch (err) {
81
+ lastError = err instanceof Error ? err.message : String(err);
82
+ if (attempt < MAX_RETRIES) {
83
+ await new Promise((r) => setTimeout(r, RETRY_DELAYS[attempt - 1]));
84
+ continue;
85
+ }
86
+ return { ok: false, error: lastError };
87
+ }
88
+ }
89
+ return { ok: false, error: lastError };
90
+ }
91
+ /**
92
+ * 使用模板发送邮件
93
+ */
94
+ async sendWithTemplate(to, template, data, opts) {
95
+ const subject = interpolate(template.subject, data);
96
+ const html = interpolate(template.html, data);
97
+ return this.send({ to, subject, html, from: opts?.from });
98
+ }
99
+ /**
100
+ * 健康检查 — 验证 API Key 是否有效
101
+ */
102
+ async healthCheck() {
103
+ try {
104
+ const res = await fetch("https://api.resend.com/emails", {
105
+ method: "POST",
106
+ headers: {
107
+ Authorization: `Bearer ${this.config.apiKey}`,
108
+ "Content-Type": "application/json",
109
+ },
110
+ body: JSON.stringify({ from: "test@test.com", to: "test@test.com", subject: "", html: "" }),
111
+ });
112
+ // 422 = 参数无效但 Key 有效; 401/403 = Key 无效
113
+ return res.status !== 401 && res.status !== 403;
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ }
119
+ }
120
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../features/email/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,kFAAkF;AAClF,OAAO;AACP,kFAAkF;AAElF,MAAM,UAAU,UAAU,CAAC,CAAS;IAClC,OAAO,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC,EAAE,EAAE,CACjC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAClF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,QAAgB,EAAE,IAA4B;IACxE,OAAO,QAAQ;SACZ,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;SAC1E,OAAO,CAAC,0CAA0C,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE,CACvE,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC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 调用都应通过此函数,避免 Workers CPU 耗尽。
6
+ */
7
+ /**
8
+ * 带超时和指数退避重试的 fetch 封装。
9
+ *
10
+ * HTTP 4xx 不重试(客户端错误),5xx/网络错误重试。
11
+ * 超时通过 AbortController 实现,兼容 Workers 环境。
12
+ */
13
+ export declare function fetchWithRetry(url: string, options?: RequestInit & {
14
+ retries?: number;
15
+ timeoutMs?: number;
16
+ }): Promise<Response>;
17
+ //# sourceMappingURL=fetch-utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-utils.d.ts","sourceRoot":"","sources":["../../../features/payment/fetch-utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAMH;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,WAAW,GAAG;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAO,GACnE,OAAO,CAAC,QAAQ,CAAC,CA4CnB"}
@@ -0,0 +1,56 @@
1
+ /**
2
+ * 支付功能模块 — HTTP 工具
3
+ *
4
+ * 带超时和指数退避重试的 fetch 封装。
5
+ * 所有第三方 API 调用都应通过此函数,避免 Workers CPU 耗尽。
6
+ */
7
+ const FETCH_TIMEOUT_MS = 10_000;
8
+ const FETCH_RETRIES = 2;
9
+ const RETRY_DELAYS = [500, 1500];
10
+ /**
11
+ * 带超时和指数退避重试的 fetch 封装。
12
+ *
13
+ * HTTP 4xx 不重试(客户端错误),5xx/网络错误重试。
14
+ * 超时通过 AbortController 实现,兼容 Workers 环境。
15
+ */
16
+ export async function fetchWithRetry(url, options = {}) {
17
+ const maxRetries = options.retries ?? FETCH_RETRIES;
18
+ const timeoutMs = options.timeoutMs ?? FETCH_TIMEOUT_MS;
19
+ let lastError = "";
20
+ for (let attempt = 1; attempt <= maxRetries + 1; attempt++) {
21
+ try {
22
+ const controller = new AbortController();
23
+ const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
24
+ const resp = await fetch(url, {
25
+ ...options,
26
+ signal: controller.signal,
27
+ });
28
+ clearTimeout(timeoutId);
29
+ // 4xx 不重试(客户端错误)
30
+ if (resp.status >= 400 && resp.status < 500 && resp.status !== 429)
31
+ return resp;
32
+ // 5xx 或 429 重试
33
+ if (!resp.ok && attempt <= maxRetries) {
34
+ lastError = `HTTP ${resp.status}`;
35
+ await new Promise((r) => setTimeout(r, RETRY_DELAYS[attempt - 1] ?? 1000));
36
+ continue;
37
+ }
38
+ return resp;
39
+ }
40
+ catch (err) {
41
+ if (err instanceof DOMException && err.name === "AbortError") {
42
+ lastError = `Timeout after ${timeoutMs}ms`;
43
+ }
44
+ else {
45
+ lastError = err instanceof Error ? err.message : String(err);
46
+ }
47
+ if (attempt <= maxRetries) {
48
+ await new Promise((r) => setTimeout(r, RETRY_DELAYS[attempt - 1] ?? 1000));
49
+ continue;
50
+ }
51
+ throw new Error(`[fetchWithRetry] ${lastError} (after ${attempt - 1} retries)`);
52
+ }
53
+ }
54
+ throw new Error(`[fetchWithRetry] ${lastError} (after ${maxRetries + 1} attempts)`);
55
+ }
56
+ //# sourceMappingURL=fetch-utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch-utils.js","sourceRoot":"","sources":["../../../features/payment/fetch-utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,MAAM,gBAAgB,GAAG,MAAM,CAAC;AAChC,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAEjC;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,GAAW,EACX,UAAkE,EAAE;IAEpE,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,IAAI,aAAa,CAAC;IACpD,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,gBAAgB,CAAC;IACxD,IAAI,SAAS,GAAG,EAAE,CAAC;IAEnB,KAAK,IAAI,OAAO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;YAED,IAAI,OAAO,IAAI,UAAU,EAAE,CAAC;gBAC1B,MAAM,IAAI,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,CAAC,EAAE,YAAY,CAAC,OAAO,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC;gBAC3E,SAAS;YACX,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,oBAAoB,SAAS,WAAW,OAAO,GAAG,CAAC,WAAW,CAAC,CAAC;QAClF,CAAC;IACH,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,oBAAoB,SAAS,WAAW,UAAU,GAAG,CAAC,YAAY,CAAC,CAAC;AACtF,CAAC"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @usethink/cf-core/features/payment — 支付功能模块
3
+ *
4
+ * 统一导出所有支付相关能力。支持两种导入方式:
5
+ *
6
+ * 1. 从根导入(适合小项目):
7
+ * import { alipayFactory, stripeFactory } from "@usethink/cf-core/features/payment";
8
+ *
9
+ * 2. 按子路径导入(推荐,tree-shakeable):
10
+ * import { alipayFactory } from "@usethink/cf-core/features/payment/providers/alipay";
11
+ * import { stripeFactory } from "@usethink/cf-core/features/payment/providers/stripe";
12
+ */
13
+ export type { CreatePaymentInput, CreatePaymentResult, CallbackResult, QueryStatusResult, RefundInput, RefundResult, PaymentProvider, ProviderRegistry, ProviderFactory, } from "./types";
14
+ export { createProviderRegistry } from "./registry";
15
+ export type { DbProviderConfig, DbProviderConfigMap } from "./registry";
16
+ export { AlipayProvider, alipayFactory, signRSA2, verifyRSA2 } from "./providers/alipay";
17
+ export type { AlipayConfig } from "./providers/alipay";
18
+ export { StripeProvider, stripeFactory } from "./providers/stripe";
19
+ export { Trc20Provider, trc20Factory } from "./providers/trc20";
20
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../features/payment/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,YAAY,EACV,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,EACd,iBAAiB,EACjB,WAAW,EACX,YAAY,EACZ,eAAe,EACf,gBAAgB,EAChB,eAAe,GAChB,MAAM,SAAS,CAAC;AAGjB,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,YAAY,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAGxE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACzF,YAAY,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAGvD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAGnE,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC"}
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @usethink/cf-core/features/payment — 支付功能模块
3
+ *
4
+ * 统一导出所有支付相关能力。支持两种导入方式:
5
+ *
6
+ * 1. 从根导入(适合小项目):
7
+ * import { alipayFactory, stripeFactory } from "@usethink/cf-core/features/payment";
8
+ *
9
+ * 2. 按子路径导入(推荐,tree-shakeable):
10
+ * import { alipayFactory } from "@usethink/cf-core/features/payment/providers/alipay";
11
+ * import { stripeFactory } from "@usethink/cf-core/features/payment/providers/stripe";
12
+ */
13
+ // ── 注册表 ──
14
+ export { createProviderRegistry } from "./registry";
15
+ // ── 支付宝 ──
16
+ export { AlipayProvider, alipayFactory, signRSA2, verifyRSA2 } from "./providers/alipay";
17
+ // ── Stripe ──
18
+ export { StripeProvider, stripeFactory } from "./providers/stripe";
19
+ // ── USDT/TRC20 ──
20
+ export { Trc20Provider, trc20Factory } from "./providers/trc20";
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../features/payment/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAeH,YAAY;AACZ,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAGpD,YAAY;AACZ,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGzF,eAAe;AACf,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnE,mBAAmB;AACnB,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC"}