Skip to content

Commit

Permalink
update docs
Browse files Browse the repository at this point in the history
  • Loading branch information
paul-phan committed Jun 7, 2024
1 parent 801de73 commit 444a83c
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 86 deletions.
101 changes: 62 additions & 39 deletions docs/guides/csp.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,46 +2,65 @@
title: Content Security Policy
description: Content Security Policy in Weaverse, how it is automatically configured, and the ability to customize policies for your unique needs
publishedAt: November 20, 2023
updatedAt: April 16, 2024
order: 9
updatedAt: Jun 7, 2024
order: 10
published: true
---


### Content Security Policy (CSP) Overview

**Content Security Policy (CSP)** is a security measure used by web browsers to help safeguard your websites by specifying which external resources are allowed to load. Essentially, CSP serves as a safeguard, letting you define approved sources for scripts, stylesheets, and other content.
**Content Security Policy (CSP)** is a security measure used by web browsers to protect your website by specifying which external resources are allowed to load. CSP serves as a safeguard, letting you define approved sources for scripts, stylesheets, and other content.

### Automatic CSP Configuration in Weaverse

Weaverse automatically sets up CSP for your projects using the `createContentSecurityPolicy` utility from the `@shopify/hydrogen` package. This is integrated within your project's [`entry.server.jsx`](https://github.com/Weaverse/pilot/blob/main/app/entry.server.tsx) file. Here's how it's typically implemented:
Weaverse automatically configures CSP for your projects using the `createContentSecurityPolicy` utility from the `@shopify/hydrogen` package. This is integrated within your project's [`entry.server.jsx`](https://github.com/Weaverse/pilot/blob/main/app/entry.server.tsx) file. Here's a typical implementation:

```tsx
import { RemixServer } from '@remix-run/react';
import { createContentSecurityPolicy } from '@shopify/hydrogen';
import type { EntryContext } from '@shopify/remix-oxygen';
import { getWeaverseCsp } from '~/weaverse/create-weaverse.server';
import { renderToReadableStream } from 'react-dom/server';
import { RemixServer } from '@remix-run/react'
import { createContentSecurityPolicy } from '@shopify/hydrogen'
import type { AppLoadContext, EntryContext } from '@shopify/remix-oxygen'
import { getWeaverseCsp } from '~/weaverse/create-weaverse.server'
import { isbot } from 'isbot'
import { renderToReadableStream } from 'react-dom/server'

export default async function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
context: AppLoadContext,
) {
const { nonce, header, NonceProvider } = createContentSecurityPolicy(getWeaverseCsp(request));
const { nonce, header, NonceProvider } = createContentSecurityPolicy({
...getWeaverseCsp(request, context),
shop: {
checkoutDomain: context.env?.PUBLIC_CHECKOUT_DOMAIN || context.env?.PUBLIC_STORE_DOMAIN,
storeDomain: context.env?.PUBLIC_STORE_DOMAIN,
},
})
const body = await renderToReadableStream(
<NonceProvider>
<RemixServer context={remixContext} url={request.url} />
</NonceProvider>,
{
nonce,
// other options
signal: request.signal,
onError(error) {
console.error(error)
responseStatusCode = 500
},
},
);
)

if (isbot(request.headers.get('user-agent'))) {
await body.allReady
}

responseHeaders.set('Content-Security-Policy', header);
// further response handling
responseHeaders.set('Content-Type', 'text/html')
responseHeaders.set('Content-Security-Policy', header)
return new Response(body, {
headers: responseHeaders,
status: responseStatusCode,
})
}
```

