Skip to content

Commit ce78ddf

Browse files
committed
Initial commit
1 parent 408c8a0 commit ce78ddf

File tree

126 files changed

+26033
-6
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

126 files changed

+26033
-6
lines changed

AWS_CDK/.gitignore

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
# Logs
2+
logs
3+
*.log
4+
npm-debug.log*
5+
yarn-debug.log*
6+
yarn-error.log*
7+
lerna-debug.log*
8+
.pnpm-debug.log*
9+
10+
# Diagnostic reports (https://nodejs.org/api/report.html)
11+
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
12+
13+
# Runtime data
14+
pids
15+
*.pid
16+
*.seed
17+
*.pid.lock
18+
19+
# Directory for instrumented libs generated by jscoverage/JSCover
20+
lib-cov
21+
22+
# Coverage directory used by tools like istanbul
23+
coverage
24+
*.lcov
25+
26+
# nyc test coverage
27+
.nyc_output
28+
29+
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
30+
.grunt
31+
32+
# Bower dependency directory (https://bower.io/)
33+
bower_components
34+
35+
# node-waf configuration
36+
.lock-wscript
37+
38+
# Compiled binary addons (https://nodejs.org/api/addons.html)
39+
build/Release
40+
41+
42+
# Dependency directories
43+
node_modules/
44+
jspm_packages/
45+
46+
# Snowpack dependency directory (https://snowpack.dev/)
47+
web_modules/
48+
49+
# TypeScript cache
50+
*.tsbuildinfo
51+
52+
# Optional npm cache directory
53+
.npm
54+
55+
# Optional eslint cache
56+
.eslintcache
57+
58+
# Optional stylelint cache
59+
.stylelintcache
60+
61+
# Microbundle cache
62+
.rpt2_cache/
63+
.rts2_cache_cjs/
64+
.rts2_cache_es/
65+
.rts2_cache_umd/
66+
67+
# Optional REPL history
68+
.node_repl_history
69+
70+
# Output of 'npm pack'
71+
*.tgz
72+
73+
# Yarn Integrity file
74+
.yarn-integrity
75+
76+
# dotenv environment variable files
77+
.env
78+
.env.development.local
79+
.env.test.local
80+
.env.production.local
81+
.env.local
82+
83+
# parcel-bundler cache (https://parceljs.org/)
84+
.cache
85+
.parcel-cache
86+
87+
# Next.js build output
88+
.next
89+
out
90+
91+
# Nuxt.js build / generate output
92+
.nuxt
93+
dist
94+
95+
# Gatsby files
96+
.cache/
97+
# Comment in the public line in if your project uses Gatsby and not Next.js
98+
# https://nextjs.org/blog/next-9-1#public-directory-support
99+
# public
100+
101+
# vuepress build output
102+
.vuepress/dist
103+
104+
# vuepress v2.x temp and cache directory
105+
.temp
106+
.cache
107+
108+
# Docusaurus cache and generated files
109+
.docusaurus
110+
111+
# Serverless directories
112+
.serverless/
113+
114+
# FuseBox cache
115+
.fusebox/
116+
117+
# DynamoDB Local files
118+
.dynamodb/
119+
120+
# TernJS port file
121+
.tern-port
122+
123+
# Stores VSCode versions used for testing VSCode extensions
124+
.vscode-test
125+
126+
# yarn v2
127+
.yarn/cache
128+
.yarn/unplugged
129+
.yarn/build-state.yml
130+
.yarn/install-state.gz
131+
.pnp.*
132+
133+
# CDK asset staging directory
134+
.cdk.staging
135+
cdk.out/
136+
.idea
137+
outfile*
138+

AWS_CDK/.npmignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
*.ts
2+
!*.d.ts
3+
4+
# CDK asset staging directory
5+
.cdk.staging
6+
cdk.out

