@easypayment/medusa-payment-paypal 1.3.3 → 1.3.4

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 (41) hide show
  1. package/.medusa/server/src/admin/index.js +91 -7
  2. package/.medusa/server/src/admin/index.mjs +91 -7
  3. package/.medusa/server/src/api/admin/paypal/logs/route.d.ts +10 -0
  4. package/.medusa/server/src/api/admin/paypal/logs/route.d.ts.map +1 -0
  5. package/.medusa/server/src/api/admin/paypal/logs/route.js +43 -0
  6. package/.medusa/server/src/api/admin/paypal/logs/route.js.map +1 -0
  7. package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
  8. package/.medusa/server/src/api/middlewares.js +22 -4
  9. package/.medusa/server/src/api/middlewares.js.map +1 -1
  10. package/.medusa/server/src/api/utils/request-logger.d.ts +11 -0
  11. package/.medusa/server/src/api/utils/request-logger.d.ts.map +1 -0
  12. package/.medusa/server/src/api/utils/request-logger.js +69 -0
  13. package/.medusa/server/src/api/utils/request-logger.js.map +1 -0
  14. package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +3 -3
  15. package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
  16. package/.medusa/server/src/modules/paypal/service.js +9 -0
  17. package/.medusa/server/src/modules/paypal/service.js.map +1 -1
  18. package/.medusa/server/src/modules/paypal/types/config.js +1 -1
  19. package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
  20. package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
  21. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +10 -0
  22. package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
  23. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
  24. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +39 -0
  25. package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
  26. package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts +62 -0
  27. package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts.map +1 -0
  28. package/.medusa/server/src/modules/paypal/utils/request-logger.js +297 -0
  29. package/.medusa/server/src/modules/paypal/utils/request-logger.js.map +1 -0
  30. package/CHANGELOG.md +7 -0
  31. package/README.md +4 -0
  32. package/package.json +1 -1
  33. package/src/admin/routes/settings/paypal/additional-settings/page.tsx +87 -0
  34. package/src/api/admin/paypal/logs/route.ts +50 -0
  35. package/src/api/middlewares.ts +22 -4
  36. package/src/api/utils/request-logger.ts +84 -0
  37. package/src/modules/paypal/service.ts +11 -0
  38. package/src/modules/paypal/types/config.ts +1 -1
  39. package/src/modules/paypal/utils/credential-resolver.ts +9 -0
  40. package/src/modules/paypal/utils/paypal-fetch.ts +42 -0
  41. package/src/modules/paypal/utils/request-logger.ts +358 -0
