diff --git a/.github/workflows/aws-service-sanity-check.yml b/.github/workflows/aws-service-sanity-check.yml new file mode 100644 index 00000000..8b0bf20f --- /dev/null +++ b/.github/workflows/aws-service-sanity-check.yml @@ -0,0 +1,38 @@ +name: Main Branch Checks +permissions: + contents: read + +on: + push: + branches-ignore: + - 'main' + - 'docs' + +jobs: + verify-documentation-links: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Verify documentation files and links + # check if the files exists in the repository. The file list is in utils/doc-links.txt. + run: | + missing=0 + while read -r file || [ -n "$file" ]; do + if [ ! -f "$file" ]; then + if [ $missing -eq 0 ]; then + echo "❌ Missing files referenced in AWS documentation:" + missing=$((missing + 1)) + fi + echo " - $file" + fi + done < utils/ci-aws-doc-links.txt + + if [ $missing -ge 1 ]; then + echo "Instructions:" + echo " The above files are required for AWS services or documentations." + echo " Restore missing files or update documentation before merge." + echo " Refer to team wiki "AWS Service and Documentation Links" for details. " + exit 1 + else + echo "✅ All documentation-referenced files exist" + fi diff --git a/codebuild/cd/test-publish.sh b/codebuild/cd/test-publish.sh index b6d77733..2cfaffe1 100755 --- a/codebuild/cd/test-publish.sh +++ b/codebuild/cd/test-publish.sh @@ -42,12 +42,12 @@ if [ "$PUBLISHED_TAG_VERSION" == "$VERSION" ]; then npm install # Move to the sample folder and get the endpoint - cd samples/node/pub_sub + cd samples/node/mqtt/mqtt5_x509 ENDPOINT=$(aws secretsmanager get-secret-value --secret-id "ci/endpoint" --region us-east-1 --query "SecretString" | cut -f2 -d":" | sed -e 's/[\\\"\}]//g') # Run the sample! npm install - node dist/index.js --endpoint $ENDPOINT --ca_file /tmp/AmazonRootCA1.pem --cert /tmp/certificate.pem --key /tmp/privatekey.pem + node dist/index.js --endpoint $ENDPOINT --cert /tmp/certificate.pem --key /tmp/privatekey.pem exit 0 diff --git a/documents/FAQ.md b/documents/FAQ.md index fd1d8ef0..45aea629 100644 --- a/documents/FAQ.md +++ b/documents/FAQ.md @@ -14,7 +14,7 @@ ### Where should I start? -If you are just getting started make sure you [install this sdk](https://github.com/aws/aws-iot-device-sdk-js-v2#installation) and then build and run the basic PubSub in [node](https://github.com/aws/aws-iot-device-sdk-js-v2/tree/main/samples/node/pub_sub_mqtt5) or in the [browser](https://github.com/aws/aws-iot-device-sdk-js-v2/tree/main/samples/browser/pub_sub_mqtt5) +If you are just getting started make sure you [install this sdk](https://github.com/aws/aws-iot-device-sdk-js-v2#installation) and then build and run the basic PubSub in [node](https://github.com/aws/aws-iot-device-sdk-js-v2/tree/main/samples/node/mqtt/mqtt5_x509) or in the [browser](https://github.com/aws/aws-iot-device-sdk-js-v2/tree/main/samples/browser/pub_sub_mqtt5) ### How do I enable logging? @@ -72,14 +72,13 @@ Here is an example launch.json file to run the pubsub sample { "type": "node", "request": "launch", - "name": "pub_sub", + "name": "mqtt5_x509", "skipFiles": [ "/**" ], - "program": "${workspaceFolder}/samples/node/pub_sub/dist/index.js", + "program": "${workspaceFolder}/samples/node/mqtt/mqtt5_x509/dist/index.js", "args": [ "--endpoint", "-ats.iot..amazonaws.com", - "--ca_file", "", "--cert", "", "--key", "", "--client-id", "test-client" diff --git a/samples/node/pub_sub/README.md b/samples/node/pub_sub/README.md deleted file mode 100644 index e6dd1a12..00000000 --- a/samples/node/pub_sub/README.md +++ /dev/null @@ -1,285 +0,0 @@ -# Node: MQTT5 PubSub - -[**Return to main sample list**](../../README.md) - -This sample uses the -[Message Broker](https://docs.aws.amazon.com/iot/latest/developerguide/iot-message-broker.html) -for AWS IoT to send and receive messages through an MQTT connection using MQTT5. - -MQTT5 introduces additional features and enhancements that improve the development experience with MQTT. You can read more about MQTT5 in the Java V2 SDK by checking out the [MQTT5 user guide](https://github.com/awslabs/aws-crt-nodejs/blob/main/MQTT5-UserGuide.md). - -Your IoT Core Thing's [Policy](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html) must provide privileges for this sample to connect, subscribe, publish, and receive. Below is a sample policy that can be used on your IoT Core Thing that will allow this sample to run as intended. - -
-(see sample policy) -
-{
-  "Version": "2012-10-17",
-  "Statement": [
-    {
-      "Effect": "Allow",
-      "Action": [
-        "iot:Publish",
-        "iot:Receive"
-      ],
-      "Resource": [
-        "arn:aws:iot:region:account:topic/test/topic"
-      ]
-    },
-    {
-      "Effect": "Allow",
-      "Action": [
-        "iot:Subscribe"
-      ],
-      "Resource": [
-        "arn:aws:iot:region:account:topicfilter/test/topic"
-      ]
-    },
-    {
-      "Effect": "Allow",
-      "Action": [
-        "iot:Connect"
-      ],
-      "Resource": [
-        "arn:aws:iot:region:account:client/test-*"
-      ]
-    }
-  ]
-}
-
- -Replace with the following with the data from your AWS account: -* ``: The AWS IoT Core region where you created your AWS IoT Core thing you wish to use with this sample. For example `us-east-1`. -* ``: Your AWS IoT Core account ID. This is the set of numbers in the top right next to your AWS account name when using the AWS IoT Core website. - -Note that in a real application, you may want to avoid the use of wildcards in your ClientID or use them selectively. Please follow best practices when working with AWS on production applications using the SDK. Also, for the purposes of this sample, please make sure your policy allows a client ID of `test-*` to connect or use `--client_id ` to send the client ID your policy supports. - -
- -## How to run - -### Direct MQTT via mTLS - -To Run this sample using a direct MQTT connection with a key and certificate, go to the `node/pub_sub_mqtt5` folder and run the following commands: - -``` sh -npm install -node dist/index.js --endpoint --cert --key -``` - -You can also pass a Certificate Authority file (CA) if your certificate and key combination requires it: - -``` sh -npm install -node dist/index.js --endpoint --cert --key --ca_file -``` - -### Websockets - -To Run this sample using Websockets, go to the `node/pub_sub_mqtt5` folder and run the follow commands: - -``` sh -npm install -node dist/index.js --endpoint --region -``` - -Note that to run this sample using Websockets, you will need to set your AWS credentials in your environment variables or local files. See the [authorizing direct AWS](https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html) page for documentation on how to get the AWS credentials, which then you can set to the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` environment variables. - -## Alternate Connection Configuration Methods supported by AWS IoT Core -We strongly recommend using the AwsIotMqtt5ClientConfigBuilder class to configure MQTT5 clients when connecting to AWS IoT Core. The builder -simplifies configuration for all authentication methods supported by AWS IoT Core. This section shows samples for all authentication -possibilities. - -### Authentication Methods -* [Direct MQTT with X509-based mutual TLS](#direct-mqtt-with-x509-based-mutual-tls) -* [MQTT over Websockets with Sigv4 authentication](#mqtt-over-websockets-with-sigv4-authentication) -* [Direct MQTT with Custom Authentication](#direct-mqtt-with-custom-authentication) -* [Direct MQTT with PKCS11](#direct-mqtt-with-pkcs11-method) -* [Direct MQTT with PKCS12](#direct-mqtt-with-pkcs12-method) -### HTTP Proxy -* [Adding an HTTP Proxy](#adding-an-http-proxy) - -#### Direct MQTT with X509-based mutual TLS -For X509 based mutual TLS, you can create a client where the certificate and private key are configured by path: - -```typescript - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPath( - , - , - - ); - - // other builder configuration - // ... - let client : Mqtt5Client = new Mqtt5Client(builder.build())); -``` - -You can also create a client where the certificate and private key are in memory: - -```typescript - let cert = fs.readFileSync(,'utf8'); - let key = fs.readFileSync(,'utf8'); - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromMemory( - , - cert, - key - ); - - // other builder configuration - // ... - let client : Mqtt5Client = new Mqtt5Client(builder.build()); -``` - -#### MQTT over Websockets with Sigv4 authentication -Sigv4-based authentication requires a credentials provider capable of sourcing valid AWS credentials. Sourced credentials -will sign the websocket upgrade request made by the client while connecting. The default credentials provider chain supported by -the SDK is capable of resolving credentials in a variety of environments according to a chain of priorities: - -``` - Environment -> Profile (local file system) -> STS Web Identity -> IMDS (ec2) or ECS -``` - -If the default credentials provider chain and built-in AWS region extraction logic are sufficient, you do not need to specify -any additional configuration: - -```typescript - let builder = AwsIotMqtt5ClientConfigBuilder.newWebsocketMqttBuilderWithSigv4Auth( - - ); - // other builder configuration - // ... - let client : Mqtt5Client = new Mqtt5Client(builder.build()); -``` - -Alternatively, if you're connecting to a special region for which standard pattern matching does not work, or if you -need a specific credentials provider, you can specify advanced websocket configuration options. - -```typescript - // sourcing credentials from the Cognito service in this example - let cognitoConfig: CognitoCredentialsProviderConfig = { - endpoint: "", - identity: "" - }; - - let overrideProvider: CredentialsProvider = AwsCredentialsProvider.newCognito(cognitoConfig); - - let wsConfig : WebsocketSigv4Config = { - credentialsProvider: overrideProvider, - region: "" - }; - - let builder = AwsIotMqtt5ClientConfigBuilder.newWebsocketMqttBuilderWithSigv4Auth( - "", - wsConfig - ); - // other builder configuration - // ... - let client : Mqtt5Client = new Mqtt5Client(builder.build()); -``` - -#### Direct MQTT with Custom Authentication -AWS IoT Core Custom Authentication allows you to use a lambda to gate access to IoT Core resources. For this authentication method, -you must supply an additional configuration structure containing fields relevant to AWS IoT Core Custom Authentication. - -If your custom authenticator does not use signing, you don't specify anything related to the token signature: - -```typescript - let customAuthConfig : MqttConnectCustomAuthConfig = { - authorizerName: "", - username: "", - password: - }; - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithCustomAuth( - "", - customAuthConfig - ); - let client : Mqtt5Client = new mqtt5.Mqtt5Client(builder.build()); -``` - -If your custom authorizer uses signing, you must specify the three signed token properties as well. The token signature must be -the URI-encoding of the base64 encoding of the digital signature of the token value via the private key associated with the public key -that was registered with the custom authorizer. It is your responsibility to URI-encode the token signature. - -```typescript - let customAuthConfig : MqttConnectCustomAuthConfig = { - authorizerName: "", - username: "", - password: , - tokenKeyName: "", - tokenValue: "", - tokenSignature: "" - }; - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithCustomAuth( - "", - customAuthConfig - ); - let client : Mqtt5Client = new mqtt5.Mqtt5Client(builder.build()); -``` - -In both cases, the builder will construct a final CONNECT packet username field value for you based on the values configured. Do not add the -token-signing fields to the value of the username that you assign within the custom authentication config structure. Similarly, do not -add any custom authentication related values to the username in the CONNECT configuration optionally attached to the client configuration. -The builder will do everything for you. - -#### Direct MQTT with PKCS11 Method - -A MQTT5 direct connection can be made using a PKCS11 device rather than using a PEM encoded private key, the private key for mutual TLS is stored on a PKCS#11 compatible smart card or Hardware Security Module (HSM). To create a MQTT5 builder configured for this connection, see the following code: - -```typescript - let pkcs11Options : Pkcs11Options = { - pkcs11_lib: "", - user_pin: "", - slot_id: "", - token_label: "", - private_key_object_label: "", - cert_file_path: "", - cert_file_contents: "" - }; - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPkcs11( - "", - pkcs11Options - ); - let client : Mqtt5Client = new mqtt5.Mqtt5Client(builder.build()); -``` - -Note: Currently, TLS integration with PKCS#11 is only available on Unix devices. - -#### Direct MQTT with PKCS12 Method - -A MQTT5 direct connection can be made using a PKCS12 file rather than using a PEM encoded private key. To create a MQTT5 builder configured for this connection, see the following code: - -```typescript - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPkcs12( - "", - "", - "" - ); - let client : Mqtt5Client = new mqtt5.Mqtt5Client(builder.build()); -``` - -Note: Currently, TLS integration with PKCS#12 is only available on MacOS devices. - -### Adding An HTTP Proxy -No matter what your connection transport or authentication method is, you may connect through an HTTP proxy -by applying proxy configuration to the builder: - -```typescript - let builder = AwsIoTMqtt5ClientConfigBuilder.(...); - let proxyOptions : HttpProxyOptions = new HttpProxyOptions("", ); - builder.withHttpProxyOptions(proxyOptions); - - let client : Mqtt5Client = new Mqtt5Client(builder.build()); -``` - -SDK Proxy support also includes support for basic authentication and TLS-to-proxy. SDK proxy support does not include any additional -proxy authentication methods (kerberos, NTLM, etc...) nor does it include non-HTTP proxies (SOCKS5, for example). - -## ⚠️ Usage disclaimer - -These code examples interact with services that may incur charges to your AWS account. For more information, see [AWS Pricing](https://aws.amazon.com/pricing/). - -Additionally, example code might theoretically modify or delete existing AWS resources. As a matter of due diligence, do the following: - -- Be aware of the resources that these examples create or delete. -- Be aware of the costs that might be charged to your account as a result. -- Back up your important data. \ No newline at end of file diff --git a/samples/node/pub_sub/index.ts b/samples/node/pub_sub/index.ts deleted file mode 100644 index 1aa1127e..00000000 --- a/samples/node/pub_sub/index.ts +++ /dev/null @@ -1,198 +0,0 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -import {mqtt5, iot} from "aws-iot-device-sdk-v2"; -import {ICrtError} from "aws-crt"; -import {once} from "events"; -import { toUtf8 } from '@aws-sdk/util-utf8-browser'; - -type Args = { [index: string]: any }; - -const yargs = require('yargs'); - -yargs.command('*', false, (yargs: any) => { - yargs.option('endpoint', { - alias: 'e', - description: 'Your AWS IoT custom endpoint, not including a port.', - type: 'string', - required: true - }) - .option('cert', { - alias: 'c', - description: ': File path to a PEM encoded certificate to use with mTLS.', - type: 'string', - required: false - }) - .option('key', { - alias: 'k', - description: ': File path to a PEM encoded private key that matches cert.', - type: 'string', - required: false - }) - .option('region', { - alias: 'r', - description: 'AWS region to establish a websocket connection to. Only required if using websockets and a non-standard endpoint.', - type: 'string', - required: false - }) - .option('client_id', { - alias: 'C', - description: 'Client ID for MQTT connection.', - type: 'string', - required: false - }) - .option('ca_file', { - description: ': File path to a Root CA certificate file in PEM format (optional, system trust store used by default).', - type: 'string', - required: false - }) -}, main).parse(); - -function createClientConfig(args : any) : mqtt5.Mqtt5ClientConfig { - let builder : iot.AwsIotMqtt5ClientConfigBuilder | undefined = undefined; - - if (args.key && args.cert) { - builder = iot.AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPath( - args.endpoint, - args.cert, - args.key - ); - } else { - let wsOptions : iot.WebsocketSigv4Config | undefined = undefined; - if (args.region) { - wsOptions = { region: args.region }; - } - - builder = iot.AwsIotMqtt5ClientConfigBuilder.newWebsocketMqttBuilderWithSigv4Auth( - args.endpoint, - // the region extraction logic does not work for gamma endpoint formats so pass in region manually - wsOptions - ); - } - - - if (args.ca_file) { - builder.withCertificateAuthorityFromPath(undefined, args.ca_file); - } - - builder.withConnectProperties({ - clientId: args.client_id || "test-" + Math.floor(Math.random() * 100000000), - keepAliveIntervalSeconds: 1200 - }); - - return builder.build(); -} - -function createClient(args: any) : mqtt5.Mqtt5Client { - - let config : mqtt5.Mqtt5ClientConfig = createClientConfig(args); - - console.log("Creating client for " + config.hostName); - let client : mqtt5.Mqtt5Client = new mqtt5.Mqtt5Client(config); - - client.on('error', (error: ICrtError) => { - console.log("Error event: " + error.toString()); - }); - - client.on("messageReceived",(eventData: mqtt5.MessageReceivedEvent) : void => { - console.log("Message Received event: " + JSON.stringify(eventData.message)); - if (eventData.message.payload) { - console.log(" with payload: " + toUtf8(new Uint8Array(eventData.message.payload as ArrayBuffer))); - } - } ); - - client.on('attemptingConnect', (eventData: mqtt5.AttemptingConnectEvent) => { - console.log("Attempting Connect event"); - }); - - client.on('connectionSuccess', (eventData: mqtt5.ConnectionSuccessEvent) => { - console.log("Connection Success event"); - console.log ("Connack: " + JSON.stringify(eventData.connack)); - console.log ("Settings: " + JSON.stringify(eventData.settings)); - }); - - client.on('connectionFailure', (eventData: mqtt5.ConnectionFailureEvent) => { - console.log("Connection failure event: " + eventData.error.toString()); - if (eventData.connack) { - console.log ("Connack: " + JSON.stringify(eventData.connack)); - } - }); - - client.on('disconnection', (eventData: mqtt5.DisconnectionEvent) => { - console.log("Disconnection event: " + eventData.error.toString()); - if (eventData.disconnect !== undefined) { - console.log('Disconnect packet: ' + JSON.stringify(eventData.disconnect)); - } - }); - - client.on('stopped', (eventData: mqtt5.StoppedEvent) => { - console.log("Stopped event"); - }); - - return client; -} - -async function runSample(args : any) { - - let client : mqtt5.Mqtt5Client = createClient(args); - - const connectionSuccess = once(client, "connectionSuccess"); - - client.start(); - - await connectionSuccess; - - const suback = await client.subscribe({ - subscriptions: [ - { qos: mqtt5.QoS.AtLeastOnce, topicFilter: "hello/world/qos1" }, - { qos: mqtt5.QoS.AtMostOnce, topicFilter: "hello/world/qos0" } - ] - }); - console.log('Suback result: ' + JSON.stringify(suback)); - - const qos0PublishResult = await client.publish({ - qos: mqtt5.QoS.AtMostOnce, - topicName: "hello/world/qos0", - payload: JSON.stringify("This is a qos 0 payload"), - userProperties: [ - {name: "test", value: "userproperty"} - ] - }); - console.log('QoS 0 Publish result: ' + JSON.stringify(qos0PublishResult)); - - const qos1PublishResult = await client.publish({ - qos: mqtt5.QoS.AtLeastOnce, - topicName: "hello/world/qos1", - payload: JSON.stringify("This is a qos 1 payload") - }); - console.log('QoS 1 Publish result: ' + JSON.stringify(qos1PublishResult)); - - let unsuback = await client.unsubscribe({ - topicFilters: [ - "hello/world/qos1" - ] - }); - console.log('Unsuback result: ' + JSON.stringify(unsuback)); - - const stopped = once(client, "stopped"); - - client.stop(); - - await stopped; - - client.close(); -} - -async function main(args : Args){ - // make it wait as long as possible once the promise completes we'll turn it off. - const timer = setTimeout(() => {}, 2147483647); - - await runSample(args); - - clearTimeout(timer); - - process.exit(0); -} - diff --git a/samples/node/pub_sub/package.json b/samples/node/pub_sub/package.json deleted file mode 100644 index acd59071..00000000 --- a/samples/node/pub_sub/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "pub-sub-mqtt5", - "version": "1.0.0", - "description": "NodeJS IoT SDK v2 MQTT5 Pub Sub Sample", - "homepage": "https://github.com/aws/aws-iot-device-sdk-js-v2", - "repository": { - "type": "git", - "url": "git+https://github.com/aws/aws-iot-device-sdk-js-v2.git" - }, - "contributors": [ - "AWS SDK Common Runtime Team " - ], - "license": "Apache-2.0", - "main": "./dist/index.js", - "scripts": { - "tsc": "tsc", - "prepare": "npm run tsc" - }, - "devDependencies": { - "@types/node": "^10.17.50", - "typescript": "^4.7.4" - }, - "dependencies": { - "aws-iot-device-sdk-v2": "file:../../..", - "yargs": "^16.2.0" - } -} diff --git a/samples/node/pub_sub/tsconfig.json b/samples/node/pub_sub/tsconfig.json deleted file mode 100644 index 92617173..00000000 --- a/samples/node/pub_sub/tsconfig.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "compilerOptions": { - /* Basic Options */ - "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ - // "lib": [], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ - "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "./dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "removeComments": false, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - "strictNullChecks": true, /* Enable strict null checks. */ - "strictFunctionTypes": true, /* Enable strict checking of function types. */ - "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - /* Additional Checks */ - "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - /* Experimental Options */ - // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - }, - "include": [ - "*.ts" - ], - "exclude": [ - "node_modules", - "dist" - ] -} \ No newline at end of file diff --git a/samples/node/pub_sub_electron_node/README.md b/samples/node/pub_sub_electron_node/README.md index 64f9343e..cc7e657e 100644 --- a/samples/node/pub_sub_electron_node/README.md +++ b/samples/node/pub_sub_electron_node/README.md @@ -2,9 +2,6 @@ [**Return to main sample list**](../../README.md) -# NOTE: The sample is affected by Electron vulnerability: https://debricked.com/vulnerability-database/vulnerability/CVE-2023-5217. Electron support would be updated in future versions. - - This sample uses the [Message Broker](https://docs.aws.amazon.com/iot/latest/developerguide/iot-message-broker.html) for AWS IoT to send and receive messages through an MQTT connection using MQTT5. diff --git a/samples/node/pub_sub_mqtt5/README.md b/samples/node/pub_sub_mqtt5/README.md deleted file mode 100644 index e6dd1a12..00000000 --- a/samples/node/pub_sub_mqtt5/README.md +++ /dev/null @@ -1,285 +0,0 @@ -# Node: MQTT5 PubSub - -[**Return to main sample list**](../../README.md) - -This sample uses the -[Message Broker](https://docs.aws.amazon.com/iot/latest/developerguide/iot-message-broker.html) -for AWS IoT to send and receive messages through an MQTT connection using MQTT5. - -MQTT5 introduces additional features and enhancements that improve the development experience with MQTT. You can read more about MQTT5 in the Java V2 SDK by checking out the [MQTT5 user guide](https://github.com/awslabs/aws-crt-nodejs/blob/main/MQTT5-UserGuide.md). - -Your IoT Core Thing's [Policy](https://docs.aws.amazon.com/iot/latest/developerguide/iot-policies.html) must provide privileges for this sample to connect, subscribe, publish, and receive. Below is a sample policy that can be used on your IoT Core Thing that will allow this sample to run as intended. - -
-(see sample policy) -
-{
-  "Version": "2012-10-17",
-  "Statement": [
-    {
-      "Effect": "Allow",
-      "Action": [
-        "iot:Publish",
-        "iot:Receive"
-      ],
-      "Resource": [
-        "arn:aws:iot:region:account:topic/test/topic"
-      ]
-    },
-    {
-      "Effect": "Allow",
-      "Action": [
-        "iot:Subscribe"
-      ],
-      "Resource": [
-        "arn:aws:iot:region:account:topicfilter/test/topic"
-      ]
-    },
-    {
-      "Effect": "Allow",
-      "Action": [
-        "iot:Connect"
-      ],
-      "Resource": [
-        "arn:aws:iot:region:account:client/test-*"
-      ]
-    }
-  ]
-}
-
- -Replace with the following with the data from your AWS account: -* ``: The AWS IoT Core region where you created your AWS IoT Core thing you wish to use with this sample. For example `us-east-1`. -* ``: Your AWS IoT Core account ID. This is the set of numbers in the top right next to your AWS account name when using the AWS IoT Core website. - -Note that in a real application, you may want to avoid the use of wildcards in your ClientID or use them selectively. Please follow best practices when working with AWS on production applications using the SDK. Also, for the purposes of this sample, please make sure your policy allows a client ID of `test-*` to connect or use `--client_id ` to send the client ID your policy supports. - -
- -## How to run - -### Direct MQTT via mTLS - -To Run this sample using a direct MQTT connection with a key and certificate, go to the `node/pub_sub_mqtt5` folder and run the following commands: - -``` sh -npm install -node dist/index.js --endpoint --cert --key -``` - -You can also pass a Certificate Authority file (CA) if your certificate and key combination requires it: - -``` sh -npm install -node dist/index.js --endpoint --cert --key --ca_file -``` - -### Websockets - -To Run this sample using Websockets, go to the `node/pub_sub_mqtt5` folder and run the follow commands: - -``` sh -npm install -node dist/index.js --endpoint --region -``` - -Note that to run this sample using Websockets, you will need to set your AWS credentials in your environment variables or local files. See the [authorizing direct AWS](https://docs.aws.amazon.com/iot/latest/developerguide/authorizing-direct-aws.html) page for documentation on how to get the AWS credentials, which then you can set to the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` environment variables. - -## Alternate Connection Configuration Methods supported by AWS IoT Core -We strongly recommend using the AwsIotMqtt5ClientConfigBuilder class to configure MQTT5 clients when connecting to AWS IoT Core. The builder -simplifies configuration for all authentication methods supported by AWS IoT Core. This section shows samples for all authentication -possibilities. - -### Authentication Methods -* [Direct MQTT with X509-based mutual TLS](#direct-mqtt-with-x509-based-mutual-tls) -* [MQTT over Websockets with Sigv4 authentication](#mqtt-over-websockets-with-sigv4-authentication) -* [Direct MQTT with Custom Authentication](#direct-mqtt-with-custom-authentication) -* [Direct MQTT with PKCS11](#direct-mqtt-with-pkcs11-method) -* [Direct MQTT with PKCS12](#direct-mqtt-with-pkcs12-method) -### HTTP Proxy -* [Adding an HTTP Proxy](#adding-an-http-proxy) - -#### Direct MQTT with X509-based mutual TLS -For X509 based mutual TLS, you can create a client where the certificate and private key are configured by path: - -```typescript - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPath( - , - , - - ); - - // other builder configuration - // ... - let client : Mqtt5Client = new Mqtt5Client(builder.build())); -``` - -You can also create a client where the certificate and private key are in memory: - -```typescript - let cert = fs.readFileSync(,'utf8'); - let key = fs.readFileSync(,'utf8'); - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromMemory( - , - cert, - key - ); - - // other builder configuration - // ... - let client : Mqtt5Client = new Mqtt5Client(builder.build()); -``` - -#### MQTT over Websockets with Sigv4 authentication -Sigv4-based authentication requires a credentials provider capable of sourcing valid AWS credentials. Sourced credentials -will sign the websocket upgrade request made by the client while connecting. The default credentials provider chain supported by -the SDK is capable of resolving credentials in a variety of environments according to a chain of priorities: - -``` - Environment -> Profile (local file system) -> STS Web Identity -> IMDS (ec2) or ECS -``` - -If the default credentials provider chain and built-in AWS region extraction logic are sufficient, you do not need to specify -any additional configuration: - -```typescript - let builder = AwsIotMqtt5ClientConfigBuilder.newWebsocketMqttBuilderWithSigv4Auth( - - ); - // other builder configuration - // ... - let client : Mqtt5Client = new Mqtt5Client(builder.build()); -``` - -Alternatively, if you're connecting to a special region for which standard pattern matching does not work, or if you -need a specific credentials provider, you can specify advanced websocket configuration options. - -```typescript - // sourcing credentials from the Cognito service in this example - let cognitoConfig: CognitoCredentialsProviderConfig = { - endpoint: "", - identity: "" - }; - - let overrideProvider: CredentialsProvider = AwsCredentialsProvider.newCognito(cognitoConfig); - - let wsConfig : WebsocketSigv4Config = { - credentialsProvider: overrideProvider, - region: "" - }; - - let builder = AwsIotMqtt5ClientConfigBuilder.newWebsocketMqttBuilderWithSigv4Auth( - "", - wsConfig - ); - // other builder configuration - // ... - let client : Mqtt5Client = new Mqtt5Client(builder.build()); -``` - -#### Direct MQTT with Custom Authentication -AWS IoT Core Custom Authentication allows you to use a lambda to gate access to IoT Core resources. For this authentication method, -you must supply an additional configuration structure containing fields relevant to AWS IoT Core Custom Authentication. - -If your custom authenticator does not use signing, you don't specify anything related to the token signature: - -```typescript - let customAuthConfig : MqttConnectCustomAuthConfig = { - authorizerName: "", - username: "", - password: - }; - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithCustomAuth( - "", - customAuthConfig - ); - let client : Mqtt5Client = new mqtt5.Mqtt5Client(builder.build()); -``` - -If your custom authorizer uses signing, you must specify the three signed token properties as well. The token signature must be -the URI-encoding of the base64 encoding of the digital signature of the token value via the private key associated with the public key -that was registered with the custom authorizer. It is your responsibility to URI-encode the token signature. - -```typescript - let customAuthConfig : MqttConnectCustomAuthConfig = { - authorizerName: "", - username: "", - password: , - tokenKeyName: "", - tokenValue: "", - tokenSignature: "" - }; - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithCustomAuth( - "", - customAuthConfig - ); - let client : Mqtt5Client = new mqtt5.Mqtt5Client(builder.build()); -``` - -In both cases, the builder will construct a final CONNECT packet username field value for you based on the values configured. Do not add the -token-signing fields to the value of the username that you assign within the custom authentication config structure. Similarly, do not -add any custom authentication related values to the username in the CONNECT configuration optionally attached to the client configuration. -The builder will do everything for you. - -#### Direct MQTT with PKCS11 Method - -A MQTT5 direct connection can be made using a PKCS11 device rather than using a PEM encoded private key, the private key for mutual TLS is stored on a PKCS#11 compatible smart card or Hardware Security Module (HSM). To create a MQTT5 builder configured for this connection, see the following code: - -```typescript - let pkcs11Options : Pkcs11Options = { - pkcs11_lib: "", - user_pin: "", - slot_id: "", - token_label: "", - private_key_object_label: "", - cert_file_path: "", - cert_file_contents: "" - }; - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPkcs11( - "", - pkcs11Options - ); - let client : Mqtt5Client = new mqtt5.Mqtt5Client(builder.build()); -``` - -Note: Currently, TLS integration with PKCS#11 is only available on Unix devices. - -#### Direct MQTT with PKCS12 Method - -A MQTT5 direct connection can be made using a PKCS12 file rather than using a PEM encoded private key. To create a MQTT5 builder configured for this connection, see the following code: - -```typescript - let builder = AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPkcs12( - "", - "", - "" - ); - let client : Mqtt5Client = new mqtt5.Mqtt5Client(builder.build()); -``` - -Note: Currently, TLS integration with PKCS#12 is only available on MacOS devices. - -### Adding An HTTP Proxy -No matter what your connection transport or authentication method is, you may connect through an HTTP proxy -by applying proxy configuration to the builder: - -```typescript - let builder = AwsIoTMqtt5ClientConfigBuilder.(...); - let proxyOptions : HttpProxyOptions = new HttpProxyOptions("", ); - builder.withHttpProxyOptions(proxyOptions); - - let client : Mqtt5Client = new Mqtt5Client(builder.build()); -``` - -SDK Proxy support also includes support for basic authentication and TLS-to-proxy. SDK proxy support does not include any additional -proxy authentication methods (kerberos, NTLM, etc...) nor does it include non-HTTP proxies (SOCKS5, for example). - -## ⚠️ Usage disclaimer - -These code examples interact with services that may incur charges to your AWS account. For more information, see [AWS Pricing](https://aws.amazon.com/pricing/). - -Additionally, example code might theoretically modify or delete existing AWS resources. As a matter of due diligence, do the following: - -- Be aware of the resources that these examples create or delete. -- Be aware of the costs that might be charged to your account as a result. -- Back up your important data. \ No newline at end of file diff --git a/samples/node/pub_sub_mqtt5/index.ts b/samples/node/pub_sub_mqtt5/index.ts deleted file mode 100644 index 5bf57213..00000000 --- a/samples/node/pub_sub_mqtt5/index.ts +++ /dev/null @@ -1,189 +0,0 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -import {mqtt5, iot} from "aws-iot-device-sdk-v2"; -import {ICrtError} from "aws-crt"; -import {once} from "events"; -import { toUtf8 } from '@aws-sdk/util-utf8-browser'; - -type Args = { [index: string]: any }; - -const yargs = require('yargs'); - -yargs.command('*', false, (yargs: any) => { - yargs.option('endpoint', { - alias: 'e', - description: 'Your AWS IoT custom endpoint, not including a port.', - type: 'string', - required: true - }) - .option('cert', { - alias: 'c', - description: ': File path to a PEM encoded certificate to use with mTLS.', - type: 'string', - required: false - }) - .option('key', { - alias: 'k', - description: ': File path to a PEM encoded private key that matches cert.', - type: 'string', - required: false - }) - .option('region', { - alias: 'r', - description: 'AWS region to establish a websocket connection to. Only required if using websockets and a non-standard endpoint.', - type: 'string', - required: false - }) - .option('client_id', { - alias: 'C', - description: 'Client ID for MQTT connection.', - type: 'string', - required: false - }) -}, main).parse(); - -function createClientConfig(args : any) : mqtt5.Mqtt5ClientConfig { - let builder : iot.AwsIotMqtt5ClientConfigBuilder | undefined = undefined; - - if (args.key && args.cert) { - builder = iot.AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPath( - args.endpoint, - args.cert, - args.key - ); - } else { - let wsOptions : iot.WebsocketSigv4Config | undefined = undefined; - if (args.region) { - wsOptions = { region: args.region }; - } - - builder = iot.AwsIotMqtt5ClientConfigBuilder.newWebsocketMqttBuilderWithSigv4Auth( - args.endpoint, - // the region extraction logic does not work for gamma endpoint formats so pass in region manually - wsOptions - ); - } - - - builder.withConnectProperties({ - clientId: args.client_id || "test-" + Math.floor(Math.random() * 100000000), - keepAliveIntervalSeconds: 1200 - }); - - return builder.build(); -} - -function createClient(args: any) : mqtt5.Mqtt5Client { - - let config : mqtt5.Mqtt5ClientConfig = createClientConfig(args); - - console.log("Creating client for " + config.hostName); - let client : mqtt5.Mqtt5Client = new mqtt5.Mqtt5Client(config); - - client.on('error', (error: ICrtError) => { - console.log("Error event: " + error.toString()); - }); - - client.on("messageReceived",(eventData: mqtt5.MessageReceivedEvent) : void => { - console.log("Message Received event: " + JSON.stringify(eventData.message)); - if (eventData.message.payload) { - console.log(" with payload: " + toUtf8(new Uint8Array(eventData.message.payload as ArrayBuffer))); - } - } ); - - client.on('attemptingConnect', (eventData: mqtt5.AttemptingConnectEvent) => { - console.log("Attempting Connect event"); - }); - - client.on('connectionSuccess', (eventData: mqtt5.ConnectionSuccessEvent) => { - console.log("Connection Success event"); - console.log ("Connack: " + JSON.stringify(eventData.connack)); - console.log ("Settings: " + JSON.stringify(eventData.settings)); - }); - - client.on('connectionFailure', (eventData: mqtt5.ConnectionFailureEvent) => { - console.log("Connection failure event: " + eventData.error.toString()); - if (eventData.connack) { - console.log ("Connack: " + JSON.stringify(eventData.connack)); - } - }); - - client.on('disconnection', (eventData: mqtt5.DisconnectionEvent) => { - console.log("Disconnection event: " + eventData.error.toString()); - if (eventData.disconnect !== undefined) { - console.log('Disconnect packet: ' + JSON.stringify(eventData.disconnect)); - } - }); - - client.on('stopped', (eventData: mqtt5.StoppedEvent) => { - console.log("Stopped event"); - }); - - return client; -} - -async function runSample(args : any) { - - let client : mqtt5.Mqtt5Client = createClient(args); - - const connectionSuccess = once(client, "connectionSuccess"); - - client.start(); - - await connectionSuccess; - - const suback = await client.subscribe({ - subscriptions: [ - { qos: mqtt5.QoS.AtLeastOnce, topicFilter: "hello/world/qos1" }, - { qos: mqtt5.QoS.AtMostOnce, topicFilter: "hello/world/qos0" } - ] - }); - console.log('Suback result: ' + JSON.stringify(suback)); - - const qos0PublishResult = await client.publish({ - qos: mqtt5.QoS.AtMostOnce, - topicName: "hello/world/qos0", - payload: JSON.stringify("This is a qos 0 payload"), - userProperties: [ - {name: "test", value: "userproperty"} - ] - }); - console.log('QoS 0 Publish result: ' + JSON.stringify(qos0PublishResult)); - - const qos1PublishResult = await client.publish({ - qos: mqtt5.QoS.AtLeastOnce, - topicName: "hello/world/qos1", - payload: JSON.stringify("This is a qos 1 payload") - }); - console.log('QoS 1 Publish result: ' + JSON.stringify(qos1PublishResult)); - - let unsuback = await client.unsubscribe({ - topicFilters: [ - "hello/world/qos1" - ] - }); - console.log('Unsuback result: ' + JSON.stringify(unsuback)); - - const stopped = once(client, "stopped"); - - client.stop(); - - await stopped; - - client.close(); -} - -async function main(args : Args){ - // make it wait as long as possible once the promise completes we'll turn it off. - const timer = setTimeout(() => {}, 2147483647); - - await runSample(args); - - clearTimeout(timer); - - process.exit(0); -} - diff --git a/samples/node/pub_sub_mqtt5/package.json b/samples/node/pub_sub_mqtt5/package.json deleted file mode 100644 index acd59071..00000000 --- a/samples/node/pub_sub_mqtt5/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "pub-sub-mqtt5", - "version": "1.0.0", - "description": "NodeJS IoT SDK v2 MQTT5 Pub Sub Sample", - "homepage": "https://github.com/aws/aws-iot-device-sdk-js-v2", - "repository": { - "type": "git", - "url": "git+https://github.com/aws/aws-iot-device-sdk-js-v2.git" - }, - "contributors": [ - "AWS SDK Common Runtime Team " - ], - "license": "Apache-2.0", - "main": "./dist/index.js", - "scripts": { - "tsc": "tsc", - "prepare": "npm run tsc" - }, - "devDependencies": { - "@types/node": "^10.17.50", - "typescript": "^4.7.4" - }, - "dependencies": { - "aws-iot-device-sdk-v2": "file:../../..", - "yargs": "^16.2.0" - } -} diff --git a/samples/node/pub_sub_mqtt5/tsconfig.json b/samples/node/pub_sub_mqtt5/tsconfig.json deleted file mode 100644 index 92617173..00000000 --- a/samples/node/pub_sub_mqtt5/tsconfig.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "compilerOptions": { - /* Basic Options */ - "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ - // "lib": [], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ - "declaration": true, /* Generates corresponding '.d.ts' file. */ - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "./dist", /* Redirect output structure to the directory. */ - // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "removeComments": false, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ - "strictNullChecks": true, /* Enable strict null checks. */ - "strictFunctionTypes": true, /* Enable strict checking of function types. */ - "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - /* Additional Checks */ - "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - // "types": [], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - /* Experimental Options */ - // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - }, - "include": [ - "*.ts" - ], - "exclude": [ - "node_modules", - "dist" - ] -} \ No newline at end of file diff --git a/samples/util/cli_args.js b/samples/util/cli_args.js deleted file mode 100644 index 636753ac..00000000 --- a/samples/util/cli_args.js +++ /dev/null @@ -1,478 +0,0 @@ -/** - * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. - * SPDX-License-Identifier: Apache-2.0. - */ - -/* - * The 'aws-iot-device-sdk-v2' module exports the same set of mqtt/http/io primitives as the crt, but - * it is not importable from this file based on js module resolution rules (because this file is sitting off - * in shared la-la-land) which walk up the directory tree from the file itself. - * - * So use the aws-crt interfaces directly, but a real application that was rooted in a single place could - * naturally use something like - * - * const iotsdk = require('aws-iot-device-sdk-v2') - * const auth = iotsdk.auth; - * etc... - * - */ -const awscrt = require('aws-crt'); -const auth = awscrt.auth; -const http = awscrt.http; -const io = awscrt.io; -const iot = awscrt.iot; -const mqtt = awscrt.mqtt; -const mqtt5 = awscrt.mqtt5; - -/* - * Arguments that control how the sample should establish its mqtt connection(s). - * Adds arguments for direct MQTT connections and websocket connections - */ -function add_connection_establishment_arguments(yargs) { - add_universal_arguments(yargs); - add_common_mqtt_arguments(yargs); - add_direct_tls_connect_arguments(yargs); - add_proxy_arguments(yargs); - add_common_websocket_arguments(yargs); -} - -/* - * Adds arguments that allow for easy direct MQTT connections. - */ -function add_direct_connection_establishment_arguments(yargs) { - add_universal_arguments(yargs); - add_common_mqtt_arguments(yargs); - add_direct_tls_connect_arguments(yargs); - add_proxy_arguments(yargs); -} - -/* - * Adds universal arguments every sample should have (help and logging verbosity) - */ -function add_universal_arguments(yargs) { - yargs - .option('verbosity', { - alias: 'v', - description: 'The amount of detail in the logging output of the sample (optional).', - type: 'string', - default: 'none', - choices: ['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'none'] - }) - .option('is_ci', { - description: 'Launches the sample in CI mode (optional, set as anything to enable)', - type: 'boolean', - default: false - }) - .help() - .alias('help', 'h') - .showHelpOnFail(false) -} - -/* - * Common MQTT arguments needed for making a connection - */ -function add_common_mqtt_arguments(yargs) { - yargs - .option('endpoint', { - alias: 'e', - description: ': Your AWS IoT custom endpoint, not including a port.', - type: 'string', - required: true - }) - .option('ca_file', { - alias: 'r', - description: ': File path to a Root CA certificate file in PEM format (optional, system trust store used by default).', - type: 'string', - required: false - }) - .option('client_id', { - alias: 'C', - description: 'Client ID for MQTT connection.', - type: 'string', - required: false - }) - .option('mqtt_version', { - alias: 'V', - default: 3, - description: 'MQTT version to use.', - type: 'number', - required: false - }) -} - -/* - * Common MQTT arguments needed for making a connection - */ -function add_direct_tls_connect_arguments(yargs, is_required=false) { - yargs - .option('cert', { - alias: 'c', - description: ': File path to a PEM encoded certificate to use with mTLS.', - type: 'string', - required: is_required - }) - .option('key', { - alias: 'k', - description: ': File path to a PEM encoded private key that matches cert.', - type: 'string', - required: is_required - }) -} - -/* - * Proxy arguments - */ -function add_proxy_arguments(yargs) { - yargs - .option('proxy_host', { - alias: 'H', - description: 'Hostname of the proxy to connect to (optional, required if --proxy_port is set).', - type: 'string', - required: false - }) - .option('proxy_port', { - alias: 'P', - default: 8080, - description: 'Port of the proxy to connect to (optional, required if --proxy_host is set).', - type: 'number', - required: false - }) -} - -/* - * Common Websocket arguments needed for making a connection - */ -function add_common_websocket_arguments(yargs, is_required=false) { - yargs - .option('signing_region', { - alias: ['s', 'region'], - description: 'If you specify --signing_region then you will use websockets to connect. This' + - 'is the region that will be used for computing the Sigv4 signature. This region must match the' + - 'AWS region in your endpoint.', - type: 'string', - required: is_required - }) -} - -/* - * Arguments specific to sending a message to a topic multiple times. We have multiple samples that use these arguments. - */ -function add_topic_message_arguments(yargs) { - yargs - .option('topic', { - alias: 't', - description: 'Topic to publish to (optional).', - type: 'string', - default: 'test/topic' - }) - .option('count', { - alias: 'n', - default: 10, - description: 'Number of messages to publish/receive before exiting. ' + - 'Specify 0 to run forever (optional).', - type: 'number', - required: false - }) - .option('message', { - alias: 'M', - description: 'Message to publish (optional).', - type: 'string', - default: 'Hello world!' - }) -} - -/* - * Arguments specific to the shadow style samples. - */ -function add_shadow_arguments(yargs) { - yargs - .option('shadow_property', { - alias: 'p', - description: 'Name of property in shadow to keep in sync', - type: 'string', - default: 'color' - }) - .option('shadow_value', { - alias: 'u', - description: 'Value for shadow property', - type: 'string', - default: 'on' - }) - .option('shadow_name', { - alias: 'N', - description: 'Use named shadow with specified name', - type: 'string' - }) - .option('thing_name', { - alias: 'n', - description: 'The name assigned to your IoT Thing', - type: 'string', - default: 'name' - }) - .option('mqtt5', { - description: 'Use an MQTT5 client rather than a MQTT311 client', - type: 'boolean', - default: false - }); -} - -/** - * Arguments specific to the custom authorizer style samples - */ -function add_custom_authorizer_arguments(yargs) { - yargs - .option('custom_auth_username', { - description: 'The name to send when connecting through the custom authorizer (optional)', - type: 'string', - default: '' - }) - .option('custom_auth_authorizer_name', { - description: 'The name of the custom authorizer to connect to (optional but required for everything but custom domains)', - type: 'string', - default: '' - }) - .option('custom_auth_authorizer_signature', { - description: 'The digital signature of the value of the `--custom_auth_token_value` parameter using the private key associated with the authorizer. The binary signature value must be base64 encoded and then URI encoded; the SDK will not do this for you. (optional)', - type: 'string', - default: '' - }) - .option('custom_auth_password', { - description: 'The password to send when connecting through a custom authorizer (optional)', - type: 'string', - default: '' - }) - .option('custom_auth_token_key_name', { - description: 'The query string parameter name that the token value should be bound to in the MQTT Connect packet. (optional)', - type: 'string', - default: undefined - }) - .option('custom_auth_token_value', { - description: 'An arbitrary value chosen by the user. You must also submit a digital signature of this value using the private key associated with the authorizer. (optional)', - type: 'string', - default: undefined - }) -} - -/* - * Arguments specific to the Jobs style samples. - */ -function add_jobs_arguments(yargs) { - yargs - .option('thing_name', { - alias: 'n', - description: 'The name assigned to your IoT Thing', - type: 'string', - default: 'name' - }) - .option('job_time', { - alias: 't', - description: 'Emulate working on a job by sleeping this many seconds (optional, default=5)', - type: 'number', - default: 5 - }) -} - -/* - * Arguments specific to the Cognito samples. - */ -function add_cognito_arguments(yargs) { - yargs - .option('cognito_identity', { - alias: 'i', - description: 'The Cognito identity ID to use to connect via Cognito', - type: 'string', - default: '', - required: true - }) -} - -function add_x509_arguments(yargs) { - yargs - .option('x509_endpoint', { - description: 'The credentials endpoint to fetch x509 credentials from', - type: 'string', - default: '', - required: true - }) - .option('x509_thing_name', { - description: 'Thing name to fetch x509 credentials on behalf of', - type: 'string', - default: '', - required: true - }) - .option('x509_role_alias', { - description: 'Role alias to use with the x509 credentials provider', - type: 'string', - default: '', - required: true - }) - .option('x509_cert', { - description: 'Path to the IoT thing certificate used in fetching x509 credentials', - type: 'string', - default: '', - required: true - }) - .option('x509_key', { - description: 'Path to the IoT thing private key used in fetching x509 credentials', - type: 'string', - default: '', - required: true - }) - .option('x509_ca_file', { - description: 'Path to the root certificate used in fetching x509 credentials', - type: 'string', - default: '', - required: false - }) -} - -/* - * Handles any non-specific arguments that are relevant to all samples - */ -function apply_sample_arguments(argv) { - if (argv.verbosity != 'none') { - const level = parseInt(io.LogLevel[argv.verbosity.toUpperCase()]); - io.enable_logging(level); - } -} - -/* - * A set of simple connection builder functions intended to cover a variety of scenarios/configurations. - * - * There is plenty of redundant code across these functions, but in this case we are trying to show, stand-alone and - * top-to-bottom, all the steps needed to establish an mqtt connection for each scenario. - * - * ToDo : Add a connection builder for custom auth case - * ToDo : Add a connection builder showing x509 provider usage. Pre-req: x509 provider binding. - * ToDo : Add a connection builder for websockets using cognito and the Aws SDK for JS (or implement and bind - * a cognito provider). - */ - -/* - * Build an mqtt connection using websockets, (http) proxy optional. - */ -function build_websocket_mqtt_connection_from_args(argv) { - let config_builder = iot.AwsIotMqttConnectionConfigBuilder.new_with_websockets({ - region: argv.signing_region, - credentials_provider: auth.AwsCredentialsProvider.newDefault() - }); - - if (argv.proxy_host) { - config_builder.with_http_proxy_options(new http.HttpProxyOptions(argv.proxy_host, argv.proxy_port)); - } - - if (argv.ca_file != null) { - config_builder.with_certificate_authority_from_path(undefined, argv.ca_file); - } - - config_builder.with_clean_session(false); - config_builder.with_client_id(argv.client_id || "test-" + Math.floor(Math.random() * 100000000)); - config_builder.with_endpoint(argv.endpoint); - const config = config_builder.build(); - - const client = new mqtt.MqttClient(); - return client.new_connection(config); -} - -/* - * Build a direct mqtt connection using mtls, (http) proxy optional - */ -function build_direct_mqtt_connection_from_args(argv) { - let config_builder = iot.AwsIotMqttConnectionConfigBuilder.new_mtls_builder_from_path(argv.cert, argv.key); - - if (argv.proxy_host) { - config_builder.with_http_proxy_options(new http.HttpProxyOptions(argv.proxy_host, argv.proxy_port)); - } - - if (argv.ca_file != null) { - config_builder.with_certificate_authority_from_path(undefined, argv.ca_file); - } - - config_builder.with_clean_session(false); - config_builder.with_client_id(argv.client_id || "test-" + Math.floor(Math.random() * 100000000)); - config_builder.with_endpoint(argv.endpoint); - const config = config_builder.build(); - - const client = new mqtt.MqttClient(); - return client.new_connection(config); -} - -/* - * Uses all of the connection-relevant arguments to create an mqtt connection as desired. - */ -function build_connection_from_cli_args(argv) { - /* - * Only basic websocket and direct mqtt connections for now. Later add custom authorizer and x509 support. - */ - if (argv.signing_region) { - return build_websocket_mqtt_connection_from_args(argv); - } else { - return build_direct_mqtt_connection_from_args(argv); - } -} - -function build_websocket_mqtt5_client_from_args(argv) { - let config_builder = iot.AwsIotMqtt5ClientConfigBuilder.newWebsocketMqttBuilderWithSigv4Auth(argv.endpoint, { - region: argv.signing_region, - credentials_provider: auth.AwsCredentialsProvider.newDefault() - }); - - if (argv.proxy_host) { - config_builder.withHttpProxyOptions(new http.HttpProxyOptions(argv.proxy_host, argv.proxy_port)); - } - - if (argv.ca_file != null) { - config_builder.withCertificateAuthorityFromPath(undefined, argv.ca_file); - } - - config_builder.withSessionBehavior(mqtt5.ClientSessionBehavior.RejoinPostSuccess); - - return new mqtt5.Mqtt5Client(config_builder.build()); -} - -function build_direct_mqtt5_client_from_args(argv) { - let config_builder = iot.AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPath(argv.endpoint, argv.cert, argv.key); - - if (argv.proxy_host) { - config_builder.withHttpProxyOptions(new http.HttpProxyOptions(argv.proxy_host, argv.proxy_port)); - } - - if (argv.ca_file != null) { - config_builder.withCertificateAuthorityFromPath(undefined, argv.ca_file); - } - - config_builder.withSessionBehavior(mqtt5.ClientSessionBehavior.RejoinPostSuccess); - config_builder.withConnectProperties({ - clientId: argv.client_id || "test-" + Math.floor(Math.random() * 100000000), - keepAliveIntervalSeconds: 120 - }) - return new mqtt5.Mqtt5Client(config_builder.build()); -} - -function build_mqtt5_client_from_cli_args(argv) { - /* - * Only basic websocket and direct mqtt connections for now. Later add custom authorizer and x509 support. - */ - if (argv.signing_region) { - return build_websocket_mqtt5_client_from_args(argv); - } else { - return build_direct_mqtt5_client_from_args(argv); - } -} - -exports.add_connection_establishment_arguments = add_connection_establishment_arguments; -exports.add_direct_connection_establishment_arguments = add_direct_connection_establishment_arguments; -exports.add_universal_arguments = add_universal_arguments; -exports.add_common_mqtt_arguments = add_common_mqtt_arguments; -exports.add_direct_tls_connect_arguments = add_direct_tls_connect_arguments; -exports.add_proxy_arguments = add_proxy_arguments; -exports.add_common_websocket_arguments = add_common_websocket_arguments; -exports.add_topic_message_arguments = add_topic_message_arguments; -exports.add_shadow_arguments = add_shadow_arguments; -exports.add_custom_authorizer_arguments = add_custom_authorizer_arguments; -exports.add_jobs_arguments = add_jobs_arguments; -exports.add_cognito_arguments = add_cognito_arguments; -exports.add_x509_arguments = add_x509_arguments -exports.apply_sample_arguments = apply_sample_arguments; -exports.build_connection_from_cli_args = build_connection_from_cli_args; -exports.build_mqtt5_client_from_cli_args = build_mqtt5_client_from_cli_args; diff --git a/samples/util/package.json b/samples/util/package.json deleted file mode 100644 index afcac912..00000000 --- a/samples/util/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "aws-iot-samples-util", - "version": "1.0.0", - "description": "Utils for NodeJS IoT SDK v2 GG IPC Samples", - "homepage": "https://github.com/aws/aws-iot-device-sdk-js-v2", - "repository": { - "type": "git", - "url": "git+https://github.com/aws/aws-iot-device-sdk-js-v2.git" - }, - "contributors": [ - "AWS SDK Common Runtime Team " - ], - "license": "Apache-2.0" -} diff --git a/servicetests/tests/fleet_provisioning/index.ts b/servicetests/tests/fleet_provisioning/index.ts index b449f3a7..14abda72 100644 --- a/servicetests/tests/fleet_provisioning/index.ts +++ b/servicetests/tests/fleet_provisioning/index.ts @@ -3,35 +3,65 @@ * SPDX-License-Identifier: Apache-2.0. */ -import { mqtt, iotidentity } from 'aws-iot-device-sdk-v2'; +import { iot, mqtt, mqtt5, iotidentity } from 'aws-iot-device-sdk-v2'; import { once } from "events" type Args = { [index: string]: any }; const fs = require('fs') const yargs = require('yargs'); -// The relative path is '../../../samples/util/cli_args' from here, but the compiled javascript file gets put one level -// deeper inside the 'dist' folder -const common_args = require('../../../../samples/util/cli_args'); - yargs.command('*', false, (yargs: any) => { - common_args.add_direct_connection_establishment_arguments(yargs); - yargs - .option('csr', { - description: ': Path to a CSR file in PEM format.', - type: 'string', - required: false - }) - .option('template_name', { - description: 'Template Name.', - type: 'string', - required: true - }) - .option('template_parameters', { - description: ': Template parameters json.', - type: 'string', - required: false - }) + yargs.option('endpoint', { + alias: 'e', + description: 'IoT endpoint hostname', + type: 'string', + required: true + }) + .option('cert', { + alias: 'c', + description: 'Path to the certificate file to use during mTLS connection establishment', + type: 'string', + required: true + }) + .option('key', { + alias: 'k', + description: 'Path to the private key file to use during mTLS connection establishment', + type: 'string', + required: true + }) + .option('region', { + alias: 'r', + description: 'AWS region to establish a websocket connection to.', + type: 'string', + required: false + }) + .option('client_id', { + alias: 'C', + description: 'Client ID for MQTT connection.', + type: 'string', + required: false + }) + .option('csr', { + description: ': Path to a CSR file in PEM format.', + type: 'string', + required: false + }) + .option('template_name', { + description: 'Template Name.', + type: 'string', + required: true + }) + .option('template_parameters', { + description: ': Template parameters json.', + type: 'string', + required: false + }) + .option('mqtt_version', { + description: 'MQTT version to use (3 or 5). Default is 5.', + type: 'number', + required: false, + default: 5 + }) }, main).parse(); @@ -208,17 +238,44 @@ async function execute_csr(identity: iotidentity.IotIdentityClient, argv: Args) }); } -async function main(argv: Args) { - common_args.apply_sample_arguments(argv); +function createConnection(args: any): mqtt.MqttClientConnection { + const config = iot.AwsIotMqttConnectionConfigBuilder.new_mtls_builder_from_path( + args.cert, + args.key + ) + .with_endpoint(args.endpoint) + .with_clean_session(false) + .with_client_id(args.client_id || "test-" + Math.floor(Math.random() * 100000000)) + .build(); + + const client = new mqtt.MqttClient(); + return client.new_connection(config); +} - var connection; - var client5; - var identity; - var timer; +function createMqtt5Client(args: any): mqtt5.Mqtt5Client { + const builder = iot.AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPath( + args.endpoint, + args.cert, + args.key + ); + + builder.withConnectProperties({ + clientId: args.client_id || "test-" + Math.floor(Math.random() * 100000000), + keepAliveIntervalSeconds: 1200 + }); + + return new mqtt5.Mqtt5Client(builder.build()); +} + +async function main(argv: any) { + let connection: mqtt.MqttClientConnection | undefined; + let client5: mqtt5.Mqtt5Client | undefined; + let identity: iotidentity.IotIdentityClient; + let timer: NodeJS.Timeout; console.log("Connecting..."); if (argv.mqtt_version == 5) { - client5 = common_args.build_mqtt5_client_from_cli_args(argv); + client5 = createMqtt5Client(argv); identity = iotidentity.IotIdentityClient.newFromMqtt5Client(client5); const connectionSuccess = once(client5, "connectionSuccess"); @@ -229,7 +286,7 @@ async function main(argv: Args) { await connectionSuccess; console.log("Connected with Mqtt5 Client!"); } else { - connection = common_args.build_connection_from_cli_args(argv); + connection = createConnection(argv); identity = new iotidentity.IotIdentityClient(connection); // force node to wait 60 seconds before killing itself, promises do not keep node alive @@ -252,7 +309,7 @@ async function main(argv: Args) { console.log("Disconnecting..."); if (connection) { await connection.disconnect(); - } else { + } else if (client5) { let stopped = once(client5, "stopped"); client5.stop(); await stopped; @@ -261,4 +318,4 @@ async function main(argv: Args) { console.log("Disconnected"); // Allow node to die if the promise above resolved clearTimeout(timer); -} +} \ No newline at end of file diff --git a/servicetests/tests/jobs_execution/index.ts b/servicetests/tests/jobs_execution/index.ts index 31ad4479..fa127d5d 100644 --- a/servicetests/tests/jobs_execution/index.ts +++ b/servicetests/tests/jobs_execution/index.ts @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -import { mqtt, iotjobs } from 'aws-iot-device-sdk-v2'; +import { mqtt, mqtt5, iot, iotjobs } from 'aws-iot-device-sdk-v2'; import {once} from "events"; const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); @@ -11,13 +11,55 @@ const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); type Args = { [index: string]: any }; const yargs = require('yargs'); -// The relative path is '../../../samples/util/cli_args' from here, but the compiled javascript file gets put one level -// deeper inside the 'dist' folder -const common_args = require('../../../../samples/util/cli_args'); - yargs.command('*', false, (yargs: any) => { - common_args.add_direct_connection_establishment_arguments(yargs); - common_args.add_jobs_arguments(yargs); + yargs.option('endpoint', { + alias: 'e', + description: 'Your AWS IoT custom endpoint, not including a port.', + type: 'string', + required: true + }) + .option('cert', { + alias: 'c', + description: ': File path to a PEM encoded certificate to use with mTLS.', + type: 'string', + required: false + }) + .option('key', { + alias: 'k', + description: ': File path to a PEM encoded private key that matches cert.', + type: 'string', + required: false + }) + .option('region', { + alias: 'r', + description: 'AWS region to establish a websocket connection to.', + type: 'string', + required: false + }) + .option('client_id', { + alias: 'C', + description: 'Client ID for MQTT connection.', + type: 'string', + required: false + }) + .option('thing_name', { + alias: 'n', + description: 'The name assigned to your IoT Thing', + type: 'string', + default: 'name' + }) + .option('job_time', { + alias: 't', + description: 'Emulate working on a job by sleeping this many seconds (optional, default=5)', + type: 'number', + default: 5 + }) + .option('mqtt_version', { + description: 'MQTT version to use (3 or 5). Default is 5.', + type: 'number', + required: false, + default: 5 + }) }, main).parse(); var available_jobs : Array = [] @@ -196,16 +238,53 @@ async function update_current_job_status(jobs_client: iotjobs.IotJobsClient, sta await jobs_client.publishUpdateJobExecution(executing_publish_request, mqtt.QoS.AtLeastOnce); } -async function main(argv: Args) { - common_args.apply_sample_arguments(argv); +function createConnection(args: any): mqtt.MqttClientConnection { + let config_builder = iot.AwsIotMqttConnectionConfigBuilder.new_mtls_builder_from_path( + args.cert, + args.key + ); + + config_builder.with_clean_session(false); + config_builder.with_client_id(args.client_id || "test-" + Math.floor(Math.random() * 100000000)); + config_builder.with_endpoint(args.endpoint); + + const config = config_builder.build(); + const client = new mqtt.MqttClient(); + return client.new_connection(config); +} + +function createMqtt5Client(args: any): mqtt5.Mqtt5Client { + let builder: iot.AwsIotMqtt5ClientConfigBuilder; + + if (args.key && args.cert) { + builder = iot.AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPath( + args.endpoint, + args.cert, + args.key + ); + } else { + builder = iot.AwsIotMqtt5ClientConfigBuilder.newWebsocketMqttBuilderWithSigv4Auth( + args.endpoint, + { region: args.region || 'us-east-1' } + ); + } + + builder.withConnectProperties({ + clientId: args.client_id || "test-" + Math.floor(Math.random() * 100000000), + keepAliveIntervalSeconds: 1200 + }); + + return new mqtt5.Mqtt5Client(builder.build()); +} - let connection; - let client5; - let jobs_client; +async function main(argv: Args) { + let connection: mqtt.MqttClientConnection | undefined; + let client5: mqtt5.Mqtt5Client | undefined; + let jobs_client: iotjobs.IotJobsClient; console.log("Connecting..."); if (argv.mqtt_version == 5) { - client5 = common_args.build_mqtt5_client_from_cli_args(argv); + client5 = createMqtt5Client(argv); jobs_client = iotjobs.IotJobsClient.newFromMqtt5Client(client5); const connectionSuccess = once(client5, "connectionSuccess"); @@ -213,7 +292,7 @@ async function main(argv: Args) { await connectionSuccess; console.log("Connected with Mqtt5 Client!"); } else { - connection = common_args.build_connection_from_cli_args(argv); + connection = createConnection(argv); jobs_client = new iotjobs.IotJobsClient(connection); await connection.connect() @@ -245,7 +324,7 @@ async function main(argv: Args) { if (connection) { await connection.disconnect(); - } else { + } else if (client5) { let stopped = once(client5, "stopped"); client5.stop(); await stopped; diff --git a/servicetests/tests/shadow_update/index.ts b/servicetests/tests/shadow_update/index.ts index 6e393b17..06e02131 100644 --- a/servicetests/tests/shadow_update/index.ts +++ b/servicetests/tests/shadow_update/index.ts @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0. */ -import { mqtt, iotshadow } from 'aws-iot-device-sdk-v2'; +import { mqtt, mqtt5, iot, iotshadow } from 'aws-iot-device-sdk-v2'; import {once} from "events"; const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); @@ -11,13 +11,66 @@ const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); type Args = { [index: string]: any }; const yargs = require('yargs'); -// The relative path is '../../../samples/util/cli_args' from here, but the compiled javascript file gets put one level -// deeper inside the 'dist' folder -const common_args = require('../../../../samples/util/cli_args'); - yargs.command('*', false, (yargs: any) => { - common_args.add_direct_connection_establishment_arguments(yargs); - common_args.add_shadow_arguments(yargs); + yargs.option('endpoint', { + alias: 'e', + description: 'Your AWS IoT custom endpoint, not including a port.', + type: 'string', + required: true + }) + .option('cert', { + alias: 'c', + description: ': File path to a PEM encoded certificate to use with mTLS.', + type: 'string', + required: false + }) + .option('key', { + alias: 'k', + description: ': File path to a PEM encoded private key that matches cert.', + type: 'string', + required: false + }) + .option('region', { + alias: 'r', + description: 'AWS region to establish a websocket connection to.', + type: 'string', + required: false + }) + .option('client_id', { + alias: 'C', + description: 'Client ID for MQTT connection.', + type: 'string', + required: false + }) + .option('shadow_property', { + alias: 'p', + description: 'Name of property in shadow to keep in sync', + type: 'string', + default: 'color' + }) + .option('shadow_value', { + alias: 'u', + description: 'Value for shadow property', + type: 'string', + default: 'on' + }) + .option('shadow_name', { + alias: 'N', + description: 'Use named shadow with specified name', + type: 'string' + }) + .option('thing_name', { + alias: 'n', + description: 'The name assigned to your IoT Thing', + type: 'string', + default: 'name' + }) + .option('mqtt_version', { + description: 'MQTT version to use (3 or 5). Default is 5.', + type: 'number', + required: false, + default: 5 + }) }, main).parse(); @@ -76,24 +129,61 @@ function change_named_shadow_value(shadow: iotshadow.IotShadowClient, argv: Args }); } -async function main(argv: Args) { - common_args.apply_sample_arguments(argv); +function createConnection(args: any): mqtt.MqttClientConnection { + let config_builder = iot.AwsIotMqttConnectionConfigBuilder.new_mtls_builder_from_path( + args.cert, + args.key + ); + + config_builder.with_clean_session(false); + config_builder.with_client_id(args.client_id || "test-" + Math.floor(Math.random() * 100000000)); + config_builder.with_endpoint(args.endpoint); + + const config = config_builder.build(); + const client = new mqtt.MqttClient(); + return client.new_connection(config); +} + +function createMqtt5Client(args: any): mqtt5.Mqtt5Client { + let builder: iot.AwsIotMqtt5ClientConfigBuilder; + + if (args.key && args.cert) { + builder = iot.AwsIotMqtt5ClientConfigBuilder.newDirectMqttBuilderWithMtlsFromPath( + args.endpoint, + args.cert, + args.key + ); + } else { + builder = iot.AwsIotMqtt5ClientConfigBuilder.newWebsocketMqttBuilderWithSigv4Auth( + args.endpoint, + { region: args.region || 'us-east-1' } + ); + } - var connection; - var client5; - var shadow; + builder.withConnectProperties({ + clientId: args.client_id || "test-" + Math.floor(Math.random() * 100000000), + keepAliveIntervalSeconds: 1200 + }); + + return new mqtt5.Mqtt5Client(builder.build()); +} + +async function main(argv: Args) { + let connection: mqtt.MqttClientConnection | undefined; + let client5: mqtt5.Mqtt5Client | undefined; + let shadow: iotshadow.IotShadowClient; console.log("Connecting..."); - if (argv.mqtt_version == 5) { // Build the mqtt5 client - client5 = common_args.build_mqtt5_client_from_cli_args(argv); + if (argv.mqtt_version == 5) { + client5 = createMqtt5Client(argv); shadow = iotshadow.IotShadowClient.newFromMqtt5Client(client5); const connectionSuccess = once(client5, "connectionSuccess"); client5.start(); await connectionSuccess; console.log("Connected with Mqtt5 Client..."); - } else { // Build the mqtt3 based connection - connection = common_args.build_connection_from_cli_args(argv); + } else { + connection = createConnection(argv); shadow = new iotshadow.IotShadowClient(connection); await connection.connect(); @@ -118,7 +208,7 @@ async function main(argv: Args) { if (connection) { await connection.disconnect(); - } else { + } else if (client5) { let stopped = once(client5, "stopped"); client5.stop(); await stopped; diff --git a/utils/ci-aws-doc-links.txt b/utils/ci-aws-doc-links.txt new file mode 100644 index 00000000..11167c38 --- /dev/null +++ b/utils/ci-aws-doc-links.txt @@ -0,0 +1,2 @@ +samples/node/mqtt/mqtt5_x509/index.js +samples/node/greengrass/basic_discovery/index.ts \ No newline at end of file