[
  {
    "path": ".gitignore",
    "content": "# Temporary files\n*.sw[op]\n\n# Configuration\nconf/*\n.DS_Store\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (http://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# Typescript v1 declaration files\ntypings/\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variables file\n.env\n\n# IntelliJ IDE files\n.idea"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2018 Amazon.com, Inc. or its affiliates\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License."
  },
  {
    "path": "README.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Extensions-Hello-World</title>\n</head>\n<body>\n\n    <h1 id=\"extensions-hello-world\">Extensions-Hello-World</h1>\n<p>The Simplest Extension in the (Hello) World.</p>\n<h2 id=\"motivation\">Motivation</h2>\n<p>The Hello World sample is designed to get you started building a Twitch Extension quickly. It contains all the key parts of a functioning Extension and can be immediately run in the <a href=\"https://github.com/twitchdev/developer-rig\">Developer Rig</a>.  For a fast guide to get started, visit the Developer Rig documentation.</p>\n<h2 id=\"whats-in-the-sample\">What's in the Sample</h2>\n<p>The Hello World Extension provides a simple scenario that demonstrates the end-to-end flow of an Extension. On the frontend, a user clicks a button that can change the color of a circle. Instead of changing the CSS locally, it calls its Extension Backend Service (EBS) to update the color of the circle. That message is then sent via Twitch PubSub to update all clients listening to the PubSub topic.</p>\n<p><strong>The sample is broken into two main components:</strong></p>\n<ol>\n<li>The Frontend of the Extension, comprised of HTML files for the different extension views and corresponding Javascript files and CSS. The frontend has the following functionality:\n<ul>\n<li>A button and script that makes a POST call to the EBS to request a color change for the circle</li>\n<li>A GET call when the Extension is initialized to change the circle to the current color stored on the EBS</li>\n<li>A listener to Twitch PubSub, that receives color change updates and then updates the circle color</li>\n</ul>\n</li>\n<li>A lightweight EBS that performs the following functionality:\n<ul>\n<li>Spins up a simple HTTPS server with a POST handler for changing color</li>\n<li>Validates an Extension JWT</li>\n<li>Sends a new color message via Twitch PubSub for a specific channel</li>\n</ul>\n</li>\n</ol>\n<h2 id=\"using-the-sample\">Using the Sample</h2>\n<p>The recommended path to using this sample is with the <a href=\"https://github.com/twitchdev/developer-rig\">Developer Rig</a>.  Use the Developer Rig's <code>extension-init</code> command to clone this repository.</p>\n<p>The Developer Rig is able to host the frontend Hello World files, but the EBS must be run and hosted separately.</p>\n<h3 id=\"setting-up-your-backend-certificates\">Setting Up Your Backend Certificates</h3>\n<p>Twitch Extensions require SSL (TLS).</p>\n<p>If you're using the Developer Rig and used it to create this extension, it will have already configured the certificates.  Otherwise, you'll need to set up a certificate for local development.  This will generate a new certificate (<code>server.crt</code> and <code>server.key</code>) for you and place it in the <code>conf/</code> directory. This certificate is different from the one used for the Developer Rig.</p>\n<h4 id=\"on-macos\">On MacOS</h4>\n<p>Navigate to the root of the Hello World extension folder and run <code>npm install</code> and then <code>npm run cert</code></p>\n<h4 id=\"on-windows\">On Windows</h4>\n<p>Run the following commands to generate the necessary certificates for your Hello World backend</p>\n<ol>\n<li><code>node scripts/ssl.js</code></li>\n<li><code>mkdir ../my-extension/conf</code></li>\n<li><code>mv ssl/selfsigned.crt ../my-extension/conf/server.crt</code></li>\n<li><code>mv ssl/selfsigned.key ../my-extension/conf/server.key</code></li>\n</ol>\n<h3 id=\"running-hello-world\">Running Hello World</h3>\n<p>If you're using the Developer Rig, it has buttons in its UI to perform the following actions.</p>\n<p>To run the EBS, run <code>node services/backend</code>, with the following command line arguments: <code>-c &lt;client id&gt;</code>, <code>-s &lt;secret&gt;</code>, <code>-o &lt;owner id&gt;</code>.</p>\n<p>This provides the EBS with your Extension client ID, Extension secret and the user ID of the Extension owner (likely you). These are necessary to validate calls to your EBS and make calls to Twitch services such as PubSub.</p>\n<p>If you do not want to pass in command line arguments, you can also directly set the following environment variables: <code>EXT_SECRET</code>, <code>EXT_CLIENT_ID</code>, <code>EXT_OWNER_ID</code> in your code.</p>\n<p>You can get your client ID and secret from your <a href=\"https://dev.twitch.tv/dashboard/extensions\">Extension Dashboard</a>.</p>\n<p>To get the owner ID, you will need to execute a simple CURL command against the Twitch <code>/users</code> endpoint. You'll need your extension client ID as part of the query (this will be made consistent with the Developer Rig shortly, by using <em>owner name</em>).</p>\n<pre><code class=\"language-bash\">curl -H &quot;Client-ID: &lt;client id&gt;&quot; -X GET &quot;https://api.twitch.tv/helix/users?login=&lt;owner name&gt;&quot;\n</code></pre>\n<p><strong>Note -</strong> If you haven't yet created an extension, you can start that process <a href=\"https://dev.twitch.tv/extensions\">here</a>.</p>\n\n\n</body>\n</html>"
  },
  {
    "path": "README.md",
    "content": "# Extensions-Hello-World\nThe Simplest Extension in the (Hello) World.\n\n## Motivation\nThe Hello World sample is designed to get you started building a Twitch Extension quickly. It contains all the key parts of a functioning Extension and can be immediately run in the [Developer Rig](https://github.com/twitchdev/developer-rig).  For a fast guide to get started, visit the Developer Rig documentation.\n\n## What's in the Sample\nThe Hello World Extension provides a simple scenario that demonstrates the end-to-end flow of an Extension. On the frontend, a user clicks a button that can change the color of a circle. Instead of changing the CSS locally, it calls its Extension Backend Service (EBS) to update the color of the circle. That message is then sent via Twitch PubSub to update all clients listening to the PubSub topic.\n\n__The sample is broken into two main components:__\n\n1. The Frontend of the Extension, comprised of HTML files for the different extension views and corresponding Javascript files and CSS. The frontend has the following functionality:\n    * A button and script that makes a POST call to the EBS to request a color change for the circle\n    * A GET call when the Extension is initialized to change the circle to the current color stored on the EBS\n    * A listener to Twitch PubSub, that receives color change updates and then updates the circle color\n2. A lightweight EBS that performs the following functionality:\n    * Spins up a simple HTTPS server with a POST handler for changing color\n    * Validates an Extension JWT\n    * Sends a new color message via Twitch PubSub for a specific channel\n\n## Using the Sample\nThe recommended path to using this sample is with the [Developer Rig](https://github.com/twitchdev/developer-rig).  Use the Developer Rig's `extension-init` command to clone this repository.\n\nThe Developer Rig is able to host the frontend Hello World files, but the EBS must be run and hosted separately.\n\n### Setting Up Your Backend Certificates\nTwitch Extensions require SSL (TLS).\n\nIf you're using the Developer Rig and used it to create this extension, it will have already configured the certificates.  Otherwise, you'll need to set up a certificate for local development.  This will generate a new certificate (`server.crt` and `server.key`) for you and place it in the `conf/` directory. This certificate is different from the one used for the Developer Rig.\n\n#### On MacOS\nNavigate to the root of the Hello World extension folder and run `npm install` and then `npm run cert`\n\n#### On Windows\nRun the following commands to generate the necessary certificates for your Hello World backend\n1. `node scripts/ssl.js`\n2. `mkdir ../my-extension/conf`\n3. `mv ssl/selfsigned.crt ../my-extension/conf/server.crt`\n4. `mv ssl/selfsigned.key ../my-extension/conf/server.key`\n\n### Running Hello World\nIf you're using the Developer Rig, it has buttons in its UI to perform the following actions.\n\nTo run the EBS, run `node services/backend`, with the following command line arguments: `-c <client id>`, `-s <secret>`, `-o <owner id>`.\n\nThis provides the EBS with your Extension client ID, Extension secret and the user ID of the Extension owner (likely you). These are necessary to validate calls to your EBS and make calls to Twitch services such as PubSub.\n\nIf you do not want to pass in command line arguments, you can also directly set the following environment variables: `EXT_SECRET`, `EXT_CLIENT_ID`, `EXT_OWNER_ID` in your code.\n\nYou can get your client ID and secret from your [Extension Dashboard](https://dev.twitch.tv/dashboard/extensions).\n\nTo get the owner ID, you will need to execute a simple CURL command against the Twitch `/users` endpoint. You'll need your extension client ID as part of the query (this will be made consistent with the Developer Rig shortly, by using _owner name_).\n\n```bash\ncurl -H \"Client-ID: <client id>\" -X GET \"https://api.twitch.tv/helix/users?login=<owner name>\"\n```\n\n**Note -** If you haven't yet created an extension, you can start that process [here](https://dev.twitch.tv/extensions).\n"
  },
  {
    "path": "bin/generate_cert.cmd",
    "content": "@ECHO OFF\nSETLOCAL\n\nSET T=%TEMP%\\%RANDOM%.cnf\nSET GIT=%ProgramFiles%\\Git\nSET CONF=%~dp0..\\conf\nSET FILE_ROOT=%CONF%\\%~1\n\nIF EXIST \"%CONF%\" RD /Q /S \"%CONF%\"\nMKDIR \"%CONF%\"\nCOPY /Y \"%GIT%\\usr\\ssl\\openssl.cnf\" %T% > nul\nECHO [SAN]>> %T%\nECHO subjectAltName='DNS:localhost'>> %T%\n\"%GIT%\\mingw64\\bin\\openssl\" req -newkey rsa:4096 -days 1001 -nodes -x509 -subj \"/C=US/ST=California/L=San Francisco/O=LULZCorp/OU=web/CN=localhost\" -extensions SAN -config \"%T%\" -keyout \"%FILE_ROOT%.key\" -out \"%FILE_ROOT%.crt\"\n\nSET EXIT_CODE=%ERRORLEVEL%\nDEL /F /Q %T%\nEXIT /B %EXIT_CODE%\n"
  },
  {
    "path": "bin/generate_cert.js",
    "content": "// Valiate the command line.\nif(process.argv.length < 3) {\n  console.log(`usage: node ${process.argv[1]} file_root`);\n  process.exit(2);\n}\n\n// Spawn the process for the platform.\nconst { spawn } = require('child_process');\nconst cmd = process.platform !== 'win32' ?\n  spawn('bin/generate_cert.sh', [process.argv[2]]) :\n  spawn('cmd.exe', ['/c', 'bin\\\\generate_cert.cmd', process.argv[2]]);\nlet output = '';\n\n// Handle process activity.\ncmd.stdout.on('data', (data) => {\n  output += data.toString();\n});\ncmd.stderr.on('data', (data) => {\n  output += data.toString();\n});\ncmd.on('exit', (code) => {\n  console.log(output);\n  if(code) {\n    process.exit(code);\n  }\n});\n"
  },
  {
    "path": "bin/generate_cert.sh",
    "content": "#!/usr/bin/env bash\nNAME=${1:-server}\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nopenssl req \\\n  -newkey rsa:4096 \\\n  -days 1001 \\\n  -nodes \\\n  -x509 \\\n  -subj \"/C=US/ST=California/L=San Francisco/O=LULZCorp/OU=web/CN=localhost\" \\\n  -extensions SAN \\\n  -config <( cat $( [[ \"Darwin\" = \"$(uname -s)\" ]]  && echo /System/Library/OpenSSL/openssl.cnf || echo /etc/ssl/openssl.cnf  ) \\\n    <(printf \"[SAN]\\nsubjectAltName='DNS:localhost'\")) \\\n  -keyout \"${DIR}/${NAME}.key\" \\\n  -out \"${DIR}/${NAME}.crt\"\n\necho \"\"\necho \"* Generated $NAME.key and $NAME.crt files in local directory\"\necho \"\"\n\nif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n  echo \"* Installing cert into local Keychain.\"\n  echo \"* To see or modify, run 'Keychain Access' app and look in the 'System' Folder\"\n  sudo security add-trusted-cert -d -p ssl -r trustRoot -k \"/Library/Keychains/System.keychain\" \"${DIR}/${NAME}.crt\"\nelse\n  echo \"* Please install and trust cert at conf/$NAME.crt\"\nfi\ncd \"$DIR\" \nif [[ ! -d \"${DIR}/../conf/\" ]]; then\n  mkdir \"${DIR}/../conf/\"\nfi\nmv ${NAME}.{key,crt} \"${DIR}/../conf/\"\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"extension-hello-world\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Simple Hello World Twitch Extension\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"cert\": \"node bin/generate_cert.js server\",\n    \"start\": \"node services/backend\"\n  },\n  \"keywords\": [\n    \"twitch\",\n    \"extension\"\n  ],\n  \"author\": \"Emily Rose <amorelandra@twitch.tv>\",\n  \"license\": \"Apache-2.0\",\n  \"dependencies\": {\n    \"boom\": \"^7.2.0\",\n    \"color\": \"^3.0.0\",\n    \"commander\": \"^2.15.0\",\n    \"hapi\": \"^17.8.4\",\n    \"inert\": \"^5.1.0\",\n    \"jsonwebtoken\": \"^8.2.0\",\n    \"request\": \"^2.85.0\",\n    \"selfsigned\": \"^1.10.2\"\n  }\n}\n"
  },
  {
    "path": "public/config.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Config Page</title>\n</head>\n<body style=\"font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\">\n    <div id=\"app\"></div>\n    <script src=\"https://extension-files.twitch.tv/helper/v1/twitch-ext.min.js\"></script>\n    <!-- If you use any external libraries, such as jQuery, you must include\n      them as part of your extension.  Twitch does not allow extensions to link\n      to external libraries. -->\n    <script src=\"jquery-3.3.1.min.js\" type=\"text/javascript\"></script>\n    <script src=\"config.js\" type=\"text/javascript\"></script>\n    <h2>Configure This</h2>\n    <p>Just kidding... hello world.</p>\n</body>\n</html>\n"
  },
  {
    "path": "public/config.js",
    "content": "let token, userId;\n\nconst twitch = window.Twitch.ext;\n\ntwitch.onContext((context) => {\n  twitch.rig.log(context);\n});\n\ntwitch.onAuthorized((auth) => {\n  token = auth.token;\n  userId = auth.userId;\n});\n"
  },
  {
    "path": "public/helper.js",
    "content": "window.addEventListener('message', (event) => {\n  console.log(event);\n});\n//debugger;\n//const local = window.frameElement.attributes.getNamedItem('helperUrl');\n//const online = 'https://extension-files.twitch.tv/helper/v1/twitch-ext.min.js';\n//const el = document.createElement('script');\n//el.src = local ? local.value : online;\n//document.head.appendChild(el);\n"
  },
  {
    "path": "public/live_config.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Live Config (Broadcaster) Page</title>\n</head>\n<body style=\"font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\">\n    <div id=\"app\" class=\"full-height\"></div>\n    <script src=\"https://extension-files.twitch.tv/helper/v1/twitch-ext.min.js\"></script>\n    <!-- If you use any external libraries, such as jQuery, you must include\n      them as part of your extension.  Twitch does not allow extensions to link\n      to external libraries. -->\n    <script src=\"jquery-3.3.1.min.js\" type=\"text/javascript\"></script>\n    <script src=\"viewer.js\" type=\"text/javascript\"></script>\n    <h2>And We're Live!</h2>\n    <p>Would you care to cycle a color?</p>\n    <div>\n        <input type=\"button\" id=\"cycle\" disabled=\"disabled\" value=\"Yes, I would\" />\n    </div>\n    <div style=\"float: left; position: relative; left: 50%\">\n        <div id=\"color\" style=\"border-radius: 50px; transition: background-color 0.5s ease; margin-top: 30px; width: 100px; height: 100px; background-color: #6441A4; float: left; position: relative; left: -50%\">\n        </div>\n    </div>\n    <div id=\"list\">\n    </div>\n</body>\n</html>\n"
  },
  {
    "path": "public/mobile.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Viewer Page</title>\n</head>\n<body style=\"font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\">\n    <div id=\"app\" class=\"full-height\"></div>\n    <script src=\"https://extension-files.twitch.tv/helper/v1/twitch-ext.min.js\"></script>\n    <!-- If you use any external libraries, such as jQuery, you must include\n      them as part of your extension.  Twitch does not allow extensions to link\n      to external libraries. -->\n    <script src=\"jquery-3.3.1.min.js\" type=\"text/javascript\"></script>\n    <script src=\"viewer.js\" type=\"text/javascript\"></script>\n    <h2>Hello, World!</h2>\n    <p>Would you care to cycle a color?</p>\n    <div>\n        <input type=\"button\" id=\"cycle\" disabled=\"disabled\" value=\"Yes, I would\" />\n    </div>\n    <div style=\"float: left; position: relative; left: 50%\">\n        <div id=\"color\" style=\"border-radius: 50px; transition: background-color 0.5s ease; margin-top: 30px; width: 100px; height: 100px; background-color: #6441A4; float: left; position: relative; left: -50%\">\n        </div>\n    </div>\n    <div id=\"list\">\n    </div>\n</body>\n</html>\n"
  },
  {
    "path": "public/panel.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Viewer Page</title>\n</head>\n<body style=\"font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\">\n    <div id=\"app\" class=\"full-height\"></div>\n    <script src=\"https://extension-files.twitch.tv/helper/v1/twitch-ext.min.js\"></script>\n    <!-- If you use any external libraries, such as jQuery, you must include\n      them as part of your extension.  Twitch does not allow extensions to link\n      to external libraries. -->\n    <script src=\"jquery-3.3.1.min.js\" type=\"text/javascript\"></script>\n    <script src=\"viewer.js\" type=\"text/javascript\"></script>\n    <h2>Hello, World!</h2>\n    <p>Would you care to cycle a color?</p>\n    <div>\n        <input type=\"button\" id=\"cycle\" disabled=\"disabled\" value=\"Yes, I would\" />\n    </div>\n    <div style=\"float: left; position: relative; left: 50%\">\n        <div id=\"color\" style=\"border-radius: 50px; transition: background-color 0.5s ease; margin-top: 30px; width: 100px; height: 100px; background-color: #6441A4; float: left; position: relative; left: -50%\">\n        </div>\n    </div>\n    <div id=\"list\">\n    </div>\n</body>\n</html>\n"
  },
  {
    "path": "public/video_component.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Viewer Page</title>\n</head>\n<body style=\"font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\">\n    <div id=\"app\" class=\"full-height\"></div>\n    <script src=\"https://extension-files.twitch.tv/helper/v1/twitch-ext.min.js\"></script>\n    <!-- If you use any external libraries, such as jQuery, you must include\n      them as part of your extension.  Twitch does not allow extensions to link\n      to external libraries. -->\n    <script src=\"jquery-3.3.1.min.js\" type=\"text/javascript\"></script>\n    <script src=\"viewer.js\" type=\"text/javascript\"></script>\n    <h2>Hello, World!</h2>\n    <p>Would you care to cycle a color?</p>\n    <div>\n        <input type=\"button\" id=\"cycle\" disabled=\"disabled\" value=\"Yes, I would\" />\n    </div>\n    <div style=\"float: left; position: relative; left: 50%\">\n        <div id=\"color\" style=\"border-radius: 50px; transition: background-color 0.5s ease; margin-top: 30px; width: 100px; height: 100px; background-color: #6441A4; float: left; position: relative; left: -50%\">\n        </div>\n    </div>\n    <div id=\"list\">\n    </div>\n</body>\n</html>\n"
  },
  {
    "path": "public/video_overlay.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Viewer Page</title>\n</head>\n<body style=\"font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;\">\n    <div id=\"app\" class=\"full-height\"></div>\n    <script src=\"https://extension-files.twitch.tv/helper/v1/twitch-ext.min.js\"></script>\n    <!-- If you use any external libraries, such as jQuery, you must include\n      them as part of your extension.  Twitch does not allow extensions to link\n      to external libraries. -->\n    <script src=\"jquery-3.3.1.min.js\" type=\"text/javascript\"></script>\n    <script src=\"viewer.js\" type=\"text/javascript\"></script>\n    <h2>Hello, World!</h2>\n    <p>Would you care to cycle a color?</p>\n    <div>\n        <input type=\"button\" id=\"cycle\" disabled=\"disabled\" value=\"Yes, I would\" />\n    </div>\n    <div style=\"float: left; position: relative; left: 50%\">\n        <div id=\"color\" style=\"border-radius: 50px; transition: background-color 0.5s ease; margin-top: 30px; width: 100px; height: 100px; background-color: #6441A4; float: left; position: relative; left: -50%\">\n        </div>\n    </div>\n    <div id=\"list\">\n    </div>\n</body>\n</html>\n"
  },
  {
    "path": "public/viewer.js",
    "content": "var token = \"\";\nvar tuid = \"\";\nvar ebs = \"\";\n\n// because who wants to type this every time?\nvar twitch = window.Twitch.ext;\n\n// create the request options for our Twitch API calls\nvar requests = {\n    set: createRequest('POST', 'cycle'),\n    get: createRequest('GET', 'query')\n};\n\nfunction createRequest(type, method) {\n\n    return {\n        type: type,\n        url: location.protocol + '//localhost:8081/color/' + method,\n        success: updateBlock,\n        error: logError\n    }\n}\n\nfunction setAuth(token) {\n    Object.keys(requests).forEach((req) => {\n        twitch.rig.log('Setting auth headers');\n        requests[req].headers = { 'Authorization': 'Bearer ' + token }\n    });\n}\n\ntwitch.onContext(function(context) {\n    twitch.rig.log(context);\n});\n\ntwitch.onAuthorized(function(auth) {\n    // save our credentials\n    token = auth.token;\n    tuid = auth.userId;\n\n    // enable the button\n    $('#cycle').removeAttr('disabled');\n\n    setAuth(token);\n    $.ajax(requests.get);\n});\n\nfunction updateBlock(hex) {\n    twitch.rig.log('Updating block color');\n    $('#color').css('background-color', hex);\n}\n\nfunction logError(_, error, status) {\n  twitch.rig.log('EBS request returned '+status+' ('+error+')');\n}\n\nfunction logSuccess(hex, status) {\n  // we could also use the output to update the block synchronously here,\n  // but we want all views to get the same broadcast response at the same time.\n  twitch.rig.log('EBS request returned '+hex+' ('+status+')');\n}\n\n$(function() {\n\n    // when we click the cycle button\n    $('#cycle').click(function() {\n        if(!token) { return twitch.rig.log('Not authorized'); }\n        twitch.rig.log('Requesting a color cycle');\n        $.ajax(requests.set);\n    });\n\n    // listen for incoming broadcast message from our EBS\n    twitch.listen('broadcast', function (target, contentType, color) {\n        twitch.rig.log('Received broadcast color');\n        updateBlock(color);\n    });\n});\n"
  },
  {
    "path": "services/backend.js",
    "content": "/**\n *    Copyright 2018 Amazon.com, Inc. or its affiliates\n *\n *    Licensed under the Apache License, Version 2.0 (the \"License\");\n *    you may not use this file except in compliance with the License.\n *    You may obtain a copy of the License at\n *\n *        http://www.apache.org/licenses/LICENSE-2.0\n *\n *    Unless required by applicable law or agreed to in writing, software\n *    distributed under the License is distributed on an \"AS IS\" BASIS,\n *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n *    See the License for the specific language governing permissions and\n *    limitations under the License.\n */\n\nconst fs = require('fs');\nconst Hapi = require('hapi');\nconst path = require('path');\nconst Boom = require('boom');\nconst color = require('color');\nconst ext = require('commander');\nconst jsonwebtoken = require('jsonwebtoken');\nconst request = require('request');\n\n// The developer rig uses self-signed certificates.  Node doesn't accept them\n// by default.  Do not use this in production.\nprocess.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';\n\n// Use verbose logging during development.  Set this to false for production.\nconst verboseLogging = true;\nconst verboseLog = verboseLogging ? console.log.bind(console) : () => { };\n\n// Service state variables\nconst initialColor = color('#6441A4');      // super important; bleedPurple, etc.\nconst serverTokenDurationSec = 30;          // our tokens for pubsub expire after 30 seconds\nconst userCooldownMs = 1000;                // maximum input rate per user to prevent bot abuse\nconst userCooldownClearIntervalMs = 60000;  // interval to reset our tracking object\nconst channelCooldownMs = 1000;             // maximum broadcast rate per channel\nconst bearerPrefix = 'Bearer ';             // HTTP authorization headers have this prefix\nconst colorWheelRotation = 30;\nconst channelColors = {};\nconst channelCooldowns = {};                // rate limit compliance\nlet userCooldowns = {};                     // spam prevention\n\nconst STRINGS = {\n  secretEnv: usingValue('secret'),\n  clientIdEnv: usingValue('client-id'),\n  ownerIdEnv: usingValue('owner-id'),\n  serverStarted: 'Server running at %s',\n  secretMissing: missingValue('secret', 'EXT_SECRET'),\n  clientIdMissing: missingValue('client ID', 'EXT_CLIENT_ID'),\n  ownerIdMissing: missingValue('owner ID', 'EXT_OWNER_ID'),\n  messageSendError: 'Error sending message to channel %s: %s',\n  pubsubResponse: 'Message to c:%s returned %s',\n  cyclingColor: 'Cycling color for c:%s on behalf of u:%s',\n  colorBroadcast: 'Broadcasting color %s for c:%s',\n  sendColor: 'Sending color %s to c:%s',\n  cooldown: 'Please wait before clicking again',\n  invalidAuthHeader: 'Invalid authorization header',\n  invalidJwt: 'Invalid JWT',\n};\n\next.\n  version(require('../package.json').version).\n  option('-s, --secret <secret>', 'Extension secret').\n  option('-c, --client-id <client_id>', 'Extension client ID').\n  option('-o, --owner-id <owner_id>', 'Extension owner ID').\n  parse(process.argv);\n\nconst ownerId = getOption('ownerId', 'EXT_OWNER_ID');\nconst secret = Buffer.from(getOption('secret', 'EXT_SECRET'), 'base64');\nconst clientId = getOption('clientId', 'EXT_CLIENT_ID');\n\nconst serverOptions = {\n  host: 'localhost',\n  port: 8081,\n  routes: {\n    cors: {\n      origin: ['*'],\n    },\n  },\n};\nconst serverPathRoot = path.resolve(__dirname, '..', 'conf', 'server');\nif (fs.existsSync(serverPathRoot + '.crt') && fs.existsSync(serverPathRoot + '.key')) {\n  serverOptions.tls = {\n    // If you need a certificate, execute \"npm run cert\".\n    cert: fs.readFileSync(serverPathRoot + '.crt'),\n    key: fs.readFileSync(serverPathRoot + '.key'),\n  };\n}\nconst server = new Hapi.Server(serverOptions);\n\n(async () => {\n  // Handle a viewer request to cycle the color.\n  server.route({\n    method: 'POST',\n    path: '/color/cycle',\n    handler: colorCycleHandler,\n  });\n\n  // Handle a new viewer requesting the color.\n  server.route({\n    method: 'GET',\n    path: '/color/query',\n    handler: colorQueryHandler,\n  });\n\n  // Start the server.\n  await server.start();\n  console.log(STRINGS.serverStarted, server.info.uri);\n\n  // Periodically clear cool-down tracking to prevent unbounded growth due to\n  // per-session logged-out user tokens.\n  setInterval(() => { userCooldowns = {}; }, userCooldownClearIntervalMs);\n})();\n\nfunction usingValue(name) {\n  return `Using environment variable for ${name}`;\n}\n\nfunction missingValue(name, variable) {\n  const option = name.charAt(0);\n  return `Extension ${name} required.\\nUse argument \"-${option} <${name}>\" or environment variable \"${variable}\".`;\n}\n\n// Get options from the command line or the environment.\nfunction getOption(optionName, environmentName) {\n  const option = (() => {\n    if (ext[optionName]) {\n      return ext[optionName];\n    } else if (process.env[environmentName]) {\n      console.log(STRINGS[optionName + 'Env']);\n      return process.env[environmentName];\n    }\n    console.log(STRINGS[optionName + 'Missing']);\n    process.exit(1);\n  })();\n  console.log(`Using \"${option}\" for ${optionName}`);\n  return option;\n}\n\n// Verify the header and the enclosed JWT.\nfunction verifyAndDecode(header) {\n  if (header.startsWith(bearerPrefix)) {\n    try {\n      const token = header.substring(bearerPrefix.length);\n      return jsonwebtoken.verify(token, secret, { algorithms: ['HS256'] });\n    }\n    catch (ex) {\n      throw Boom.unauthorized(STRINGS.invalidJwt);\n    }\n  }\n  throw Boom.unauthorized(STRINGS.invalidAuthHeader);\n}\n\nfunction colorCycleHandler(req) {\n  // Verify all requests.\n  const payload = verifyAndDecode(req.headers.authorization);\n  const { channel_id: channelId, opaque_user_id: opaqueUserId } = payload;\n\n  // Store the color for the channel.\n  let currentColor = channelColors[channelId] || initialColor;\n\n  // Bot abuse prevention:  don't allow a user to spam the button.\n  if (userIsInCooldown(opaqueUserId)) {\n    throw Boom.tooManyRequests(STRINGS.cooldown);\n  }\n\n  // Rotate the color as if on a color wheel.\n  verboseLog(STRINGS.cyclingColor, channelId, opaqueUserId);\n  currentColor = color(currentColor).rotate(colorWheelRotation).hex();\n\n  // Save the new color for the channel.\n  channelColors[channelId] = currentColor;\n\n  // Broadcast the color change to all other extension instances on this channel.\n  attemptColorBroadcast(channelId);\n\n  return currentColor;\n}\n\nfunction colorQueryHandler(req) {\n  // Verify all requests.\n  const payload = verifyAndDecode(req.headers.authorization);\n\n  // Get the color for the channel from the payload and return it.\n  const { channel_id: channelId, opaque_user_id: opaqueUserId } = payload;\n  const currentColor = color(channelColors[channelId] || initialColor).hex();\n  verboseLog(STRINGS.sendColor, currentColor, opaqueUserId);\n  return currentColor;\n}\n\nfunction attemptColorBroadcast(channelId) {\n  // Check the cool-down to determine if it's okay to send now.\n  const now = Date.now();\n  const cooldown = channelCooldowns[channelId];\n  if (!cooldown || cooldown.time < now) {\n    // It is.\n    sendColorBroadcast(channelId);\n    channelCooldowns[channelId] = { time: now + channelCooldownMs };\n  } else if (!cooldown.trigger) {\n    // It isn't; schedule a delayed broadcast if we haven't already done so.\n    cooldown.trigger = setTimeout(sendColorBroadcast, now - cooldown.time, channelId);\n  }\n}\n\nfunction sendColorBroadcast(channelId) {\n  // Set the HTTP headers required by the Twitch API.\n  const headers = {\n    'Client-ID': clientId,\n    'Content-Type': 'application/json',\n    'Authorization': bearerPrefix + makeServerToken(channelId),\n  };\n\n  // Create the POST body for the Twitch API request.\n  const currentColor = color(channelColors[channelId] || initialColor).hex();\n  const body = JSON.stringify({\n    content_type: 'application/json',\n    message: currentColor,\n    targets: ['broadcast'],\n  });\n\n  // Send the broadcast request to the Twitch API.\n  verboseLog(STRINGS.colorBroadcast, currentColor, channelId);\n  request(\n    `https://api.twitch.tv/extensions/message/${channelId}`,\n    {\n      method: 'POST',\n      headers,\n      body,\n    }\n    , (err, res) => {\n      if (err) {\n        console.log(STRINGS.messageSendError, channelId, err);\n      } else {\n        verboseLog(STRINGS.pubsubResponse, channelId, res.statusCode);\n      }\n    });\n}\n\n// Create and return a JWT for use by this service.\nfunction makeServerToken(channelId) {\n  const payload = {\n    exp: Math.floor(Date.now() / 1000) + serverTokenDurationSec,\n    channel_id: channelId,\n    user_id: ownerId, // extension owner ID for the call to Twitch PubSub\n    role: 'external',\n    pubsub_perms: {\n      send: ['*'],\n    },\n  };\n  return jsonwebtoken.sign(payload, secret, { algorithm: 'HS256' });\n}\n\nfunction userIsInCooldown(opaqueUserId) {\n  // Check if the user is in cool-down.\n  const cooldown = userCooldowns[opaqueUserId];\n  const now = Date.now();\n  if (cooldown && cooldown > now) {\n    return true;\n  }\n\n  // Voting extensions must also track per-user votes to prevent skew.\n  userCooldowns[opaqueUserId] = now + userCooldownMs;\n  return false;\n}\n"
  }
]