-
Notifications
You must be signed in to change notification settings - Fork 396
poc: Create passing JS context for PSP #20740
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Matejk00
wants to merge
1
commit into
develop
Choose a base branch
from
feature/CXSPA-10980
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
212 changes: 212 additions & 0 deletions
212
integration-libs/opf/examples/context-injection-example.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,212 @@ | ||
# OPF Context Injection Implementation | ||
|
||
## Overview | ||
|
||
This implementation provides a **session-scoped context injection** solution that allows PSP scripts to access backend context data without modifications. PSP scripts can simply use `OpfContext.orderId`, `OpfContext.amount`, etc. | ||
|
||
|
||
## Implementation | ||
|
||
### 1. Spartacus Context Injection | ||
|
||
```typescript | ||
// OpfResourceLoaderService | ||
executeScriptFromHtml(html: string | undefined, dynamicContext?: string): void { | ||
if (!isPlatformServer(this.platformId) && html) { | ||
const element = new DOMParser().parseFromString(html, 'text/html'); | ||
const script = element.getElementsByTagName('script'); | ||
|
||
if (!script?.[0]?.innerText) { | ||
return; | ||
} | ||
|
||
const originalScript = script[0].innerText; | ||
const sessionId = this.generateSessionId(); | ||
|
||
let wrappedScript: string; | ||
|
||
if (dynamicContext) { | ||
try { | ||
const contextData = JSON.parse(dynamicContext); | ||
wrappedScript = this.createSessionScopedScript(originalScript, contextData, sessionId); | ||
} catch (error) { | ||
console.warn('Failed to parse dynamic context:', error); | ||
wrappedScript = this.createSecureScript(originalScript, sessionId); | ||
} | ||
} else { | ||
wrappedScript = this.createSecureScript(originalScript, sessionId); | ||
} | ||
|
||
this.executeScriptWithSession(wrappedScript, sessionId); | ||
} | ||
} | ||
``` | ||
|
||
### 2. Session-Scoped Script Creation | ||
|
||
```typescript | ||
private createSessionScopedScript(originalScript: string, contextData: any, sessionId: string): string { | ||
return ` | ||
(function() { | ||
'use strict'; | ||
|
||
// Session-isolated context (no global pollution) | ||
const OpfContext = ${JSON.stringify(contextData)}; | ||
const SessionId = '${sessionId}'; | ||
|
||
// Context is immediately available - no async waiting | ||
console.log('PSP: Session', SessionId, 'Context:', OpfContext); | ||
|
||
// Original PSP script runs with context available immediately | ||
${originalScript} | ||
|
||
})(); | ||
`; | ||
} | ||
``` | ||
|
||
### 3. PSP Script Usage | ||
|
||
```javascript | ||
// PSP Script - No modifications needed! | ||
(function() { | ||
'use strict'; | ||
|
||
// Context is immediately available | ||
console.log('PSP: Order ID:', OpfContext.orderId); | ||
console.log('PSP: Amount:', OpfContext.amount); | ||
console.log('PSP: Session:', SessionId); | ||
|
||
// Use context data for PSP operations | ||
const paymentData = { | ||
orderId: OpfContext.orderId, | ||
amount: OpfContext.amount || 0, | ||
currency: OpfContext.currency || 'USD', | ||
billingAddress: OpfContext.billingAddress | ||
}; | ||
|
||
// Initialize PSP with context data | ||
initializePaymentForm(paymentData); | ||
|
||
})(); | ||
``` | ||
|
||
## Complete Flow Example | ||
|
||
### 1. OPF Backend Response | ||
|
||
```json | ||
{ | ||
"dynamicScript": { | ||
"dynamicContext": "{\"orderId\":\"12345\",\"billingAddress\":{\"addressLine1\":\"test street\"},\"amount\":99.99,\"currency\":\"USD\"}", | ||
"html": "<script>/* PSP script content */</script>" | ||
} | ||
} | ||
``` | ||
|
||
### 2. Spartacus Processing | ||
|
||
```typescript | ||
// 1. Parse context | ||
const contextData = JSON.parse(dynamicContext); | ||
// contextData = { orderId: "12345", billingAddress: {...}, amount: 99.99, currency: "USD" } | ||
|
||
// 2. Generate session ID | ||
const sessionId = "opf-session-1703123456789-abc123"; | ||
|
||
// 3. Wrap PSP script with context | ||
const wrappedScript = ` | ||
(function() { | ||
'use strict'; | ||
|
||
const OpfContext = ${JSON.stringify(contextData)}; | ||
const SessionId = '${sessionId}'; | ||
|
||
// Original PSP script content | ||
// ... PSP script code ... | ||
|
||
})(); | ||
`; | ||
|
||
// 4. Execute wrapped script | ||
executeScriptWithSession(wrappedScript, sessionId); | ||
``` | ||
|
||
### 3. PSP Script Execution | ||
|
||
```javascript | ||
// PSP script runs with context immediately available | ||
console.log('PSP: Session', SessionId); // "opf-session-1703123456789-abc123" | ||
console.log('PSP: Order ID:', OpfContext.orderId); // "12345" | ||
console.log('PSP: Amount:', OpfContext.amount); // 99.99 | ||
|
||
// No async waiting, no event listeners needed | ||
initializePaymentForm(); | ||
``` | ||
|
||
## CSP Compliance | ||
|
||
### With Nonce Support | ||
|
||
```typescript | ||
// CSP-compliant version with nonce | ||
private createNonceSecuredScript(originalScript: string, contextData: any, nonce: string, sessionId: string): string { | ||
return ` | ||
(function() { | ||
'use strict'; | ||
|
||
// Validate nonce for security | ||
if (!'${nonce}' || '${nonce}'.length < 16) { | ||
throw new Error('Invalid nonce provided'); | ||
} | ||
|
||
// Session-isolated context | ||
const OpfContext = ${JSON.stringify(contextData)}; | ||
const SessionId = '${sessionId}'; | ||
const Nonce = '${nonce}'; | ||
|
||
// Original PSP script runs with context available immediately | ||
${originalScript} | ||
|
||
})(); | ||
`; | ||
} | ||
``` | ||
|
||
### CSP Headers | ||
|
||
```http | ||
Content-Security-Policy: | ||
script-src 'self' 'nonce-{random-nonce}' https://trusted-psp.com; | ||
object-src 'none'; | ||
base-uri 'self'; | ||
default-src 'self'; | ||
``` | ||
|
||
## Usage | ||
|
||
PSP scripts can now simply use: | ||
|
||
```javascript | ||
// Access order information | ||
const orderId = OpfContext.orderId; | ||
const amount = OpfContext.amount; | ||
const currency = OpfContext.currency; | ||
|
||
// Access billing information | ||
const billingAddress = OpfContext.billingAddress; | ||
const customerEmail = OpfContext.customerEmail; | ||
|
||
// Access session information | ||
const sessionId = SessionId; | ||
|
||
// Use in PSP operations | ||
const paymentData = { | ||
orderId: OpfContext.orderId, | ||
amount: OpfContext.amount, | ||
currency: OpfContext.currency, | ||
billingAddress: OpfContext.billingAddress | ||
}; | ||
``` | ||
|
||
This approach provides the **easiest integration** for PSP customers while maintaining **maximum security** and **CSP compliance**. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / CodeQL
Insecure randomness High
Copilot Autofix
AI 21 days ago
To fix the problem, we should replace the usage of
Math.random()
ingenerateSessionId()
with a call to a cryptographically secure random number generator. In Node.js and modern browsers, thecrypto
module provides such functionality. To maintain compatibility with the rest of the code and stay within the shown region, we should import Node's built-incrypto
module and usecrypto.randomBytes()
to generate a random string value for the session ID. The rest of the function can remain unchanged.In file
integration-libs/opf/base/root/services/opf-resource-loader.service.ts
, we need to:crypto
module.Math.random().toString(36).substring(2)
, we use a securely generated random string, e.g., fromcrypto.randomBytes(16).toString('hex')
.