@easypayment/medusa-payment-paypal 1.3.3 → 1.3.5

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 +250 -166
  2. package/.medusa/server/src/admin/index.mjs +250 -166
  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 +19 -3
  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 +27 -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 +21 -3
  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
@@ -0,0 +1,50 @@
1
+ import fs from "fs"
2
+ import path from "path"
3
+ import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
4
+ import {
5
+ isRequestLoggingEnabled,
6
+ listLogFiles,
7
+ resolveLogFile,
8
+ } from "../../../../modules/paypal/utils/request-logger"
9
+
10
+ /**
11
+ * GET /admin/paypal/logs
12
+ * → { enabled, files: [{ name, size, modified }] }
13
+ *
14
+ * GET /admin/paypal/logs?file=<name>&download=1 (file optional → newest)
15
+ * → the raw log file as a text/plain attachment, for sending to PayPal.
16
+ */
17
+ export async function GET(req: MedusaRequest, res: MedusaResponse) {
18
+ try {
19
+ const query = req.query as Record<string, string | undefined>
20
+ const wantsDownload =
21
+ query.download === "1" ||
22
+ query.download === "true" ||
23
+ typeof query.file === "string"
24
+
25
+ if (wantsDownload) {
26
+ const filePath = resolveLogFile(query.file)
27
+ if (!filePath) {
28
+ return res.status(404).json({ message: "Log file not found" })
29
+ }
30
+ const name = path.basename(filePath)
31
+ res.setHeader("Content-Type", "text/plain; charset=utf-8")
32
+ res.setHeader(
33
+ "Content-Disposition",
34
+ `attachment; filename="${name}"`
35
+ )
36
+ return res.send(fs.readFileSync(filePath, "utf8"))
37
+ }
38
+
39
+ return res.json({
40
+ enabled: isRequestLoggingEnabled(),
41
+ files: listLogFiles(),
42
+ })
43
+ } catch (e: unknown) {
44
+ console.error(
45
+ "[PayPal] logs GET failed:",
46
+ e instanceof Error ? e.message : e
47
+ )
48
+ return res.status(500).json({ message: "Failed to read PayPal logs" })
49
+ }
50
+ }
@@ -1,8 +1,30 @@
1
1
  import { defineMiddlewares } from "@medusajs/framework/http"
2
2
  import { createRateLimiter } from "./utils/rate-limit"
3
+ import { createInboundLogger } from "./utils/request-logger"
3
4
 