AWS_CDK/README.md

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Amazon API Gateway WebSocket API demo
2+
3+
This is the Amazon Web Services (AWS) Cloud Development Kit (CDK) backend for a Unity game that uses an authenticated WebSocket connection to pass game actions between players.
4+
5+
![Alt](../docs/img/websocket-api-architecture.jpg "Amazon API Gateway WebSocket API architecture diagram showing the AWS Lambda integrations and Amazon DynamoDB database.")<br />
6+
*Reference architecture for the WebSocket API*
7+
8+
The sample AWS CDK code deploys an API Gateway WebSockets API with the following routes:
9+
* $connect – handles client connections
10+
* $default – default route that doesn’t perform any function
11+
* heartbeat – prevents idle timeout by keeping the connection alive
12+
* message – handles client messages to other connected clients
13+
* $disconnect – handles client disconnections
14+
15+
Each route has a Lambda function integration which receives the request information and performs an action. Connection state is maintained inside a DynamoDB table. When a client connects via the $connect route, the Lambda integration is executed and the connection ID is stored in the table. When a client disconnects, the $disconnect Lambda integration is executed and the connection ID is removed from the table. When a client sends a message to the message route, the Lambda integration retrieves all connection IDs from the DynamoDB table and broadcasts the message to all other connected clients.
16+
17+
In addition to the WebSocket API architecture, Amazon Cognito is used to authenticate users when connecting to the WebSocket API. A configuration file is generated when this code is deployed, which provides a local credentials cache for the associated Unity application's Cognito login process.
18+
19+
20+
## Prerequisites
21+
* An [AWS Account](https://aws.amazon.com/)
22+
* [AWS CLI](https://github.com/aws/aws-cli#getting-started) installed and configured.
23+
* [Node.js](https://nodejs.org/en/download/) v14.15.0+
24+
* [AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)
25+
26+
## Steps to create the backend on your AWS Account
27+
1. Navigate to the AWS_CDK directory.
28+
2. ```npm run install-all``` to install all dependencies.
29+
4. ```export CDK_DEFAULT_REGION=<your-desired-region>``` to set the default AWS region, e.g. `us-east-1`.
30+
5. ```export CDK_DEFAULT_ACCOUNT=<your-aws-account>``` to set the default AWS account, e.g. `123456789012`.
31+
6. ```cdk bootstrap``` to bootstrap your AWS Account.
32+
7. ```cdk deploy WebSocketDemoStack --parameters AdminEmailAddress="<insert-your-email>"``` to deploy.
33+
8. Download the `aws-config.json` from the Config S3 bucket in your account. This will be used to authenticate users to the Amazon API Gateway WebSocket API.
34+
9. ```aws cognito-idp admin-set-user-password --user-pool-id <User Pool from Config file> --username <insert-your-email> --password <insert-your-password> --permanent``` to set the password for your admin account.
35+
10. [Return to the application setup README.](../README.md)
36+
37+
## Clean up
38+
When you are finished with this demo you should destroy the deployed AWS resources to avoid unwanted costs. To destroy the resources:
39+
1. Navigate to the AWS_CDK directory.
40+
2. ```cdk destroy``` to destroy all deployed resources.
41+

AWS_CDK/bin/unity-websocket-demo.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#!/usr/bin/env node
2+
3+
import 'source-map-support/register';
4+
import * as cdk from 'aws-cdk-lib';
5+
import { WebSocketDemoStack } from '../lib/websocket-demo-stack';
6+
import {AwsSolutionsChecks} from 'cdk-nag';
7+
8+
const app = new cdk.App();
9+
10+
cdk.Aspects.of(app).add(new AwsSolutionsChecks({ verbose: true }));
11+
12+
new WebSocketDemoStack(app, 'WebSocketDemoStack', {
13+
/* If you don't specify 'env', this stack will be environment-agnostic.
14+
* Account/Region-dependent features and context lookups will not work,
15+
* but a single synthesized template can be deployed anywhere. */
16+
17+
/* Uncomment the next line to specialize this stack for the AWS Account
18+
* and Region that are implied by the current CLI configuration. */
19+
env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: process.env.CDK_DEFAULT_REGION },
20+
21+
/* Uncomment the next line if you know exactly what Account and Region you
22+
* want to deploy the stack to. */
23+
// env: { account: '123456789012', region: 'us-east-1' },
24+
25+
/* For more information, see https://docs.aws.amazon.com/cdk/latest/guide/environments.html */
26+
});

AWS_CDK/cdk.json

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
{
2+
"app": "npx ts-node --prefer-ts-exts bin/unity-websocket-demo.ts",
3+
"watch": {
4+
"include": [
5+
"**"
6+
],
7+
"exclude": [
8+
"README.md",
9+
"cdk*.json",
10+
"**/*.d.ts",
11+
"**/*.js",
12+
"tsconfig.json",
13+
"package*.json",
14+
"yarn.lock",
15+
"node_modules",
16+
"test"
17+
]
18+
},
19+
"context": {
20+
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
21+
"@aws-cdk/core:checkSecretUsage": true,
22+
"@aws-cdk/core:target-partitions": [
23+
"aws",
24+
"aws-cn"
25+
],
26+
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
27+
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
28+
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
29+
"@aws-cdk/aws-iam:minimizePolicies": true,
30+
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
31+
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
32+
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
33+
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
34+
"@aws-cdk/aws-apigateway:disableCloudWatchRole": true,
35+
"@aws-cdk/core:enablePartitionLiterals": true,
36+
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
37+
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
38+
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
39+
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
40+
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
41+
"@aws-cdk/aws-route53-patters:useCertificate": true,
42+
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
43+
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
44+
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
45+
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
46+
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
47+
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
48+
"@aws-cdk/aws-redshift:columnId": true,
49+
"@aws-cdk/aws-stepfunctions-tasks:enableEmrServicePolicyV2": true,
50+
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
51+
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
52+
"@aws-cdk/aws-kms:aliasNameRef": true,
53+
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
54+
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
55+
"@aws-cdk/aws-opensearchservice:enableOpensearchMultiAzWithStandby": true
56+
}
57+
}

AWS_CDK/jest.config.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
module.exports = {
2+
testEnvironment: 'node',
3+
roots: ['<rootDir>/test'],
4+
testMatch: ['**/*.test.ts'],
5+
transform: {
6+
'^.+\\.tsx?$': 'ts-jest'
7+
}
8+
};

AWS_CDK/lib/cognito-stack.ts

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/*!
2+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
* SPDX-License-Identifier: MIT-0
4+
*/
5+
6+
import * as cdk from 'aws-cdk-lib';
7+
import { RemovalPolicy } from 'aws-cdk-lib';
8+
import { Construct } from 'constructs';
9+
10+
import * as cognito from 'aws-cdk-lib/aws-cognito'
11+
import { NagSuppressions } from 'cdk-nag';
12+
13+
export class CognitoStack extends cdk.NestedStack {
14+
public AWS_Region: string;
15+
public UserPool: cognito.UserPool;
16+
public UserPoolId: string;
17+
public AppClient: cognito.UserPoolClient;
18+
public AppClientId: string;
19+
public IdentityPool: cognito.CfnIdentityPool;
20+
public IdentityPoolId: string;
21+
22+
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
23+
super(scope, id, props);
24+
this.AWS_Region = this.region;
25+
this.UserPool = new cognito.UserPool(this, 'websocket-api-demo-user-pool', {
26+
userPoolName: 'websocket-api-demo-user-pool',
27+
selfSignUpEnabled: false,
28+
removalPolicy: RemovalPolicy.DESTROY,
29+
passwordPolicy: {
30+
minLength: 8,
31+
requireDigits: true,
32+
requireLowercase: true,
33+
requireSymbols: true,
34+
requireUppercase: true
35+
},
36+
advancedSecurityMode: cognito.AdvancedSecurityMode.ENFORCED
37+
});
38+
this.UserPoolId = this.UserPool.userPoolId;
39+
this.AppClient = this.UserPool.addClient('unity-client', {
40+
supportedIdentityProviders: [
41+
cognito.UserPoolClientIdentityProvider.COGNITO
42+
],
43+
authFlows: {
44+
userPassword: true,
45+
userSrp: true
46+
}
47+
});
48+
this.AppClientId = this.AppClient.userPoolClientId;
49+
this.IdentityPool = new cognito.CfnIdentityPool(this, id + "IdentityPool", {
50+
allowUnauthenticatedIdentities: false,
51+
cognitoIdentityProviders: [
52+
{
53+
clientId: this.AppClientId,
54+
providerName: this.UserPool.userPoolProviderName
55+
}
56+
]
57+
});
58+
this.IdentityPoolId = this.IdentityPool.ref;
59+
60+
// CDK Nag Suppressions
61+
62+
NagSuppressions.addResourceSuppressions(this.UserPool, [
63+
{
64+
id: 'AwsSolutions-COG2',
65+
reason: 'MFA should be added in a production environment.'
66+
}
67+
]);
68+
69+
}
70+
71+
exportConfig() {
72+
const config = {
73+
'AWS_Region': this.AWS_Region,
74+
'CognitoUserPool': this.UserPool.userPoolId,
75+
'CognitoIdentityPool': this.IdentityPoolId,
76+
'AppClientId': this.AppClient.userPoolClientId
77+
}
78+
return config;
79+
}
80+
81+
}

0 commit comments

Comments
 (0)