Skip to content
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

feat: Adds Setup CLI Command to Configure GraphQL Trusted Documents #9800

Merged
merged 27 commits into from
Jan 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
446ae64
WIP to have graphql setup of trusted docs
dthyresson Jan 4, 2024
cc647b3
cleanup command and add docs
dthyresson Jan 4, 2024
608b5d4
Update docs/docs/cli-commands.md
dthyresson Jan 8, 2024
9cd43eb
Update docs/docs/cli-commands.md
dthyresson Jan 8, 2024
bc27569
Update docs/docs/cli-commands.md
dthyresson Jan 8, 2024
a68de95
Update docs/docs/graphql/trusted-documents.md
dthyresson Jan 8, 2024
75773d6
Refactor to improve toml setup
dthyresson Jan 8, 2024
8f15513
removed commandDir
dthyresson Jan 8, 2024
717be40
removed force option
dthyresson Jan 8, 2024
27d6cdc
Merge branch 'main' into dt-setup-gql-trusted-docs
dthyresson Jan 8, 2024
d9eeed3
Adds tests for trusted document toml updates
dthyresson Jan 9, 2024
1677049
Tests for graphql handler store updates
dthyresson Jan 9, 2024
d865c58
Merge branch 'main' into dt-setup-gql-trusted-docs
Tobbe Jan 11, 2024
89a06df
async handler and TS fixes
Tobbe Jan 11, 2024
d69acf3
Fix import and TS issue in test
Tobbe Jan 11, 2024
2cb9ad3
Update test snapshot
Tobbe Jan 11, 2024
2b551f2
More robust redwood.toml handling
Tobbe Jan 11, 2024
e01e962
Fix tsconfig
Tobbe Jan 11, 2024
063a67f
Move all tasks to array, and silence logs in test
Tobbe Jan 11, 2024
7ad7da2
Move __fixtures__
Tobbe Jan 11, 2024
23f281c
Fix whiteline in test
Tobbe Jan 11, 2024
bd476be
fragments: refactor->rename
Tobbe Jan 12, 2024
6b144bb
Move to jscodeshift
Tobbe Jan 12, 2024
911f3fe
Merge branch 'main' into dt-setup-gql-trusted-docs
Tobbe Jan 12, 2024
c8f0bbb
Fix paths
Tobbe Jan 12, 2024
f5af938
Update filepath in test
Tobbe Jan 12, 2024
d4615ac
Merge branch 'main' into dt-setup-gql-trusted-docs
Tobbe Jan 12, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion docs/docs/cli-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -1999,11 +1999,55 @@ We perform a simple compatibility check in an attempt to make you aware of poten

It's the author of the npm package's responsibility to specify the correct compatibility range, so **you should always research the packages you use with this command**. Especially since they will be executing code on your machine!

### setup graphql

This command creates the necessary files to support GraphQL features like trusted documents.

#### Usage

Run `yarn rw setup graphql <feature>`


#### setup graphql trusted-docs

This command creates the necessary configuratiion to start using [GraphQL Trusted Documents](./graphql/trusted-documents.md).
dthyresson marked this conversation as resolved.
Show resolved Hide resolved


```
yarn redwood setup graphql trusted-documents
```

| Arguments & Options | Description |
| :------------------ | :----------------------- |
| `--force, -f` | Forgo compatibility checks |

#### Usage

Run `yarn rw graphql trusted-documents`
dthyresson marked this conversation as resolved.
Show resolved Hide resolved

#### Example

```bash
~/redwood-app$ yarn rw graphql trusted-documents
dthyresson marked this conversation as resolved.
Show resolved Hide resolved
✔ Update Redwood Project Configuration to enable GraphQL Trusted Documents ...
✔ Generating Trusted Documents store ...
✔ Configuring the GraphQL Handler to use a Trusted Documents store ...
```


If you have not setup the RedwoodJS server file, it will be setup:

```bash
✔ Adding the experimental server file...
✔ Adding config to redwood.toml...
✔ Adding required api packages...
```


### setup realtime

This command creates the necessary files, installs the required packages, and provides examples to setup RedwoodJS Realtime from GraphQL live queries and subscriptions. See the Realtime docs for more information.


```
yarn redwood setup realtime
```
Expand Down
5 changes: 5 additions & 0 deletions docs/docs/graphql/trusted-documents.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,11 @@ Thus preventing unwanted queries or GraphQl traversal attacks,

## Configure Trusted Documents

Below are instructions to manually configure Trusted Documents in your redwoodJS project.
dthyresson marked this conversation as resolved.
Show resolved Hide resolved

