@easypayment/medusa-payment-paypal 1.3.2 → 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.
- package/.medusa/server/src/admin/index.js +99 -15
- package/.medusa/server/src/admin/index.mjs +99 -15
- package/.medusa/server/src/api/admin/paypal/logs/route.d.ts +10 -0
- package/.medusa/server/src/api/admin/paypal/logs/route.d.ts.map +1 -0
- package/.medusa/server/src/api/admin/paypal/logs/route.js +43 -0
- package/.medusa/server/src/api/admin/paypal/logs/route.js.map +1 -0
- package/.medusa/server/src/api/middlewares.d.ts.map +1 -1
- package/.medusa/server/src/api/middlewares.js +22 -4
- package/.medusa/server/src/api/middlewares.js.map +1 -1
- package/.medusa/server/src/api/store/paypal/create-order/route.d.ts.map +1 -1
- package/.medusa/server/src/api/store/paypal/create-order/route.js +10 -24
- package/.medusa/server/src/api/store/paypal/create-order/route.js.map +1 -1
- package/.medusa/server/src/api/utils/request-logger.d.ts +11 -0
- package/.medusa/server/src/api/utils/request-logger.d.ts.map +1 -0
- package/.medusa/server/src/api/utils/request-logger.js +69 -0
- package/.medusa/server/src/api/utils/request-logger.js.map +1 -0
- package/.medusa/server/src/modules/paypal/payment-provider/base-provider.d.ts +3 -3
- package/.medusa/server/src/modules/paypal/service.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/service.js +12 -1
- package/.medusa/server/src/modules/paypal/service.js.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.d.ts +10 -0
- package/.medusa/server/src/modules/paypal/types/config.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/types/config.js +14 -20
- package/.medusa/server/src/modules/paypal/types/config.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js +10 -0
- package/.medusa/server/src/modules/paypal/utils/credential-resolver.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/paypal-fetch.d.ts.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js +39 -0
- package/.medusa/server/src/modules/paypal/utils/paypal-fetch.js.map +1 -1
- package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts +62 -0
- package/.medusa/server/src/modules/paypal/utils/request-logger.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/request-logger.js +297 -0
- package/.medusa/server/src/modules/paypal/utils/request-logger.js.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/storefront-url.d.ts +21 -0
- package/.medusa/server/src/modules/paypal/utils/storefront-url.d.ts.map +1 -0
- package/.medusa/server/src/modules/paypal/utils/storefront-url.js +25 -0
- package/.medusa/server/src/modules/paypal/utils/storefront-url.js.map +1 -0
- package/CHANGELOG.md +27 -0
- package/README.md +194 -190
- package/package.json +1 -1
- package/src/admin/routes/settings/paypal/additional-settings/page.tsx +87 -0
- package/src/api/admin/paypal/logs/route.ts +50 -0
- package/src/api/middlewares.ts +22 -4
- package/src/api/store/paypal/create-order/route.ts +10 -28
- package/src/api/utils/request-logger.ts +84 -0
- package/src/modules/paypal/service.ts +14 -1
- package/src/modules/paypal/types/config.ts +15 -24
- package/src/modules/paypal/utils/credential-resolver.ts +9 -0
- package/src/modules/paypal/utils/paypal-fetch.ts +42 -0
- package/src/modules/paypal/utils/request-logger.ts +358 -0
- package/src/modules/paypal/utils/storefront-url.ts +41 -0
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
getStoredPayPalOrderId,
|
|
17
17
|
updatePayPalSessionData,
|
|
18
18
|
} from "../../../../modules/paypal/utils/payment-session"
|
|
19
|
+
import { resolveStorefrontUrl } from "../../../../modules/paypal/utils/storefront-url"
|
|
19
20
|
|
|
20
21
|
type Body = {
|
|
21
22
|
cart_id: string
|
|
@@ -74,24 +75,6 @@ async function getExistingPayPalOrderId(req: MedusaRequest, cartId: string) {
|
|
|
74
75
|
return getStoredPayPalOrderId(session?.session_data)
|
|
75
76
|
}
|
|
76
77
|
|
|
77
|
-
/** Storefront return URL from env (`STOREFRONT_URL` / `STORE_URL`), if set. */
|
|
78
|
-
function resolveReturnUrl() {
|
|
79
|
-
const configured = process.env.STOREFRONT_URL || process.env.STORE_URL
|
|
80
|
-
if (!configured) {
|
|
81
|
-
return undefined
|
|
82
|
-
}
|
|
83
|
-
return `${configured.replace(/\/$/, "")}/checkout`
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
/** Storefront cancel URL from env (`STOREFRONT_URL` / `STORE_URL`), if set. */
|
|
87
|
-
function resolveCancelUrl() {
|
|
88
|
-
const configured = process.env.STOREFRONT_URL || process.env.STORE_URL
|
|
89
|
-
if (!configured) {
|
|
90
|
-
return undefined
|
|
91
|
-
}
|
|
92
|
-
return `${configured.replace(/\/$/, "")}/cart`
|
|
93
|
-
}
|
|
94
|
-
|
|
95
78
|
/**
|
|
96
79
|
* POST /store/paypal/create-order — create (or reuse) the PayPal order for a
|
|
97
80
|
* cart and store its id on the cart's PayPal payment session.
|
|
@@ -301,16 +284,15 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|
|
301
284
|
: ""
|
|
302
285
|
const cartIdSuffix = cart.id.slice(-12).toUpperCase()
|
|
303
286
|
const invoiceId = `${invoicePrefix}${cartIdSuffix}`.trim() || cart.id
|
|
304
|
-
const
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
: resolveCancelUrl()
|
|
287
|
+
const storefrontUrl = resolveStorefrontUrl({
|
|
288
|
+
configured: apiDetails.storefront_url,
|
|
289
|
+
envUrl: process.env.STOREFRONT_URL || process.env.STORE_URL,
|
|
290
|
+
origin: req.headers.origin,
|
|
291
|
+
storeCors: req.scope.resolve(ContainerRegistrationKeys.CONFIG_MODULE)
|
|
292
|
+
.projectConfig.http.storeCors,
|
|
293
|
+
})
|
|
294
|
+
const returnUrl = storefrontUrl ? `${storefrontUrl}/checkout` : undefined
|
|
295
|
+
const cancelUrl = storefrontUrl ? `${storefrontUrl}/cart` : undefined
|
|
314
296
|
|
|
315
297
|
// brand_name should show the MERCHANT, not "PayPal": use the admin-set
|
|
316
298
|
// brand name, falling back to the store's own name (PayPal partner review,
|
|
@@ -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
|
|
|
@@ -119,7 +120,9 @@ class PayPalModuleService extends MedusaService({
|
|
|
119
120
|
onboarding.backend_url = this.cfg.backendUrl
|
|
120
121
|
changed = true
|
|
121
122
|
}
|
|
122
|
-
|
|
123
|
+
// Overwrite, not just fill: installs on 1.1.0–1.3.2 persisted a random
|
|
124
|
+
// nonce the partner service never saw, which breaks the token exchange.
|
|
125
|
+
if (onboarding.seller_nonce !== this.cfg.sellerNonce) {
|
|
123
126
|
onboarding.seller_nonce = this.cfg.sellerNonce
|
|
124
127
|
changed = true
|
|
125
128
|
}
|
|
@@ -1666,6 +1669,16 @@ class PayPalModuleService extends MedusaService({
|
|
|
1666
1669
|
const row = rows?.[0]
|
|
1667
1670
|
const result = { data: (row?.data || {}) as Record<string, any> }
|
|
1668
1671
|
setCachedSettings("module-settings", result)
|
|
1672
|
+
// Keep the process-local request-logging flag in step with the admin toggle.
|
|
1673
|
+
try {
|
|
1674
|
+
const addl = (result.data?.additional_settings || {}) as Record<
|
|
1675
|
+
string,
|
|
1676
|
+
unknown
|
|
1677
|
+
>
|
|
1678
|
+
setRequestLoggingEnabled(!!(addl.debugLogging ?? addl.debug_logging))
|
|
1679
|
+
} catch {
|
|
1680
|
+
// never let a logging-flag sync break settings reads
|
|
1681
|
+
}
|
|
1669
1682
|
return result
|
|
1670
1683
|
}
|
|
1671
1684
|
|
|
@@ -1,6 +1,17 @@
|
|
|
1
|
-
import { randomBytes } from "crypto"
|
|
2
1
|
import { PAYPAL_PARTNER_ATTRIBUTION_ID } from "../utils/partner"
|
|
3
2
|
|
|
3
|
+
/**
|
|
4
|
+
* The seller nonce the hosted partner service (`partnerServiceUrl`) embeds in
|
|
5
|
+
* every partner-referral it creates. The onboarding token exchange sends it as
|
|
6
|
+
* the PKCE `code_verifier`, so it MUST equal the value the referral was minted
|
|
7
|
+
* with — the link request does not send a nonce, so a locally generated one
|
|
8
|
+
* makes every exchange fail with invalid_grant. It is not a secret: the
|
|
9
|
+
* single-use authCode and sharedId are what protect the exchange.
|
|
10
|
+
* Only override PAYPAL_SELLER_NONCE together with your own partner service.
|
|
11
|
+
*/
|
|
12
|
+
export const PARTNER_SELLER_NONCE =
|
|
13
|
+
"a1233wtergfsdt4365tzrshgfbaewa36AGa1233wtergfsdt4365tzrshgfbaewa36AG"
|
|
14
|
+
|
|
4
15
|
/** Partner-level configuration, resolved from env vars with built-in defaults. */
|
|
5
16
|
export type PayPalModuleConfig = {
|
|
6
17
|
partnerServiceUrl: string
|
|
@@ -15,37 +26,17 @@ export type PayPalModuleConfig = {
|
|
|
15
26
|
|
|
16
27
|
const STATIC_CFG: PayPalModuleConfig = {
|
|
17
28
|
partnerServiceUrl:
|
|
18
|
-
"https://mbjtechnolabs.com/
|
|
29
|
+
"https://mbjtechnolabs.com/medusa-seller-onboarding/seller-onboarding.php?from=medusa",
|
|
19
30
|
partnerJsUrl:
|
|
20
31
|
"https://www.paypal.com/webapps/merchantboarding/js/lib/lightbox/partner.js",
|
|
21
32
|
backendUrl: "http://localhost:9000",
|
|
22
|
-
sellerNonce:
|
|
33
|
+
sellerNonce: PARTNER_SELLER_NONCE,
|
|
23
34
|
bnCode: PAYPAL_PARTNER_ATTRIBUTION_ID,
|
|
24
35
|
partnerMerchantIdSandbox: "K6QLN2LPGQRHL",
|
|
25
36
|
partnerMerchantIdLive: "GT5R877JNBPLL",
|
|
26
37
|
alertWebhookUrls: [],
|
|
27
38
|
}
|
|
28
39
|
|
|
29
|
-
let warnedGeneratedNonce = false
|
|
30
|
-
|
|
31
|
-
function generateSellerNonce(): string {
|
|
32
|
-
// The nonce doubles as the OAuth code_verifier for the onboarding exchange,
|
|
33
|
-
// so every instance must agree on it. It is persisted into settings on first
|
|
34
|
-
// boot, but two instances booting simultaneously can race to persist
|
|
35
|
-
// different generated values — an onboarding link minted against the losing
|
|
36
|
-
// nonce then fails its token exchange with an opaque invalid_grant. Pinning
|
|
37
|
-
// PAYPAL_SELLER_NONCE removes the race entirely.
|
|
38
|
-
if (!warnedGeneratedNonce) {
|
|
39
|
-
warnedGeneratedNonce = true
|
|
40
|
-
console.warn(
|
|
41
|
-
"[PayPal] PAYPAL_SELLER_NONCE is not set — generating a random seller nonce. " +
|
|
42
|
-
"For multi-instance deployments, set PAYPAL_SELLER_NONCE to a fixed random string " +
|
|
43
|
-
"so all instances share the same onboarding code_verifier."
|
|
44
|
-
)
|
|
45
|
-
}
|
|
46
|
-
return randomBytes(32).toString("hex")
|
|
47
|
-
}
|
|
48
|
-
|
|
49
40
|
/** Resolve the module configuration from the environment. */
|
|
50
41
|
export function getPayPalConfig(): PayPalModuleConfig {
|
|
51
42
|
const backendUrl = process.env.MEDUSA_BACKEND_URL || STATIC_CFG.backendUrl
|
|
@@ -55,7 +46,7 @@ export function getPayPalConfig(): PayPalModuleConfig {
|
|
|
55
46
|
partnerServiceUrl:
|
|
56
47
|
process.env.PAYPAL_PARTNER_SERVICE_URL || STATIC_CFG.partnerServiceUrl,
|
|
57
48
|
backendUrl,
|
|
58
|
-
sellerNonce: process.env.PAYPAL_SELLER_NONCE ||
|
|
49
|
+
sellerNonce: process.env.PAYPAL_SELLER_NONCE || STATIC_CFG.sellerNonce,
|
|
59
50
|
partnerMerchantIdSandbox:
|
|
60
51
|
process.env.PAYPAL_PARTNER_MERCHANT_ID_SANDBOX ||
|
|
61
52
|
STATIC_CFG.partnerMerchantIdSandbox,
|
|
@@ -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
|
+
}
|