├── .env.template ├── views ├── 404.handlebars ├── unauthorized.handlebars ├── postlink.handlebars ├── login.handlebars ├── dashboard.handlebars ├── layouts │ └── main.handlebars └── links.handlebars ├── README.md ├── libs └── database.js ├── package.json ├── .gitignore ├── authcord.sql ├── LICENSE └── app.js /.env.template: -------------------------------------------------------------------------------- 1 | ENV=development 2 | PORT=3000 3 | 4 | DB_HOST= 5 | DB_USER= 6 | DB_PASS= 7 | DB_NAME= 8 | 9 | SECRET=permsarecutechangethisthough -------------------------------------------------------------------------------- /views/404.handlebars: -------------------------------------------------------------------------------- 1 |

Link not found :(

2 |

Unfortunately, a link with this code could not be found in the database. It could have possibly been deleted. Sorry about that.

-------------------------------------------------------------------------------- /views/unauthorized.handlebars: -------------------------------------------------------------------------------- 1 |

Unauthorized

2 |

Unfortunately you can't access this page. Please login to your Authcord account to authenticate yourself and check you have a valid membership.

-------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Authcord 2 | 3 | Middleware to prevent Discord links being leaked. Please take a read of the Medium article here to understand more. 4 | 5 | https://conordevs.medium.com/authcord-protecting-discord-links-7cba4e2bbf99 6 | -------------------------------------------------------------------------------- /views/postlink.handlebars: -------------------------------------------------------------------------------- 1 |

Redirecting. Please wait.

2 | 3 |
4 | {{#if data}} 5 | {{#each data}} 6 | 7 | {{/each}} 8 | {{/if}} 9 |
10 | 11 | -------------------------------------------------------------------------------- /views/login.handlebars: -------------------------------------------------------------------------------- 1 |
2 |

Login

3 | 4 | 5 | 6 | {{#if error }} 7 |

{{ error }}

8 | {{/if}} 9 |
10 | -------------------------------------------------------------------------------- /libs/database.js: -------------------------------------------------------------------------------- 1 | const Knex = require("knex") 2 | const dotenv = require("dotenv").config() 3 | 4 | const knex = database => { 5 | const db = Knex({ 6 | client: "mysql", 7 | useNullAsDefault: true, 8 | connection: { 9 | host: process.env.DB_HOST, 10 | database: database, 11 | user: process.env.DB_USER, 12 | password: process.env.DB_PASS, 13 | supportBigNumbers: true, 14 | }, 15 | }) 16 | 17 | return db 18 | } 19 | 20 | module.exports = knex 21 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Authcord", 3 | "version": "1.0.0", 4 | "description": "Middleware to prevent Discord links being leaked.", 5 | "main": "app.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/unreleased/Authcord.git" 12 | }, 13 | "keywords": [ 14 | "Authcord", 15 | "Authentication" 16 | ], 17 | "author": "@unreleased", 18 | "license": "ISC", 19 | "bugs": { 20 | "url": "https://github.com/unreleased/Authcord/issues" 21 | }, 22 | "homepage": "https://github.com/unreleased/Authcord#readme", 23 | "dependencies": { 24 | "bcryptjs": "^2.4.3", 25 | "body-parser": "^1.19.0", 26 | "cookie-parser": "^1.4.5", 27 | "dotenv": "^8.2.0", 28 | "express": "^4.17.1", 29 | "express-handlebars": "^5.2.0", 30 | "express-session": "^1.17.1", 31 | "knex": "^0.21.12", 32 | "mysql": "^2.18.1", 33 | "uuid": "^8.3.2" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /views/dashboard.handlebars: -------------------------------------------------------------------------------- 1 |

Dashboard

2 | 3 | 6 | 7 |
8 | {{#if member}} 9 |

You are a member

10 | {{else}} 11 |

You are not a member

12 | {{/if}} 13 |
14 | 15 |
16 |

Authenticated IPs

17 |

These IPs will be given unlimited authentication. The device does not matter. The IP you are currently accessing this webpage from is: {{ ip }}. Having an IP authed means you will not have to authenticate the browser you are requesting on if you are using one of your listed IP addresses.

18 | 19 | 20 | 21 | 22 | {{#if ip_error}} 23 |

{{ ip_error }}

24 | {{/if}} 25 | 26 |
27 | 28 |
29 |

Browser sessions

30 |

You can authenticate a maximum of 5 browser sessions. For every new authentication afterwards the oldest session will be deleted.

31 | {{#each sessions }} 32 |
33 |

{{ this.id}}
({{ this.user_agent }})

34 |

{{ this.created_at }}

35 |
36 | {{/each}} 37 | 38 |
39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /views/layouts/main.handlebars: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Authcord 7 | 8 | 97 | 98 | 99 |
100 | {{{ body }}} 101 |
102 | 103 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /views/links.handlebars: -------------------------------------------------------------------------------- 1 |

Link Creator

2 |

Here is an example of link creation using a GUI rather than an API request. We use this in Express so staff can create private GB links without needing development experience.

3 | 4 |
5 |

Shortlink code

6 | 7 | 8 |

Destination URL

9 | 10 | 11 |

Method

12 | 16 | 17 | 22 | 23 | 24 |

Link Obfuscation

25 | 29 | 33 | 37 | 38 |

39 |

40 | 41 | 42 |
43 | 44 | -------------------------------------------------------------------------------- /authcord.sql: -------------------------------------------------------------------------------- 1 | -- phpMyAdmin SQL Dump 2 | -- version 4.8.5 3 | -- https://www.phpmyadmin.net/ 4 | -- 5 | -- Host: [REDACTED] 6 | -- Generation Time: Dec 12, 2020 at 05:54 PM 7 | -- Server version: 5.7.25-google-log 8 | -- PHP Version: 7.2.15 9 | 10 | SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 11 | SET AUTOCOMMIT = 0; 12 | START TRANSACTION; 13 | SET time_zone = "+00:00"; 14 | 15 | 16 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 17 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 18 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 19 | /*!40101 SET NAMES utf8mb4 */; 20 | 21 | -- 22 | -- Database: `authcord` 23 | -- 24 | CREATE DATABASE IF NOT EXISTS `authcord` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin; 25 | USE `authcord`; 26 | 27 | -- -------------------------------------------------------- 28 | 29 | -- 30 | -- Table structure for table `dynamic_urls` 31 | -- 32 | 33 | CREATE TABLE `dynamic_urls` ( 34 | `id` int(11) NOT NULL, 35 | `user_id` int(11) NOT NULL, 36 | `full_url` varchar(512) COLLATE utf8mb4_bin NOT NULL, 37 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 38 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; 39 | 40 | -- -------------------------------------------------------- 41 | 42 | -- 43 | -- Table structure for table `ips` 44 | -- 45 | 46 | CREATE TABLE `ips` ( 47 | `id` int(11) NOT NULL, 48 | `user_id` int(11) NOT NULL, 49 | `ip_address` varchar(128) COLLATE utf8mb4_bin NOT NULL, 50 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 51 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; 52 | 53 | -- -------------------------------------------------------- 54 | 55 | -- 56 | -- Table structure for table `outbound` 57 | -- 58 | 59 | CREATE TABLE `outbound` ( 60 | `id` int(11) NOT NULL, 61 | `ip_address` varchar(128) COLLATE utf8mb4_bin NOT NULL, 62 | `user_agent` varchar(255) COLLATE utf8mb4_bin NOT NULL, 63 | `code` varchar(6) COLLATE utf8mb4_bin NOT NULL, 64 | `auth_method` varchar(32) COLLATE utf8mb4_bin NOT NULL, 65 | `auth_value` varchar(64) COLLATE utf8mb4_bin NOT NULL, 66 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 67 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; 68 | 69 | -- -------------------------------------------------------- 70 | 71 | -- 72 | -- Table structure for table `saved_ips` 73 | -- 74 | 75 | CREATE TABLE `saved_ips` ( 76 | `id` int(11) NOT NULL, 77 | `user_id` int(11) NOT NULL, 78 | `ip_address` varchar(128) COLLATE utf8mb4_bin NOT NULL, 79 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 80 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; 81 | 82 | -- -------------------------------------------------------- 83 | 84 | -- 85 | -- Table structure for table `saved_sessions` 86 | -- 87 | 88 | CREATE TABLE `saved_sessions` ( 89 | `id` varchar(64) COLLATE utf8mb4_bin NOT NULL, 90 | `user_id` int(11) NOT NULL, 91 | `user_agent` varchar(512) COLLATE utf8mb4_bin NOT NULL, 92 | `ip_address` varchar(64) COLLATE utf8mb4_bin NOT NULL, 93 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 94 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; 95 | 96 | -- -------------------------------------------------------- 97 | 98 | -- 99 | -- Table structure for table `sessions` 100 | -- 101 | 102 | CREATE TABLE `sessions` ( 103 | `id` varchar(64) COLLATE utf8mb4_bin NOT NULL, 104 | `user_id` int(11) NOT NULL, 105 | `user_agent` varchar(512) COLLATE utf8mb4_bin NOT NULL, 106 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 107 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; 108 | 109 | -- -------------------------------------------------------- 110 | 111 | -- 112 | -- Table structure for table `shortlinks` 113 | -- 114 | 115 | CREATE TABLE `shortlinks` ( 116 | `id` int(11) NOT NULL, 117 | `code` varchar(6) COLLATE utf8mb4_bin NOT NULL, 118 | `method` enum('GET','POST') COLLATE utf8mb4_bin NOT NULL DEFAULT 'GET', 119 | `data` json DEFAULT NULL, 120 | `linkbust` varchar(64) COLLATE utf8mb4_bin DEFAULT NULL, 121 | `destination` varchar(512) COLLATE utf8mb4_bin NOT NULL, 122 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 123 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; 124 | 125 | -- -------------------------------------------------------- 126 | 127 | -- 128 | -- Table structure for table `users` 129 | -- 130 | 131 | CREATE TABLE `users` ( 132 | `id` int(11) NOT NULL, 133 | `email` varchar(255) COLLATE utf8mb4_bin NOT NULL, 134 | `member` tinyint(1) NOT NULL DEFAULT '0', 135 | `password` varchar(128) COLLATE utf8mb4_bin NOT NULL, 136 | `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 137 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin; 138 | 139 | -- 140 | -- Indexes for dumped tables 141 | -- 142 | 143 | -- 144 | -- Indexes for table `dynamic_urls` 145 | -- 146 | ALTER TABLE `dynamic_urls` 147 | ADD PRIMARY KEY (`id`), 148 | ADD KEY `user_id` (`user_id`); 149 | 150 | -- 151 | -- Indexes for table `ips` 152 | -- 153 | ALTER TABLE `ips` 154 | ADD PRIMARY KEY (`id`); 155 | 156 | -- 157 | -- Indexes for table `outbound` 158 | -- 159 | ALTER TABLE `outbound` 160 | ADD PRIMARY KEY (`id`); 161 | 162 | -- 163 | -- Indexes for table `saved_ips` 164 | -- 165 | ALTER TABLE `saved_ips` 166 | ADD PRIMARY KEY (`id`); 167 | 168 | -- 169 | -- Indexes for table `saved_sessions` 170 | -- 171 | ALTER TABLE `saved_sessions` 172 | ADD PRIMARY KEY (`id`), 173 | ADD UNIQUE KEY `session_id` (`id`); 174 | 175 | -- 176 | -- Indexes for table `sessions` 177 | -- 178 | ALTER TABLE `sessions` 179 | ADD PRIMARY KEY (`id`), 180 | ADD UNIQUE KEY `session_id` (`id`); 181 | 182 | -- 183 | -- Indexes for table `shortlinks` 184 | -- 185 | ALTER TABLE `shortlinks` 186 | ADD PRIMARY KEY (`id`), 187 | ADD KEY `code` (`code`); 188 | 189 | -- 190 | -- Indexes for table `users` 191 | -- 192 | ALTER TABLE `users` 193 | ADD PRIMARY KEY (`id`), 194 | ADD UNIQUE KEY `email` (`email`); 195 | 196 | -- 197 | -- AUTO_INCREMENT for dumped tables 198 | -- 199 | 200 | -- 201 | -- AUTO_INCREMENT for table `dynamic_urls` 202 | -- 203 | ALTER TABLE `dynamic_urls` 204 | MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; 205 | 206 | -- 207 | -- AUTO_INCREMENT for table `ips` 208 | -- 209 | ALTER TABLE `ips` 210 | MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; 211 | 212 | -- 213 | -- AUTO_INCREMENT for table `outbound` 214 | -- 215 | ALTER TABLE `outbound` 216 | MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; 217 | 218 | -- 219 | -- AUTO_INCREMENT for table `saved_ips` 220 | -- 221 | ALTER TABLE `saved_ips` 222 | MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; 223 | 224 | -- 225 | -- AUTO_INCREMENT for table `shortlinks` 226 | -- 227 | ALTER TABLE `shortlinks` 228 | MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; 229 | 230 | -- 231 | -- AUTO_INCREMENT for table `users` 232 | -- 233 | ALTER TABLE `users` 234 | MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; 235 | COMMIT; 236 | 237 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 238 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 239 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 240 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /app.js: -------------------------------------------------------------------------------- 1 | const dotenv = require("dotenv").config() 2 | const express = require("express") 3 | const knex = require("./libs/database")(process.env.DB_NAME) 4 | const handlebars = require("express-handlebars") 5 | const session = require("express-session") 6 | const bcrypt = require("bcryptjs") 7 | const bodyParser = require("body-parser") 8 | const { v4: uuidv4 } = require("uuid") 9 | const cookieParser = require("cookie-parser") 10 | 11 | const app = express() 12 | 13 | app.engine( 14 | "handlebars", 15 | handlebars({ 16 | layoutsDir: __dirname + "/views/layouts", 17 | }) 18 | ) 19 | 20 | app.use(bodyParser.urlencoded({ extended: true })) 21 | app.use(bodyParser.json()) 22 | app.use(cookieParser()) 23 | 24 | /** 25 | * You may need to configure forwarding IPs if you're using NGINX as a reverse proxy 26 | */ 27 | 28 | const sess = { 29 | secret: process.env.SECRET, 30 | cookie: {}, 31 | resave: true, 32 | saveUninitialized: true, 33 | } 34 | 35 | if (process.env.ENV === "production") { 36 | app.set("trust proxy", 1) 37 | sess.cookie.secure = true 38 | } 39 | 40 | app.use(session(sess)) 41 | 42 | app.use(function (req, res, next) { 43 | // req.session.user = true 44 | 45 | // Careful with this, if you're not using a reverse proxy people could just spoof x-forwarded-for and "pretend" to be an IP address 46 | // This was designed for use with NGINX but would be really easy to convert for any other platform. 47 | req.ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress 48 | next() 49 | }) 50 | 51 | /** 52 | * Authentication middleware. Check if the user has an active browser session or has their IP authed. 53 | */ 54 | 55 | const authed = async (req, res, next) => { 56 | if (req.session.user) { 57 | return next() 58 | } 59 | 60 | // Return unauthorized 61 | return res.redirect("/login") 62 | } 63 | 64 | /** 65 | * Homepage, this is the "control panel". 66 | * It requires authentication to access. This lets the user customise their IP address and manage their browser sessions. 67 | */ 68 | 69 | app.get( 70 | "/l/:code", 71 | async (req, res, next) => { 72 | /** 73 | * So I discussed this a fair bit with Prism's @mzchael_ - We concluded that if a user is spoofing a sessionId cookie then it doesn't really matter how long it takes for them to be redirected because they're trying be malicious. A user using an expired browser session would be quite rare and ideally we want to only do a two-table lookup (user,session or user,ip) rather than using multiple joins and comparing them all at once, we could also improve this by using redis/memcache for faster lookups than db queries. 74 | */ 75 | 76 | // Check if they have a valid user session (No query required) 77 | if (req.session.user) { 78 | req.method_name = "USER" 79 | req.method_value = req.user_id = req.session.user.id 80 | 81 | if (req.session.user.member) { 82 | return next() 83 | } 84 | } 85 | 86 | // Check if they have a valid session_id cookie. 87 | if (req.cookies.sessionId) { 88 | const session = await knex("users") 89 | .select(["users.id", "users.member", "sessions.id as session_id"]) 90 | .innerJoin("sessions", "sessions.user_id", "=", "users.id") 91 | .where("sessions.id", req.cookies.sessionId) 92 | .first() 93 | 94 | if (session && session.member) { 95 | req.method_name = "SESSION" 96 | req.method_value = req.cookies.sessionId 97 | req.user_id = session.id 98 | return next() 99 | } else if (!session) { 100 | // We could also log the session and compare it against the "saved_sessions" table to see if it _used_ to be active or was spoofed. 101 | res.clearCookie("sessionId") 102 | } 103 | } 104 | 105 | // Check IP is authed then redirect the user. 106 | const ip = req.ip || null 107 | const ipSession = await knex("users") 108 | .select(["users.id", "users.member", "ips.ip_address"]) 109 | .innerJoin("ips", "ips.user_id", "=", "users.id") 110 | .where("ips.ip_address", ip) 111 | .first() 112 | 113 | if (ipSession && ipSession.member) { 114 | req.method_name = "IP" 115 | req.method_value = req.ip 116 | req.user_id = ipSession.id 117 | return next() 118 | } 119 | 120 | // Return unauthorized 121 | return res.status(401).render("unauthorized.handlebars") 122 | }, 123 | async (req, res) => { 124 | // We have to be careful here because there can be an unlimited amount of user sessions 125 | // We will record outbound traffic requests incase of anything malicious 126 | knex("outbound") 127 | .insert({ 128 | ip_address: req.ip, 129 | user_agent: req.headers["user-agent"], 130 | code: req.params.code, 131 | auth_method: req.method_name, 132 | auth_value: req.method_value, 133 | }) 134 | .then(res => { 135 | // Successfully stored traffic data. 136 | }) 137 | 138 | // Select shortlink (get lastest one in case of duplicates) 139 | const shortlink = await knex("shortlinks").where("code", req.params.code).orderBy("id", "DESC").first() 140 | 141 | if (!shortlink) { 142 | return res.render("404.handlebars") 143 | } 144 | 145 | // Link obfuscation techniques: 146 | if (shortlink.linkbust) { 147 | const techniques = shortlink.linkbust.split("|") 148 | for (const technique of techniques) { 149 | switch (technique) { 150 | // Random capitalization 151 | case "CAPITALS": 152 | shortlink.destination = shortlink.destination 153 | .split("") 154 | .map(v => (Math.round(Math.random()) ? v.toUpperCase() : v.toLowerCase())) 155 | .join("") 156 | break 157 | case "CACHEBUST": 158 | // Random query parameter 159 | const url = new URL(shortlink.destination) 160 | const ranKey = rs(5) 161 | const ranVal = rs(5) 162 | url.searchParams.append(ranKey, ranVal) 163 | shortlink.destination = url.href 164 | break 165 | case "RANDOM": 166 | // Replace %RAN% inside URL with random values 167 | for (let i = 0; i < shortlink.destination.split("%RAN%").length; i++) { 168 | const ran = rs(5) 169 | shortlink.destination = shortlink.destination.replace("%RAN%", ran) 170 | } 171 | 172 | break 173 | } 174 | } 175 | } 176 | 177 | knex("dynamic_urls") 178 | .insert({ 179 | user_id: req.user_id, 180 | full_url: shortlink.destination, 181 | }) 182 | .then(res => { 183 | console.log(`[USER: ${req.user_id}] ACCESS: ${shortlink.destination}`) 184 | }) 185 | 186 | if (shortlink.method === "GET") { 187 | return res.redirect(shortlink.destination) 188 | } else { 189 | return res.render("postlink.handlebars", { 190 | data: JSON.parse(shortlink.data), 191 | destination: shortlink.destination, 192 | }) 193 | } 194 | } 195 | ) 196 | 197 | app.post("/l", async (req, res) => { 198 | /** 199 | * You will want to add some admin/private key authentication here so not anyone can create a link. 200 | * You can also save the link directly to the database from a script rather than doing through an API which would require a HTTP request rather than just a single SQL query. 201 | * If a code is not set it will be randomly generated. 202 | */ 203 | 204 | let code = req.body.code 205 | if (!code) { 206 | code = rs(5) 207 | } 208 | 209 | /** 210 | * Link bust should be an array containing the type of link obfuscation you want to perform to the URL 211 | */ 212 | 213 | if (!req.body.method) { 214 | return res.status(400).json({ 215 | error: "Missing `method` parameter.", 216 | }) 217 | } 218 | 219 | if (!["GET", "POST"].includes(req.body.method.toUpperCase())) { 220 | return res.status(400).json({ 221 | error: "Invalid `method` parameter. The method must either be POST or GET.", 222 | }) 223 | } 224 | 225 | if (!req.body.destination) { 226 | return res.status(400).json({ 227 | error: "Missing `destination` parameter.", 228 | }) 229 | } 230 | 231 | if (req.body.data) { 232 | if (req.body.method === "GET") { 233 | return res.status(400).json({ 234 | error: "A method of `GET` cannot contain form-data.", 235 | }) 236 | } 237 | 238 | if (typeof req.body.data !== "object") { 239 | return res.status(400).json({ 240 | error: "The `data` parameter must be a key-value object.", 241 | }) 242 | } 243 | } 244 | 245 | // The order of linkbusting is important, this script automatically corrects that. 246 | let linkbustList = req.body.linkbust ? [] : null 247 | if (req.body.linkbust) { 248 | if (typeof req.body.linkbust !== "object") { 249 | return res.status(400).json({ 250 | error: "The `linkbust` parameter must be an array.", 251 | }) 252 | } 253 | 254 | linkbust = req.body.linkbust.map(lb => lb.toUpperCase()) 255 | 256 | if (linkbust.includes("RANDOM")) { 257 | linkbustList.push("RANDOM") 258 | } 259 | 260 | if (linkbust.includes("CACHEBUST")) { 261 | linkbustList.push("CACHEBUST") 262 | } 263 | 264 | if (linkbust.includes("CAPITALS")) { 265 | linkbustList.push("CAPITALS") 266 | } 267 | 268 | linkbustList = linkbustList.join("|") 269 | } 270 | 271 | knex("shortlinks") 272 | .insert({ 273 | code: code, 274 | method: req.body.method.toUpperCase(), 275 | data: req.body.data ? JSON.stringify(req.body.data) : null, 276 | destination: req.body.destination, 277 | linkbust: linkbustList, 278 | }) 279 | .then(res => { 280 | console.log(`[SHORTLINK] [${code}] Shortlink destined to: ${req.body.destination} has been created`) 281 | }) 282 | .catch(err => { 283 | console.log(`[SHORTLINK] [${code}] There was an error trying to save the link inside the database. ${err.message}`) 284 | }) 285 | 286 | return res.json({ 287 | message: "Shortlink creation in progress.", 288 | code: code, 289 | }) 290 | }) 291 | 292 | app.get("/links", authed, async (req, res) => { 293 | return res.render("links.handlebars") 294 | }) 295 | 296 | app.get("/", authed, async (req, res) => { 297 | // Update user 298 | req.session.user.ips = (await knex("ips").where("user_id", req.session.user.id)).map(row => row.ip_address) 299 | req.session.user.sessions = await knex("sessions").where("user_id", req.session.user.id) 300 | 301 | return res.render("dashboard.handlebars", { 302 | ip: req.ip, 303 | ips: req.session.user.ips, 304 | sessions: req.session.user.sessions, 305 | member: req.session.user.member, 306 | }) 307 | }) 308 | 309 | app.post("/", authed, async (req, res) => { 310 | if (req.body.type === "ip_change") { 311 | const { ip_1, ip_2 } = req.body 312 | 313 | // Delete their current IPs from the database & resave them, we also save all the IPs used/changed inside saved_ips so we can relate them to any outbound traffic session 314 | // IP format validation could be added here... 315 | try { 316 | await knex("ips").where("user_id", req.session.user.id).delete() 317 | 318 | if (ip_1) { 319 | const ip = { 320 | user_id: req.session.user.id, 321 | ip_address: ip_1, 322 | } 323 | 324 | await knex("ips").insert(ip) 325 | await knex("saved_ips").insert(ip) 326 | } 327 | 328 | if (ip_2) { 329 | const ip = { 330 | user_id: req.session.user.id, 331 | ip_address: ip_2, 332 | } 333 | 334 | await knex("ips").insert(ip) 335 | await knex("saved_ips").insert(ip) 336 | } 337 | 338 | req.session.user.ips = (await knex("ips").where("user_id", req.session.user.id)).map(row => row.ip_address) 339 | } catch (err) { 340 | return res.render("dashboard.handlebars", { 341 | ip_error: "There was an erroring trying to update your IP addresses.", 342 | }) 343 | } 344 | } 345 | 346 | return res.redirect("/") 347 | }) 348 | 349 | app.get("/login", (req, res) => { 350 | if (req.session.user) { 351 | return res.redirect("/") 352 | } 353 | 354 | return res.render("login.handlebars") 355 | }) 356 | 357 | app.post("/login", async (req, res) => { 358 | // Check if login details are correct 359 | const { email, password } = req.body 360 | 361 | if (!email) { 362 | return res.status(400).render("login.handlebars", { 363 | error: "Missing email address.", 364 | }) 365 | } 366 | 367 | if (!password) { 368 | return res.status(400).render("login.handlebars", { 369 | error: "Missing password.", 370 | }) 371 | } 372 | 373 | const user = await knex("users").where("email", email).first() 374 | if (!user) { 375 | return res.status(400).render("login.handlebars", { 376 | error: "User does not exist.", 377 | }) 378 | } 379 | 380 | const match = await bcrypt.compare(password, user.password) 381 | if (!match) { 382 | return res.status(400).render("login.handlebars", { 383 | error: "Invalid password.", 384 | }) 385 | } 386 | 387 | // Check the cookie the user has is actually valid (remember, cookies can be spoofed) 388 | let validSession = false 389 | if (req.cookies.sessionId) { 390 | const currentSession = await knex("sessions").where("id", req.cookies.sessionId).first() 391 | if (currentSession) { 392 | if (currentSession.user_id === user.id) { 393 | validSession = true 394 | } else { 395 | // A clash between two account sessions, you could perform logging here. 396 | } 397 | } 398 | } 399 | 400 | // Set a cookie on the users browser with their browser session ID and create a session in the database 401 | 402 | if (!req.cookies.sessionId && !validSession) { 403 | const sessionId = uuidv4() 404 | const currentSessions = await knex("sessions").where("user_id", user.id).orderBy("id", "ASC") 405 | 406 | if (currentSessions.length === 5) { 407 | const lastSession = currentSessions[0] 408 | // Delete oldest session 409 | await knex("sessions").where("user_id", user.id).where("id", lastSession.id).delete() 410 | } 411 | 412 | await knex("sessions").insert({ 413 | id: sessionId, 414 | user_id: user.id, 415 | user_agent: req.headers["user-agent"], 416 | }) 417 | 418 | // Used for tracking malicious activity. 419 | await knex("saved_sessions").insert({ 420 | id: sessionId, 421 | user_id: user.id, 422 | user_agent: req.headers["user-agent"], 423 | ip_address: req.ip, 424 | }) 425 | 426 | res.cookie("sessionId", sessionId) 427 | } 428 | 429 | // Pull latest information from database and store in session 430 | req.session.user = user 431 | req.session.user.ips = (await knex("ips").where("user_id", user.id)).map(row => row.ip_address) 432 | req.session.user.sessions = await knex("sessions").where("user_id", user.id) 433 | 434 | return res.redirect("/") 435 | }) 436 | 437 | app.listen(process.env.PORT, () => { 438 | console.log(`[AUTHCORD] Authcording listening at http://localhost:${process.env.PORT}`) 439 | }) 440 | 441 | function rs(length) { 442 | /** 443 | * Thanks stackoverflow. I use this wayyy too much. 444 | */ 445 | 446 | let result = "" 447 | let characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" 448 | let charactersLength = characters.length 449 | for (let i = 0; i < length; i++) { 450 | result += characters.charAt(Math.floor(Math.random() * charactersLength)) 451 | } 452 | return result 453 | } 454 | --------------------------------------------------------------------------------