Alternatively, you can use the `yarn redwood setup graphql trusted-documents` [CLI setup command](../cli-commands.md#setup-graphql-trusted-docs).


### Configure redwood.toml

Setting `trustedDocuments` to true will
Expand Down
179 changes: 179 additions & 0 deletions packages/cli/src/commands/setup/graphql/features/trusted-docs.ts
dthyresson marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import fs from 'fs'
import path from 'path'

import execa from 'execa'
import { Listr } from 'listr2'
import { format } from 'prettier'
import { Project, SyntaxKind, type PropertyAssignment } from 'ts-morph'

import {
recordTelemetryAttributes,
prettierOptions,
} from '@redwoodjs/cli-helpers'
import { getConfigPath } from '@redwoodjs/project-config'

import { getPaths } from '../../../../lib'
import c from '../../../../lib/colors'

export const command = 'trusted-docs'
export const description = 'Set up Trusted Documents for GraphQL'

export function builder(yargs: any) {
yargs.option('force', {
alias: 'f',
default: false,
description: 'Overwrite existing configuration',
type: 'boolean',
})
}

function configureGraphQLHandlerWithStore() {
return {
title:
'Configuring the GraphQL Handler to use a Trusted Documents store ...',
task: async () => {
// locate "api/functions/graphql.[js|ts]"
let graphQlSourcePath: string | undefined
const functionsDir = getPaths().api.functions
if (fs.existsSync(path.join(functionsDir, 'graphql.ts'))) {
graphQlSourcePath = path.join(functionsDir, 'graphql.ts')
} else if (fs.existsSync(path.join(functionsDir, 'graphql.js'))) {
graphQlSourcePath = path.join(functionsDir, 'graphql.js')
}

if (!graphQlSourcePath) {
console.warn(
c.warning(
`Unable to find the GraphQL Handler source file: ${path.join(
functionsDir,
'graphql.(js|ts)'
)}`
)
)
return
}

// add import
const project = new Project()
const graphQlSourceFile =
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
project.addSourceFileAtPathIfExists(graphQlSourcePath)!
dthyresson marked this conversation as resolved.
Show resolved Hide resolved
let graphQlSourceFileChanged = false
let identified = false

const imports = graphQlSourceFile.getImportDeclarations()
if (
!imports.some(
(i) => i.getModuleSpecifierValue() === 'src/lib/trustedDocumentsStore'
)
) {
graphQlSourceFile.addImportDeclaration({
moduleSpecifier: 'src/lib/trustedDocumentsStore',
namedImports: ['store'],
})
graphQlSourceFileChanged = true
}

// add "trustedDocuments" option to `createGraphQLHandler` call
graphQlSourceFile
.getDescendantsOfKind(SyntaxKind.CallExpression)
.forEach((expr) => {
if (identified) {
return
}

if (
expr.getExpression().asKind(SyntaxKind.Identifier)?.getText() ===
'createGraphQLHandler'
) {
const arg = expr
.getArguments()[0]
?.asKind(SyntaxKind.ObjectLiteralExpression)
if (arg) {
identified = true
const props = arg.getProperties()
const trustedDocsProp = props.find(
(p): p is PropertyAssignment =>
p.asKind(SyntaxKind.PropertyAssignment)?.getName() ===
'trustedDocuments'
)
if (!trustedDocsProp) {
arg.addPropertyAssignment({
name: 'trustedDocuments',
initializer: '{ store }',
})
graphQlSourceFileChanged = true
}
}
}
})

if (!identified) {
console.warn(
c.warning(
'Unable to determine how to setup Trusted Documents in the GraphQL Handler. Please add it manually following https://docs.redwoodjs.com/docs/graphql/trusted-documents#configure-graphql-handler'
)
)
}

if (graphQlSourceFileChanged) {
await project.save()
const updatedHandler = fs.readFileSync(graphQlSourcePath, 'utf-8')
const prettifiedHandler = format(updatedHandler, {
...prettierOptions(),
parser: 'babel-ts',
})
fs.writeFileSync(graphQlSourcePath, prettifiedHandler, 'utf-8')
}
},
}
}

export async function handler({
force,
install,
}: {
force: boolean
install: boolean
}) {
recordTelemetryAttributes({
command: 'setup graphql trusted-docs',
dthyresson marked this conversation as resolved.
Show resolved Hide resolved
force,
install,
})

const tasks = new Listr(
[
{
title:
'Update Redwood Project Configuration to enable GraphQL Trusted Documents ...',
skip: () => false,
dthyresson marked this conversation as resolved.
Show resolved Hide resolved
task: () => {
const redwoodTomlPath = getConfigPath()
const originalTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8')

const tomlToAppend = `[graphql]\n trustedDocuments = true`
dthyresson marked this conversation as resolved.
Show resolved Hide resolved

const newConfig = originalTomlContent + '\n' + tomlToAppend

fs.writeFileSync(redwoodTomlPath, newConfig, 'utf-8')
},
},
{
title: 'Generating Trusted Documents store ...',
task: () => {
execa.commandSync('yarn redwood generate types', { stdio: 'ignore' })
},
},
configureGraphQLHandlerWithStore(),
],
{ rendererOptions: { collapseSubtasks: false } }
)

try {
await tasks.run()
} catch (e: any) {
console.error(c.error(e.message))
process.exit(e?.exitCode || 1)
}
}
14 changes: 14 additions & 0 deletions packages/cli/src/commands/setup/graphql/graphql.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import terminalLink from 'terminal-link'

export const command = 'graphql <feature>'
export const description = 'Set up GraphQL feature support'
export const builder = (yargs) =>
yargs
.commandDir('./features')
dthyresson marked this conversation as resolved.
Show resolved Hide resolved
.demandCommand()
.epilogue(
`Also see the ${terminalLink(
'Redwood CLI Reference',
'https://redwoodjs.com/docs/cli-commands#setup-graphql'
)}`
)
Loading