Skip to content

Commit

Permalink
🔄 synced local 'packages' with remote 'packages'
Browse files Browse the repository at this point in the history
systemadmin-asm committed May 3, 2023
1 parent b5bb708 commit 83f402d
Showing 44 changed files with 18,581 additions and 171 deletions.
3 changes: 2 additions & 1 deletion packages/core-backend/package.json
Original file line number Diff line number Diff line change
@@ -11,7 +11,8 @@
"@aws-sdk/client-dynamodb": "^3.267.0",
"@aws-sdk/client-secrets-manager": "^3.267.0",
"@aws-sdk/lib-dynamodb": "^3.267.0",
"aws-lambda": "^1.0.7",
"@sentry/integrations": "^6.19.6",
"@sentry/serverless": "^6.19.6",
"dotenv": "8.2.0",
"fp-ts": "^2.12.3",
"fp-ts-contrib": "^0.1.29",
2 changes: 1 addition & 1 deletion packages/core-backend/src/sentry.ts
Original file line number Diff line number Diff line change
@@ -11,7 +11,7 @@ if (sentryDSN) {
integrations: [
new CaptureConsole({
levels: ['error'],
}),
}) as any,
],
environment,
beforeSend: (event, hint) => {
1 change: 0 additions & 1 deletion packages/event-handlers/package.json
Original file line number Diff line number Diff line change
@@ -13,7 +13,6 @@
},
"dependencies": {
"@aws-sdk/client-sfn": "^3.289.0",
"aws-lambda": "^1.0.7",
"fp-ts": "^2.12.3",
"io-ts": "^2.2.16"
}
11 changes: 4 additions & 7 deletions packages/gql-api/package.json
Original file line number Diff line number Diff line change
@@ -24,17 +24,14 @@
"typescript": "^4.9.5"
},
"dependencies": {
"@apollo/server": "^4.7.0",
"@apollo/server-plugin-landing-page-graphql-playground": "^4.0.0",
"@as-integrations/aws-lambda": "^2.0.1",
"@graphql-tools/schema": "^9.0.4",
"@graphql-tools/utils": "^8.12.0",
"@sentry/integrations": "^6.19.6",
"@sentry/serverless": "^6.19.6",
"apollo-server": "^3.10.0",
"apollo-server-core": "^3.10.0",
"apollo-server-lambda": "^3.10.0",
"aws-lambda": "^1.0.7",
"ethers": "^5.7.2",
"fp-ts": "^2.12.3",
"graphql": "^16.0.1",
"graphql": "^16.6.0",
"graphql-tag": "^2.12.6",
"io-ts": "^2.2.16",
"siwe": "^1.1.6"
10 changes: 7 additions & 3 deletions packages/gql-api/src/graphql/directives/authenticated.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { getDirective, MapperKind, mapSchema } from '@graphql-tools/utils'
import { AuthenticationError } from 'apollo-server-core'
import type { GraphQLFieldConfig, GraphQLSchema } from 'graphql'
import { defaultFieldResolver } from 'graphql'
import { defaultFieldResolver, GraphQLError } from 'graphql'

import type { AuthenticatedContext, Context } from '../context'

@@ -44,8 +43,13 @@ export const authenticatedDirective = (schema: GraphQLSchema) => {
// If the user is not authenticated, throw an error
const { walletAddress } = context
if (!walletAddress) {
throw new AuthenticationError(
throw new GraphQLError(
'You must be authenticated to use this field.',
{
extensions: {
code: 'UNAUTHENTICATED',
},
},
)
}

107 changes: 52 additions & 55 deletions packages/gql-api/src/handlers/graphql-handler.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
import { ApolloServer } from '@apollo/server'
import { ApolloServerPluginLandingPageGraphQLPlayground } from '@apollo/server-plugin-landing-page-graphql-playground'
import {
handlers,
startServerAndCreateLambdaHandler,
} from '@as-integrations/aws-lambda'
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { SecretsManagerClient } from '@aws-sdk/client-secrets-manager'
import { DynamoDBDocument } from '@aws-sdk/lib-dynamodb'
import { makeExecutableSchema } from '@graphql-tools/schema'
import {
ApolloServerPluginLandingPageGraphQLPlayground,
AuthenticationError,
} from 'apollo-server-core'
import type { Config } from 'apollo-server-lambda'
import { ApolloServer } from 'apollo-server-lambda'
import type { LambdaContextFunctionParams } from 'apollo-server-lambda/dist/ApolloServer'
import type {
APIGatewayProxyEventHeaders,
APIGatewayProxyEventV2,
} from 'aws-lambda'
import { typeDefs } from 'core/src/graphql/type-defs'
import { BrainMetadataInteractions } from 'core-backend/src/assets/brain-metadata-interactions'
import { ComputeManagerInteractions } from 'core-backend/src/contracts/compute-manager-interactions'
@@ -23,6 +18,8 @@ import { sentryWrapper } from 'core-backend/src/sentry'
import { providers, Wallet } from 'ethers'
import { either } from 'fp-ts'
import type { GraphQLFormattedError } from 'graphql'
import { GraphQLError } from 'graphql'
import type { IncomingHttpHeaders } from 'http'
import * as decoder from 'io-ts/Decoder'
import type {
AuthenticatedContext,
@@ -39,12 +36,6 @@ import { TrainingService } from 'src/services/training-service'

import { SecretsC } from './handler-secrets'

interface APIGatewayV2ContextFunctionParams
extends LambdaContextFunctionParams {
event: APIGatewayProxyEventV2
context: Context
}

const buildCachedServicesPromise = (async (): Promise<Context> => {
const env = getEnvOrThrow({
ENVIRONMENT: decoder.literal('dev', 'staging', 'prod'),
@@ -129,56 +120,62 @@ const augmentedSchema = directives.reduce(
schema,
)

interface APIGatewayV2ContextFunctionParams
extends LambdaContextFunctionParams {
event: APIGatewayProxyEventV2
context: Context
}
export const getContext = async (
headers: IncomingHttpHeaders,
): Promise<Context> => {
const services: BaseContext = await buildCachedServicesPromise

// auth token is passed in the request header
const token = headers['authorization']?.slice('Bearer '.length)
if (token) {
const decodedWalletAddress = services.authenticationService.verifyJwt(token)

if (either.isLeft(decodedWalletAddress)) {
throw new GraphQLError('Invalid wallet address', {
extensions: {
code: 'UNAUTHENTICATED',
},
})
}

const context: AuthenticatedContext<BaseContext> = {
...services,
walletAddress: decodedWalletAddress.right,
}

const getHeaders = (req: APIGatewayV2ContextFunctionParams) => {
return req.event?.headers as APIGatewayProxyEventHeaders
return context
}

return services
}

// GraphQL Server Initialization
export const getApolloSettings = (
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getHeaders: (req: any) => any,
): Config<APIGatewayV2ContextFunctionParams> => ({
export const ApolloSettings = {
schema: augmentedSchema,
context: async (req): Promise<Context> => {
const headers = getHeaders(req)
const services: BaseContext = await buildCachedServicesPromise

// auth token is passed in the request header
const token = headers['authorization']?.slice('Bearer '.length)
if (token) {
const decodedWalletAddress =
services.authenticationService.verifyJwt(token)

if (either.isLeft(decodedWalletAddress)) {
throw new AuthenticationError('Invalid wallet address')
}

return {
...services,
walletAddress: decodedWalletAddress.right,
} as AuthenticatedContext<BaseContext>
}

return services
},
introspection: true,
plugins: [ApolloServerPluginLandingPageGraphQLPlayground],
formatError: err => {
plugins: [ApolloServerPluginLandingPageGraphQLPlayground()],
formatError: (err: GraphQLFormattedError) => {
console.log(err)

// Otherwise return the original error. The error can also
// be manipulated in other ways, as long as it's returned.
return err as GraphQLFormattedError
return err
},
})
}

/* Run the graphql server as a lambda */
const server = new ApolloServer(getApolloSettings(getHeaders))
const server = new ApolloServer(ApolloSettings)

const graphqlHandler = startServerAndCreateLambdaHandler(
server,
// We will be using the Proxy V2 handler
handlers.createAPIGatewayProxyEventV2RequestHandler(),
{
context: async req => {
return getContext(req.event.headers)
},
},
)

export const handler = sentryWrapper(server.createHandler())
export const handler = sentryWrapper(graphqlHandler)
20 changes: 8 additions & 12 deletions packages/gql-api/src/local/local.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import './local-setup'

import { ApolloServer } from 'apollo-server'
import type { ExpressContext } from 'apollo-server-express'
import { ApolloServer } from '@apollo/server'
import { startStandaloneServer } from '@apollo/server/standalone'

const getHeaders = (context: ExpressContext) => {
return context.req.headers
}
import { ApolloSettings, getContext } from '../handlers/graphql-handler'

export const startServer = async () => {
const { getApolloSettings } = await import('../handlers/graphql-handler')

await new ApolloServer(getApolloSettings(getHeaders))
.listen()
.then(({ url }) => {
console.log(`🚀 Server ready at ${url}`)
})
await startStandaloneServer(new ApolloServer(ApolloSettings), {
context: async ({ req }) => getContext(req.headers),
}).then(({ url }) => {
console.log(`🚀 Server ready at ${url}`)
})
}

startServer().catch(err => {
6 changes: 5 additions & 1 deletion packages/gql-api/src/services/authentication-service.ts
Original file line number Diff line number Diff line change
@@ -5,6 +5,7 @@ import { pipe } from 'fp-ts/function'
import { sign, verify } from 'jsonwebtoken'
import { generateNonce } from 'siwe'

type JwtPayload = { sub: ChainAddress }
export class AuthenticationService {
public constructor(
private loginNonceRepository: LoginNonceRepository,
@@ -52,7 +53,10 @@ export class AuthenticationService {
*/
verifyJwt = (jwtToken: string) => {
return pipe(
either.tryCatch(() => verify(jwtToken, this.jwtSecret), either.toError),
either.tryCatch(
() => verify(jwtToken, this.jwtSecret) as JwtPayload,
either.toError,
),
either.map(payload => payload.sub),
)
}
1 change: 1 addition & 0 deletions packages/gql-api/src/services/gas-faucet-service.ts
Original file line number Diff line number Diff line change
@@ -28,6 +28,7 @@ export class GasFaucetService {
this.wallet,
)
const tx = await contract.faucet(walletAddress, {
gasLimit: 100000,
gasPrice: '15000000000000',
})
return right({ __typename: 'GasFaucetSuccessResponse', hash: tx.hash })
1 change: 1 addition & 0 deletions packages/gql-api/tsconfig.json
Original file line number Diff line number Diff line change
@@ -2,6 +2,7 @@
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"baseUrl": ".",
"lib": ["dom", "es2020"],
"outDir": "dist",
"module": "commonjs",
"resolveJsonModule": true,
24 changes: 24 additions & 0 deletions packages/replay-component-2d/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
13 changes: 13 additions & 0 deletions packages/replay-component-2d/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Reply app</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
31 changes: 31 additions & 0 deletions packages/replay-component-2d/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "replay-component-2d",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"types": "json2ts -i ../schemas/src/im/simulation_events.json -o ./src/types/simulation.ts",
"typescript": "tsc --project tsconfig.json --pretty --noEmit",
"typescript:clean": "rm -rf .tscache",
"ts": "yarn typescript --watch"
},
"dependencies": {
"lodash.findlast": "^4.6.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"usehooks-ts": "^2.9.1"
},
"devDependencies": {
"@types/lodash.findlast": "^4.6.7",
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"@vitejs/plugin-react": "^3.1.0",
"fs": "^0.0.1-security",
"json-schema-to-typescript": "^12.0.0",
"typescript": "^4.9.5",
"vite": "^4.1.4"
}
}
Loading
Oops, something went wrong.

0 comments on commit 83f402d

Please sign in to comment.