-
Notifications
You must be signed in to change notification settings - Fork 307
PoC HWB #2298
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
base: canary
Are you sure you want to change the base?
PoC HWB #2298
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,282 @@ | ||
import { print } from 'graphql'; | ||
import { graphql as gql, HttpResponse } from 'msw'; | ||
import { NextRequest } from 'next/server'; | ||
import { beforeEach, describe, expect, test } from 'vitest'; | ||
|
||
import { graphql } from '~/client/graphql'; | ||
import { server } from '~/msw.server'; | ||
|
||
import { POST } from './route'; | ||
|
||
// Mock the API requests | ||
beforeEach(() => { | ||
server.use( | ||
gql.query('PaymentWalletWithInitializationDataQuery', () => { | ||
return HttpResponse.json({ data: { site: { paymentWalletWithInitializationData: null } } }); | ||
}), | ||
gql.mutation('CreatePaymentWalletIntentMutation', () => { | ||
return HttpResponse.json({ | ||
data: { | ||
payment: { | ||
paymentWallet: { | ||
createPaymentWalletIntent: { | ||
paymentWalletIntentData: { | ||
__typename: 'PayPalCommercePaymentWalletIntentData', | ||
orderId: '123', | ||
approvalUrl: 'https://example.com/approval', | ||
initializationEntityId: '456', | ||
}, | ||
errors: [], | ||
}, | ||
}, | ||
}, | ||
}, | ||
}); | ||
}), | ||
); | ||
}); | ||
|
||
describe('query validation', () => { | ||
test('route handler with valid query', async () => { | ||
const query = graphql(` | ||
query PaymentWalletWithInitializationDataQuery( | ||
$paymentWalletEntityId: String! | ||
$cartEntityId: String | ||
) { | ||
site { | ||
paymentWalletWithInitializationData( | ||
filter: { paymentWalletEntityId: $paymentWalletEntityId, cartEntityId: $cartEntityId } | ||
) { | ||
initializationData | ||
} | ||
} | ||
} | ||
`); | ||
|
||
const request = new NextRequest('http://localhost:3000/api/wallets/graphql', { | ||
method: 'POST', | ||
body: JSON.stringify({ | ||
query: print(query), | ||
variables: JSON.stringify({ | ||
paymentWalletEntityId: '123', | ||
cartEntityId: '456', | ||
}), | ||
}), | ||
}); | ||
|
||
const response = await POST(request); | ||
const data: unknown = await response.json(); | ||
|
||
expect(data).toMatchObject({ site: { paymentWalletWithInitializationData: null } }); | ||
}); | ||
|
||
test('route handler with invalid query name', async () => { | ||
const query = graphql(` | ||
query FooBar($paymentWalletEntityId: String!, $cartEntityId: String) { | ||
site { | ||
paymentWalletWithInitializationData( | ||
filter: { paymentWalletEntityId: $paymentWalletEntityId, cartEntityId: $cartEntityId } | ||
) { | ||
initializationData | ||
} | ||
} | ||
} | ||
`); | ||
|
||
const request = new NextRequest('http://localhost:3000/api/wallets/graphql', { | ||
method: 'POST', | ||
body: JSON.stringify({ | ||
query: print(query), | ||
variables: JSON.stringify({ | ||
paymentWalletEntityId: '123', | ||
cartEntityId: '456', | ||
}), | ||
}), | ||
}); | ||
|
||
const response = await POST(request); | ||
const text = await response.text(); | ||
|
||
expect(response.status).toBe(403); | ||
expect(text).toBe('Operation not allowed'); | ||
}); | ||
|
||
test('route handler with invalid query data', async () => { | ||
const query = graphql(` | ||
query PaymentWalletWithInitializationDataQuery { | ||
site { | ||
settings { | ||
storeName | ||
} | ||
} | ||
} | ||
`); | ||
|
||
const request = new NextRequest('http://localhost:3000/api/wallets/graphql', { | ||
method: 'POST', | ||
body: JSON.stringify({ | ||
query: print(query), | ||
}), | ||
}); | ||
|
||
const response = await POST(request); | ||
const text = await response.text(); | ||
|
||
expect(response.status).toBe(400); | ||
expect(text).toBe('Query is invalid'); | ||
}); | ||
}); | ||
|
||
describe('mutation validation', () => { | ||
test('route handler with valid mutation', async () => { | ||
const mutation = graphql(` | ||
mutation CreatePaymentWalletIntentMutation( | ||
$paymentWalletEntityId: String! | ||
$cartEntityId: String! | ||
) { | ||
payment { | ||
paymentWallet { | ||
createPaymentWalletIntent( | ||
input: { paymentWalletEntityId: $paymentWalletEntityId, cartEntityId: $cartEntityId } | ||
) { | ||
paymentWalletIntentData { | ||
__typename | ||
... on PayPalCommercePaymentWalletIntentData { | ||
orderId | ||
approvalUrl | ||
initializationEntityId | ||
} | ||
} | ||
errors { | ||
__typename | ||
... on CreatePaymentWalletIntentGenericError { | ||
message | ||
} | ||
... on Error { | ||
message | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
`); | ||
|
||
const request = new NextRequest('http://localhost:3000/api/wallets/graphql', { | ||
method: 'POST', | ||
body: JSON.stringify({ | ||
query: print(mutation), | ||
variables: JSON.stringify({ | ||
paymentWalletEntityId: '123', | ||
cartEntityId: '456', | ||
}), | ||
}), | ||
}); | ||
|
||
const response = await POST(request); | ||
const data: unknown = await response.json(); | ||
|
||
expect(data).toMatchObject({ | ||
payment: { | ||
paymentWallet: { | ||
createPaymentWalletIntent: { | ||
errors: [], | ||
paymentWalletIntentData: { | ||
__typename: 'PayPalCommercePaymentWalletIntentData', | ||
approvalUrl: 'https://example.com/approval', | ||
initializationEntityId: '456', | ||
orderId: '123', | ||
}, | ||
}, | ||
}, | ||
}, | ||
}); | ||
}); | ||
|
||
test('route handler with invalid mutation name', async () => { | ||
const mutation = graphql(` | ||
mutation FooBar($paymentWalletEntityId: String!, $cartEntityId: String!) { | ||
payment { | ||
paymentWallet { | ||
createPaymentWalletIntent( | ||
input: { paymentWalletEntityId: $paymentWalletEntityId, cartEntityId: $cartEntityId } | ||
) { | ||
paymentWalletIntentData { | ||
__typename | ||
... on PayPalCommercePaymentWalletIntentData { | ||
orderId | ||
approvalUrl | ||
initializationEntityId | ||
} | ||
} | ||
errors { | ||
__typename | ||
... on CreatePaymentWalletIntentGenericError { | ||
message | ||
} | ||
... on Error { | ||
message | ||
} | ||
} | ||
} | ||
} | ||
} | ||
} | ||
`); | ||
|
||
const request = new NextRequest('http://localhost:3000/api/wallets/graphql', { | ||
method: 'POST', | ||
body: JSON.stringify({ | ||
query: print(mutation), | ||
variables: JSON.stringify({ | ||
paymentWalletEntityId: '123', | ||
cartEntityId: '456', | ||
}), | ||
}), | ||
}); | ||
|
||
const response = await POST(request); | ||
const text = await response.text(); | ||
|
||
expect(response.status).toBe(403); | ||
expect(text).toBe('Operation not allowed'); | ||
}); | ||
|
||
test('route handler with invalid mutation data', async () => { | ||
const query = graphql(` | ||
mutation CreatePaymentWalletIntentMutation { | ||
logout { | ||
result | ||
} | ||
} | ||
`); | ||
|
||
const request = new NextRequest('http://localhost:3000/api/wallets/graphql', { | ||
method: 'POST', | ||
body: JSON.stringify({ | ||
query: print(query), | ||
}), | ||
}); | ||
|
||
const response = await POST(request); | ||
const text = await response.text(); | ||
|
||
expect(response.status).toBe(400); | ||
expect(text).toBe('Query is invalid'); | ||
}); | ||
}); | ||
|
||
test('route handler with invalid operation', async () => { | ||
const request = new NextRequest('http://localhost:3000/api/wallets/graphql', { | ||
method: 'POST', | ||
body: JSON.stringify({ | ||
query: 'fragment Foo on Bar { baz }', | ||
}), | ||
}); | ||
|
||
const response = await POST(request); | ||
const text = await response.text(); | ||
|
||
expect(response.status).toBe(400); | ||
expect(text).toBe('No operation found'); | ||
}); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,143 @@ | ||
import { OperationDefinitionNode, parse, SelectionNode } from 'graphql'; | ||
import { NextRequest } from 'next/server'; | ||
import { z } from 'zod'; | ||
|
||
import { client } from '~/client'; | ||
import { graphql } from '~/client/graphql'; | ||
|
||
const ENABLE_LIST = [ | ||
{ | ||
name: 'PaymentWalletWithInitializationDataQuery', | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As mentioned earlier (#2298 (comment)), I think we should not enforce specific operation names. Otherwise, the exact operation names become a part of the API contract and we're not free to change in the future. Also, ideally I want to move the filtering logic out of Catalyst to the API layer so the clients won't be coupled to a specific version of Catalyst. |
||
type: 'query', | ||
allowedFields: { | ||
site: { | ||
paymentWalletWithInitializationData: true, // allow any subfields of paymentWallets | ||
}, | ||
}, | ||
}, | ||
{ | ||
name: 'CreatePaymentWalletIntentMutation', | ||
type: 'mutation', | ||
allowedFields: { | ||
payment: { | ||
paymentWallet: { | ||
createPaymentWalletIntent: { | ||
paymentWalletIntentData: true, | ||
errors: true, | ||
}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
{ | ||
name: 'CheckoutRedirectMutation', | ||
type: 'mutation', | ||
allowedFields: { | ||
cart: { | ||
createCartRedirectUrls: true, | ||
}, | ||
}, | ||
}, | ||
{ | ||
name: 'AddCheckoutBillingAddressMutation', | ||
type: 'mutation', | ||
allowedFields: { | ||
checkout: { | ||
billingAddress: true, | ||
}, | ||
}, | ||
}, | ||
{ | ||
name: 'UpdateCheckoutBillingAddressMutation', | ||
type: 'mutation', | ||
allowedFields: { | ||
checkout: { | ||
billingAddress: true, | ||
}, | ||
}, | ||
}, | ||
]; | ||
|
||
export const POST = async (request: NextRequest) => { | ||
const body: unknown = await request.json(); | ||
const { document, variables } = z | ||
.object({ document: z.string(), variables: z.string().optional() }) | ||
.parse(body); | ||
|
||
const ast = parse(document, { noLocation: true }); | ||
|
||
// Validate operation structure | ||
const operation = ast.definitions.find( | ||
(definition): definition is OperationDefinitionNode => | ||
definition.kind === 'OperationDefinition', | ||
); | ||
|
||
if (!operation) return new Response('No operation found', { status: 400 }); | ||
|
||
const config = ENABLE_LIST.find( | ||
(entry) => entry.name === operation.name?.value && entry.type === operation.operation, | ||
); | ||
|
||
if (!config) return new Response('Operation not allowed', { status: 403 }); | ||
|
||
try { | ||
assertFieldsAllowed(operation.selectionSet.selections, config.allowedFields); | ||
} catch { | ||
return new Response('Query is invalid', { status: 400 }); | ||
} | ||
|
||
const response = await client.fetch({ | ||
document: graphql(document), | ||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment | ||
variables: variables ? JSON.parse(variables) : undefined, | ||
errorPolicy: 'ignore', | ||
}); | ||
|
||
return new Response(JSON.stringify(response), { | ||
status: 200, | ||
headers: { 'Content-Type': 'application/json' }, | ||
}); | ||
}; | ||
|
||
interface Allowed { | ||
[key: string]: Allowed | boolean | null | undefined; | ||
} | ||
|
||
function assertFieldsAllowed( | ||
selections: readonly SelectionNode[], | ||
allowed: Allowed, | ||
path: string[] = ['site'], | ||
): asserts selections is readonly SelectionNode[] { | ||
selections.forEach((selection) => { | ||
if (selection.kind !== 'Field') return; | ||
|
||
const fieldName = selection.name.value; | ||
const currentPath = [...path, fieldName]; | ||
|
||
if (!(fieldName in allowed)) { | ||
throw new Error(`Disallowed field: ${currentPath.join('.')}`); | ||
} | ||
|
||
const allowedValue = allowed[fieldName]; | ||
|
||
if (allowedValue === true) { | ||
// All descendants allowed | ||
return; | ||
} | ||
|
||
if (typeof allowedValue === 'object' && allowedValue !== null) { | ||
if (!selection.selectionSet) { | ||
throw new Error(`Expected subfields for: ${currentPath.join('.')}`); | ||
} | ||
|
||
assertFieldsAllowed(selection.selectionSet.selections, allowedValue, currentPath); | ||
|
||
return; | ||
} | ||
|
||
if (typeof allowedValue !== 'object' && selection.selectionSet) { | ||
throw new Error(`Field ${currentPath.join('.')} does not allow subfields`); | ||
} | ||
// If allowedValue is falsy and no selectionSet, it's fine (already checked above) | ||
}); | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
'use client'; | ||
|
||
import { useEffect, useRef } from 'react'; | ||
|
||
import { Stream, Streamable, useStreamable } from '@/vibes/soul/lib/streamable'; | ||
import { WalletButtonsInitializer } from '~/lib/wallet-buttons'; | ||
import { InitializeButtonProps } from '~/lib/wallet-buttons/types'; | ||
|
||
export const ClientWalletButtons = ({ | ||
walletButtonsInitOptions, | ||
cartId, | ||
}: { | ||
walletButtonsInitOptions: Streamable<InitializeButtonProps[]>; | ||
cartId: string; | ||
}) => { | ||
const isMountedRef = useRef(false); | ||
const initButtonProps = useStreamable(walletButtonsInitOptions); | ||
|
||
useEffect(() => { | ||
if (!isMountedRef.current && initButtonProps.length) { | ||
isMountedRef.current = true; | ||
|
||
const initWalletButtons = async () => { | ||
await new WalletButtonsInitializer().initialize(initButtonProps); | ||
}; | ||
|
||
void initWalletButtons(); | ||
} | ||
}, [cartId, initButtonProps]); | ||
|
||
return ( | ||
<Stream fallback={null} value={walletButtonsInitOptions}> | ||
{(buttonOptions) => ( | ||
<div style={{ display: 'flex', alignItems: 'end', flexDirection: 'column' }}> | ||
{buttonOptions.map((button) => | ||
button.containerId ? <div id={button.containerId} key={button.containerId} /> : null, | ||
)} | ||
</div> | ||
)} | ||
</Stream> | ||
); | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
export class InitializationError extends Error { | ||
constructor() { | ||
super( | ||
'Unable to initialize the checkout button because the required script has not been loaded yet.', | ||
); | ||
|
||
this.name = 'InitializationError'; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
import { InitializationError } from './error'; | ||
import { InitializeButtonProps } from './types'; | ||
|
||
export class WalletButtonsInitializer { | ||
private origin = window.location.origin; | ||
private checkoutSdkUrl = `${this.origin}/v1/loader.js`; | ||
|
||
async initialize( | ||
walletButtonsInitOptions: InitializeButtonProps[], | ||
): Promise<InitializeButtonProps[]> { | ||
await this.initializeCheckoutKitLoader(); | ||
|
||
const checkoutButtonInitializer = await this.initCheckoutButtonInitializer(); | ||
|
||
return walletButtonsInitOptions.map((buttonOption) => { | ||
checkoutButtonInitializer.initializeWalletButton(buttonOption); | ||
|
||
return buttonOption; | ||
}); | ||
} | ||
|
||
private async initializeCheckoutKitLoader(): Promise<void> { | ||
if (window.checkoutKitLoader) { | ||
return; | ||
} | ||
|
||
await new Promise((resolve, reject) => { | ||
const script = document.createElement('script'); | ||
|
||
script.type = 'text/javascript'; | ||
script.defer = true; | ||
script.src = this.checkoutSdkUrl; | ||
|
||
script.onload = resolve; | ||
script.onerror = reject; | ||
script.onabort = reject; | ||
|
||
document.body.append(script); | ||
}); | ||
} | ||
|
||
private async initCheckoutButtonInitializer() { | ||
if (!window.checkoutKitLoader) { | ||
throw new InitializationError(); | ||
} | ||
|
||
const checkoutButtonModule = await window.checkoutKitLoader.load('wallet-button'); | ||
|
||
return checkoutButtonModule.createWalletButtonInitializer({ | ||
graphQLEndpoint: 'api/wallets/graphql', | ||
}); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
declare global { | ||
interface Window { | ||
checkoutKitLoader?: CheckoutKitLoader; | ||
} | ||
} | ||
|
||
interface CheckoutKitLoader { | ||
load(moduleName: string): Promise<CheckoutKitModule>; | ||
} | ||
|
||
interface CheckoutKitModule { | ||
createWalletButtonInitializer(options: { | ||
graphQLEndpoint: string; | ||
}): CheckoutHeadlessButtonInitializer; | ||
} | ||
|
||
interface CheckoutHeadlessButtonInitializer { | ||
initializeWalletButton(option: InitializeButtonProps): void; | ||
} | ||
|
||
export interface InitializeButtonProps { | ||
[key: string]: unknown; | ||
containerId: string; | ||
methodId: string; | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
import { setupServer } from 'msw/node'; | ||
|
||
export const server = setupServer(); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
import { loadEnv } from 'vite'; | ||
import tsconfigPaths from 'vite-tsconfig-paths'; | ||
import { defineConfig } from 'vitest/config'; | ||
|
||
export default defineConfig(({ mode }) => ({ | ||
plugins: [tsconfigPaths()], | ||
test: { | ||
environment: 'node', | ||
env: loadEnv(mode, process.cwd(), ''), | ||
exclude: ['**/node_modules/**', '**/dist/**', '**/tests/**'], | ||
setupFiles: ['./vitest.setup.ts'], | ||
}, | ||
})); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
import { afterAll, afterEach, beforeAll } from 'vitest'; | ||
|
||
import { server } from './msw.server'; | ||
|
||
beforeAll(() => server.listen()); | ||
afterEach(() => server.resetHandlers()); | ||
afterAll(() => server.close()); |
Large diffs are not rendered by default.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems this request can be made concurrently, as the requests below don't depend on the result of this request.