@@ -26,7 +26,7 @@ export type PayPalModuleConfig = {
26
26
 
27
27
  const STATIC_CFG: PayPalModuleConfig = {
28
28
  partnerServiceUrl:
29
- "https://mbjtechnolabs.com/ppcp-seller-onboarding/seller-onboarding.php?from=medusa",
29
+ "https://mbjtechnolabs.com/medusa-seller-onboarding/seller-onboarding.php?from=medusa",
30
30
  partnerJsUrl:
31
31
  "https://www.paypal.com/webapps/merchantboarding/js/lib/lightbox/partner.js",
32
32
  backendUrl: "http://localhost:9000",
@@ -1,5 +1,6 @@
1
1
  import { recordMetricAtomic } from "./metrics"
2
2
  import { getCachedSettings, setCachedSettings } from "./settings-cache"
3
+ import { setRequestLoggingEnabled } from "./request-logger"
3
4
  import { PAYPAL_PARTNER_ATTRIBUTION_ID as BN_CODE } from "./partner"
4
5
  import { paypalFetch } from "./paypal-fetch"
5
6
  import { decryptSecret, encryptSecret } from "./secret-crypto"
@@ -284,6 +285,14 @@ export class PayPalCredentialResolver {
284
285
  apiDetails: (data.api_details || {}) as Record<string, unknown>,
285
286
  }
286
287
  setCachedSettings("resolver-settings", resolved)
288
+ // Sync the request-logging flag for THIS container (payment module runs
289
+ // isolated from the app container, so it needs its own sync).
290
+ try {
291
+ const addl = resolved.additionalSettings as Record<string, unknown>
292
+ setRequestLoggingEnabled(!!(addl?.debugLogging ?? addl?.debug_logging))
293
+ } catch {
294
+ // never let a logging-flag sync break settings reads
295
+ }
287
296
  return resolved
288
297
  } catch {
289
298
  return {
@@ -3,6 +3,8 @@
3
3
  * optional retry for critical payment operations.
4
4
  */
5
5
 
6
+ import { isRequestLoggingEnabled, logOutbound } from "./request-logger"
7
+
6
8
  export const PAYPAL_HTTP_TIMEOUT_MS = (() => {
7
9
  const v = Number(process.env.PAYPAL_HTTP_TIMEOUT_MS)
8
10
  return Number.isFinite(v) && v > 0 ? v : 30_000
@@ -120,6 +122,9 @@ export function paypalFetch(
120
122
  return Promise.reject(new CircuitOpenError())
121
123
  }
122
124
 
125
+ const logging = isRequestLoggingEnabled()
126
+ const startedAt = logging ? Date.now() : 0
127
+
123
128
  const fetchPromise = init.signal
124
129
  ? fetch(input, init)
125
130
  : fetch(input, {
@@ -134,10 +139,47 @@ export function paypalFetch(
134
139
  } else {
135
140
  cbRecordSuccess(host)
136
141
  }
142
+ if (logging) {
143
+ // Read the body off a CLONE so the caller's stream is untouched, and
144
+ // fire-and-forget so logging never delays the response.
145
+ res
146
+ .clone()
147
+ .text()
148
+ .then((responseBody) =>
149
+ logOutbound({
150
+ method: String(init.method || "GET").toUpperCase(),
151
+ url: String(input),
152
+ requestHeaders: init.headers,
153
+ requestBody: init.body,
154
+ status: res.status,
155
+ statusText: res.statusText,
156
+ responseHeaders: res.headers,
157
+ responseBody,
158
+ durationMs: Date.now() - startedAt,
159
+ })
160
+ )
161
+ .catch(() => {
162
+ // best-effort: logging must never affect the payment flow
163
+ })
164
+ }
137
165
  return res
138
166
  },
139
167
  (err) => {
140
168
  cbRecordFailure(host)
169
+ if (logging) {
170
+ try {
171
+ logOutbound({
172
+ method: String(init.method || "GET").toUpperCase(),
173
+ url: String(input),
174
+ requestHeaders: init.headers,
175
+ requestBody: init.body,
176
+ durationMs: Date.now() - startedAt,
177
+ error: err,
178
+ })
179
+ } catch {
180
+ // best-effort only
181
+ }
182
+ }
141
183
  throw err
142
184
  }
143
185
  )
@@ -0,0 +1,358 @@
1
+ /**
2
+ * Opt-in request/response file logger for the PayPal integration.
3
+ *
4
+ * Purpose: produce a complete, human-readable log of the HTTP traffic between
5
+ * this plugin and PayPal (outbound) plus the plugin's own API routes (inbound),
6
+ * so it can be exported and handed to PayPal's integration-review team.
7
+ *
8
+ * Disabled by default. Turned on from the admin settings (the
9
+ * `additional_settings.debug_logging` flag, synced into this module via
10
+ * `setRequestLoggingEnabled`) or, as a convenience, by the `PAYPAL_REQUEST_LOG`
11
+ * env var. When off, every entry point here is a cheap no-op.
12
+ *
13
+ * The log intentionally KEEPS the `PayPal-Partner-Attribution-Id` (BN code)
14
+ * header — PayPal validates it during review — while redacting credentials
15
+ * (Authorization headers, access/refresh tokens, client secrets, raw card
16
+ * fields) so the exported file is safe to share.
17
+ */
18
+
19
+ import fs from "fs"
20
+ import path from "path"
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Enable flag
24
+ // ---------------------------------------------------------------------------
25
+
26
+ /**
27
+ * `PAYPAL_REQUEST_LOG=1|true|yes|on` forces logging on regardless of the admin
28
+ * setting — handy on a box where you can't reach the admin UI. The admin
29
+ * setting controls the process-local flag below.
30
+ */
31
+ const ENV_FORCE_ON = /^(1|true|yes|on)$/i.test(
32
+ (process.env.PAYPAL_REQUEST_LOG || "").trim()
33
+ )
34
+
35
+ let settingEnabled = false
36
+
37
+ /** Sync the on/off flag from the persisted `additional_settings.debug_logging`. */
38
+ export function setRequestLoggingEnabled(enabled: boolean): void {
39
+ settingEnabled = !!enabled
40
+ }
41
+
42
+ /** Whether request/response logging is currently active in this process. */
43
+ export function isRequestLoggingEnabled(): boolean {
44
+ return ENV_FORCE_ON || settingEnabled
45
+ }
46
+
47
+ // ---------------------------------------------------------------------------
48
+ // Redaction
49
+ // ---------------------------------------------------------------------------
50
+
51
+ // Body keys whose VALUES must never hit the exported file. Card fields are
52
+ // included even though they normally never reach the backend (the JS SDK sends
53
+ // them straight to PayPal) — defence in depth for the advanced-card flow.
54
+ const SENSITIVE_BODY_KEY_RE =
55
+ /secret|password|client_secret|access_token|refresh_token|authorization|auth_code|code_verifier|api[_-]?key|private[_-]?key|security_code|\bcvv2?\b|card[_-]?number|(^|_)number$|expiry|exp_(month|year)/i
56
+
57
+ // Request/response HEADER names to redact. The BN code header is deliberately
58
+ // NOT here — PayPal needs to see it in the log.
59
+ const SENSITIVE_HEADER_RE =
60
+ /^(authorization|proxy-authorization|cookie|set-cookie|x-api-key)$/i
61
+
62
+ const REDACTED = "[REDACTED]"
63
+
64
+ function redactBody(value: unknown, depth = 0): unknown {
65
+ if (depth > 8 || value === null || typeof value !== "object") {
66
+ return value
67
+ }
68
+ if (Array.isArray(value)) {
69
+ return value.slice(0, 200).map((v) => redactBody(v, depth + 1))
70
+ }
71
+ const out: Record<string, unknown> = {}
72
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
73
+ out[k] = SENSITIVE_BODY_KEY_RE.test(k) ? REDACTED : redactBody(v, depth + 1)
74
+ }
75
+ return out
76
+ }
77
+
78
+ function redactHeaders(
79
+ headers: Record<string, string>
80
+ ): Record<string, string> {
81
+ const out: Record<string, string> = {}
82
+ for (const [k, v] of Object.entries(headers)) {
83
+ out[k] = SENSITIVE_HEADER_RE.test(k) ? REDACTED : v
84
+ }
85
+ return out
86
+ }
87
+
88
+ /** Best-effort parse + redact of a body that may be JSON, form-encoded, or text. */
89
+ function redactSerializedBody(body: unknown): string {
90
+ if (body === undefined || body === null) return ""
91
+ // Already a plain object/array (inbound res.json payloads).
92
+ if (typeof body === "object" && !(body instanceof Uint8Array)) {
93
+ try {
94
+ return JSON.stringify(redactBody(body), null, 2)
95
+ } catch {
96
+ return "[unserializable object]"
97
+ }
98
+ }
99
+ const text = String(body)
100
+ if (!text) return ""
101
+ const trimmed = text.trim()
102
+ // JSON?
103
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
104
+ try {
105
+ return JSON.stringify(redactBody(JSON.parse(trimmed)), null, 2)
106
+ } catch {
107
+ // fall through to form / raw handling
108
+ }
109
+ }
110
+ // Form-encoded (grant_type=...&code_verifier=...)?
111
+ if (/^[^=\s]+=[^&\s]*(&[^=\s]+=[^&\s]*)*$/.test(trimmed)) {
112
+ try {
113
+ const params = new URLSearchParams(trimmed)
114
+ const obj: Record<string, string> = {}
115
+ for (const [k, v] of params.entries()) {
116
+ obj[k] = SENSITIVE_BODY_KEY_RE.test(k) ? REDACTED : v
117
+ }
118
+ return JSON.stringify(obj, null, 2)
119
+ } catch {
120
+ // fall through
121
+ }
122
+ }
123
+ return trimmed.slice(0, 20_000)
124
+ }
125
+
126
+ function normalizeHeaders(
127
+ headers: unknown
128
+ ): Record<string, string> {
129
+ const out: Record<string, string> = {}
130
+ if (!headers) return out
131
+ try {
132
+ // Fetch Headers / Response.headers
133
+ if (typeof (headers as Headers).forEach === "function") {
134
+ ;(headers as Headers).forEach((v, k) => {
135
+ out[k] = v
136
+ })
137
+ return out
138
+ }
139
+ if (Array.isArray(headers)) {
140
+ for (const pair of headers as [string, string][]) {
141
+ if (pair && pair.length >= 2) out[String(pair[0])] = String(pair[1])
142
+ }
143
+ return out
144
+ }
145
+ for (const [k, v] of Object.entries(headers as Record<string, unknown>)) {
146
+ out[k] = Array.isArray(v) ? v.join(", ") : String(v)
147
+ }
148
+ } catch {
149
+ // ignore malformed header containers
150
+ }
151
+ return out
152
+ }
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // File sink
156
+ // ---------------------------------------------------------------------------
157
+
158
+ function getLogDir(): string {
159
+ const dir = (process.env.PAYPAL_LOG_DIR || "").trim()
160
+ return dir ? path.resolve(dir) : path.join(process.cwd(), "logs")
161
+ }
162
+
163
+ const LOG_PREFIX = "paypal-requests-"
164
+
165
+ function dateStamp(d = new Date()): string {
166
+ return d.toISOString().slice(0, 10) // YYYY-MM-DD
167
+ }
168
+
169
+ /** Absolute path of the log file for the current day. */
170
+ export function getCurrentLogFilePath(): string {
171
+ return path.join(getLogDir(), `${LOG_PREFIX}${dateStamp()}.log`)
172
+ }
173
+
174
+ let dirEnsured = false
175
+ function ensureDir(dir: string): boolean {
176
+ if (dirEnsured) return true
177
+ try {
178
+ fs.mkdirSync(dir, { recursive: true })
179
+ dirEnsured = true
180
+ return true
181
+ } catch (e) {
182
+ // Only warn once; never throw into the request path.
183
+ console.warn(
184
+ "[paypal_request_log] could not create log dir",
185
+ dir,
186
+ (e as Error)?.message
187
+ )
188
+ return false
189
+ }
190
+ }
191
+
192
+ function write(block: string): void {
193
+ try {
194
+ const dir = getLogDir()
195
+ if (!ensureDir(dir)) return
196
+ fs.appendFileSync(getCurrentLogFilePath(), block)
197
+ } catch (e) {
198
+ console.warn(
199
+ "[paypal_request_log] write failed:",
200
+ (e as Error)?.message
201
+ )
202
+ }
203
+ }
204
+
205
+ const DIVIDER = "=".repeat(80)
206
+
207
+ function renderHeaders(headers: Record<string, string>): string {
208
+ const keys = Object.keys(headers)
209
+ if (keys.length === 0) return " (none)"
210
+ return keys.map((k) => ` ${k}: ${headers[k]}`).join("\n")
211
+ }
212
+
213
+ // ---------------------------------------------------------------------------
214
+ // Public logging entry points
215
+ // ---------------------------------------------------------------------------
216
+
217
+ export type OutboundLog = {
218
+ method: string
219
+ url: string
220
+ requestHeaders?: unknown
221
+ requestBody?: unknown
222
+ status?: number
223
+ statusText?: string
224
+ responseHeaders?: unknown
225
+ responseBody?: unknown
226
+ durationMs?: number
227
+ error?: unknown
228
+ }
229
+
230
+ /** Append one outbound (plugin → PayPal / onboarding service) call. */
231
+ export function logOutbound(entry: OutboundLog): void {
232
+ if (!isRequestLoggingEnabled()) return
233
+ const reqHeaders = redactHeaders(normalizeHeaders(entry.requestHeaders))
234
+ const resHeaders = redactHeaders(normalizeHeaders(entry.responseHeaders))
235
+ const outcome = entry.error
236
+ ? `ERROR ${(entry.error as Error)?.message || String(entry.error)}`
237
+ : `-> ${entry.status ?? "?"}${
238
+ entry.statusText ? " " + entry.statusText : ""
239
+ }`
240
+ const duration =
241
+ typeof entry.durationMs === "number" ? ` (${entry.durationMs}ms)` : ""
242
+
243
+ const block =
244
+ [
245
+ DIVIDER,
246
+ `[${new Date().toISOString()}] OUTBOUND ${entry.method} ${entry.url} ${outcome}${duration}`,
247
+ "Request Headers:",
248
+ renderHeaders(reqHeaders),
249
+ "Request Body:",
250
+ redactSerializedBody(entry.requestBody) || " (empty)",
251
+ "Response Headers:",
252
+ renderHeaders(resHeaders),
253
+ "Response Body:",
254
+ entry.error
255
+ ? ` ${(entry.error as Error)?.stack || String(entry.error)}`
256
+ : redactSerializedBody(entry.responseBody) || " (empty)",
257
+ DIVIDER,
258
+ "",
259
+ "",
260
+ ].join("\n")
261
+
262
+ write(block)
263
+ }
264
+
265
+ export type InboundLog = {
266
+ method: string
267
+ path: string
268
+ query?: unknown
269
+ requestHeaders?: unknown
270
+ requestBody?: unknown
271
+ status?: number
272
+ responseBody?: unknown
273
+ durationMs?: number
274
+ }
275
+
276
+ /** Append one inbound (client → plugin API route) request. */
277
+ export function logInbound(entry: InboundLog): void {
278
+ if (!isRequestLoggingEnabled()) return
279
+ const reqHeaders = redactHeaders(normalizeHeaders(entry.requestHeaders))
280
+ const duration =
281
+ typeof entry.durationMs === "number" ? ` (${entry.durationMs}ms)` : ""
282
+ const query =
283
+ entry.query && Object.keys(entry.query as object).length
284
+ ? `?${new URLSearchParams(
285
+ entry.query as Record<string, string>
286
+ ).toString()}`
287
+ : ""
288
+
289
+ const block =
290
+ [
291
+ DIVIDER,
292
+ `[${new Date().toISOString()}] INBOUND ${entry.method} ${entry.path}${query} -> ${
293
+ entry.status ?? "?"
294
+ }${duration}`,
295
+ "Request Headers:",
296
+ renderHeaders(reqHeaders),
297
+ "Request Body:",
298
+ redactSerializedBody(entry.requestBody) || " (empty)",
299
+ "Response Body:",
300
+ redactSerializedBody(entry.responseBody) || " (empty)",
301
+ DIVIDER,
302
+ "",
303
+ "",
304
+ ].join("\n")
305
+
306
+ write(block)
307
+ }
308
+
309
+ // ---------------------------------------------------------------------------
310
+ // Read helpers (for the admin download endpoint)
311
+ // ---------------------------------------------------------------------------
312
+
313
+ export type LogFileInfo = {
314
+ name: string
315
+ size: number
316
+ modified: string
317
+ }
318
+
319
+ /** List the available daily log files, newest first. */
320
+ export function listLogFiles(): LogFileInfo[] {
321
+ try {
322
+ const dir = getLogDir()
323
+ if (!fs.existsSync(dir)) return []
324
+ return fs
325
+ .readdirSync(dir)
326
+ .filter((f) => f.startsWith(LOG_PREFIX) && f.endsWith(".log"))
327
+ .map((name) => {
328
+ const stat = fs.statSync(path.join(dir, name))
329
+ return {
330
+ name,
331
+ size: stat.size,
332
+ modified: stat.mtime.toISOString(),
333
+ }
334
+ })
335
+ .sort((a, b) => (a.name < b.name ? 1 : -1))
336
+ } catch {
337
+ return []
338
+ }
339
+ }
340
+
341
+ /**
342
+ * Resolve a requested log file name to an absolute path INSIDE the log dir, or
343
+ * null if it escapes the dir / doesn't exist. Guards against path traversal.
344
+ */
345
+ export function resolveLogFile(name?: string): string | null {
346
+ const dir = getLogDir()
347
+ const target = name && name.trim() ? name.trim() : null
348
+ const chosen = target
349
+ ? path.join(dir, path.basename(target))
350
+ : listLogFiles()[0]
351
+ ? path.join(dir, listLogFiles()[0].name)
352
+ : null
353
+ if (!chosen) return null
354
+ // basename() already strips any directory component; verify containment.
355
+ if (path.dirname(chosen) !== path.resolve(dir)) return null
356
+ if (!fs.existsSync(chosen)) return null
357
+ return chosen
358
+ }