4
5
  export default defineMiddlewares({
5
6
  routes: [
7
+ // Opt-in request/response logging for the plugin's API routes. One catch-all
8
+ // per namespace is enough — every /store/paypal/*, /admin/paypal/* and
9
+ // /hooks/paypal/* request matches its namespace entry, and the logger
10
+ // de-dupes per request so overlapping matchers can't double-log. It is a
11
+ // pass-through unless logging is enabled in settings.
12
+ {
13
+ matcher: "/store/paypal/:path*",
14
+ middlewares: [createInboundLogger()],
15
+ },
16
+ {
17
+ matcher: "/store/paypal-complete",
18
+ middlewares: [createInboundLogger()],
19
+ },
20
+ {
21
+ matcher: "/admin/paypal/:path*",
22
+ middlewares: [createInboundLogger()],
23
+ },
24
+ {
25
+ matcher: "/hooks/paypal/:path*",
26
+ middlewares: [createInboundLogger()],
27
+ },
6
28
  {
7
29
  // Keep the exact bytes PayPal signed (`req.rawBody`) so webhook signature
8
30
  // verification hashes the original payload, not a re-serialized copy. This
@@ -61,9 +83,5 @@ export default defineMiddlewares({
61
83
  method: ["GET"],
62
84
  middlewares: [createRateLimiter("config")],
63
85
  },
64
- {
65
- matcher: "/store/paypal/:path*",
66
- middlewares: [],
67
- },
68
86
  ],
69
87
  })
@@ -0,0 +1,84 @@
1
+ import type {
2
+ MedusaNextFunction,
3
+ MedusaRequest,
4
+ MedusaResponse,
5
+ } from "@medusajs/framework/http"
6
+ import {
7
+ isRequestLoggingEnabled,
8
+ logInbound,
9
+ } from "../../modules/paypal/utils/request-logger"
10
+
11
+ /**
12
+ * Inbound request/response logger for the plugin's own API routes.
13
+ *
14
+ * Opt-in: a pass-through unless logging is enabled (admin setting or the
15
+ * `PAYPAL_REQUEST_LOG` env var). Captures the request body and the response
16
+ * payload by wrapping `res.json` / `res.send`, then appends one entry to the
17
+ * shared PayPal request log. Redaction of secrets happens in the logger.
18
+ */
19
+ export function createInboundLogger() {
20
+ return function inboundLogger(
21
+ req: MedusaRequest,
22
+ res: MedusaResponse,
23
+ next: MedusaNextFunction
24
+ ) {
25
+ if (!isRequestLoggingEnabled()) {
26
+ return next()
27
+ }
28
+ // Several route entries can match one request (e.g. the webhook raw-body
29
+ // entry AND the /store/paypal catch-all). Guard so we log it only once.
30
+ const reqAny = req as any
31
+ if (reqAny.__paypalLogged) {
32
+ return next()
33
+ }
34
+ reqAny.__paypalLogged = true
35
+
36
+ const startedAt = Date.now()
37
+ let responseBody: unknown
38
+ let captured = false
39
+
40
+ const origJson = res.json.bind(res)
41
+ const origSend = res.send.bind(res)
42
+
43
+ res.json = ((body: unknown) => {
44
+ if (!captured) {
45
+ responseBody = body
46
+ captured = true
47
+ }
48
+ return origJson(body as any)
49
+ }) as typeof res.json
50
+
51
+ res.send = ((body: unknown) => {
52
+ if (!captured) {
53
+ responseBody = body
54
+ captured = true
55
+ }
56
+ return origSend(body as any)
57
+ }) as typeof res.send
58
+
59
+ const flush = () => {
60
+ try {
61
+ logInbound({
62
+ method: req.method,
63
+ path: (req as any).baseUrl
64
+ ? `${(req as any).baseUrl}${req.path || ""}`
65
+ : (req as any).originalUrl || req.path || req.url || "",
66
+ query: req.query,
67
+ requestHeaders: req.headers,
68
+ requestBody: (req as any).body,
69
+ status: res.statusCode,
70
+ responseBody,
71
+ durationMs: Date.now() - startedAt,
72
+ })
73
+ } catch {
74
+ // logging must never break the request
75
+ }
76
+ }
77
+
78
+ // `finish` fires once the response is fully flushed, for every response
79
+ // path (json, send, raw end, errors) — a single reliable hook.
80
+ res.once("finish", flush)
81
+
82
+ return next()
83
+ }
84
+ }
@@ -15,6 +15,7 @@ import {
15
15
  invalidateSettingsCache,
16
16
  setCachedSettings,
17
17
  } from "./utils/settings-cache"
18
+ import { setRequestLoggingEnabled } from "./utils/request-logger"
18
19
 
19
20
  type Environment = "sandbox" | "live"
20
21
 
@@ -107,7 +108,11 @@ class PayPalModuleService extends MedusaService({
107
108
  const apiDetails = { ...(data.api_details || {}) } as Record<string, any>
108
109
  let changed = false
109
110
 
110
- if (!onboarding.partner_service_url) {
111
+ // Overwrite, not just fill: the stored URL is what the onboarding link
112
+ // request is sent to, so a fill-only default left upgraded installs on the
113
+ // previous partner service and ignored a later PAYPAL_PARTNER_SERVICE_URL.
114
+ // Admins cannot edit onboarding_config, so config is the only source.
115
+ if (onboarding.partner_service_url !== this.cfg.partnerServiceUrl) {
111
116
  onboarding.partner_service_url = this.cfg.partnerServiceUrl
112
117
  changed = true
113
118
  }
@@ -125,8 +130,11 @@ class PayPalModuleService extends MedusaService({
125
130
  onboarding.seller_nonce = this.cfg.sellerNonce
126
131
  changed = true
127
132
  }
128
- if (!onboarding.bn_code && this.cfg.bnCode) {
129
- onboarding.bn_code = this.cfg.bnCode
133
+ // Overwrite, not just fill: installs that predate the switch to
134
+ // "MBJ_Medusa_SI" persisted the previous BN code, which then stayed in the
135
+ // stored settings (and the admin settings response) forever.
136
+ if (onboarding.bn_code !== this.bnCode) {
137
+ onboarding.bn_code = this.bnCode
130
138
  changed = true
131
139
  }
132
140
  if (!onboarding.partner_merchant_id_sandbox) {
@@ -1668,6 +1676,16 @@ class PayPalModuleService extends MedusaService({
1668
1676
  const row = rows?.[0]
1669
1677
  const result = { data: (row?.data || {}) as Record<string, any> }
1670
1678
  setCachedSettings("module-settings", result)
1679
+ // Keep the process-local request-logging flag in step with the admin toggle.
1680
+ try {
1681
+ const addl = (result.data?.additional_settings || {}) as Record<
1682
+ string,
1683
+ unknown
1684
+ >
1685
+ setRequestLoggingEnabled(!!(addl.debugLogging ?? addl.debug_logging))
1686
+ } catch {
1687
+ // never let a logging-flag sync break settings reads
1688
+ }
1671
1689
  return result
1672
1690
  }
1673
1691
 
@@ -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
+ }