Expand All @@ -57,43 +76,47 @@ Weaverse uses default CSP policies that are suitable for most needs, defined in
* Modify the return directives based on your requirements.
*
* @param request
* @param context
* @returns CSP policies
*/
export function getWeaverseCsp(request: Request) {
let url = new URL(request.url);
let weaverseHost = url.searchParams.get('weaverseHost');
let isDesignMode = url.searchParams.get('weaverseHost');
let weaverseHosts = ['*.weaverse.io', '*.shopify.com', '*.myshopify.com'];

export function getWeaverseCsp(request: Request, context: AppLoadContext) {
let url = new URL(request.url)
let weaverseHost = url.searchParams.get('weaverseHost') || context.env.WEAVERSE_HOST
let isDesignMode = url.searchParams.get('weaverseHost')
let weaverseHosts = ['*.weaverse.io', '*.shopify.com', '*.myshopify.com']
if (weaverseHost) {
weaverseHosts.push(weaverseHost);
weaverseHosts.push(weaverseHost)
}
let updatedCsp: {
[x: string]: string[] | string | boolean
} = {
defaultSrc: [
'data:',
'*.youtube.com',
'*.google.com',
'*.google-analytics.com',
'*.googletagmanager.com',
...weaverseHosts,
],
connectSrc: ['vimeo.com', '*.google-analytics.com', ...weaverseHosts],
}

let updatedCsp = {
defaultSrc: ['data:', '*.youtube.com', '*.vimeo.com', '*.google.com', 'fonts.gstatic.com', ...weaverseHosts],
styleSrc: ['fonts.googleapis.com', ...weaverseHosts],
connectSrc: ['https://vimeo.com', ...weaverseHosts],
};

if (isDesignMode) {
updatedCsp.frameAncestors = ['*'];
updatedCsp.frameAncestors = ['*']
}

return updatedCsp;
return updatedCsp
}
```

#### Common Customizations

If you need to customize CSP for specific needs, such as loading external scripts or enabling additional integrations, update the `getWeaverseCsp` function with the appropriate sources. For example, to allow scripts from additional external domains, you might modify the `scriptSrc` directive:
If you need to customize CSP for specific requirements, such as loading external scripts or enabling additional integrations, update the `getWeaverseCsp` function with the appropriate sources. For example, to allow scripts from additional external domains, you might modify the `scriptSrc` directive:

```tsx
scriptSrc: [
'cdn.example.com',
'www.googletagmanager.com',
'*.clarity.ms',
...weaverseHosts
]
scriptSrc: ['cdn.example.com', 'www.googletagmanager.com', '*.clarity.ms', ...weaverseHosts]
```

For detailed guidance on CSP directive values, visit [content-security-policy.com](https://content-security-policy.com/).

### Conclusion

CSP is a critical security feature that helps protect your website by controlling the sources of content. Weaverse provides automatic CSP configuration, but you can customize it to fit your specific needs. Properly managing CSP can enhance the security and functionality of your Weaverse Hydrogen theme.
70 changes: 25 additions & 45 deletions docs/guides/environment-variables.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,59 +2,47 @@
title: Environment Variables
description: Setting up and managing environment variables in Weaverse Hydrogen theme.
publishedAt: November 20, 2023
updatedAt: January 17, 2024
updatedAt: Jun 7, 2024
order: 2
published: true
---

## Introduction

Environment variables offer a mechanism to protect sensitive data, manage configurations, and streamline different
environments like development, testing, and production. In **Weaverse Hydrogen**, you'll frequently interact with a set
of predefined variables specially tailored for the framework.
Environment variables provide a mechanism to protect sensitive data, manage configurations, and streamline different environments like development, testing, and production. In **Weaverse Hydrogen**, you'll frequently interact with a set of predefined variables tailored specifically for the framework.

## Essential Environment Variables for a Hydrogen Theme

1. **`SESSION_SECRET`**: A secret key used to sign session cookies. For more details, you can refer to
the [Remix documentation on using sessions](https://remix.run/docs/en/v1/api/remix#use-session).

2. **`PUBLIC_STOREFRONT_API_TOKEN`**: The public access token for the Storefront API. This is not required if you are
using the **`mock.shop`** demo setup.

3. **`PUBLIC_STORE_DOMAIN`**: The domain of the store used to communicate with the Storefront API. By default, if you're
using the demo setup, the **`.env`** file will point to **`mock.shop`**.
4. **`PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID`**: The public access token for the Customer Account API. This is not required if you are using the old login method with password.
5. **`PUBLIC_CUSTOMER_ACCOUNT_API_URL`**: The API URL for the Customer Account API, it should look like this: `https://shopify.com/12345678`.

6. **`PRIVATE_STOREFRONT_API_TOKEN`** (optional): The private access token for the Storefront API.

7. **`PUBLIC_STOREFRONT_API_VERSION`** (optional): The Storefront API version. If not specified, it defaults to the
version of the Storefront API used by Hydrogen.
1. **`SESSION_SECRET`**: A secret key used to sign session cookies. For more details, refer to the [Remix documentation on using sessions](https://remix.run/docs/en/v1/api/remix#use-session).
2. **`PUBLIC_STOREFRONT_API_TOKEN`**: The public access token for the Storefront API. This is not required if you are using the **`mock.shop`** demo setup.
3. **`PUBLIC_STORE_DOMAIN`**: The domain of the store used to communicate with the Storefront API. By default, if you're using the demo setup, the **`.env`** file will point to **`mock.shop`**.
4. **`PUBLIC_CHECKOUT_DOMAIN`**: The domain of the checkout page (or the original Online Store domain). This is used for the consent banner and analytics.
5. **`PUBLIC_CUSTOMER_ACCOUNT_API_CLIENT_ID`**: The public access token for the Customer Account API. This is not required if you are using the old login method with a password.
6. **`PUBLIC_CUSTOMER_ACCOUNT_API_URL`**: The API URL for the Customer Account API, which should look like this: `https://shopify.com/12345678`.
7. **`PRIVATE_STOREFRONT_API_TOKEN`** (optional): The private access token for the Storefront API.
8. **`PUBLIC_STOREFRONT_API_VERSION`** (optional): The Storefront API version. If not specified, it defaults to the version used by Hydrogen.

## Weaverse Specific Environment Variables

1. **`WEAVERSE_PROJECT_ID`**: A unique ID representing your specific **Weaverse** project. You can find this ID inside
the Weaverse Studio under the **Project Settings**.

2. **`WEAVERSE_API_KEY`** (optional): Weaverse API Key that is retrieved from your Weaverse Account setting. This is used for some secured backend operations.

1. **`WEAVERSE_PROJECT_ID`**: A unique ID representing your specific **Weaverse** project. You can find this ID inside the Weaverse Studio under **Project Settings**.
2. **`WEAVERSE_API_KEY`** (optional): Weaverse API Key retrieved from your Weaverse Account settings. This is used for some secured backend operations.
3. **`WEAVERSE_HOST`** (optional): The host URL for Weaverse services. If not specified, the default value is **`https://studio.weaverse.io`**.

## Setting Up Environment Variables

Define these environment variables in your **`.env`** file located at the root of your theme.

#### Using demo setup (with `mock.shop`)
### Using Demo Setup (with `mock.shop`)

```text data-line-numbers=false
```plaintext
SESSION_SECRET="my-secret-key"
PUBLIC_STORE_DOMAIN="mock.shop"
WEAVERSE_PROJECT_ID="weaverse-project-id"
```

#### When having a token
### When Using a Token

```text data-line-numbers=false
```plaintext
# These variables are only available locally in MiniOxygen
SESSION_SECRET="my-secret-key"
Expand All @@ -65,25 +53,21 @@ PUBLIC_CUSTOMER_ACCOUNT_API_URL="https://shopify.com/12345678"
WEAVERSE_PROJECT_ID="weaverse-project-id"
```

📌 **Note**: Always avoid committing the **`.env`** file to version control. This could inadvertently expose sensitive
data. Instead, use the **`.env.example`** file to display the required variables without revealing the actual values.
📌 **Note**: Avoid committing the **`.env`** file to version control to prevent exposing sensitive data. Use the **`.env.example`** file to display required variables without revealing actual values.

## Obtaining the Public Storefront API Token

To get your **`PUBLIC_STOREFRONT_API_TOKEN`** to preview your real store data, please install
the [Headless](https://apps.shopify.com/headless) or [Hydrogen](https://apps.shopify.com/hydrogen) app and
follow [this instruction](https://shopify.dev/docs/custom-storefronts/building-with-the-storefront-api/manage-headless-channels)
to obtain the _Storefront API Token_
<doc-warning>If you are on Shopify Starter plan, please create a custom app to obtain the Storefront API token. [Learn more](https://help.shopify.com/en/manual/apps/app-types/custom-apps) </doc-warning>
To get your **`PUBLIC_STOREFRONT_API_TOKEN`** and preview your real store data, install the [Headless](https://apps.shopify.com/headless) or [Hydrogen](https://apps.shopify.com/hydrogen) app and follow [these instructions](https://shopify.dev/docs/custom-storefronts/building-with-the-storefront-api/manage-headless-channels) to obtain the _Storefront API Token_.

<doc-warning>If you are on the Shopify Starter plan, please create a custom app to obtain the Storefront API token. [Learn more](https://help.shopify.com/en/manual/apps/app-types/custom-apps)</doc-warning>

![](https://downloads.intercomcdn.com/i/o/848678475/033f78182979523f9a7a23e1/image.png)
![API Token](https://downloads.intercomcdn.com/i/o/848678475/033f78182979523f9a7a23e1/image.png)

Then you can add them to the **.env** file.
Then, add them to the **.env** file.

## Using Environment Variables

Within your Weaverse Hydrogen theme, you can access environment variables via routes' `loader` function or Weaverse
component's `loader` function
Within your Weaverse Hydrogen theme, access environment variables via routes' `loader` function or Weaverse component's `loader` function.

For instance, within a **`loader`** function:

Expand Down Expand Up @@ -117,10 +101,6 @@ export let loader = async ({ weaverse }: ComponentLoaderArgs) => {

## Conclusion

Correctly understanding and managing environment variables is crucial for both the security and functionality of your
Weaverse Hydrogen theme. Always ensure that they are treated with the utmost care, keeping any sensitive data well
protected.
Correctly understanding and managing environment variables is crucial for both the security and functionality of your Weaverse Hydrogen theme. Always ensure that they are treated with the utmost care, keeping any sensitive data well protected.

Now let's learn about creating and managing
**[Weaverse Component](/docs/guides/weaverse-component)** – the foundational building
blocks of your theme.
Next, learn about creating and managing **[Weaverse Components](/docs/guides/weaverse-component)** – the foundational building blocks of your theme.
2 changes: 1 addition & 1 deletion docs/guides/global-section.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description: Learn how to create and reuse global sections in your Weaverse them
publishedAt: May 31, 2024
updatedAt: Jun 7, 2024
order: 9
published: false
published: true
---

**Global Sections** in Weaverse empower you to create and reuse sections across multiple pages and components. This feature enhances the organization and structure of your theme’s content, making maintenance and updates more efficient.
Expand Down
2 changes: 1 addition & 1 deletion docs/guides/localization.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ title: Localization
description: Explore how Weaverse empowers you to create a multilingual storefront with ease.
publishedAt: November 20, 2023
updatedAt: January 17, 2024
order: 10
order: 12
published: false
---

Expand Down

0 comments on commit 444a83c

Please sign in to comment.