35 Commits

Author SHA1 Message Date
nai-degen 15f697aa6e adds users sqlite migration and WIP repository 2024-05-26 19:51:47 -05:00
nai-degen a59b6555e7 redacts de3u api-key from diagnostic logs 2024-05-26 15:13:21 -05:00
scrappyanon 2d82e55d72 Sqlite backend with user event logging (khanon/oai-reverse-proxy!69) 2024-05-26 17:31:12 +00:00
nai-degen 6352df5d5a fixes mixed ipv4-ipv6 handling in cidr module 2024-05-24 02:55:11 -05:00
nai-degen 7d517a4c5f fixes Refresh Token UI incorrectly discarding expired (but refreshable) temp tokens 2024-05-22 22:18:23 -05:00
nai-degen 0418951928 tries to provide better guidance on CSRF errors 2024-05-21 13:10:54 -05:00
nai-degen 3012aa651e adds slightly less-ugly global stylesheet; improves mobile compat 2024-05-21 12:56:25 -05:00
nai-degen 1b68ad7c6f docs update 2024-05-21 12:46:51 -05:00
nai-degen 68b48428de adjusts gatekeeper module to send auth errors as fake chat completions 2024-05-21 12:44:43 -05:00
nai-degen b76db652e0 adds configurable PoW timeout and iteration count 2024-05-21 12:38:41 -05:00
nai-degen 63ab1a7685 reverts debug change that broke info page 2024-05-20 07:47:46 -05:00
nai-degen a3462e21bc adds config setting for PoW verification timeout 2024-05-19 15:17:25 -05:00
nai-degen 8d2ed23522 fixes inverted refreshtoken logic 2024-05-19 12:35:15 -05:00
khanon 205ffa69ce Temporary usertokens via proof-of-work challenge (khanon/oai-reverse-proxy!68) 2024-05-19 16:31:56 +00:00
nai-degen 930bac0072 bumps ejs package version 2024-05-17 21:46:27 -05:00
nai-degen 3ad826851c adds proper GPT4o model family for separate cost/quota tracking 2024-05-14 13:51:19 -05:00
nai-degen 6dabc82bcf adds preliminary gpt4o 2024-05-13 12:43:39 -05:00
nai-degen d3e7ef3c14 prevents leaking headers to upstream API when serving via Tailscale 2024-05-01 11:26:15 -05:00
nai-degen b1062dc9b3 minor adjustments to jsonl log backend to reduce filesize 2024-04-26 15:06:12 -05:00
nai-degen 32b623d6bc partial googleai fixes; adds jsonl file backend for promptlogger stolen from fiz 2024-04-23 03:43:38 -05:00
nai-degen 0a27345c29 upgrades firebase-admin from 11.10.1 to 12.1.0 2024-04-22 12:36:41 -05:00
nai-degen c15f07c0d8 adds OpenAI-to-AWS Claude3 compat endpoint 2024-04-17 21:23:30 -05:00
nai-degen db28e90c51 adds proper Opus model check to aws claude keychecker 2024-04-17 21:09:00 -05:00
nai-degen c0cd2c7549 adds aws opus maybe, idk cannot test 2024-04-16 11:33:44 -05:00
nai-degen 9445110727 adds gpt-4-turbo stable 2024-04-09 16:31:42 -05:00
nai-degen 34a673a80a adds option to disable multimodal prompts 2024-03-23 14:30:14 -05:00
nai-degen 8cb960e174 fixes incorrect model assignment when requesting Haiku from AWS 2024-03-21 23:21:27 -05:00
nai-degen 32fea30c91 handles Anthropic keys which cannot support multimodal requests 2024-03-20 00:03:10 -05:00
nai-degen 3f9fd25004 exempt 'special' token type from context size limits 2024-03-19 11:14:51 -05:00
nai-degen e068edcf48 adds Anthropic key tier detection and trial key display 2024-03-18 15:20:34 -05:00
nai-degen 2098948b7a reduces Anthropic keychecker frequency 2024-03-18 15:19:41 -05:00
nai-degen 7705ee58a0 minor cleanup of error-generator.ts 2024-03-18 15:18:18 -05:00
nai-degen 7c64d9209e minor refactoring of response middleware handlers 2024-03-17 22:20:39 -05:00
nai-degen 59107af3d6 minor fixes for google sheets backend for anthropic-chat 2024-03-17 12:08:11 -05:00
nai-degen 435280fa04 fixes missing system prompt on AWS anthropic-chat schema 2024-03-16 16:00:59 -05:00
88 changed files with 5803 additions and 1265 deletions
+15 -2
View File
@@ -40,12 +40,14 @@ NODE_ENV=production
# Which model types users are allowed to access.
# The following model families are recognized:
# turbo | gpt4 | gpt4-32k | gpt4-turbo | dall-e | claude | claude-opus | gemini-pro | mistral-tiny | mistral-small | mistral-medium | mistral-large | aws-claude | azure-turbo | azure-gpt4 | azure-gpt4-32k | azure-gpt4-turbo | azure-dall-e
# turbo | gpt4 | gpt4-32k | gpt4-turbo | gpt4o | dall-e | claude | claude-opus | gemini-pro | mistral-tiny | mistral-small | mistral-medium | mistral-large | aws-claude | aws-claude-opus | azure-turbo | azure-gpt4 | azure-gpt4-32k | azure-gpt4-turbo | azure-gpt4o | azure-dall-e
# By default, all models are allowed except for 'dall-e' / 'azure-dall-e'.
# To allow DALL-E image generation, uncomment the line below and add 'dall-e' or
# 'azure-dall-e' to the list of allowed model families.
# ALLOWED_MODEL_FAMILIES=turbo,gpt4,gpt4-32k,gpt4-turbo,claude,claude-opus,gemini-pro,mistral-tiny,mistral-small,mistral-medium,mistral-large,aws-claude,azure-turbo,azure-gpt4,azure-gpt4-32k,azure-gpt4-turbo
# ALLOWED_MODEL_FAMILIES=turbo,gpt4,gpt4-32k,gpt4-turbo,gpt4o,claude,claude-opus,gemini-pro,mistral-tiny,mistral-small,mistral-medium,mistral-large,aws-claude,aws-claude-opus,azure-turbo,azure-gpt4,azure-gpt4-32k,azure-gpt4-turbo,azure-gpt4o
# IP addresses or CIDR blocks from which requests will be blocked.
# IP_BLACKLIST=10.0.0.1/24
# URLs from which requests will be blocked.
# BLOCKED_ORIGINS=reddit.com,9gag.com
# Message to show when requests are blocked.
@@ -74,6 +76,13 @@ NODE_ENV=production
# Detail level of logging. (trace | debug | info | warn | error)
# LOG_LEVEL=info
# Captcha verification settings. Refer to docs/pow-captcha.md for guidance.
# CAPTCHA_MODE=none
# POW_TOKEN_HOURS=24
# POW_TOKEN_MAX_IPS=2
# POW_DIFFICULTY_LEVEL=low
# POW_CHALLENGE_TIMEOUT=30
# ------------------------------------------------------------------------------
# Optional settings for user management, access control, and quota enforcement:
# See `docs/user-management.md` for more information and setup instructions.
@@ -136,6 +145,10 @@ AZURE_CREDENTIALS=azure-resource-name:deployment-id:api-key,another-azure-resour
# With user_token gatekeeper, the admin password used to manage users.
# ADMIN_KEY=your-very-secret-key
# To restrict access to the admin interface to specific IP addresses, set the
# ADMIN_WHITELIST environment variable to a comma-separated list of CIDR blocks.
# ADMIN_WHITELIST=0.0.0.0/0
# With firebase_rtdb gatekeeper storage, the Firebase project credentials.
# FIREBASE_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+3 -4
View File
@@ -1,11 +1,10 @@
{
"plugins": ["prettier-plugin-ejs"],
"overrides": [
{
"files": [
"*.ejs"
],
"files": "*.ejs",
"options": {
"printWidth": 160,
"printWidth": 120,
"bracketSameLine": true
}
}
+135
View File
@@ -0,0 +1,135 @@
# Proof-of-work Verification
You can require users to complete a proof-of-work before they can access the
proxy. This can increase the cost of denial of service attacks and slow down
automated abuse.
When configured, users access the challenge UI and request a token. The server
sends a challenge to the client, which asks the user's browser to find a
solution to the challenge that meets a certain constraint (the difficulty
level). Once the user has found a solution, they can submit it to the server
and get a user token valid for a period you specify.
The proof-of-work challenge uses the argon2id hash function.
## Configuration
To enable proof-of-work verification, set the following environment variables:
```
GATEKEEPER=user_token
CAPTCHA_MODE=proof_of_work
# Validity of the token in hours
POW_TOKEN_HOURS=24
# Max number of IPs that can use a user_token issued via proof-of-work
POW_TOKEN_MAX_IPS=2
# The difficulty level of the proof-of-work challenge. You can use one of the
# predefined levels specified below, or you can specify a custom number of
# expected hash iterations.
POW_DIFFICULTY_LEVEL=low
# The time limit for solving the challenge, in minutes
POW_CHALLENGE_TIMEOUT=30
```
## Difficulty Levels
The difficulty level controls how long, on average, it will take for a user to
solve the proof-of-work challenge. Due to randomness, the actual time can very
significantly; lucky users may solve the challenge in a fraction of the average
time, while unlucky users may take much longer.
The difficulty level doesn't affect the speed of the hash function itself, only
the number of hashes that will need to be computed. Therefore, the time required
to complete the challenge scales linearly with the difficulty level's iteration
count.
You can adjust the difficulty level while the proxy is running from the admin
interface.
Be aware that there is a time limit for solving the challenge, by default set to
30 minutes. Above 'high' difficulty, you will probably need to increase the time
limit or it will be very hard for users with slow devices to find a solution
within the time limit.
### Low
- Average of 200 iterations required
- Default setting.
### Medium
- Average of 900 iterations required
### High
- Average of 1900 iterations required
### Extreme
- Average of 4000 iterations required
- Not recommended unless you are expecting very high levels of abuse
- May require increasing `POW_CHALLENGE_TIMEOUT`
### Custom
Setting `POW_DIFFICULTY_LEVEL` to an integer will use that number of iterations
as the difficulty level.
## Other challenge settings
- `POW_CHALLENGE_TIMEOUT`: The time limit for solving the challenge, in minutes.
Default is 30.
- `POW_TOKEN_HOURS`: The period of time for which a user token issued via proof-
of-work can be used. Default is 24 hours. Starts when the challenge is solved.
- `POW_TOKEN_MAX_IPS`: The maximum number of unique IPs that can use a single
user token issued via proof-of-work. Default is 2.
- `POW_TOKEN_PURGE_HOURS`: The period of time after which an expired user token
issued via proof-of-work will be removed from the database. Until it is
purged, users can refresh expired tokens by completing a half-difficulty
challenge. Default is 48 hours.
- `POW_MAX_TOKENS_PER_IP`: The maximum number of active user tokens that can
be associated with a single IP address. After this limit is reached, the
oldest token will be forcibly expired when a new token is issued. Set to 0
to disable this feature. Default is 0.
## Custom argon2id parameters
You can set custom argon2id parameters for the proof-of-work challenge.
Generally, you should not need to change these unless you have a specific
reason to do so.
The listed values are the defaults.
```
ARGON2_TIME_COST=8
ARGON2_MEMORY_KB=65536
ARGON2_PARALLELISM=1
ARGON2_HASH_LENGTH=32
```
Increasing parallelism will not do much except increase memory consumption for
both the client and server, because browser proof-of-work implementations are
single-threaded. It's better to increase the time cost if you want to increase
the difficulty.
Increasing memory too much may cause memory exhaustion on some mobile devices,
particularly on iOS due to the way Safari handles WebAssembly memory allocation.
## Tested hash rates
These were measured with the default argon2id parameters listed above. These
tests were not at all scientific so take them with a grain of salt.
Safari does not like large WASM memory usage, so concurrency is limited to 4 to
avoid overallocating memory on mobile WebKit browsers. Thermal throttling can
also significantly reduce hash rates on mobile devices.
- Intel Core i9-13900K (Chrome): 33-35 H/s
- Intel Core i9-13900K (Firefox): 29-32 H/s
- Intel Core i9-13900K (Chrome, in VM limited to 4 cores): 12.2 - 13.0 H/s
- iPad Pro (M2) (Safari, 6 workers): 8.0 - 10 H/s
- Thermal throttles early. 8 cores is normal concurrency, but unstable.
- iPhone 13 Pro (Safari): 4.0 - 4.6 H/s
- Samsung Galaxy S10e (Chrome): 3.6 - 3.8 H/s
- This is a 2019 phone almost matching an iPhone five years newer because of
bad Safari performance.
+10
View File
@@ -12,6 +12,7 @@ Several of these features require you to set secrets in your environment. If usi
- [Memory](#memory)
- [Firebase Realtime Database](#firebase-realtime-database)
- [Firebase setup instructions](#firebase-setup-instructions)
- [Whitelisting admin IP addresses](#whitelisting-admin-ip-addresses)
## No user management (`GATEKEEPER=none`)
@@ -61,3 +62,12 @@ To use Firebase Realtime Database to persist user data, set the following enviro
8. Set `GATEKEEPER_STORE` to `firebase_rtdb` in your environment if you haven't already.
The proxy server will attempt to connect to your Firebase Realtime Database at startup and will throw an error if it cannot connect. If you see this error, check that your `FIREBASE_RTDB_URL` and `FIREBASE_KEY` secrets are set correctly.
## Whitelisting admin IP addresses
You can add your own IP ranges to the `ADMIN_WHITELIST` environment variable for additional security.
You can provide a comma-separated list containing individual IPv4 or IPv6 addresses, or CIDR ranges.
To whitelist an entire IP range, use CIDR notation. For example, `192.168.0.1/24` would whitelist all addresses from `192.168.0.0` to `192.168.0.255`.
To disable the whitelist, set `ADMIN_WHITELIST=0.0.0.0/0`, which will allow access from any IP address. This is the default behavior.
+1156 -711
View File
File diff suppressed because it is too large Load Diff
+9 -3
View File
@@ -4,6 +4,7 @@
"description": "Reverse proxy for the OpenAI API",
"scripts": {
"build": "tsc && copyfiles -u 1 src/**/*.ejs build",
"database:migrate": "ts-node scripts/migrate.ts",
"prepare": "husky install",
"start": "node build/server.js",
"start:dev": "nodemon --watch src --exec ts-node --transpile-only src/server.ts",
@@ -19,6 +20,7 @@
"dependencies": {
"@anthropic-ai/tokenizer": "^0.0.4",
"@aws-crypto/sha256-js": "^5.2.0",
"@node-rs/argon2": "^1.8.3",
"@smithy/eventstream-codec": "^2.1.3",
"@smithy/eventstream-serde-node": "^2.1.3",
"@smithy/protocol-http": "^3.2.1",
@@ -26,18 +28,21 @@
"@smithy/types": "^2.10.1",
"@smithy/util-utf8": "^2.1.1",
"axios": "^1.3.5",
"better-sqlite3": "^10.0.0",
"check-disk-space": "^3.4.0",
"cookie-parser": "^1.4.6",
"copyfiles": "^2.4.1",
"cors": "^2.8.5",
"csrf-csrf": "^2.3.0",
"dotenv": "^16.3.1",
"ejs": "^3.1.9",
"ejs": "^3.1.10",
"express": "^4.18.2",
"express-session": "^1.17.3",
"firebase-admin": "^11.10.1",
"firebase-admin": "^12.1.0",
"glob": "^10.3.12",
"googleapis": "^122.0.0",
"http-proxy-middleware": "^3.0.0-beta.1",
"ipaddr.js": "^2.1.0",
"memorystore": "^1.6.7",
"multer": "^1.4.5-lts.1",
"node-schedule": "^2.1.1",
@@ -55,6 +60,7 @@
"zod-error": "^1.5.0"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.10",
"@types/cookie-parser": "^1.4.3",
"@types/cors": "^2.8.13",
"@types/express": "^4.17.17",
@@ -72,11 +78,11 @@
"nodemon": "^3.0.1",
"pino-pretty": "^10.2.3",
"prettier": "^3.0.3",
"prettier-plugin-ejs": "^1.0.3",
"ts-node": "^10.9.1",
"typescript": "^5.4.2"
},
"overrides": {
"google-gax": "^3.6.1",
"postcss": "^8.4.31",
"follow-redirects": "^1.15.4"
}
+349
View File
@@ -0,0 +1,349 @@
/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */
/* Document
========================================================================== */
/**
* 1. Correct the line height in all browsers.
* 2. Prevent adjustments of font size after orientation changes in iOS.
*/
html {
line-height: 1.15; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/* Sections
========================================================================== */
/**
* Remove the margin in all browsers.
*/
body {
margin: 0;
}
/**
* Render the `main` element consistently in IE.
*/
main {
display: block;
}
/**
* Correct the font size and margin on `h1` elements within `section` and
* `article` contexts in Chrome, Firefox, and Safari.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/* Grouping content
========================================================================== */
/**
* 1. Add the correct box sizing in Firefox.
* 2. Show the overflow in Edge and IE.
*/
hr {
box-sizing: content-box; /* 1 */
height: 0; /* 1 */
overflow: visible; /* 2 */
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
pre {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/* Text-level semantics
========================================================================== */
/**
* Remove the gray background on active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* 1. Remove the bottom border in Chrome 57-
* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.
*/
abbr[title] {
border-bottom: none; /* 1 */
text-decoration: underline; /* 2 */
text-decoration: underline dotted; /* 2 */
}
/**
* Add the correct font weight in Chrome, Edge, and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
* 1. Correct the inheritance and scaling of font size in all browsers.
* 2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp {
font-family: monospace, monospace; /* 1 */
font-size: 1em; /* 2 */
}
/**
* Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` elements from affecting the line height in
* all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/* Embedded content
========================================================================== */
/**
* Remove the border on images inside links in IE 10.
*/
img {
border-style: none;
}
/* Forms
========================================================================== */
/**
* 1. Change the font styles in all browsers.
* 2. Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit; /* 1 */
font-size: 100%; /* 1 */
line-height: 1.15; /* 1 */
margin: 0; /* 2 */
}
/**
* Show the overflow in IE.
* 1. Show the overflow in Edge.
*/
button,
input { /* 1 */
overflow: visible;
}
/**
* Remove the inheritance of text transform in Edge, Firefox, and IE.
* 1. Remove the inheritance of text transform in Firefox.
*/
button,
select { /* 1 */
text-transform: none;
}
/**
* Correct the inability to style clickable types in iOS and Safari.
*/
button,
[type="button"],
[type="reset"],
[type="submit"] {
-webkit-appearance: button;
}
/**
* Remove the inner border and padding in Firefox.
*/
button::-moz-focus-inner,
[type="button"]::-moz-focus-inner,
[type="reset"]::-moz-focus-inner,
[type="submit"]::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
* Restore the focus styles unset by the previous rule.
*/
button:-moz-focusring,
[type="button"]:-moz-focusring,
[type="reset"]:-moz-focusring,
[type="submit"]:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
* Correct the padding in Firefox.
*/
fieldset {
padding: 0.35em 0.75em 0.625em;
}
/**
* 1. Correct the text wrapping in Edge and IE.
* 2. Correct the color inheritance from `fieldset` elements in IE.
* 3. Remove the padding so developers are not caught out when they zero out
* `fieldset` elements in all browsers.
*/
legend {
box-sizing: border-box; /* 1 */
color: inherit; /* 2 */
display: table; /* 1 */
max-width: 100%; /* 1 */
padding: 0; /* 3 */
white-space: normal; /* 1 */
}
/**
* Add the correct vertical alignment in Chrome, Firefox, and Opera.
*/
progress {
vertical-align: baseline;
}
/**
* Remove the default vertical scrollbar in IE 10+.
*/
textarea {
overflow: auto;
}
/**
* 1. Add the correct box sizing in IE 10.
* 2. Remove the padding in IE 10.
*/
[type="checkbox"],
[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Correct the cursor style of increment and decrement buttons in Chrome.
*/
[type="number"]::-webkit-inner-spin-button,
[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Correct the odd appearance in Chrome and Safari.
* 2. Correct the outline style in Safari.
*/
[type="search"] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/**
* Remove the inner padding in Chrome and Safari on macOS.
*/
[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* 1. Correct the inability to style clickable types in iOS and Safari.
* 2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/* Interactive
========================================================================== */
/*
* Add the correct display in Edge, IE 10+, and Firefox.
*/
details {
display: block;
}
/*
* Add the correct display in all browsers.
*/
summary {
display: list-item;
}
/* Misc
========================================================================== */
/**
* Add the correct display in IE 10+.
*/
template {
display: none;
}
/**
* Add the correct display in IE 10.
*/
[hidden] {
display: none;
}
+231
View File
@@ -0,0 +1,231 @@
/* modified https://github.com/oxalorg/sakura */
html {
font-size: 62.5%;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, "Noto Sans", sans-serif;
}
body {
font-size: 1.8rem;
line-height: 1.618;
max-width: 38em;
margin: auto;
color: #c9c9c9;
background-color: #222222;
padding: 13px;
}
@media (max-width: 684px) {
body {
font-size: 1.53rem;
}
}
@media (max-width: 382px) {
body {
font-size: 1.35rem;
}
}
h1,
h2,
h3,
h4,
h5,
h6 {
line-height: 1.1;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, "Noto Sans", sans-serif;
font-weight: 700;
margin-top: 3rem;
margin-bottom: 1.5rem;
overflow-wrap: break-word;
word-wrap: break-word;
-ms-word-break: break-all;
word-break: break-word;
}
h1 {
font-size: 2.35em;
}
h2 {
font-size: 2em;
}
h3 {
font-size: 1.75em;
}
h4 {
font-size: 1.5em;
}
h5 {
font-size: 1.25em;
}
h6 {
font-size: 1em;
}
p {
margin-top: 0px;
margin-bottom: 2.5rem;
}
small,
sub,
sup {
font-size: 75%;
}
hr {
border-color: #ffffff;
}
a {
text-decoration: none;
color: #ffffff;
}
a:visited {
color: #e6e6e6;
}
a:hover {
color: #c9c9c9;
text-decoration: underline;
}
ul {
padding-left: 1.4em;
margin-top: 0px;
margin-bottom: 2.5rem;
}
li {
margin-bottom: 0.4em;
}
blockquote {
margin-left: 0px;
margin-right: 0px;
padding-left: 1em;
padding-top: 0.8em;
padding-bottom: 0.8em;
padding-right: 0.8em;
border-left: 5px solid #ffffff;
margin-bottom: 2.5rem;
background-color: #4a4a4a;
}
blockquote p {
margin-bottom: 0;
}
img,
video {
height: auto;
max-width: 100%;
margin-top: 0px;
margin-bottom: 2.5rem;
}
pre {
background-color: #4a4a4a;
display: block;
padding: 1em;
overflow-x: auto;
margin-top: 0px;
margin-bottom: 2.5rem;
font-size: 0.9em;
}
code,
kbd,
samp {
font-size: 0.9em;
padding: 0 0.5em;
background-color: #4a4a4a;
white-space: pre-wrap;
}
pre > code {
padding: 0;
background-color: transparent;
white-space: pre;
font-size: 1em;
}
table {
text-align: justify;
width: 100%;
border-collapse: collapse;
margin-bottom: 2rem;
}
td,
th {
padding: 0.5em;
border-bottom: 1px solid #4a4a4a;
}
input,
textarea {
border: 1px solid #c9c9c9;
}
input:focus,
textarea:focus {
border: 1px solid #ffffff;
}
textarea {
width: 100%;
}
.button,
button,
input[type="submit"],
input[type="reset"],
input[type="button"],
input[type="file"]::file-selector-button {
display: inline-block;
padding: 5px 10px;
text-align: center;
text-decoration: none;
white-space: nowrap;
background-color: #ffffff;
color: #222222;
border-radius: 1px;
border: 1px solid #ffffff;
cursor: pointer;
box-sizing: border-box;
}
.button[disabled],
button[disabled],
input[type="submit"][disabled],
input[type="reset"][disabled],
input[type="button"][disabled],
input[type="file"][disabled] {
cursor: default;
opacity: 0.5;
}
.button:hover,
button:hover,
input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="button"]:hover,
input[type="file"]::file-selector-button:hover {
background-color: #c9c9c9;
color: #222222;
outline: 0;
}
.button:focus-visible,
button:focus-visible,
input[type="submit"]:focus-visible,
input[type="reset"]:focus-visible,
input[type="button"]:focus-visible,
input[type="file"]::file-selector-button:focus-visible {
outline-style: solid;
outline-width: 2px;
}
textarea,
select,
input {
color: #c9c9c9;
padding: 6px 10px;
margin-bottom: 10px;
background-color: #4a4a4a;
border: 1px solid #4a4a4a;
border-radius: 4px;
box-shadow: none;
box-sizing: border-box;
}
textarea:focus,
select:focus,
input:focus {
border: 1px solid #ffffff;
outline: 0;
}
input[type="checkbox"]:focus {
outline: 1px dotted #ffffff;
}
label,
legend,
fieldset {
display: block;
margin-bottom: 0.5rem;
font-weight: 600;
}
+237
View File
@@ -0,0 +1,237 @@
/* modified https://github.com/oxalorg/sakura */
:root {
--accent-color: #4a4a4a;
--accent-color-hover: #5a5a5a;
--link-color: #58739c;
--link-visted-color: #6f5e6f;
}
html {
font-size: 62.5%;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, "Noto Sans", sans-serif;
}
body {
font-size: 1.8rem;
line-height: 1.618;
max-width: 38em;
margin: auto;
color: #4a4a4a;
background-color: #f9f9f9;
padding: 13px;
}
@media (max-width: 684px) {
body {
font-size: 1.53rem;
}
}
@media (max-width: 382px) {
body {
font-size: 1.35rem;
}
}
h1,
h2,
h3,
h4,
h5,
h6 {
line-height: 1.1;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, "Noto Sans", sans-serif;
font-weight: 700;
margin-top: 3rem;
margin-bottom: 1.5rem;
overflow-wrap: break-word;
word-wrap: break-word;
-ms-word-break: break-all;
word-break: break-word;
}
h1 {
font-size: 2.35em;
}
h2 {
font-size: 2em;
}
h3 {
font-size: 1.75em;
}
h4 {
font-size: 1.5em;
}
h5 {
font-size: 1.25em;
}
h6 {
font-size: 1em;
}
p {
margin-top: 0;
margin-bottom: 2.5rem;
}
small,
sub,
sup {
font-size: 75%;
}
hr {
border-color: var(--accent-color);
}
a {
text-decoration: none;
color: var(--link-color);
}
a:visited {
color: var(--link-visted-color);
}
a:hover {
color: var(--accent-color-hover);
text-decoration: underline;
}
ul {
padding-left: 1.4em;
margin-top: 0;
margin-bottom: 2.5rem;
}
li {
margin-bottom: 0.4em;
}
blockquote {
margin-left: 0;
margin-right: 0;
padding-left: 1em;
padding-top: 0.8em;
padding-bottom: 0.8em;
padding-right: 0.8em;
border-left: 5px solid var(--accent-color);
margin-bottom: 2.5rem;
background-color: #f1f1f1;
}
blockquote p {
margin-bottom: 0;
}
img,
video {
height: auto;
max-width: 100%;
margin-top: 0;
margin-bottom: 2.5rem;
}
pre {
background-color: #f1f1f1;
display: block;
padding: 1em;
overflow-x: auto;
margin-top: 0;
margin-bottom: 2.5rem;
font-size: 0.9em;
}
code,
kbd,
samp {
font-size: 0.9em;
padding: 0 0.5em;
background-color: #f1f1f1;
white-space: pre-wrap;
}
pre > code {
padding: 0;
background-color: transparent;
white-space: pre;
font-size: 1em;
}
table {
text-align: justify;
width: 100%;
border-collapse: collapse;
margin-bottom: 2rem;
}
td,
th {
padding: 0.5em;
border-bottom: 1px solid #f1f1f1;
}
input,
textarea {
border: 1px solid #4a4a4a;
}
input:focus,
textarea:focus {
border: 1px solid var(--accent-color);
}
textarea {
width: 100%;
}
.button,
button,
input[type="submit"],
input[type="reset"],
input[type="button"],
input[type="file"]::file-selector-button {
display: inline-block;
padding: 5px 10px;
text-align: center;
text-decoration: none;
white-space: nowrap;
background-color: var(--accent-color);
color: #f9f9f9;
border-radius: 2px;
border: 1px solid var(--accent-color);
cursor: pointer;
box-sizing: border-box;
}
.button[disabled],
button[disabled],
input[type="submit"][disabled],
input[type="reset"][disabled],
input[type="button"][disabled],
input[type="file"][disabled] {
cursor: default;
opacity: 0.5;
}
.button:hover,
button:hover,
input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="button"]:hover,
input[type="file"]::file-selector-button:hover {
background-color: var(--accent-color-hover);
color: #f9f9f9;
outline: 0;
}
.button:focus-visible,
button:focus-visible,
input[type="submit"]:focus-visible,
input[type="reset"]:focus-visible,
input[type="button"]:focus-visible,
input[type="file"]::file-selector-button:focus-visible {
outline-style: solid;
outline-width: 2px;
}
textarea,
select,
input {
color: #4a4a4a;
padding: 6px 10px;
margin-bottom: 10px;
background-color: #f1f1f1;
border: 1px solid #f1f1f1;
border-radius: 4px;
box-shadow: none;
box-sizing: border-box;
}
textarea:focus,
select:focus,
input:focus {
border: 1px solid var(--accent-color);
outline: 0;
}
input[type="checkbox"]:focus {
outline: 1px dotted var(--accent-color);
}
label,
legend,
fieldset {
display: block;
margin-bottom: 0.5rem;
font-weight: 600;
}
+121
View File
@@ -0,0 +1,121 @@
importScripts(
"https://cdn.jsdelivr.net/npm/hash-wasm@4.11.0/dist/argon2.umd.min.js"
);
let active = false;
let nonce = 0;
let signature = "";
let lastNotify = 0;
let hashesSinceLastNotify = 0;
let params = {
salt: null,
hashLength: 0,
iterations: 0,
memorySize: 0,
parallelism: 0,
targetValue: BigInt(0),
safariFix: false,
};
self.onmessage = async (event) => {
const { data } = event;
switch (data.type) {
case "stop":
active = false;
self.postMessage({ type: "paused", hashes: hashesSinceLastNotify });
return;
case "start":
active = true;
signature = data.signature;
nonce = data.nonce;
const c = data.challenge;
// decode salt to Uint8Array
const salt = new Uint8Array(c.s.length / 2);
for (let i = 0; i < c.s.length; i += 2) {
salt[i / 2] = parseInt(c.s.slice(i, i + 2), 16);
}
params = {
salt: salt,
hashLength: c.hl,
iterations: c.t,
memorySize: c.m,
parallelism: c.p,
targetValue: BigInt(c.d.slice(0, -1)),
safariFix: data.isMobileWebkit,
};
console.log("Started", params);
self.postMessage({ type: "started" });
setTimeout(solve, 0);
break;
}
};
const doHash = async (password) => {
const { salt, hashLength, iterations, memorySize, parallelism } = params;
return await self.hashwasm.argon2id({
password,
salt,
hashLength,
iterations,
memorySize,
parallelism,
});
};
const checkHash = (hash) => {
const { targetValue } = params;
const hashValue = BigInt(`0x${hash}`);
return hashValue <= targetValue;
};
const solve = async () => {
if (!active) {
console.log("Stopped solver", nonce);
return;
}
// Safari WASM doesn't like multiple calls in one worker
const batchSize = 1;
const batch = [];
for (let i = 0; i < batchSize; i++) {
batch.push(nonce++);
}
try {
const results = await Promise.all(
batch.map(async (nonce) => {
const hash = await doHash(String(nonce));
return { hash, nonce };
})
);
hashesSinceLastNotify += batchSize;
const solution = results.find(({ hash }) => checkHash(hash));
if (solution) {
console.log("Solution found", solution, params.salt);
self.postMessage({ type: "solved", nonce: solution.nonce });
active = false;
} else {
if (Date.now() - lastNotify > 1000) {
console.log("Last nonce", nonce, "Hashes", hashesSinceLastNotify);
self.postMessage({ type: "progress", hashes: hashesSinceLastNotify });
lastNotify = Date.now();
hashesSinceLastNotify = 0;
}
setTimeout(solve, 10);
}
} catch (error) {
console.error("Error", error);
const stack = error.stack;
const debug = {
stack,
lastNonce: nonce,
targetValue: params.targetValue,
};
self.postMessage({ type: "error", error: error.message, debug });
active = false;
}
};
+39
View File
@@ -0,0 +1,39 @@
import Database from "better-sqlite3";
import { DATABASE_VERSION, migrateDatabase } from "../src/shared/database";
import { logger } from "../src/logger";
import { config } from "../src/config";
const log = logger.child({ module: "scripts/migrate" });
async function runMigration() {
let targetVersion = Number(process.argv[2]) || undefined;
if (!targetVersion) {
log.info("Enter target version or leave empty to use the latest version.");
process.stdin.resume();
process.stdin.setEncoding("utf8");
const input = await new Promise<string>((resolve) => {
process.stdin.on("data", (text) => {
resolve((String(text) || "").trim());
});
});
process.stdin.pause();
targetVersion = Number(input);
if (!targetVersion) {
targetVersion = DATABASE_VERSION;
}
}
const db = new Database(config.sqliteDataPath, {
verbose: (msg, ...args) => log.debug({ args }, String(msg)),
});
const currentVersion = db.pragma("user_version", { simple: true });
log.info({ currentVersion, targetVersion }, "Running migrations.");
migrateDatabase(targetVersion, db);
}
runMigration().catch((error) => {
log.error(error, "Migration failed.");
process.exit(1);
});
+100
View File
@@ -0,0 +1,100 @@
import Database from "better-sqlite3";
import { v4 as uuidv4 } from "uuid";
import { config } from "../src/config";
function generateRandomIP() {
return (
Math.floor(Math.random() * 255) +
"." +
Math.floor(Math.random() * 255) +
"." +
Math.floor(Math.random() * 255) +
"." +
Math.floor(Math.random() * 255)
);
}
function generateRandomDate() {
const end = new Date();
const start = new Date(end);
start.setDate(end.getDate() - 90);
const randomDate = new Date(
start.getTime() + Math.random() * (end.getTime() - start.getTime())
);
return randomDate.toISOString();
}
function generateMockSHA256() {
const characters = 'abcdef0123456789';
let hash = '';
for (let i = 0; i < 64; i++) {
const randomIndex = Math.floor(Math.random() * characters.length);
hash += characters[randomIndex];
}
return hash;
}
function getRandomModelFamily() {
const modelFamilies = [
"turbo",
"gpt4",
"gpt4-32k",
"gpt4-turbo",
"claude",
"claude-opus",
"gemini-pro",
"mistral-tiny",
"mistral-small",
"mistral-medium",
"mistral-large",
"aws-claude",
"aws-claude-opus",
"azure-turbo",
"azure-gpt4",
"azure-gpt4-32k",
"azure-gpt4-turbo",
"dall-e",
"azure-dall-e",
];
return modelFamilies[Math.floor(Math.random() * modelFamilies.length)];
}
(async () => {
const db = new Database(config.sqliteDataPath);
const numRows = 100;
const insertStatement = db.prepare(`
INSERT INTO events (type, ip, date, model, family, hashes, userToken, inputTokens, outputTokens)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const users = Array.from({ length: 10 }, () => uuidv4());
function getRandomUser() {
return users[Math.floor(Math.random() * users.length)];
}
const transaction = db.transaction(() => {
for (let i = 0; i < numRows; i++) {
insertStatement.run(
"chat_completion",
generateRandomIP(),
generateRandomDate(),
getRandomModelFamily() + "-" + Math.floor(Math.random() * 100),
getRandomModelFamily(),
Array.from(
{ length: Math.floor(Math.random() * 10) },
generateMockSHA256
).join(","),
getRandomUser(),
Math.floor(Math.random() * 500),
Math.floor(Math.random() * 6000)
);
}
});
transaction();
console.log(`Inserted ${numRows} rows into the events table.`);
db.close();
})();
+49
View File
@@ -0,0 +1,49 @@
import { Router } from "express";
import { z } from "zod";
import { encodeCursor, decodeCursor } from "../../shared/utils";
import { eventsRepo } from "../../shared/database/repos/events";
const router = Router();
/**
* Returns events for the given user token.
* GET /admin/events/:token
* @query first - The number of events to return.
* @query after - The cursor to start returning events from (exclusive).
*/
router.get("/:token", (req, res) => {
const schema = z.object({
token: z.string(),
first: z.coerce.number().int().positive().max(200).default(25),
after: z
.string()
.optional()
.transform((v) => {
try {
return decodeCursor(v);
} catch {
return null;
}
})
.nullable(),
sort: z.string().optional(),
});
const args = schema.safeParse({ ...req.params, ...req.query });
if (!args.success) {
return res.status(400).json({ error: args.error });
}
const data = eventsRepo
.getUserEvents(args.data.token, {
limit: args.data.first,
cursor: args.data.after,
})
.map((e) => ({ node: e, cursor: encodeCursor(e.date) }));
res.json({
data,
endCursor: data[data.length - 1]?.cursor,
});
});
export { router as eventsApiRouter };
+1 -1
View File
@@ -2,7 +2,7 @@ import { Router } from "express";
import { z } from "zod";
import * as userStore from "../../shared/users/user-store";
import { parseSort, sortBy } from "../../shared/utils";
import { UserPartialSchema, UserSchema } from "../../shared/users/schema";
import { UserPartialSchema, UserSchema } from "../../shared/database/repos/users";
const router = Router();
+19 -4
View File
@@ -1,17 +1,31 @@
import express, { Router } from "express";
import { authorize } from "./auth";
import { createWhitelistMiddleware } from "../shared/cidr";
import { HttpError } from "../shared/errors";
import { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf";
import { injectLocals } from "../shared/inject-locals";
import { withSession } from "../shared/with-session";
import { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf";
import { config } from "../config";
import { renderPage } from "../info-page";
import { buildInfo } from "../service-info";
import { authorize } from "./auth";
import { loginRouter } from "./login";
import { usersApiRouter as apiRouter } from "./api/users";
import { eventsApiRouter } from "./api/events";
import { usersApiRouter } from "./api/users";
import { usersWebRouter as webRouter } from "./web/manage";
import { logger } from "../logger";
const adminRouter = Router();
const whitelist = createWhitelistMiddleware(
"ADMIN_WHITELIST",
config.adminWhitelist
);
if (!whitelist.ranges.length && config.adminKey?.length) {
logger.error("ADMIN_WHITELIST is empty. No admin requests will be allowed. Set 0.0.0.0/0 to allow all.");
}
adminRouter.use(whitelist);
adminRouter.use(
express.json({ limit: "20mb" }),
express.urlencoded({ extended: true, limit: "20mb" })
@@ -19,7 +33,8 @@ adminRouter.use(
adminRouter.use(withSession);
adminRouter.use(injectCsrfToken);
adminRouter.use("/users", authorize({ via: "header" }), apiRouter);
adminRouter.use("/users", authorize({ via: "header" }), usersApiRouter);
adminRouter.use("/events", authorize({ via: "header" }), eventsApiRouter);
adminRouter.use(checkCsrfToken);
adminRouter.use(injectLocals);
+193 -10
View File
@@ -1,4 +1,5 @@
import { Router } from "express";
import ipaddr from "ipaddr.js";
import multer from "multer";
import { z } from "zod";
import { config } from "../../config";
@@ -8,13 +9,10 @@ import { parseSort, sortBy, paginate } from "../../shared/utils";
import { keyPool } from "../../shared/key-management";
import { LLMService, MODEL_FAMILIES } from "../../shared/models";
import { getTokenCostUsd, prettyTokens } from "../../shared/stats";
import {
User,
UserPartialSchema,
UserSchema,
UserTokenCounts,
} from "../../shared/users/schema";
import { getLastNImages } from "../../shared/file-storage/image-history";
import { blacklists, parseCidrs, whitelists } from "../../shared/cidr";
import { invalidatePowHmacKey } from "../../user/web/pow-captcha";
import { User, UserPartialSchema, UserSchema, UserTokenCounts } from "../../shared/database/repos/users";
const router = Router();
@@ -40,6 +38,74 @@ router.get("/create-user", (req, res) => {
});
});
router.get("/anti-abuse", (_req, res) => {
const wl = [...whitelists.entries()];
const bl = [...blacklists.entries()];
res.render("admin_anti-abuse", {
captchaMode: config.captchaMode,
difficulty: config.powDifficultyLevel,
whitelists: wl.map((w) => ({
name: w[0],
mode: "whitelist",
ranges: w[1].ranges,
})),
blacklists: bl.map((b) => ({
name: b[0],
mode: "blacklist",
ranges: b[1].ranges,
})),
});
});
router.post("/cidr", (req, res) => {
const body = req.body;
const valid = z
.object({
action: z.enum(["add", "remove"]),
mode: z.enum(["whitelist", "blacklist"]),
name: z.string().min(1),
mask: z.string().min(1),
})
.safeParse(body);
if (!valid.success) {
throw new HttpError(
400,
valid.error.issues.flatMap((issue) => issue.message).join(", ")
);
}
const { mode, name, mask } = valid.data;
const list = (mode === "whitelist" ? whitelists : blacklists).get(name);
if (!list) {
throw new HttpError(404, "List not found");
}
if (valid.data.action === "remove") {
const newRanges = new Set(list.ranges);
newRanges.delete(mask);
list.updateRanges([...newRanges]);
req.session.flash = {
type: "success",
message: `${mode} ${name} updated`,
};
return res.redirect("/admin/manage/anti-abuse");
} else if (valid.data.action === "add") {
const result = parseCidrs(mask);
if (result.length === 0) {
throw new HttpError(400, "Invalid CIDR mask");
}
const newRanges = new Set([...list.ranges, mask]);
list.updateRanges([...newRanges]);
req.session.flash = {
type: "success",
message: `${mode} ${name} updated`,
};
return res.redirect("/admin/manage/anti-abuse");
}
});
router.post("/create-user", (req, res) => {
const body = req.body;
@@ -223,10 +289,14 @@ router.post("/maintenance", (req, res) => {
break;
}
case "downloadImageMetadata": {
const data = JSON.stringify({
const data = JSON.stringify(
{
exportedAt: new Date().toISOString(),
generations: getLastNImages()
}, null, 2);
generations: getLastNImages(),
},
null,
2
);
res.setHeader(
"Content-Disposition",
`attachment; filename=image-metadata-${new Date().toISOString()}.json`
@@ -234,14 +304,127 @@ router.post("/maintenance", (req, res) => {
res.setHeader("Content-Type", "application/json");
return res.send(data);
}
case "expireTempTokens": {
const users = userStore.getUsers();
const temps = users.filter((u) => u.type === "temporary");
temps.forEach((user) => {
user.expiresAt = Date.now();
user.disabledReason = "Admin forced expiration.";
userStore.upsertUser(user);
});
invalidatePowHmacKey();
flash.type = "success";
flash.message = `${temps.length} temporary users marked for expiration.`;
break;
}
case "cleanTempTokens": {
const users = userStore.getUsers();
const disabledTempUsers = users.filter(
(u) => u.type === "temporary" && u.expiresAt && u.expiresAt < Date.now()
);
disabledTempUsers.forEach((user) => {
user.disabledAt = 1; //will be cleaned up by the next cron job
userStore.upsertUser(user);
});
flash.type = "success";
flash.message = `${disabledTempUsers.length} disabled temporary users marked for cleanup.`;
break;
}
case "setDifficulty": {
const selected = req.body["pow-difficulty"];
const valid = ["low", "medium", "high", "extreme"];
if (!selected || !valid.includes(selected)) {
throw new HttpError(400, "Invalid difficulty" + selected);
}
config.powDifficultyLevel = selected;
break;
}
case "generateTempIpReport": {
const tempUsers = userStore
.getUsers()
.filter((u) => u.type === "temporary");
const ipv4RangeMap: Map<string, Set<string>> = new Map<
string,
Set<string>
>();
const ipv6RangeMap: Map<string, Set<string>> = new Map<
string,
Set<string>
>();
tempUsers.forEach((u) => {
u.ip.forEach((ip) => {
try {
const parsed = ipaddr.parse(ip);
if (parsed.kind() === "ipv4") {
const subnet =
parsed.toNormalizedString().split(".").slice(0, 3).join(".") +
".0/24";
const userSet = ipv4RangeMap.get(subnet) || new Set<string>();
userSet.add(u.token);
ipv4RangeMap.set(subnet, userSet);
} else if (parsed.kind() === "ipv6") {
const subnet =
parsed.toNormalizedString().split(":").slice(0, 4).join(":") +
"::/48";
const userSet = ipv6RangeMap.get(subnet) || new Set<string>();
userSet.add(u.token);
ipv6RangeMap.set(subnet, userSet);
}
} catch (e) {
req.log.warn(
{ ip, error: e.message },
"Invalid IP address; skipping"
);
}
});
});
const ipv4Ranges = Array.from(ipv4RangeMap.entries())
.map(([subnet, userSet]) => ({
subnet,
distinctTokens: userSet.size,
}))
.sort((a, b) => b.distinctTokens - a.distinctTokens);
const ipv6Ranges = Array.from(ipv6RangeMap.entries())
.map(([subnet, userSet]) => ({
subnet,
distinctTokens: userSet.size,
}))
.sort((a, b) => {
if (a.distinctTokens === b.distinctTokens) {
return a.subnet.localeCompare(b.subnet);
}
return b.distinctTokens - a.distinctTokens;
});
const data = JSON.stringify(
{
exportedAt: new Date().toISOString(),
ipv4Ranges,
ipv6Ranges,
},
null,
2
);
res.setHeader(
"Content-Disposition",
`attachment; filename=temp-ip-report-${new Date().toISOString()}.json`
);
res.setHeader("Content-Type", "application/json");
return res.send(data);
}
default: {
throw new HttpError(400, "Invalid action");
}
}
req.session.flash = flash;
const referer = req.get("referer");
return res.redirect(`/admin/manage`);
return res.redirect(referer || "/admin/manage");
});
router.get("/download-stats", (_req, res) => {
+140
View File
@@ -0,0 +1,140 @@
<%- include("partials/shared_header", { title: "Proof of Work Verification Settings - OAI Reverse Proxy Admin" }) %>
<style>
details {
margin-top: 1em;
}
details summary {
font-weight: bold;
cursor: pointer;
}
details p {
margin-left: 1em;
}
#token-manage {
display: flex;
width: 100%;
}
#token-manage button {
flex-grow: 1;
margin: 0 0.5em;
}
</style>
<h1>Abuse Mitigation Settings</h1>
<div>
<h2>Proof-of-Work Verification</h2>
<p>
The Proof-of-Work difficulty level is used to determine how much work a client must perform to earn a temporary user
token. Higher difficulty levels require more work, which can help mitigate abuse by making it more expensive for
attackers to generate tokens. However, higher difficulty levels can also make it more difficult for legitimate users
to generate tokens. Refer to documentation for guidance.
</p>
<%if (captchaMode === "none") { %>
<p>
<strong>PoW verification is not enabled. Set <code>CAPTCHA_MODE=proof_of_work</code> to enable.</strong>
</p>
<% } else { %>
<h3>Difficulty Level</h3>
<div>
<label for="difficulty">Difficulty Level:</label>
<span id="currentDifficulty">Current: <%= difficulty %></span>
<select name="difficulty" id="difficulty">
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
<option value="extreme">Extreme</option>
</select>
<button onclick='doAction("setDifficulty")'>Update Difficulty</button>
</div>
<% } %>
<form id="maintenanceForm" action="/admin/manage/maintenance" method="post">
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
<input id="hiddenAction" type="hidden" name="action" value="" />
<input id="hiddenDifficulty" type="hidden" name="pow-difficulty" value="" />
</form>
<h3>Manage Temporary User Tokens</h3>
<div id="token-manage">
<p><button onclick='doAction("expireTempTokens")'>🕒 Expire All Temp Tokens</button></p>
<p><button onclick='doAction("cleanTempTokens")'>🧹 Delete Expired Temp Tokens</button></p>
<p><button onclick='doAction("generateTempIpReport")'>📊 Generate Temp Token IP Report</button></p>
</div>
</div>
<div>
<h2>IP Whitelists and Blacklists</h2>
<p>
You can specify IP ranges to whitelist or blacklist from accessing the proxy. Note that changes here are not
persisted across server restarts. If you want to make changes permanent, you can copy the values to your deployment
configuration.
</p>
<p>
Entries can be specified as single addresses or
<a href="https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation">CIDR notation</a>. IPv6 is
supported but not recommended for use with the current version of the proxy.
</p>
<% for (let i = 0; i < whitelists.length; i++) { %>
<%- include("partials/admin-cidr-widget", { list: whitelists[i] }) %>
<% } %>
<% for (let i = 0; i < blacklists.length; i++) { %>
<%- include("partials/admin-cidr-widget", { list: blacklists[i] }) %>
<% } %>
<form action="/admin/manage/cidr" method="post" id="cidrForm">
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
<input type="hidden" name="action" value="add" />
<input type="hidden" name="name" value="" />
<input type="hidden" name="mode" value="" />
<input type="hidden" name="mask" value="" />
</form>
<details>
<summary>Copy environment variables</summary>
<p>
If you have made changes with the UI, you can copy the values below to your deployment configuration to persist
them across server restarts.
</p>
<pre>
<% for (let i = 0; i < whitelists.length; i++) { %><%= whitelists[i].name %>=<%= whitelists[i].ranges.join(",") %><% } %>
<% for (let i = 0; i < blacklists.length; i++) { %><%= blacklists[i].name %>=<%= blacklists[i].ranges.join(",") %><% } %>
</pre>
</details>
</div>
<script>
function doAction(action) {
document.getElementById("hiddenAction").value = action;
if (action === "setDifficulty") {
document.getElementById("hiddenDifficulty").value = document.getElementById("difficulty").value;
}
document.getElementById("maintenanceForm").submit();
}
function onAddCidr(event) {
const list = event.target.dataset;
const newMask = prompt("Enter the IP or CIDR range to add to the list:");
if (!newMask) {
return;
}
const form = document.getElementById("cidrForm");
form["action"].value = "add";
form["name"].value = list.name;
form["mode"].value = list.mode;
form["mask"].value = newMask;
form.submit();
}
function onRemoveCidr(event) {
const list = event.target.dataset;
const removeMask = event.target.dataset.mask;
if (!removeMask) {
return;
}
const form = document.getElementById("cidrForm");
form["action"].value = "remove";
form["name"].value = list.name;
form["mode"].value = list.mode;
form["mask"].value = removeMask;
form.submit();
}
</script>
<%- include("partials/admin-footer") %>
+2 -3
View File
@@ -51,9 +51,8 @@
<legend>Temporary User Options</legend>
<div class="temporary-user-fieldset">
<p class="full-width">
Temporary users will be disabled after the specified duration, and their records will be deleted 72 hours after that.
These options apply only to new
temporary users; existing ones use whatever options were in effect when they were created.
Temporary users will be disabled after the specified duration, and their records will be permanently deleted after some time.
These options apply only to new temporary users; existing ones use whatever options were in effect when they were created.
</p>
<label for="temporaryUserDuration" class="full-width">Access duration (in minutes)</label>
<input type="number" name="temporaryUserDuration" id="temporaryUserDuration" value="60" class="full-width" />
+23 -32
View File
@@ -5,18 +5,6 @@
flex-direction: column;
}
#statsForm div {
display: flex;
flex-direction: row;
margin-bottom: 0.5em;
}
#statsForm div label {
width: 6em;
text-align: right;
margin-right: 1em;
}
#statsForm ul {
margin: 0;
padding-left: 2em;
@@ -33,17 +21,17 @@
}
</style>
<h1>Download Stats</h1>
<p>
Download usage statistics to a Markdown document. You can paste this into a service like Rentry.org to share it.
</p>
<p>Download usage statistics to a Markdown document. You can paste this into a service like Rentry.org to share it.</p>
<div>
<h3>Options</h3>
<form id="statsForm" action="/admin/manage/generate-stats" method="post"
style="display: flex; flex-direction: column;">
<form
id="statsForm"
action="/admin/manage/generate-stats"
method="post"
style="display: flex; flex-direction: column">
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
<div>
<label for="anon">Anonymize</label>
<input id="anon" type="checkbox" name="anon" value="true" />
<label for="anon"><input id="anon" type="checkbox" name="anon" value="true" /> <span>Anonymize</span></label>
</div>
<div>
<label for="sort">Sort</label>
@@ -64,11 +52,12 @@
</select>
</div>
<div>
<label for="format">Custom Format <ul>
<label for="format">Custom Format</label>
<ul>
<li><code>{{header}}</code></li>
<li><code>{{stats}}</code></li>
<li><code>{{time}}</code></li>
</ul></label>
</ul>
<textarea id="format" name="format" rows="10" cols="50" placeholder="{{stats}}">
# Stats
{{header}}
@@ -115,33 +104,35 @@
loadDefaults();
async function fetchAndCopy() {
const form = document.getElementById('statsForm');
const form = document.getElementById("statsForm");
const formData = new FormData(form);
const response = await fetch(form.action, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
credentials: 'same-origin',
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
credentials: "same-origin",
body: new URLSearchParams(formData),
});
if (response.ok) {
const content = await response.text();
copyToClipboard(content);
} else {
throw new Error('Failed to fetch generated stats. Try reloading the page.');
throw new Error("Failed to fetch generated stats. Try reloading the page.");
}
}
function copyToClipboard(text) {
navigator.clipboard.writeText(text).then(() => {
alert('Copied to clipboard');
}).catch(err => {
alert('Failed to copy to clipboard. Try downloading the file instead.');
navigator.clipboard
.writeText(text)
.then(() => {
alert("Copied to clipboard");
})
.catch((err) => {
alert("Failed to copy to clipboard. Try downloading the file instead.");
});
}
document.getElementById('copyButton').addEventListener('click', fetchAndCopy);
document.getElementById("copyButton").addEventListener("click", fetchAndCopy);
</script>
<%- include("partials/admin-footer") %>
+2 -1
View File
@@ -25,13 +25,14 @@
<li><a href="/admin/manage/import-users">Import Users</a></li>
<li><a href="/admin/manage/export-users">Export Users</a></li>
<li><a href="/admin/manage/download-stats">Download Rentry Stats</a>
<li><a href="/admin/manage/anti-abuse">Abuse Mitigation Settings</a></li>
<li><a href="/admin/service-info">Service Info</a></li>
</ul>
<h3>Maintenance</h3>
<form id="maintenanceForm" action="/admin/manage/maintenance" method="post">
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
<input id="hiddenAction" type="hidden" name="action" value="" />
<div display="flex" flex-direction="column">
<div>
<fieldset>
<legend>Key Recheck</legend>
<button id="recheck-keys" type="button" onclick="submitForm('recheck')">Force Key Recheck</button>
+2 -3
View File
@@ -4,9 +4,8 @@
<% if (users.length === 0) { %>
<p>No users found.</p>
<% } else { %>
<input type="checkbox" id="toggle-nicknames" onchange="toggleNicknames()" />
<label for="toggle-nicknames">Show Nicknames</label>
<table class="striped">
<label for="toggle-nicknames"><input type="checkbox" id="toggle-nicknames" onchange="toggleNicknames()" /> Show Nicknames</label>
<table class="striped full-width">
<thead>
<tr>
<th>User</th>
+16 -6
View File
@@ -55,8 +55,9 @@
<td><%- user.disabledReason %></td>
<% if (user.disabledAt) { %>
<td class="actions">
<a title="Edit" id="edit-disabledReason" href="#" data-field="disabledReason"
data-token="<%= user.token %>">✏️</a>
<a title="Edit" id="edit-disabledReason" href="#" data-field="disabledReason" data-token="<%= user.token %>"
>✏️</a
>
</td>
<% } %>
</tr>
@@ -72,7 +73,8 @@
<td colspan="2"><%- include("partials/shared_user_ip_list", { user, shouldRedact: false }) %></td>
</tr>
<tr>
<th scope="row">Admin Note <span title="Unlike nickname, this is not visible to or editable by the user">🔒</span>
<th scope="row">
Admin Note <span title="Unlike nickname, this is not visible to or editable by the user">🔒</span>
</th>
<td><%- user.adminNote ?? "none" %></td>
<td class="actions">
@@ -85,10 +87,16 @@
<td colspan="2"><%- user.expiresAt %></td>
</tr>
<% } %>
<% if (user.meta) { %>
<tr>
<th scope="row">Meta</th>
<td colspan="2"><%- JSON.stringify(user.meta) %></td>
</tr>
<% } %>
</tbody>
</table>
<form style="display:none" id="current-values">
<form style="display: none" id="current-values">
<input type="hidden" name="token" value="<%- user.token %>" />
<% ["nickname", "type", "disabledAt", "disabledReason", "maxIps", "adminNote"].forEach(function (key) { %>
<input type="hidden" name="<%- key %>" value="<%- user[key] %>" />
@@ -102,7 +110,8 @@
<input type="hidden" name="_csrf" value="<%- csrfToken %>" />
<button type="submit" class="btn btn-primary">Refresh Quotas for User</button>
</form>
<% } %> <%- include("partials/shared_quota-info", { quota, user }) %>
<% } %>
<%- include("partials/shared_quota-info", { quota, user }) %>
<p><a href="/admin/manage/list-users">Back to User List</a></p>
@@ -144,4 +153,5 @@
});
</script>
<%- include("partials/admin-ban-xhr-script") %> <%- include("partials/admin-footer") %>
<%- include("partials/admin-ban-xhr-script") %>
<%- include("partials/admin-footer") %>
@@ -0,0 +1,13 @@
<h3>
<%= list.name %>
(<%= list.mode %>)
</h3>
<ul>
<% list.ranges.forEach(function(mask) { %>
<li>
<%= mask %>
<button class="remove" data-mode="<%= list.mode %>" data-name="<%= list.name %>" data-mask="<%= mask %>" onclick="onRemoveCidr(event)">Remove</button>
</li>
<% }); %>
</ul>
<button class="add" data-mode="<%= list.mode %>" data-name="<%= list.name %>" onclick="onAddCidr(event)">Add</button>
+200 -13
View File
@@ -1,3 +1,4 @@
import crypto from "crypto";
import dotenv from "dotenv";
import type firebase from "firebase-admin";
import path from "path";
@@ -107,9 +108,70 @@ type Config = {
* `maxIpsPerUser` limit, or if only connections from new IPs are be rejected.
*/
maxIpsAutoBan: boolean;
/** Per-IP limit for requests per minute to text and chat models. */
/**
* Which captcha verification mode to use. Requires `user_token` gatekeeper.
* Allows users to automatically obtain a token by solving a captcha.
* - `none`: No captcha verification; tokens are issued manually.
* - `proof_of_work`: Users must solve an Argon2 proof of work to obtain a
* temporary usertoken valid for a limited period.
*/
captchaMode: "none" | "proof_of_work";
/**
* Duration (in hours) for which a PoW-issued temporary user token is valid.
*/
powTokenHours: number;
/**
* The maximum number of IPs from which a single temporary user token can be
* used. Upon reaching the limit, the `maxIpsAutoBan` behavior is triggered.
*/
powTokenMaxIps: number;
/**
* Difficulty level for the proof-of-work challenge.
* - `low`: 200 iterations
* - `medium`: 900 iterations
* - `high`: 1900 iterations
* - `extreme`: 4000 iterations
* - `number`: A custom number of iterations to use.
*
* Difficulty level only affects the number of iterations used in the PoW,
* not the complexity of the hash itself. Therefore, the average time-to-solve
* will scale linearly with the number of iterations.
*
* Refer to docs/proof-of-work.md for guidance and hashrate benchmarks.
*/
powDifficultyLevel: "low" | "medium" | "high" | "extreme" | number;
/**
* Duration (in minutes) before a PoW challenge expires. Users' browsers must
* solve the challenge within this time frame or it will be rejected. Should
* be kept somewhat low to prevent abusive clients from working on many
* challenges in parallel, but you may need to increase this value for higher
* difficulty levels or older devices will not be able to solve the challenge
* in time.
*
* Defaults to 30 minutes.
*/
powChallengeTimeout: number;
/**
* Duration (in hours) before expired temporary user tokens are purged from
* the user database. Users can refresh expired tokens by solving a faster PoW
* challenge as long as the original token has not been purged. Once purged,
* the user must solve a full PoW challenge to obtain a new token.
*
* Defaults to 48 hours. At 0, tokens are purged immediately upon expiry.
*/
powTokenPurgeHours: number;
/**
* Maximum number of active temporary user tokens that can be associated with
* a single IP address. Note that this may impact users sending requests from
* hosted AI chat clients such as Agnaistic or RisuAI, as they may share IPs.
*
* When the limit is reached, the oldest token with the same IP will be
* expired. At 0, no limit is enforced. Defaults to 0.
*/
// powMaxTokensPerIp: number;
/** Per-user limit for requests per minute to text and chat models. */
textModelRateLimit: number;
/** Per-IP limit for requests per minute to image generation models. */
/** Per-user limit for requests per minute to image generation models. */
imageModelRateLimit: number;
/**
* For OpenAI, the maximum number of context tokens (prompt + max output) a
@@ -146,10 +208,38 @@ type Config = {
* key and can't attach the policy, you can set this to true.
*/
allowAwsLogging?: boolean;
/**
* Path to the SQLite database file for storing data such as event logs. By
* default, the database will be stored at `data/database.sqlite`.
*
* Ensure target is writable by the server process, and be careful not to
* select a path that is served publicly. The default path is safe.
*/
sqliteDataPath?: string;
/**
* Whether to log events, such as generated completions, to the database.
* Events are associated with IP+user token pairs. If user_token mode is
* disabled, no events will be logged.
*
* Currently there is no pruning mechanism for the events table, so it will
* grow indefinitely. You may want to periodically prune the table manually.
*/
eventLogging?: boolean;
/**
* When hashing prompt histories, how many messages to trim from the end.
* If zero, only the full prompt hash will be stored.
* If greater than zero, for each number N, a hash of the prompt with the
* last N messages removed will be stored.
*
* Experimental function, config may change in future versions.
*/
eventLoggingTrim?: number;
/** Whether prompts and responses should be logged to persistent storage. */
promptLogging?: boolean;
/** Which prompt logging backend to use. */
promptLoggingBackend?: "google_sheets";
promptLoggingBackend?: "google_sheets" | "file";
/** Prefix for prompt logging files when using the file backend. */
promptLoggingFilePrefix?: string;
/** Base64-encoded Google Sheets API key. */
googleSheetsKey?: string;
/** Google Sheets spreadsheet ID. */
@@ -249,11 +339,33 @@ type Config = {
* risk.
*/
allowOpenAIToolUsage?: boolean;
/**
* Whether to allow prompts containing images, for use with multimodal models.
* Avoid giving this to untrusted users, as they can submit illegal content.
*
* Applies to GPT-4 Vision and Claude Vision. Users with `special` role are
* exempt from this restriction.
*/
allowImagePrompts?: boolean;
/**
* Allows overriding the default proxy endpoint route. Defaults to /proxy.
* A leading slash is required.
*/
proxyEndpointRoute: string;
/**
* If set, only requests from these IP addresses will be permitted to use the
* admin API and UI. Provide a comma-separated list of IP addresses or CIDR
* ranges. If not set, the admin API and UI will be open to all requests.
*/
adminWhitelist: string[];
/**
* If set, requests from these IP addresses will be blocked from using the
* application. Provide a comma-separated list of IP addresses or CIDR ranges.
* If not set, no IP addresses will be blocked.
*
* Takes precedence over the adminWhitelist.
*/
ipBlacklist: string[];
};
// To change configs, create a file called .env in the root directory.
@@ -270,10 +382,22 @@ export const config: Config = {
proxyKey: getEnvWithDefault("PROXY_KEY", ""),
adminKey: getEnvWithDefault("ADMIN_KEY", ""),
serviceInfoPassword: getEnvWithDefault("SERVICE_INFO_PASSWORD", ""),
sqliteDataPath: getEnvWithDefault(
"SQLITE_DATA_PATH",
path.join(DATA_DIR, "database.sqlite")
),
eventLogging: getEnvWithDefault("EVENT_LOGGING", false),
eventLoggingTrim: getEnvWithDefault("EVENT_LOGGING_TRIM", 5),
gatekeeper: getEnvWithDefault("GATEKEEPER", "none"),
gatekeeperStore: getEnvWithDefault("GATEKEEPER_STORE", "memory"),
maxIpsPerUser: getEnvWithDefault("MAX_IPS_PER_USER", 0),
maxIpsAutoBan: getEnvWithDefault("MAX_IPS_AUTO_BAN", true),
maxIpsAutoBan: getEnvWithDefault("MAX_IPS_AUTO_BAN", false),
captchaMode: getEnvWithDefault("CAPTCHA_MODE", "none"),
powTokenHours: getEnvWithDefault("POW_TOKEN_HOURS", 24),
powTokenMaxIps: getEnvWithDefault("POW_TOKEN_MAX_IPS", 2),
powDifficultyLevel: getEnvWithDefault("POW_DIFFICULTY_LEVEL", "low"),
powChallengeTimeout: getEnvWithDefault("POW_CHALLENGE_TIMEOUT", 30),
powTokenPurgeHours: getEnvWithDefault("POW_TOKEN_PURGE_HOURS", 48),
firebaseRtdbUrl: getEnvWithDefault("FIREBASE_RTDB_URL", undefined),
firebaseKey: getEnvWithDefault("FIREBASE_KEY", undefined),
textModelRateLimit: getEnvWithDefault("TEXT_MODEL_RATE_LIMIT", 4),
@@ -296,6 +420,7 @@ export const config: Config = {
"gpt4",
"gpt4-32k",
"gpt4-turbo",
"gpt4o",
"claude",
"claude-opus",
"gemini-pro",
@@ -304,10 +429,12 @@ export const config: Config = {
"mistral-medium",
"mistral-large",
"aws-claude",
"aws-claude-opus",
"azure-turbo",
"azure-gpt4",
"azure-gpt4-turbo",
"azure-gpt4-32k",
"azure-gpt4-turbo",
"azure-gpt4o",
]),
rejectPhrases: parseCsv(getEnvWithDefault("REJECT_PHRASES", "")),
rejectMessage: getEnvWithDefault(
@@ -320,6 +447,10 @@ export const config: Config = {
allowAwsLogging: getEnvWithDefault("ALLOW_AWS_LOGGING", false),
promptLogging: getEnvWithDefault("PROMPT_LOGGING", false),
promptLoggingBackend: getEnvWithDefault("PROMPT_LOGGING_BACKEND", undefined),
promptLoggingFilePrefix: getEnvWithDefault(
"PROMPT_LOGGING_FILE_PREFIX",
"prompt-logs"
),
googleSheetsKey: getEnvWithDefault("GOOGLE_SHEETS_KEY", undefined),
googleSheetsSpreadsheetId: getEnvWithDefault(
"GOOGLE_SHEETS_SPREADSHEET_ID",
@@ -348,20 +479,46 @@ export const config: Config = {
staticServiceInfo: getEnvWithDefault("STATIC_SERVICE_INFO", false),
trustedProxies: getEnvWithDefault("TRUSTED_PROXIES", 1),
allowOpenAIToolUsage: getEnvWithDefault("ALLOW_OPENAI_TOOL_USAGE", false),
allowImagePrompts: getEnvWithDefault("ALLOW_IMAGE_PROMPTS", false),
proxyEndpointRoute: getEnvWithDefault("PROXY_ENDPOINT_ROUTE", "/proxy"),
adminWhitelist: parseCsv(getEnvWithDefault("ADMIN_WHITELIST", "0.0.0.0/0")),
ipBlacklist: parseCsv(getEnvWithDefault("IP_BLACKLIST", "")),
} as const;
function generateCookieSecret() {
function generateSigningKey() {
if (process.env.COOKIE_SECRET !== undefined) {
// legacy, replaced by SIGNING_KEY
return process.env.COOKIE_SECRET;
} else if (process.env.SIGNING_KEY !== undefined) {
return process.env.SIGNING_KEY;
}
const seed = "" + config.adminKey + config.openaiKey + config.anthropicKey;
const crypto = require("crypto");
const secrets = [
config.adminKey,
config.openaiKey,
config.anthropicKey,
config.googleAIKey,
config.mistralAIKey,
config.awsCredentials,
config.azureCredentials,
];
if (secrets.filter((s) => s).length === 0) {
startupLogger.warn(
"No SIGNING_KEY or secrets are set. All sessions, cookies, and proofs of work will be invalidated on restart."
);
return crypto.randomBytes(32).toString("hex");
}
startupLogger.info("No SIGNING_KEY set; one will be generated from secrets.");
startupLogger.info(
"It's recommended to set SIGNING_KEY explicitly to ensure users' sessions and cookies always persist across restarts."
);
const seed = secrets.map((s) => s || "n/a").join("");
return crypto.createHash("sha256").update(seed).digest("hex");
}
export const COOKIE_SECRET = generateCookieSecret();
const signingKey = generateSigningKey();
export const COOKIE_SECRET = signingKey;
export async function assertConfigIsValid() {
if (process.env.MODEL_RATE_LIMIT !== undefined) {
@@ -377,6 +534,12 @@ export async function assertConfigIsValid() {
);
}
if (config.promptLogging && !config.promptLoggingBackend) {
throw new Error(
"Prompt logging is enabled but no backend is configured. Set PROMPT_LOGGING_BACKEND to 'google_sheets' or 'file'."
);
}
if (!["none", "proxy_key", "user_token"].includes(config.gatekeeper)) {
throw new Error(
`Invalid gatekeeper mode: ${config.gatekeeper}. Must be one of: none, proxy_key, user_token.`
@@ -389,15 +552,32 @@ export async function assertConfigIsValid() {
);
}
if (config.gatekeeper === "proxy_key" && !config.proxyKey) {
if (
config.captchaMode === "proof_of_work" &&
config.gatekeeper !== "user_token"
) {
throw new Error(
"`proxy_key` gatekeeper mode requires a `PROXY_KEY` to be set."
"Captcha mode 'proof_of_work' requires gatekeeper mode 'user_token'."
);
}
if (config.gatekeeper !== "proxy_key" && config.proxyKey) {
if (config.captchaMode === "proof_of_work") {
const val = config.powDifficultyLevel;
const isDifficulty =
typeof val === "string" &&
["low", "medium", "high", "extreme"].includes(val);
const isIterations =
typeof val === "number" && Number.isInteger(val) && val > 0;
if (!isDifficulty && !isIterations) {
throw new Error(
"`PROXY_KEY` is set, but gatekeeper mode is not `proxy_key`. Make sure to set `GATEKEEPER=proxy_key`."
"Invalid POW_DIFFICULTY_LEVEL. Must be one of: low, medium, high, extreme, or a positive integer."
);
}
}
if (config.gatekeeper === "proxy_key" && !config.proxyKey) {
throw new Error(
"`proxy_key` gatekeeper mode requires a `PROXY_KEY` to be set."
);
}
@@ -453,9 +633,13 @@ export const OMITTED_KEYS = [
"rejectPhrases",
"rejectMessage",
"showTokenCosts",
"promptLoggingFilePrefix",
"googleSheetsKey",
"firebaseKey",
"firebaseRtdbUrl",
"sqliteDataPath",
"eventLogging",
"eventLoggingTrim",
"gatekeeperStore",
"maxIpsPerUser",
"blockedOrigins",
@@ -469,6 +653,9 @@ export const OMITTED_KEYS = [
"allowedModelFamilies",
"trustedProxies",
"proxyEndpointRoute",
"adminWhitelist",
"ipBlacklist",
"powTokenPurgeHours",
] satisfies (keyof Config)[];
type OmitKeys = (typeof OMITTED_KEYS)[number];
+32 -13
View File
@@ -16,6 +16,7 @@ const MODEL_FAMILY_FRIENDLY_NAME: { [f in ModelFamily]: string } = {
gpt4: "GPT-4",
"gpt4-32k": "GPT-4 32k",
"gpt4-turbo": "GPT-4 Turbo",
gpt4o: "GPT-4o",
"dall-e": "DALL-E",
claude: "Claude (Sonnet)",
"claude-opus": "Claude (Opus)",
@@ -25,10 +26,12 @@ const MODEL_FAMILY_FRIENDLY_NAME: { [f in ModelFamily]: string } = {
"mistral-medium": "Mistral Medium",
"mistral-large": "Mistral Large",
"aws-claude": "AWS Claude (Sonnet)",
"aws-claude-opus": "AWS Claude (Opus)",
"azure-turbo": "Azure GPT-3.5 Turbo",
"azure-gpt4": "Azure GPT-4",
"azure-gpt4-32k": "Azure GPT-4 32k",
"azure-gpt4-turbo": "Azure GPT-4 Turbo",
"azure-gpt4o": "Azure GPT-4o",
"azure-dall-e": "Azure DALL-E",
};
@@ -60,36 +63,42 @@ export function renderPage(info: ServiceInfo) {
const title = getServerTitle();
const headerHtml = buildInfoPageHeader(info);
return `<!DOCTYPE html>
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="robots" content="noindex" />
<title>${title}</title>
<link rel="stylesheet" href="/res/css/reset.css" media="screen" />
<link rel="stylesheet" href="/res/css/sakura.css" media="screen" />
<link rel="stylesheet" href="/res/css/sakura-dark.css" media="screen and (prefers-color-scheme: dark)" />
<style>
body {
font-family: sans-serif;
background-color: #f0f0f0;
padding: 1em;
}
@media (prefers-color-scheme: dark) {
body {
background-color: #222;
color: #eee;
max-width: 900px;
margin: 0;
}
a:link, a:visited {
color: #bbe;
.self-service-links {
display: flex;
justify-content: center;
margin-bottom: 1em;
padding: 0.5em;
font-size: 0.8em;
}
.self-service-links a {
margin: 0 0.5em;
}
</style>
</head>
<body>
${headerHtml}
<hr />
${getSelfServiceLinks()}
<h2>Service Info</h2>
<pre>${JSON.stringify(info, null, 2)}</pre>
${getSelfServiceLinks()}
</body>
</html>`;
}
@@ -143,7 +152,15 @@ This proxy keeps full logs of all prompts and AI responses. Prompt logs are anon
function getSelfServiceLinks() {
if (config.gatekeeper !== "user_token") return "";
return `<footer style="font-size: 0.8em;"><hr /><a target="_blank" href="/user/lookup">Check your user token info</a></footer>`;
const links = [["Check your user token", "/user/lookup"]];
if (config.captchaMode !== "none") {
links.unshift(["Request a user token", "/user/captcha"]);
}
return `<div class="self-service-links">${links
.map(([text, link]) => `<a target="_blank" href="${link}">${text}</a>`)
.join(" | ")}</div>`;
}
function getServerTitle() {
@@ -190,7 +207,7 @@ function buildRecentImageSection() {
</div>`;
}
html += `</div>`;
html += `<p style="clear: both; text-align: center;"><a href="/user/image-history">View all recent images</a></p>`
html += `<p style="clear: both; text-align: center;"><a href="/user/image-history">View all recent images</a></p>`;
return html;
}
@@ -201,7 +218,9 @@ function escapeHtml(unsafe: string) {
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
.replace(/'/g, "&#39;")
.replace(/\[/g, "&#91;")
.replace(/]/g, "&#93;");
}
function getExternalUrlForHuggingfaceSpaceId(spaceId: string) {
+1 -1
View File
@@ -156,7 +156,7 @@ function transformAnthropicTextResponseToOpenAI(
};
}
function transformAnthropicChatResponseToOpenAI(
export function transformAnthropicChatResponseToOpenAI(
anthropicBody: Record<string, any>
): Record<string, any> {
return {
+39 -11
View File
@@ -16,7 +16,7 @@ import {
ProxyResHandlerWithBody,
createOnProxyResHandler,
} from "./middleware/response";
import { transformAnthropicChatResponseToAnthropicText } from "./anthropic";
import { transformAnthropicChatResponseToAnthropicText, transformAnthropicChatResponseToOpenAI } from "./anthropic";
import { sendErrorToClient } from "./middleware/response/error-generator";
const LATEST_AWS_V2_MINOR_VERSION = "1";
@@ -37,6 +37,7 @@ const getModelsResponse = () => {
"anthropic.claude-v2:1",
"anthropic.claude-3-haiku-20240307-v1:0",
"anthropic.claude-3-sonnet-20240229-v1:0",
"anthropic.claude-3-opus-20240229-v1:0",
];
const models = variants.map((id) => ({
@@ -76,8 +77,10 @@ const awsResponseHandler: ProxyResHandlerWithBody = async (
req.log.info("Transforming Anthropic Text back to OpenAI format");
newBody = transformAwsTextResponseToOpenAI(body, req);
break;
// case "openai<-anthropic-chat":
// todo: implement this
case "openai<-anthropic-chat":
req.log.info("Transforming AWS Anthropic Chat back to OpenAI format");
newBody = transformAnthropicChatResponseToOpenAI(body);
break;
case "anthropic-text<-anthropic-chat":
req.log.info("Transforming AWS Anthropic Chat back to Text format");
newBody = transformAnthropicChatResponseToAnthropicText(body);
@@ -159,7 +162,7 @@ const textToChatPreprocessor = createPreprocessorMiddleware(
* Routes text completion prompts to aws anthropic-chat if they need translation
* (claude-3 based models do not support the old text completion endpoint).
*/
const awsTextCompletionRouter: RequestHandler = (req, res, next) => {
const preprocessAwsTextRequest: RequestHandler = (req, res, next) => {
if (req.body.model?.includes("claude-3")) {
textToChatPreprocessor(req, res, next);
} else {
@@ -167,10 +170,32 @@ const awsTextCompletionRouter: RequestHandler = (req, res, next) => {
}
};
const oaiToAwsTextPreprocessor = createPreprocessorMiddleware(
{ inApi: "openai", outApi: "anthropic-text", service: "aws" },
{ afterTransform: [maybeReassignModel] }
);
const oaiToAwsChatPreprocessor = createPreprocessorMiddleware(
{ inApi: "openai", outApi: "anthropic-chat", service: "aws" },
{ afterTransform: [maybeReassignModel] }
);
/**
* Routes an OpenAI prompt to either the legacy Claude text completion endpoint
* or the new Claude chat completion endpoint, based on the requested model.
*/
const preprocessOpenAICompatRequest: RequestHandler = (req, res, next) => {
if (req.body.model?.includes("claude-3")) {
oaiToAwsChatPreprocessor(req, res, next);
} else {
oaiToAwsTextPreprocessor(req, res, next);
}
};
const awsRouter = Router();
awsRouter.get("/v1/models", handleModelRequest);
// Native(ish) Anthropic text completion endpoint.
awsRouter.post("/v1/complete", ipLimiter, awsTextCompletionRouter, awsProxy);
awsRouter.post("/v1/complete", ipLimiter, preprocessAwsTextRequest, awsProxy);
// Native Anthropic chat completion endpoint.
awsRouter.post(
"/v1/messages",
@@ -198,10 +223,7 @@ awsRouter.post(
awsRouter.post(
"/v1/chat/completions",
ipLimiter,
createPreprocessorMiddleware(
{ inApi: "openai", outApi: "anthropic-text", service: "aws" },
{ afterTransform: [maybeReassignModel] }
),
preprocessOpenAICompatRequest,
awsProxy
);
@@ -222,7 +244,7 @@ function maybeReassignModel(req: Request) {
}
const pattern =
/^(claude-)?(instant-)?(v)?(\d+)(\.(\d+))?(-\d+k)?(-sonnet-?|-opus-?)(\d*)/i;
/^(claude-)?(instant-)?(v)?(\d+)(\.(\d+))?(-\d+k)?(-sonnet-?|-opus-?|-haiku-?)(\d*)/i;
const match = model.match(pattern);
// If there's no match, return the latest v2 model
@@ -257,10 +279,16 @@ function maybeReassignModel(req: Request) {
}
// AWS currently only supports one v3 model.
const variant = match[8]; // sonnet or opus
const variant = match[8]; // sonnet, opus, or haiku
const variantVersion = match[9];
if (major === "3") {
if (variant.includes("opus")) {
req.body.model = "anthropic.claude-3-opus-20240229-v1:0";
} else if (variant.includes("haiku")) {
req.body.model = "anthropic.claude-3-haiku-20240307-v1:0";
} else {
req.body.model = "anthropic.claude-3-sonnet-20240229-v1:0";
}
return;
}
+41 -10
View File
@@ -1,6 +1,7 @@
import type { Request, RequestHandler } from "express";
import type { Request, Response, RequestHandler } from "express";
import { config } from "../config";
import { authenticate, getUser } from "../shared/users/user-store";
import { sendErrorToClient } from "./middleware/response/error-generator";
const GATEKEEPER = config.gatekeeper;
const PROXY_KEY = config.proxyKey;
@@ -50,9 +51,9 @@ export const gatekeeper: RequestHandler = (req, res, next) => {
// IP alone to distinguish between them and prevent usertoken sharing.
// Risu sends a signed token in the request headers with an anonymous user
// ID that we can instead use to associate requests with an individual.
const ip = req.risuToken?.length ?
`risu${req.risuToken}-${req.ip}` :
req.ip;
const ip = req.risuToken?.length
? `risu${req.risuToken}-${req.ip}`
: req.ip;
const { user, result } = authenticate(token, ip);
@@ -61,17 +62,47 @@ export const gatekeeper: RequestHandler = (req, res, next) => {
req.user = user;
return next();
case "limited":
return res.status(403).json({
error: `Forbidden: no more IPs can authenticate with this token`,
});
return sendError(
req,
res,
403,
"Forbidden: no more IPs can authenticate with this user token"
);
case "disabled":
const bannedUser = getUser(token);
if (bannedUser?.disabledAt) {
const reason = bannedUser.disabledReason || "Token disabled";
return res.status(403).json({ error: `Forbidden: ${reason}` });
const reason = bannedUser.disabledReason || "User token disabled";
return sendError(req, res, 403, `Forbidden: ${reason}`);
}
}
}
res.status(401).json({ error: "Unauthorized" });
sendError(req, res, 401, "Unauthorized");
};
function sendError(
req: Request,
res: Response,
status: number,
message: string
) {
const isPost = req.method === "POST";
const hasBody = isPost && req.body;
const hasModel = hasBody && req.body.model;
if (!hasModel) {
return res.status(status).json({ error: message });
}
sendErrorToClient({
req,
res,
options: {
title: `Proxy gatekeeper error (HTTP ${status})`,
message,
format: "unknown",
statusCode: status,
reqId: req.id,
},
});
}
+3 -3
View File
@@ -3,10 +3,10 @@ import http from "http";
import httpProxy from "http-proxy";
import { ZodError } from "zod";
import { generateErrorMessage } from "zod-error";
import { HttpError } from "../../shared/errors";
import { assertNever } from "../../shared/utils";
import { QuotaExceededError } from "./request/preprocessors/apply-quota-limits";
import { sendErrorToClient } from "./response/error-generator";
import { HttpError } from "../../shared/errors";
const OPENAI_CHAT_COMPLETION_ENDPOINT = "/v1/chat/completions";
const OPENAI_TEXT_COMPLETION_ENDPOINT = "/v1/completions";
@@ -54,13 +54,13 @@ export function sendProxyError(
const msg =
statusCode === 500
? `The proxy encountered an error while trying to process your prompt.`
: `The proxy encountered an error while trying to send your prompt to the upstream service.`;
: `The proxy encountered an error while trying to send your prompt to the API.`;
sendErrorToClient({
options: {
format: req.inboundApi,
title: `Proxy error (HTTP ${statusCode} ${statusMessage})`,
message: `${msg} Further technical details are provided below.`,
message: `${msg} Further details are provided below.`,
obj: errorPayload,
reqId: req.id,
model: req.body?.model,
+3 -2
View File
@@ -11,16 +11,17 @@ export {
// Express middleware (runs before http-proxy-middleware, can be async)
export { addAzureKey } from "./preprocessors/add-azure-key";
export { applyQuotaLimits } from "./preprocessors/apply-quota-limits";
export { validateContextSize } from "./preprocessors/validate-context-size";
export { countPromptTokens } from "./preprocessors/count-prompt-tokens";
export { languageFilter } from "./preprocessors/language-filter";
export { setApiFormat } from "./preprocessors/set-api-format";
export { signAwsRequest } from "./preprocessors/sign-aws-request";
export { transformOutboundPayload } from "./preprocessors/transform-outbound-payload";
export { validateContextSize } from "./preprocessors/validate-context-size";
export { validateVision } from "./preprocessors/validate-vision";
// http-proxy-middleware callbacks (runs on onProxyReq, cannot be async)
export { addKey, addKeyForEmbeddingsRequest } from "./onproxyreq/add-key";
export { addAnthropicPreamble } from "./onproxyreq/add-anthropic-preamble";
export { addKey, addKeyForEmbeddingsRequest } from "./onproxyreq/add-key";
export { blockZoomerOrigins } from "./onproxyreq/block-zoomer-origins";
export { checkModelFamily } from "./onproxyreq/check-model-family";
export { finalizeBody } from "./onproxyreq/finalize-body";
@@ -1,3 +1,5 @@
import { AnthropicChatMessage } from "../../../../shared/api-schemas";
import { containsImageContent } from "../../../../shared/api-schemas/anthropic";
import { Key, OpenAIKey, keyPool } from "../../../../shared/key-management";
import { isEmbeddingsRequest } from "../../common";
import { HPMRequestCallback } from "../index";
@@ -19,17 +21,24 @@ export const addKey: HPMRequestCallback = (proxyReq, req) => {
throw new Error("You must specify a model with your request.");
}
let needsMultimodal = false;
if (outboundApi === "anthropic-chat") {
needsMultimodal = containsImageContent(
body.messages as AnthropicChatMessage[]
);
}
if (inboundApi === outboundApi) {
assignedKey = keyPool.get(body.model, service);
assignedKey = keyPool.get(body.model, service, needsMultimodal);
} else {
switch (outboundApi) {
// If we are translating between API formats we may need to select a model
// for the user, because the provided model is for the inbound API.
// TODO: This whole else condition is probably no longer needed since API
// translation now reassigns the model earlier in the request pipeline.
case "anthropic-chat":
case "anthropic-text":
assignedKey = keyPool.get("claude-v1", service);
case "anthropic-chat":
assignedKey = keyPool.get("claude-v1", service, needsMultimodal);
break;
case "openai-text":
assignedKey = keyPool.get("gpt-3.5-turbo-instruct", service);
@@ -7,10 +7,15 @@ import { HPMRequestCallback } from "../index";
export const stripHeaders: HPMRequestCallback = (proxyReq) => {
proxyReq.setHeader("origin", "");
proxyReq.setHeader("referer", "");
proxyReq.removeHeader("tailscale-user-login");
proxyReq.removeHeader("tailscale-user-name");
proxyReq.removeHeader("tailscale-headers-info");
proxyReq.removeHeader("tailscale-user-profile-pic")
proxyReq.removeHeader("cf-connecting-ip");
proxyReq.removeHeader("forwarded");
proxyReq.removeHeader("true-client-ip");
proxyReq.removeHeader("x-forwarded-for");
proxyReq.removeHeader("x-forwarded-host");
proxyReq.removeHeader("x-forwarded-proto");
proxyReq.removeHeader("x-real-ip");
};
@@ -4,11 +4,12 @@ import { initializeSseStream } from "../../../shared/streaming";
import { classifyErrorAndSend } from "../common";
import {
RequestPreprocessor,
validateContextSize,
countPromptTokens,
languageFilter,
setApiFormat,
transformOutboundPayload,
languageFilter,
validateContextSize,
validateVision,
} from ".";
type RequestPreprocessorOptions = {
@@ -50,6 +51,7 @@ export const createPreprocessorMiddleware = (
languageFilter,
...(afterTransform ?? []),
validateContextSize,
validateVision,
];
return async (...args) => executePreprocessors(preprocessors, args);
};
@@ -31,7 +31,10 @@ export const countPromptTokens: RequestPreprocessor = async (req) => {
}
case "anthropic-chat": {
req.outputTokens = req.body.max_tokens;
const prompt: AnthropicChatMessage[] = req.body.messages;
const prompt = {
system: req.body.system ?? "",
messages: req.body.messages,
};
result = await countTokens({ req, prompt, service });
break;
}
@@ -38,6 +38,7 @@ export const signAwsRequest: RequestPreprocessor = async (req) => {
if (req.outboundApi === "anthropic-chat") {
strippedParams = AnthropicV1MessagesSchema.pick({
messages: true,
system: true,
max_tokens: true,
stop_sequences: true,
temperature: true,
@@ -46,9 +46,18 @@ export const validateContextSize: RequestPreprocessor = async (req) => {
}
proxyMax ||= Number.MAX_SAFE_INTEGER;
if (req.user?.type === "special") {
req.log.debug("Special user, not enforcing proxy context limit.");
proxyMax = Number.MAX_SAFE_INTEGER;
}
let modelMax: number;
if (model.match(/gpt-3.5-turbo-16k/)) {
modelMax = 16384;
} else if (model.match(/^gpt-4o/)) {
modelMax = 128000;
} else if (model.match(/gpt-4-turbo(-\d{4}-\d{2}-\d{2})?$/)) {
modelMax = 131072;
} else if (model.match(/gpt-4-turbo(-preview)?$/)) {
modelMax = 131072;
} else if (model.match(/gpt-4-(0125|1106)(-preview)?$/)) {
@@ -56,7 +65,7 @@ export const validateContextSize: RequestPreprocessor = async (req) => {
} else if (model.match(/^gpt-4(-\d{4})?-vision(-preview)?$/)) {
modelMax = 131072;
} else if (model.match(/gpt-3.5-turbo/)) {
modelMax = 4096;
modelMax = 16384;
} else if (model.match(/gpt-4-32k/)) {
modelMax = 32768;
} else if (model.match(/gpt-4/)) {
@@ -75,7 +84,7 @@ export const validateContextSize: RequestPreprocessor = async (req) => {
modelMax = GOOGLE_AI_MAX_CONTEXT;
} else if (model.match(/^mistral-(tiny|small|medium)$/)) {
modelMax = MISTRAL_AI_MAX_CONTENT;
} else if (model.match(/^anthropic\.claude-3-sonnet/)) {
} else if (model.match(/^anthropic\.claude-3/)) {
modelMax = 200000;
} else if (model.match(/^anthropic\.claude-v2:\d/)) {
modelMax = 200000;
@@ -0,0 +1,38 @@
import { config } from "../../../../config";
import { assertNever } from "../../../../shared/utils";
import { RequestPreprocessor } from "../index";
import { containsImageContent as containsImageContentOpenAI } from "../../../../shared/api-schemas/openai";
import { containsImageContent as containsImageContentAnthropic } from "../../../../shared/api-schemas/anthropic";
import { ForbiddenError } from "../../../../shared/errors";
/**
* Rejects prompts containing images if multimodal prompts are disabled.
*/
export const validateVision: RequestPreprocessor = async (req) => {
if (config.allowImagePrompts) return;
if (req.user?.type === "special") return;
let hasImage = false;
switch (req.outboundApi) {
case "openai":
hasImage = containsImageContentOpenAI(req.body.messages);
break;
case "anthropic-chat":
hasImage = containsImageContentAnthropic(req.body.messages);
break;
case "anthropic-text":
case "google-ai":
case "mistral-ai":
case "openai-image":
case "openai-text":
return;
default:
assertNever(req.outboundApi);
}
if (hasImage) {
throw new ForbiddenError(
"Prompts containing images are not permitted. Disable 'Send Inline Images' in your client and try again."
);
}
};
@@ -31,17 +31,28 @@ function getMessageContent({
}
```
*/
const note = obj?.proxy_note || obj?.error?.message || "";
const friendlyMessage = note ? `${message}\n\n***\n\n*${note}*` : message;
const details = JSON.parse(JSON.stringify(obj ?? {}));
let stack = "";
if (details.stack) {
stack = `\n\nInclude this trace when reporting an issue.\n\`\`\`\n${details.stack}\n\`\`\``;
delete details.stack;
const header = `### **${title}**`;
const friendlyMessage = note ? `${message}\n\n----\n\n*${note}*` : message;
const serializedObj = obj
? ["```", JSON.stringify(obj, null, 2), "```"].join("\n")
: "";
const { stack } = JSON.parse(JSON.stringify(obj ?? {}));
let prettyTrace = "";
if (stack && obj) {
prettyTrace = [
"Include this trace when reporting an issue.",
"```",
stack,
"```",
].join("\n");
delete obj.stack;
}
return `\n\n**${title}**\n${friendlyMessage}${
obj ? `\n\`\`\`\n${JSON.stringify(obj, null, 2)}\n\`\`\`\n${stack}` : ""
}`;
return [header, friendlyMessage, serializedObj, prettyTrace].join("\n\n");
}
type ErrorGeneratorOptions = {
@@ -0,0 +1,76 @@
import util from "util";
import zlib from "zlib";
import { sendProxyError } from "../common";
import type { RawResponseBodyHandler } from "./index";
const DECODER_MAP = {
gzip: util.promisify(zlib.gunzip),
deflate: util.promisify(zlib.inflate),
br: util.promisify(zlib.brotliDecompress),
};
const isSupportedContentEncoding = (
contentEncoding: string
): contentEncoding is keyof typeof DECODER_MAP => {
return contentEncoding in DECODER_MAP;
};
/**
* Handles the response from the upstream service and decodes the body if
* necessary. If the response is JSON, it will be parsed and returned as an
* object. Otherwise, it will be returned as a string. Does not handle streaming
* responses.
* @throws {Error} Unsupported content-encoding or invalid application/json body
*/
export const handleBlockingResponse: RawResponseBodyHandler = async (
proxyRes,
req,
res
) => {
if (req.isStreaming) {
const err = new Error(
"handleBlockingResponse called for a streaming request."
);
req.log.error({ stack: err.stack, api: req.inboundApi }, err.message);
throw err;
}
return new Promise<string>((resolve, reject) => {
let chunks: Buffer[] = [];
proxyRes.on("data", (chunk) => chunks.push(chunk));
proxyRes.on("end", async () => {
let body = Buffer.concat(chunks);
const contentEncoding = proxyRes.headers["content-encoding"];
if (contentEncoding) {
if (isSupportedContentEncoding(contentEncoding)) {
const decoder = DECODER_MAP[contentEncoding];
// @ts-ignore - started failing after upgrading TypeScript, don't care
// as it was never a problem.
body = await decoder(body);
} else {
const error = `Proxy received response with unsupported content-encoding: ${contentEncoding}`;
req.log.warn({ contentEncoding, key: req.key?.hash }, error);
sendProxyError(req, res, 500, "Internal Server Error", {
error,
contentEncoding,
});
return reject(error);
}
}
try {
if (proxyRes.headers["content-type"]?.includes("application/json")) {
const json = JSON.parse(body.toString());
return resolve(json);
}
return resolve(body.toString());
} catch (e) {
const msg = `Proxy received response with invalid JSON: ${e.message}`;
req.log.warn({ error: e.stack, key: req.key?.hash }, msg);
sendProxyError(req, res, 500, "Internal Server Error", { error: msg });
return reject(msg);
}
});
});
};
@@ -3,20 +3,21 @@ import { pipeline, Readable, Transform } from "stream";
import StreamArray from "stream-json/streamers/StreamArray";
import { StringDecoder } from "string_decoder";
import { promisify } from "util";
import type { logger } from "../../../logger";
import { BadRequestError, RetryableError } from "../../../shared/errors";
import { APIFormat, keyPool } from "../../../shared/key-management";
import {
copySseResponseHeaders,
initializeSseStream,
} from "../../../shared/streaming";
import type { logger } from "../../../logger";
import { enqueue } from "../../queue";
import { decodeResponseBody, RawResponseBodyHandler, RetryableError } from ".";
import { reenqueueRequest } from "../../queue";
import type { RawResponseBodyHandler } from ".";
import { handleBlockingResponse } from "./handle-blocking-response";
import { buildSpoofedSSE, sendErrorToClient } from "./error-generator";
import { getAwsEventStreamDecoder } from "./streaming/aws-event-stream-decoder";
import { EventAggregator } from "./streaming/event-aggregator";
import { SSEMessageTransformer } from "./streaming/sse-message-transformer";
import { SSEStreamAdapter } from "./streaming/sse-stream-adapter";
import { buildSpoofedSSE, sendErrorToClient } from "./error-generator";
import { BadRequestError } from "../../../shared/errors";
const pipelineAsync = promisify(pipeline);
@@ -50,7 +51,7 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
{ statusCode: proxyRes.statusCode, key: hash },
`Streaming request returned error status code. Falling back to non-streaming response handler.`
);
return decodeResponseBody(proxyRes, req, res);
return handleBlockingResponse(proxyRes, req, res);
}
req.log.debug({ headers: proxyRes.headers }, `Starting to proxy SSE stream.`);
@@ -105,12 +106,7 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
} catch (err) {
if (err instanceof RetryableError) {
keyPool.markRateLimited(req.key!);
req.log.warn(
{ key: req.key!.hash, retryCount: req.retryCount },
`Re-enqueueing request due to retryable error during streaming response.`
);
req.retryCount++;
await enqueue(req);
await reenqueueRequest(req);
} else if (err instanceof BadRequestError) {
sendErrorToClient({
req,
@@ -138,8 +134,18 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
res.write(`data: [DONE]\n\n`);
res.end();
}
// At this point the response is closed. If the request resulted in any
// tokens being consumed (suggesting a mid-stream error), we will resolve
// and continue the middleware chain so tokens can be counted.
if (aggregator.hasEvents()) {
return aggregator.getFinalResponse();
} else {
// If there is nothing, then this was a completely failed prompt that
// will not have billed any tokens. Throw to stop the middleware chain.
throw err;
}
}
};
function handleAbortedStream(req: express.Request, res: express.Response) {
+55 -126
View File
@@ -1,10 +1,8 @@
/* This file is fucking horrendous, sorry */
import { Request, Response } from "express";
import * as http from "http";
import util from "util";
import zlib from "zlib";
import { enqueue, trackWaitTime } from "../../queue";
import { HttpError } from "../../../shared/errors";
import { config } from "../../../config";
import { HttpError, RetryableError } from "../../../shared/errors";
import { keyPool } from "../../../shared/key-management";
import { getOpenAIModelFamily } from "../../../shared/models";
import { countTokens } from "../../../shared/tokenization";
@@ -13,6 +11,7 @@ import {
incrementTokenCount,
} from "../../../shared/users/user-store";
import { assertNever } from "../../../shared/utils";
import { reenqueueRequest, trackWaitTime } from "../../queue";
import { refundLastAttempt } from "../../rate-limit";
import {
getCompletionFromBody,
@@ -20,39 +19,23 @@ import {
isTextGenerationRequest,
sendProxyError,
} from "../common";
import { handleBlockingResponse } from "./handle-blocking-response";
import { handleStreamedResponse } from "./handle-streamed-response";
import { logPrompt } from "./log-prompt";
import { logEvent } from "./log-event";
import { saveImage } from "./save-image";
import { config } from "../../../config";
const DECODER_MAP = {
gzip: util.promisify(zlib.gunzip),
deflate: util.promisify(zlib.inflate),
br: util.promisify(zlib.brotliDecompress),
};
const isSupportedContentEncoding = (
contentEncoding: string
): contentEncoding is keyof typeof DECODER_MAP => {
return contentEncoding in DECODER_MAP;
};
export class RetryableError extends Error {
constructor(message: string) {
super(message);
this.name = "RetryableError";
}
}
/**
* Either decodes or streams the entire response body and then passes it as the
* last argument to the rest of the middleware stack.
* Either decodes or streams the entire response body and then resolves with it.
* @returns The response body as a string or parsed JSON object depending on the
* response's content-type.
*/
export type RawResponseBodyHandler = (
proxyRes: http.IncomingMessage,
req: Request,
res: Response
) => Promise<string | Record<string, any>>;
export type ProxyResHandlerWithBody = (
proxyRes: http.IncomingMessage,
req: Request,
@@ -76,6 +59,10 @@ export type ProxyResMiddleware = ProxyResHandlerWithBody[];
* middleware from executing as it consumes the stream and forwards events to
* the client. Once the stream is closed, the finalized body will be attached
* to res.body and the remaining middleware will execute.
*
* @param apiMiddleware - Custom middleware to execute after the common response
* handlers. These *only* execute for non-streaming responses, so should be used
* to transform non-streaming responses into the desired format.
*/
export const createOnProxyResHandler = (apiMiddleware: ProxyResMiddleware) => {
return async (
@@ -83,36 +70,35 @@ export const createOnProxyResHandler = (apiMiddleware: ProxyResMiddleware) => {
req: Request,
res: Response
) => {
const initialHandler = req.isStreaming
const initialHandler: RawResponseBodyHandler = req.isStreaming
? handleStreamedResponse
: decodeResponseBody;
: handleBlockingResponse;
let lastMiddleware = initialHandler.name;
try {
const body = await initialHandler(proxyRes, req, res);
const middlewareStack: ProxyResMiddleware = [];
if (req.isStreaming) {
// `handleStreamedResponse` writes to the response and ends it, so
// we can only execute middleware that doesn't write to the response.
// Handlers for streaming requests must never write to the response.
middlewareStack.push(
trackRateLimit,
trackKeyRateLimit,
countResponseTokens,
incrementUsage,
logPrompt
logPrompt,
logEvent
);
} else {
middlewareStack.push(
trackRateLimit,
addProxyInfo,
trackKeyRateLimit,
injectProxyInfo,
handleUpstreamErrors,
countResponseTokens,
incrementUsage,
copyHttpHeaders,
saveImage,
logPrompt,
logEvent,
...apiMiddleware
);
}
@@ -154,72 +140,6 @@ export const createOnProxyResHandler = (apiMiddleware: ProxyResMiddleware) => {
};
};
async function reenqueueRequest(req: Request) {
req.log.info(
{ key: req.key?.hash, retryCount: req.retryCount },
`Re-enqueueing request due to retryable error`
);
req.retryCount++;
await enqueue(req);
}
/**
* Handles the response from the upstream service and decodes the body if
* necessary. If the response is JSON, it will be parsed and returned as an
* object. Otherwise, it will be returned as a string.
* @throws {Error} Unsupported content-encoding or invalid application/json body
*/
export const decodeResponseBody: RawResponseBodyHandler = async (
proxyRes,
req,
res
) => {
if (req.isStreaming) {
const err = new Error("decodeResponseBody called for a streaming request.");
req.log.error({ stack: err.stack, api: req.inboundApi }, err.message);
throw err;
}
return new Promise<string>((resolve, reject) => {
let chunks: Buffer[] = [];
proxyRes.on("data", (chunk) => chunks.push(chunk));
proxyRes.on("end", async () => {
let body = Buffer.concat(chunks);
const contentEncoding = proxyRes.headers["content-encoding"];
if (contentEncoding) {
if (isSupportedContentEncoding(contentEncoding)) {
const decoder = DECODER_MAP[contentEncoding];
// @ts-ignore - started failing after upgrading TypeScript, don't care
// as it was never a problem.
body = await decoder(body);
} else {
const error = `Proxy received response with unsupported content-encoding: ${contentEncoding}`;
req.log.warn({ contentEncoding, key: req.key?.hash }, error);
sendProxyError(req, res, 500, "Internal Server Error", {
error,
contentEncoding,
});
return reject(error);
}
}
try {
if (proxyRes.headers["content-type"]?.includes("application/json")) {
const json = JSON.parse(body.toString());
return resolve(json);
}
return resolve(body.toString());
} catch (e) {
const msg = `Proxy received response with invalid JSON: ${e.message}`;
req.log.warn({ error: e.stack, key: req.key?.hash }, msg);
sendProxyError(req, res, 500, "Internal Server Error", { error: msg });
return reject(msg);
}
});
});
};
type ProxiedErrorPayload = {
error?: Record<string, any>;
message?: string;
@@ -242,15 +162,9 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
) => {
const statusCode = proxyRes.statusCode || 500;
const statusMessage = proxyRes.statusMessage || "Internal Server Error";
if (statusCode < 400) {
return;
}
let errorPayload: ProxiedErrorPayload;
const tryAgainMessage = keyPool.available(req.body?.model)
? `There may be more keys available for this model; try again in a few seconds.`
: "There are no more keys available for this model.";
if (statusCode < 400) return;
try {
assertJsonResponse(body);
@@ -281,6 +195,9 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
`Received error response from upstream. (${proxyRes.statusMessage})`
);
// TODO: split upstream error handling into separate modules for each service,
// this is out of control.
const service = req.key!.service;
if (service === "aws") {
// Try to standardize the error format for AWS
@@ -289,8 +206,6 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
}
if (statusCode === 400) {
// Bad request. For OpenAI, this is usually due to prompt length.
// For Anthropic, this is usually due to missing preamble.
switch (service) {
case "openai":
case "google-ai":
@@ -303,7 +218,7 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
} else if (errorPayload.error?.code === "billing_hard_limit_reached") {
// For some reason, some models return this 400 error instead of the
// same 429 billing error that other models return.
await handleOpenAIRateLimitError(req, tryAgainMessage, errorPayload);
await handleOpenAIRateLimitError(req, errorPayload);
} else {
errorPayload.proxy_note = `The upstream API rejected the request. Your prompt may be too long for ${req.body?.model}.`;
}
@@ -318,18 +233,32 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
} else if (statusCode === 401) {
// Key is invalid or was revoked
keyPool.disable(req.key!, "revoked");
errorPayload.proxy_note = `API key is invalid or revoked. ${tryAgainMessage}`;
errorPayload.proxy_note = `Assigned API key is invalid or revoked, please try again.`;
} else if (statusCode === 403) {
if (service === "anthropic") {
switch (service) {
case "anthropic":
if (
errorType === "permission_error" &&
errorPayload.error?.message?.toLowerCase().includes("multimodal")
) {
req.log.warn(
{ key: req.key?.hash },
"This Anthropic key does not support multimodal prompts."
);
keyPool.update(req.key!, { allowsMultimodality: false });
await reenqueueRequest(req);
throw new RetryableError("Claude request re-enqueued because key does not support multimodality.");
} else {
keyPool.disable(req.key!, "revoked");
errorPayload.proxy_note = `API key is invalid or revoked. ${tryAgainMessage}`;
return;
errorPayload.proxy_note = `Assigned API key is invalid or revoked, please try again.`;
}
return;
case "aws":
switch (errorType) {
case "UnrecognizedClientException":
// Key is invalid.
keyPool.disable(req.key!, "revoked");
errorPayload.proxy_note = `API key is invalid or revoked. ${tryAgainMessage}`;
errorPayload.proxy_note = `Assigned API key is invalid or revoked, please try again.`;
break;
case "AccessDeniedException":
const isModelAccessError =
@@ -346,10 +275,11 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
default:
errorPayload.proxy_note = `Received 403 error. Key may be invalid.`;
}
}
} else if (statusCode === 429) {
switch (service) {
case "openai":
await handleOpenAIRateLimitError(req, tryAgainMessage, errorPayload);
await handleOpenAIRateLimitError(req, errorPayload);
break;
case "anthropic":
await handleAnthropicRateLimitError(req, errorPayload);
@@ -459,7 +389,7 @@ async function handleAnthropicBadRequestError(
"Anthropic key has been disabled."
);
keyPool.disable(req.key!, "revoked");
errorPayload.proxy_note = `Assigned key has been disabled. ${error?.message}`;
errorPayload.proxy_note = `Assigned key has been disabled. (${error?.message})`;
return;
}
@@ -499,7 +429,6 @@ async function handleAwsRateLimitError(
async function handleOpenAIRateLimitError(
req: Request,
tryAgainMessage: string,
errorPayload: ProxiedErrorPayload
): Promise<Record<string, any>> {
const type = errorPayload.error?.type;
@@ -508,17 +437,17 @@ async function handleOpenAIRateLimitError(
case "invalid_request_error": // this is the billing_hard_limit_reached error seen in some cases
// Billing quota exceeded (key is dead, disable it)
keyPool.disable(req.key!, "quota");
errorPayload.proxy_note = `Assigned key's quota has been exceeded. ${tryAgainMessage}`;
errorPayload.proxy_note = `Assigned key's quota has been exceeded. Please try again.`;
break;
case "access_terminated":
// Account banned (key is dead, disable it)
keyPool.disable(req.key!, "revoked");
errorPayload.proxy_note = `Assigned key has been banned by OpenAI for policy violations. ${tryAgainMessage}`;
errorPayload.proxy_note = `Assigned key has been banned by OpenAI for policy violations. Please try again.`;
break;
case "billing_not_active":
// Key valid but account billing is delinquent
keyPool.disable(req.key!, "quota");
errorPayload.proxy_note = `Assigned key has been disabled due to delinquent billing. ${tryAgainMessage}`;
errorPayload.proxy_note = `Assigned key has been disabled due to delinquent billing. Please try again.`;
break;
case "requests":
case "tokens":
@@ -684,7 +613,7 @@ const countResponseTokens: ProxyResHandlerWithBody = async (
}
};
const trackRateLimit: ProxyResHandlerWithBody = async (proxyRes, req) => {
const trackKeyRateLimit: ProxyResHandlerWithBody = async (proxyRes, req) => {
keyPool.updateRateLimits(req.key!, proxyRes.headers);
};
@@ -714,7 +643,7 @@ const copyHttpHeaders: ProxyResHandlerWithBody = async (
* or transformed.
* Only used for non-streaming requests.
*/
const addProxyInfo: ProxyResHandlerWithBody = async (
const injectProxyInfo: ProxyResHandlerWithBody = async (
_proxyRes,
req,
res,
@@ -0,0 +1,81 @@
import { createHash } from "crypto";
import { config } from "../../../config";
import { eventLogger } from "../../../shared/prompt-logging";
import { getModelFromBody, isTextGenerationRequest } from "../common";
import { ProxyResHandlerWithBody } from ".";
import {
OpenAIChatMessage,
AnthropicChatMessage,
} from "../../../shared/api-schemas";
/** If event logging is enabled, logs a chat completion event. */
export const logEvent: ProxyResHandlerWithBody = async (
_proxyRes,
req,
_res,
responseBody
) => {
if (!config.eventLogging) {
return;
}
if (typeof responseBody !== "object") {
throw new Error("Expected body to be an object");
}
if (!["openai", "anthropic-chat"].includes(req.outboundApi)) {
// only chat apis are supported
return;
}
if (!req.user) {
return;
}
const loggable = isTextGenerationRequest(req);
if (!loggable) return;
const messages = req.body.messages as
| OpenAIChatMessage[]
| AnthropicChatMessage[];
let hashes = [];
hashes.push(hashMessages(messages));
for (
let i = 1;
i <= Math.min(config.eventLoggingTrim!, messages.length);
i++
) {
hashes.push(hashMessages(messages.slice(0, -i)));
}
const model = getModelFromBody(req, responseBody);
const userToken = req.user!.token;
const family = req.modelFamily!;
eventLogger.logEvent({
ip: req.ip,
type: "chat_completion",
model,
family,
hashes,
userToken,
inputTokens: req.promptTokens ?? 0,
outputTokens: req.outputTokens ?? 0,
});
};
const hashMessages = (
messages: OpenAIChatMessage[] | AnthropicChatMessage[]
): string => {
let hasher = createHash("sha256");
let messageTexts = [];
for (const msg of messages) {
if (!["system", "user", "assistant"].includes(msg.role)) continue;
if (typeof msg.content === "string") {
messageTexts.push(msg.content);
} else if (Array.isArray(msg.content)) {
if (msg.content[0].type === "text") {
messageTexts.push(msg.content[0].text);
}
}
}
hasher.update(messageTexts.join("<|im_sep|>"));
return hasher.digest("hex");
};
+44 -11
View File
@@ -11,11 +11,10 @@ import { ProxyResHandlerWithBody } from ".";
import { assertNever } from "../../../shared/utils";
import {
AnthropicChatMessage,
flattenAnthropicMessages,
flattenAnthropicMessages, GoogleAIChatMessage,
MistralAIChatMessage,
OpenAIChatMessage,
} from "../../../shared/api-schemas";
import { APIFormat } from "../../../shared/key-management";
/** If prompt logging is enabled, enqueues the prompt for logging. */
export const logPrompt: ProxyResHandlerWithBody = async (
@@ -36,7 +35,7 @@ export const logPrompt: ProxyResHandlerWithBody = async (
if (!loggable) return;
const promptPayload = getPromptForRequest(req, responseBody);
const promptFlattened = flattenMessages(promptPayload, req.outboundApi);
const promptFlattened = flattenMessages(promptPayload);
const response = getCompletionFromBody(req, responseBody);
const model = getModelFromBody(req, responseBody);
@@ -63,7 +62,8 @@ const getPromptForRequest = (
):
| string
| OpenAIChatMessage[]
| AnthropicChatMessage[]
| { contents: GoogleAIChatMessage[] }
| { system: string; messages: AnthropicChatMessage[] }
| MistralAIChatMessage[]
| OaiImageResult => {
// Since the prompt logger only runs after the request has been proxied, we
@@ -72,8 +72,9 @@ const getPromptForRequest = (
switch (req.outboundApi) {
case "openai":
case "mistral-ai":
case "anthropic-chat":
return req.body.messages;
case "anthropic-chat":
return { system: req.body.system, messages: req.body.messages };
case "openai-text":
return req.body.prompt;
case "openai-image":
@@ -87,7 +88,7 @@ const getPromptForRequest = (
case "anthropic-text":
return req.body.prompt;
case "google-ai":
return req.body.prompt.text;
return { contents: req.body.contents };
default:
assertNever(req.outboundApi);
}
@@ -98,15 +99,26 @@ const flattenMessages = (
| string
| OaiImageResult
| OpenAIChatMessage[]
| AnthropicChatMessage[]
| MistralAIChatMessage[],
format: APIFormat
| { contents: GoogleAIChatMessage[] }
| { system: string; messages: AnthropicChatMessage[] }
| MistralAIChatMessage[]
): string => {
if (typeof val === "string") {
return val.trim();
}
if (format === "anthropic-chat") {
return flattenAnthropicMessages(val as AnthropicChatMessage[]);
if (isAnthropicChatPrompt(val)) {
const { system, messages } = val;
return `System: ${system}\n\n${flattenAnthropicMessages(messages)}`;
}
if (isGoogleAIChatPrompt(val)) {
return val.contents
.map(({ parts, role }) => {
const text = parts
.map((p) => p.text)
.join("\n");
return `${role}: ${text}`;
})
.join("\n");
}
if (Array.isArray(val)) {
return val
@@ -127,3 +139,24 @@ const flattenMessages = (
}
return val.prompt.trim();
};
function isGoogleAIChatPrompt(
val: unknown
): val is { contents: GoogleAIChatMessage[] } {
return (
typeof val === "object" &&
val !== null &&
"contents" in val
);
}
function isAnthropicChatPrompt(
val: unknown
): val is { system: string; messages: AnthropicChatMessage[] } {
return (
typeof val === "object" &&
val !== null &&
"system" in val &&
"messages" in val
);
}
@@ -67,6 +67,10 @@ export class EventAggregator {
assertNever(this.format);
}
}
hasEvents() {
return this.events.length > 0;
}
}
function eventIsOpenAIEvent(
@@ -2,9 +2,8 @@ import pino from "pino";
import { Transform, TransformOptions } from "stream";
import { Message } from "@smithy/eventstream-codec";
import { APIFormat } from "../../../../shared/key-management";
import { RetryableError } from "../index";
import { buildSpoofedSSE } from "../error-generator";
import { BadRequestError } from "../../../../shared/errors";
import { BadRequestError, RetryableError } from "../../../../shared/errors";
type SSEStreamAdapterOptions = TransformOptions & {
contentType?: string;
@@ -117,7 +116,7 @@ export class SSEStreamAdapter extends Transform {
try {
const hasParts = candidates[0].content?.parts?.length > 0;
if (hasParts) {
return `data: ${JSON.stringify(data)}`;
return `data: ${JSON.stringify(data.value ?? data)}\n`;
} else {
this.log.error({ event: data }, "Received bad Google AI event");
return `data: ${buildSpoofedSSE({
+1 -1
View File
@@ -70,7 +70,7 @@ export function generateModelList(models = KNOWN_MISTRAL_AI_MODELS) {
}
const handleModelRequest: RequestHandler = (_req, res) => {
if (new Date().getTime() - modelsCacheTime < 1000 * 60){
if (new Date().getTime() - modelsCacheTime < 1000 * 60) {
return res.status(200).json(modelsCache);
}
const result = generateModelList();
+8 -4
View File
@@ -28,10 +28,14 @@ import {
// https://platform.openai.com/docs/models/overview
export const KNOWN_OPENAI_MODELS = [
"gpt-4-turbo-preview",
"gpt-4-0125-preview",
"gpt-4-1106-preview",
"gpt-4-vision-preview",
"gpt-4o",
"gpt-4o-2024-05-13",
"gpt-4-turbo", // alias for latest gpt4-turbo stable
"gpt-4-turbo-2024-04-09", // gpt4-turbo stable, with vision
"gpt-4-turbo-preview", // alias for latest turbo preview
"gpt-4-0125-preview", // gpt4-turbo preview 2
"gpt-4-1106-preview", // gpt4-turbo preview 1
"gpt-4-vision-preview", // gpt4-turbo preview 1 with vision
"gpt-4",
"gpt-4-0613",
"gpt-4-0314", // EOL 2024-06-13
+11 -2
View File
@@ -12,7 +12,7 @@
*/
import crypto from "crypto";
import type { Handler, Request } from "express";
import { Handler, Request } from "express";
import { BadRequestError, TooManyRequestsError } from "../shared/errors";
import { keyPool } from "../shared/key-management";
import {
@@ -67,7 +67,7 @@ const sharesIdentifierWith = (incoming: Request) => (queued: Request) =>
const isFromSharedIp = (req: Request) => SHARED_IP_ADDRESSES.has(req.ip);
export async function enqueue(req: Request) {
async function enqueue(req: Request) {
const enqueuedRequestCount = queue.filter(sharesIdentifierWith(req)).length;
let isGuest = req.user?.token === undefined;
@@ -136,6 +136,15 @@ export async function enqueue(req: Request) {
}
}
export async function reenqueueRequest(req: Request) {
req.log.info(
{ key: req.key?.hash, retryCount: req.retryCount },
`Re-enqueueing request due to retryable error`
);
req.retryCount++;
await enqueue(req);
}
function getQueueForPartition(partition: ModelFamily): Request[] {
return queue
.filter((req) => getModelFamilyForRequest(req) === partition)
+39 -1
View File
@@ -8,6 +8,7 @@ import pinoHttp from "pino-http";
import os from "os";
import childProcess from "child_process";
import { logger } from "./logger";
import { createBlacklistMiddleware } from "./shared/cidr";
import { setupAssetsDir } from "./shared/file-storage/setup-assets-dir";
import { keyPool } from "./shared/key-management";
import { adminRouter } from "./admin/routes";
@@ -21,6 +22,7 @@ import { init as initUserStore } from "./shared/users/user-store";
import { init as initTokenizers } from "./shared/tokenization";
import { checkOrigin } from "./proxy/check-origin";
import { sendErrorToClient } from "./proxy/middleware/response/error-generator";
import { initializeDatabase, getDatabase } from "./shared/database";
const PORT = config.port;
const BIND_ADDRESS = config.bindAddress;
@@ -31,13 +33,19 @@ app.use(
pinoHttp({
quietReqLogger: true,
logger,
autoLogging: { ignore: ({ url }) => ["/health"].includes(url as string) },
autoLogging: {
ignore: ({ url }) => {
const ignoreList = ["/health", "/res", "/user_content"];
return ignoreList.some((path) => (url as string).startsWith(path));
},
},
redact: {
paths: [
"req.headers.cookie",
'res.headers["set-cookie"]',
"req.headers.authorization",
'req.headers["x-api-key"]',
'req.headers["api-key"]',
// Don't log the prompt text on transform errors
"body.messages",
"body.prompt",
@@ -62,9 +70,20 @@ app.set("views", [
]);
app.use("/user_content", express.static(USER_ASSETS_DIR, { maxAge: "2h" }));
app.use(
"/res",
express.static(path.join(__dirname, "..", "public"), {
maxAge: "2h",
etag: false,
})
);
app.get("/health", (_req, res) => res.sendStatus(200));
app.use(cors());
const blacklist = createBlacklistMiddleware("IP_BLACKLIST", config.ipBlacklist);
app.use(blacklist);
app.use(checkOrigin);
app.use("/admin", adminRouter);
@@ -125,6 +144,8 @@ async function start() {
await logQueue.start();
}
await initializeDatabase();
logger.info("Starting request queue...");
startRequestQueue();
@@ -146,6 +167,23 @@ async function start() {
);
}
function cleanup() {
console.log("Shutting down...");
if (config.eventLogging) {
try {
const db = getDatabase();
db.close();
console.log("Closed sqlite database.");
} catch (error) {}
}
process.exit(0);
}
process.on("exit", () => cleanup());
process.on("SIGHUP", () => process.exit(128 + 1));
process.on("SIGINT", () => process.exit(128 + 2));
process.on("SIGTERM", () => process.exit(128 + 15));
function registerUncaughtExceptionHandler() {
process.on("uncaughtException", (err: any) => {
logger.error(
+20 -16
View File
@@ -80,6 +80,7 @@ type OpenAIInfo = BaseFamilyInfo & {
overQuotaKeys?: number;
};
type AnthropicInfo = BaseFamilyInfo & {
trialKeys?: number;
prefilledKeys?: number;
overQuotaKeys?: number;
};
@@ -140,8 +141,6 @@ const SERVICE_ENDPOINTS: { [s in LLMService]: Record<string, string> } = {
},
anthropic: {
anthropic: `%BASE%/anthropic`,
"anthropic-sonnet (⚠️Temporary: for Claude 3 Sonnet)": `%BASE%/anthropic/sonnet`,
"anthropic-opus (⚠️Temporary: for Claude 3 Opus)": `%BASE%/anthropic/opus`,
},
"google-ai": {
"google-ai": `%BASE%/google-ai`,
@@ -151,7 +150,6 @@ const SERVICE_ENDPOINTS: { [s in LLMService]: Record<string, string> } = {
},
aws: {
aws: `%BASE%/aws/claude`,
"aws-sonnet (⚠️Temporary: for AWS Claude 3 Sonnet)": `%BASE%/aws/claude/sonnet`,
},
azure: {
azure: `%BASE%/azure/openai`,
@@ -211,7 +209,8 @@ export function buildInfo(baseUrl: string, forAdmin = false): ServiceInfo {
}
function getStatus() {
if (!config.checkKeys) return "Key checking is disabled.";
if (!config.checkKeys)
return "Key checking is disabled. The data displayed are not reliable.";
let unchecked = 0;
for (const service of LLM_SERVICES) {
@@ -349,6 +348,7 @@ function addKeyToAggregates(k: KeyPoolKey) {
sumTokens += tokens;
sumCost += getTokenCostUsd(f, tokens);
increment(modelStats, `${f}__tokens`, tokens);
increment(modelStats, `${f}__trial`, k.tier === "free" ? 1 : 0);
increment(modelStats, `${f}__revoked`, k.isRevoked ? 1 : 0);
increment(modelStats, `${f}__active`, k.isDisabled ? 0 : 1);
increment(modelStats, `${f}__overQuota`, k.isOverQuota ? 1 : 0);
@@ -385,21 +385,22 @@ function addKeyToAggregates(k: KeyPoolKey) {
}
case "aws": {
if (!keyIsAwsKey(k)) throw new Error("Invalid key type");
const family = "aws-claude";
sumTokens += k["aws-claudeTokens"];
sumCost += getTokenCostUsd(family, k["aws-claudeTokens"]);
increment(modelStats, `${family}__active`, k.isDisabled ? 0 : 1);
increment(modelStats, `${family}__revoked`, k.isRevoked ? 1 : 0);
increment(modelStats, `${family}__tokens`, k["aws-claudeTokens"]);
increment(modelStats, `${family}__awsSonnet`, k.sonnetEnabled ? 1 : 0);
increment(modelStats, `${family}__awsHaiku`, k.haikuEnabled ? 1 : 0);
k.modelFamilies.forEach((f) => {
const tokens = k[`${f}Tokens`];
sumTokens += tokens;
sumCost += getTokenCostUsd(f, tokens);
increment(modelStats, `${f}__tokens`, tokens);
increment(modelStats, `${f}__revoked`, k.isRevoked ? 1 : 0);
increment(modelStats, `${f}__active`, k.isDisabled ? 0 : 1);
});
increment(modelStats, `aws-claude__awsSonnet`, k.sonnetEnabled ? 1 : 0);
increment(modelStats, `aws-claude__awsHaiku`, k.haikuEnabled ? 1 : 0);
// Ignore revoked keys for aws logging stats, but include keys where the
// logging status is unknown.
const countAsLogged =
k.lastChecked && !k.isDisabled && k.awsLoggingStatus !== "disabled";
increment(modelStats, `${family}__awsLogged`, countAsLogged ? 1 : 0);
k.lastChecked && !k.isDisabled && k.awsLoggingStatus === "enabled";
increment(modelStats, `aws-claude__awsLogged`, countAsLogged ? 1 : 0);
break;
}
default:
@@ -437,17 +438,20 @@ function getInfoForFamily(family: ModelFamily): BaseFamilyInfo {
break;
case "anthropic":
info.overQuotaKeys = modelStats.get(`${family}__overQuota`) || 0;
info.trialKeys = modelStats.get(`${family}__trial`) || 0;
info.prefilledKeys = modelStats.get(`${family}__pozzed`) || 0;
break;
case "aws":
if (family === "aws-claude") {
info.sonnetKeys = modelStats.get(`${family}__awsSonnet`) || 0;
info.haikuKeys = modelStats.get(`${family}__awsHaiku`) || 0;
const logged = modelStats.get(`${family}__awsLogged`) || 0;
if (logged > 0) {
info.privacy = config.allowAwsLogging
? `${logged} active keys are potentially logged.`
? `AWS logging verification inactive. Prompts could be logged.`
: `${logged} active keys are potentially logged and can't be used. Set ALLOW_AWS_LOGGING=true to override.`;
}
}
break;
}
}
+8 -1
View File
@@ -260,7 +260,7 @@ export function flattenAnthropicMessages(
): string {
return messages
.map((msg) => {
const name = msg.role === "user" ? "\n\nHuman: " : "\n\nAssistant: ";
const name = msg.role === "user" ? "Human" : "Assistant";
const parts = Array.isArray(msg.content)
? msg.content
: [{ type: "text", text: msg.content }];
@@ -438,3 +438,10 @@ function convertOpenAIContent(
}
});
}
export function containsImageContent(messages: AnthropicChatMessage[]) {
return messages.some(
({ content }) =>
typeof content !== "string" && content.some((c) => c.type === "image")
);
}
+10
View File
@@ -131,3 +131,13 @@ export function flattenOpenAIChatMessages(messages: OpenAIChatMessage[]) {
throw new Error(`Unknown prompt version: ${PROMPT_VERSION}`);
}
}
export function containsImageContent(
messages: OpenAIChatMessage[]
): boolean {
return messages.some((m) =>
Array.isArray(m.content)
? m.content.some((contentItem) => "image_url" in contentItem)
: false
);
}
+104
View File
@@ -0,0 +1,104 @@
import { Request, Response, NextFunction } from "express";
import ipaddr, { IPv4, IPv6 } from "ipaddr.js";
import { logger } from "../logger";
const log = logger.child({ module: "cidr" });
type IpCheckMiddleware = ((
req: Request,
res: Response,
next: NextFunction
) => void) & {
ranges: string[];
updateRanges: (ranges: string[] | string) => void;
};
export const whitelists = new Map<string, IpCheckMiddleware>();
export const blacklists = new Map<string, IpCheckMiddleware>();
export function parseCidrs(cidrs: string[] | string): [IPv4 | IPv6, number][] {
const list = Array.isArray(cidrs)
? cidrs
: cidrs.split(",").map((s) => s.trim());
return list
.map((input) => {
try {
if (input.includes("/")) {
return ipaddr.parseCIDR(input.trim());
} else {
const ip = ipaddr.parse(input.trim());
return ipaddr.parseCIDR(
`${input}/${ip.kind() === "ipv4" ? 32 : 128}`
);
}
} catch (e) {
log.error({ input, error: e.message }, "Invalid CIDR mask; skipping");
return null;
}
})
.filter((cidr): cidr is [IPv4 | IPv6, number] => cidr !== null);
}
export function createWhitelistMiddleware(
name: string,
base: string[] | string
) {
let cidrs: string[] = [];
let ranges: Record<string, [IPv4 | IPv6, number][]> = {};
const middleware: IpCheckMiddleware = (req, res, next) => {
const ip = ipaddr.process(req.ip);
const match = ipaddr.subnetMatch(ip, ranges, "none");
if (match === name) {
return next();
} else {
req.log.warn({ ip: req.ip, list: name }, "Request denied by whitelist");
res.status(403).json({ error: `Forbidden (by ${name})` });
}
};
middleware.ranges = cidrs;
middleware.updateRanges = (r: string[] | string) => {
cidrs = Array.isArray(r) ? r.slice() : [r];
const parsed = parseCidrs(cidrs);
ranges = { [name]: parsed };
middleware.ranges = cidrs;
log.info({ list: name, ranges }, "IP whitelist configured");
};
middleware.updateRanges(base);
whitelists.set(name, middleware);
return middleware;
}
export function createBlacklistMiddleware(
name: string,
base: string[] | string
) {
let cidrs: string[] = [];
let ranges: Record<string, [IPv4 | IPv6, number][]> = {};
const middleware: IpCheckMiddleware = (req, res, next) => {
const ip = ipaddr.process(req.ip);
const match = ipaddr.subnetMatch(ip, ranges, "none");
if (match === name) {
req.log.warn({ ip: req.ip, list: name }, "Request denied by blacklist");
return res.status(403).json({ error: `Forbidden (by ${name})` });
} else {
return next();
}
};
middleware.ranges = cidrs;
middleware.updateRanges = (r: string[] | string) => {
cidrs = Array.isArray(r) ? r.slice() : [r];
const parsed = parseCidrs(cidrs);
ranges = { [name]: parsed };
middleware.ranges = cidrs;
log.info({ list: name, ranges }, "IP blacklist configured");
};
middleware.updateRanges(base);
blacklists.set(name, middleware);
return middleware;
}
+1 -1
View File
@@ -3,8 +3,8 @@
import type { HttpRequest } from "@smithy/types";
import { Express } from "express-serve-static-core";
import { APIFormat, Key } from "./key-management";
import { User } from "./users/schema";
import { LLMService, ModelFamily } from "./models";
import { User } from "./database/repos/users";
declare global {
namespace Express {
+94
View File
@@ -0,0 +1,94 @@
import type sqlite3 from "better-sqlite3";
import { config } from "../../config";
import { logger } from "../../logger";
import { migrations } from "./migrations";
export const DATABASE_VERSION = 3;
let database: sqlite3.Database | undefined;
let log = logger.child({ module: "database" });
export function getDatabase(): sqlite3.Database {
if (!database) {
throw new Error("Sqlite database not initialized.");
}
return database;
}
export async function initializeDatabase() {
if (!config.eventLogging) {
return;
}
log.info("Initializing database...");
const sqlite3 = await import("better-sqlite3");
database = sqlite3.default(config.sqliteDataPath, {
verbose: process.env.SQLITE_VERBOSE === "true"
? (msg, ...args) => log.debug({ args }, String(msg))
: undefined,
});
migrateDatabase();
database.pragma("journal_mode = WAL");
log.info("Database initialized.");
}
export function migrateDatabase(
targetVersion = DATABASE_VERSION,
targetDb?: sqlite3.Database
) {
const db = targetDb || getDatabase();
const currentVersion = db.pragma("user_version", { simple: true });
assertNumber(currentVersion);
if (currentVersion === targetVersion) {
log.info("No migrations to run.");
return;
}
const direction = currentVersion < targetVersion ? "up" : "down";
const pending = migrations
.slice()
.sort((a, b) =>
direction === "up" ? a.version - b.version : b.version - a.version
)
.filter((m) =>
direction === "up"
? m.version > currentVersion && m.version <= targetVersion
: m.version > targetVersion && m.version <= currentVersion
);
if (pending.length === 0) {
log.warn("No pending migrations found.");
return;
}
for (const migration of pending) {
const { version, name, up, down } = migration;
if (
(direction === "up" && version > currentVersion) ||
(direction === "down" && version <= currentVersion)
) {
if (direction === "up") {
log.info({ name }, "Applying migration.");
up(db);
db.pragma("user_version = " + version);
} else {
log.info({ name }, "Reverting migration.");
down(db);
db.pragma("user_version = " + (version - 1));
}
}
}
log.info("Migrations applied.");
}
function assertNumber(value: unknown): asserts value is number {
if (typeof value !== "number") {
throw new Error("Expected number");
}
}
export { EventLogEntry } from "./repos/events";
+122
View File
@@ -0,0 +1,122 @@
import type sqlite3 from "better-sqlite3";
type Migration = {
name: string;
version: number;
up: (db: sqlite3.Database) => void;
down: (db: sqlite3.Database) => void;
};
export const migrations = [
{
name: "create db",
version: 1,
up: () => {},
down: () => {},
},
{
name: "add events table",
version: 2,
up: (db) => {
db.exec(
`CREATE TABLE IF NOT EXISTS events
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT NOT NULL,
ip TEXT NOT NULL,
date TEXT NOT NULL,
model TEXT NOT NULL,
family TEXT NOT NULL,
hashes TEXT NOT NULL,
userToken TEXT NOT NULL,
inputTokens INTEGER NOT NULL,
outputTokens INTEGER NOT NULL
)`
);
},
down: (db) => db.exec("DROP TABLE events"),
},
{
name: "add events indexes",
version: 3,
up: (db) => {
// language=SQLite
db.exec(
`BEGIN;
CREATE INDEX IF NOT EXISTS idx_events_userToken ON events (userToken);
CREATE INDEX IF NOT EXISTS idx_events_ip ON events (ip);
COMMIT;`
);
},
down: (db) => {
// language=SQLite
db.exec(
`BEGIN;
DROP INDEX idx_events_userToken;
DROP INDEX idx_events_ip;
COMMIT;`
);
},
},
{
name: "add users schema",
version: 4,
up: (db) => {
// language=SQLite
const sql = `
CREATE TABLE IF NOT EXISTS users
(
token TEXT PRIMARY KEY NOT NULL,
nickname TEXT,
type TEXT CHECK (type IN ('normal', 'special', 'temporary')) NOT NULL,
createdAt INTEGER NOT NULL,
lastUsedAt INTEGER,
disabledAt INTEGER,
disabledReason TEXT,
expiresAt INTEGER,
maxIps INTEGER,
adminNote TEXT
);
CREATE TABLE IF NOT EXISTS user_ips
(
userToken TEXT NOT NULL,
ip TEXT NOT NULL,
PRIMARY KEY (userToken, ip),
FOREIGN KEY (userToken) REFERENCES users (token)
);
CREATE TABLE IF NOT EXISTS user_token_counts
(
userToken TEXT NOT NULL,
modelFamily TEXT NOT NULL,
inputTokens INTEGER NOT NULL,
outputTokens INTEGER NOT NULL,
tokenLimit INTEGER NOT NULL,
prompts INTEGER NOT NULL,
PRIMARY KEY (userToken, modelFamily)
);
CREATE TABLE IF NOT EXISTS user_meta
(
userToken TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (userToken, key),
FOREIGN KEY (userToken) REFERENCES users (token)
);
`;
db.exec(sql);
},
down: (db) => {
// language=SQLite
const sql = `
DROP TABLE users;
DROP TABLE user_ips;
DROP TABLE user_token_counts;
DROP TABLE user_meta;
`;
db.exec(sql);
},
},
] satisfies Migration[];
+85
View File
@@ -0,0 +1,85 @@
import { getDatabase } from "../index";
export interface EventLogEntry {
date: string;
ip: string;
type: "chat_completion";
model: string;
family: string;
/**
* Prompt hashes are SHA256.
* Each message is stripped of whitespace.
* Then joined by <|im_sep|>
* Then hashed.
* First hash: Full prompt.
* Next {trim} hashes: Hashes with last 1-{trim} messages removed.
*/
hashes: string[];
userToken: string;
inputTokens: number;
outputTokens: number;
}
export interface EventsRepo {
getUserEvents: (
userToken: string,
{ limit, cursor }: { limit: number; cursor?: string }
) => EventLogEntry[];
logEvent: (payload: EventLogEntry) => void;
}
export const eventsRepo: EventsRepo = {
getUserEvents: (userToken, { limit, cursor }) => {
const db = getDatabase();
const params = [];
let sql = `
SELECT *
FROM events
WHERE userToken = ?
`;
params.push(userToken);
if (cursor) {
sql += ` AND date < ?`;
params.push(cursor);
}
sql += ` ORDER BY date DESC LIMIT ?`;
params.push(limit);
return db.prepare(sql).all(params).map(marshalEventLogEntry);
},
logEvent: (payload) => {
const db = getDatabase();
db.prepare(
`
INSERT INTO events(date, ip, type, model, family, hashes, userToken, inputTokens, outputTokens)
VALUES (:date, :ip, :type, :model, :family, :hashes, :userToken, :inputTokens, :outputTokens)
`
).run({
date: payload.date,
ip: payload.ip,
type: payload.type,
model: payload.model,
family: payload.family,
hashes: payload.hashes.join(","),
userToken: payload.userToken,
inputTokens: payload.inputTokens,
outputTokens: payload.outputTokens,
});
},
};
function marshalEventLogEntry(row: any): EventLogEntry {
return {
date: row.date,
ip: row.ip,
type: row.type,
model: row.model,
family: row.family,
hashes: row.hashes.split(","),
userToken: row.userToken,
inputTokens: parseInt(row.inputTokens),
outputTokens: parseInt(row.outputTokens),
};
}
+420
View File
@@ -0,0 +1,420 @@
import { ZodType, z } from "zod";
import { MODEL_FAMILIES, ModelFamily } from "../../models";
import { makeOptionalPropsNullable } from "../../utils";
import { getDatabase } from "../index";
import type { Transaction } from "better-sqlite3";
// This just dynamically creates a Zod object type with a key for each model
// family and an optional number value.
export const tokenCountsSchema: ZodType<UserTokenCounts> = z.object(
MODEL_FAMILIES.reduce(
(acc, family) => {
return {
...acc,
[family]: z.object({
input: z.number().optional().default(0),
output: z.number().optional().default(0),
limit: z.number().optional().default(0),
prompts: z.number().optional().default(0),
}),
};
},
{} as Record<
ModelFamily,
ZodType<{ input: number; output: number; limit: number; prompts: number }>
>
)
);
// Old token counts schema before counts were combined into a single object.
const tokenCountsSchemaOld = z.object(
MODEL_FAMILIES.reduce(
(acc, family) => ({ ...acc, [family]: z.number().optional().default(0) }),
{} as Record<ModelFamily, ZodType<number>>
)
);
export const UserSchema = z
.object({
/** User's personal access token. */
token: z.string(),
/** IP addresses the user has connected from. */
ip: z.array(z.string()),
/** User's nickname. */
nickname: z.string().max(80).optional(),
/**
* The user's privilege level.
* - `normal`: Default role. Subject to usual rate limits and quotas.
* - `special`: Special role. Higher quotas and exempt from auto-ban/lockout.
**/
type: z.enum(["normal", "special", "temporary"]),
/** Number of prompts the user has made. */
promptCount: z.number(),
/**
* @deprecated Use `tokenCounts` instead.
* Never used; retained for backwards compatibility.
*/
tokenCount: z.any().optional(),
/** Number of tokens the user has consumed, by model family. */
tokenCounts: tokenCountsSchemaOld,
/** Maximum number of tokens the user can consume, by model family. */
tokenLimits: tokenCountsSchemaOld,
/** Token data for the user, by model family. */
modelTokenCounts: tokenCountsSchema,
/** Time at which the user was created. */
createdAt: z.number(),
/** Time at which the user last connected. */
lastUsedAt: z.number().optional(),
/** Time at which the user was disabled, if applicable. */
disabledAt: z.number().optional(),
/** Reason for which the user was disabled, if applicable. */
disabledReason: z.string().optional(),
/** Time at which the user will expire and be disabled (for temp users). */
expiresAt: z.number().optional(),
/** The user's maximum number of IP addresses; supercedes global max. */
maxIps: z.coerce.number().int().min(0).optional(),
/** Private note about the user. */
adminNote: z.string().optional(),
meta: z.record(z.any()).optional(),
})
.strict();
/**
* Variant of `;
UserSchema` which allows for partial updates, and makes any
* optional properties on the base schema nullable. Null values are used to
* indicate that the property should be deleted from the user object.
*/
export const UserPartialSchema = makeOptionalPropsNullable(UserSchema)
.partial()
.extend({ token: z.string() });
export type UserTokenCounts = {
[K in ModelFamily]: {
input: number;
output: number;
limit: number;
prompts: number;
};
};
export type UserTokenCountsOld = {
[K in ModelFamily]: number | undefined;
};
export type User = z.infer<typeof UserSchema>;
export type UserUpdate = z.infer<typeof UserPartialSchema>;
export type VirtualUser = User & { virtual: true; ipCount: number };
export const UsersRepo = {
getUserByToken: (token: string) => {
const db = getDatabase();
// language=SQLite
const sql = `
SELECT u.*,
json_group_array(ui.ip) as ip,
json_group_object(utc.modelFamily,
json_object('input', utc.inputTokens,
'output', utc.outputTokens,
'limit', utc.tokenLimit,
'prompts', utc.prompts)) as tokenCounts,
json_object(um.key, um.value) as meta
FROM users u
LEFT JOIN user_ips ui ON u.token = ui.userToken
LEFT JOIN user_token_counts utc ON u.token = utc.userToken
LEFT JOIN user_meta um ON u.token = um.userToken
WHERE u.token = ?;
`;
const user = db.prepare(sql).get(token);
if (!user) return;
return marshalUser(user);
},
getUsers: (pagination: { limit: number; cursor?: string }): VirtualUser[] => {
const db = getDatabase();
const { limit, cursor } = pagination;
const params = [];
let sql = `
SELECT u.*,
count(ui.ip) as ipCount,
json_group_object(utc.modelFamily,
json_object('input', utc.inputTokens,
'output', utc.outputTokens,
'limit', utc.tokenLimit,
'prompts', utc.prompts)) as tokenCounts,
json_object(um.key, um.value) as meta
FROM users u
LEFT JOIN user_ips ui ON u.token = ui.userToken
LEFT JOIN user_token_counts utc ON u.token = utc.userToken
LEFT JOIN user_meta um ON u.token = um.userToken
`;
if (cursor) {
sql += ` WHERE u.token < ?`;
params.push(cursor);
}
sql += ` GROUP BY u.token ORDER BY u.token DESC LIMIT ?`;
params.push(limit);
return db
.prepare(sql)
.all(params)
.map((r: any) => {
const virtual: VirtualUser = {
...marshalUser(r),
virtual: true,
ipCount: r.ipCount ?? 0,
};
return virtual;
});
},
/**
* Upserts a user record by user token. Intended for use via the REST API,
* prefer a more targeted method if possible. Undefined values are ignored,
* null values are used to indicate that the field should be cleared.
*
* @param update - The user data to upsert, with `token` required.
*/
upsertUser: (update: UserUpdate): void => {
const db = getDatabase();
if (!db.inTransaction) {
return db.transaction(() => UsersRepo.upsertUser(update))();
}
const updates: Partial<User> = {};
for (const field of Object.entries(update)) {
const [key, value] = field as [keyof User, any]; // assertion validated by zod
if (value === undefined || key === "token") continue;
updates[key] = value;
}
const setFields = Object.keys(updates)
.map((key) => `${key} = :${key}`)
.join(", ");
const params = { ...updates, token: update.token };
// scalars
const sql = `
INSERT INTO users (token, nickname, type, createdAt, lastUsedAt, disabledAt, disabledReason, expiresAt, maxIps,
adminNote)
VALUES (:token, :nickname, :type, :createdAt, :lastUsedAt, :disabledAt, :disabledReason, :expiresAt, :maxIps,
:adminNote)
ON CONFLICT(token) DO UPDATE SET ${setFields};
`;
db.prepare(sql).run(params);
// replace ip addresses
if (update.ip) {
const sql = `
DELETE
FROM user_ips
WHERE userToken = :token;
INSERT INTO user_ips (userToken, ip)
VALUES ${update.ip.map(() => "(?, ?)").join(", ")};
`;
db.prepare(sql).run(
update.ip.flatMap((ip: string) => [update.token, ip])
);
}
if (update.modelTokenCounts) {
const sql = `
INSERT INTO user_token_counts (userToken, modelFamily, inputTokens, outputTokens, tokenLimit, prompts)
VALUES (:token, :modelFamily, :inputTokens, :outputTokens, :tokenLimit, :prompts)
ON CONFLICT(userToken, modelFamily) DO UPDATE SET inputTokens = :inputTokens,
outputTokens = :outputTokens,
tokenLimit = :tokenLimit,
prompts = :prompts;
`;
for (const [family, counts] of Object.entries(update.modelTokenCounts)) {
db.prepare(sql).run({
token: update.token,
modelFamily: family,
...counts,
});
}
}
if (update.meta) {
const sql = `
DELETE
FROM user_meta
WHERE userToken = :token;
INSERT INTO user_meta (userToken, key, value)
VALUES ${Object.keys(update.meta)
.map(() => "(?, ?, ?)")
.join(", ")};
`;
db.prepare(sql).run(
Object.entries(update.meta).flatMap(([key, value]) => [
update.token,
key,
value,
])
);
}
},
/**
* Inserts or updates multiple user records in a single transaction.
* Periodically commits the transaction and yields to the event loop to
* prevent blocking the main thread for too long.
* @param updates - The user data to upsert.
*/
upsertUsers: async (updates: UserUpdate[]) => {
const db = getDatabase();
const BATCH_SIZE = 50;
const chunked = updates.reduce<UserUpdate[][]>((acc, _, i) => {
if (i % BATCH_SIZE === 0) acc.push(updates.slice(i, i + BATCH_SIZE));
return acc;
}, []);
const transaction = db.transaction((updates: UserUpdate[]) => {
for (const update of updates) {
UsersRepo.upsertUser(update);
}
});
for (const chunk of chunked) {
await new Promise((resolve) => setTimeout(resolve, 0));
transaction(chunk);
}
},
/**
* Increments the token usage counters for a user's token by the provided
* values, and increments prompt count by 1.
*/
incrementUsage(
userToken: string,
family: ModelFamily,
input: number,
output: number
) {
const db = getDatabase();
const sql = `
INSERT INTO user_token_counts (userToken, modelFamily, inputTokens, outputTokens, tokenLimit, prompts)
VALUES (:userToken, :modelFamily, :inputTokens, :outputTokens, 0, 1)
ON CONFLICT(userToken, modelFamily) DO UPDATE SET inputTokens = inputTokens + :inputTokens,
outputTokens = outputTokens + :outputTokens,
prompts = prompts + 1;
`;
db.prepare(sql).run({
userToken,
modelFamily: family,
inputTokens: input,
outputTokens: output,
});
},
/**
* Disables user, optionally with reason.
*/
disableUser(userToken: string, reason?: string) {
const db = getDatabase();
const disabledAt = Date.now();
const sql = `
UPDATE users
SET disabledAt = :disabledAt,
disabledReason = :reason
WHERE token = :userToken;
INSERT OR REPLACE INTO user_meta (userToken, key, value)
VALUES (:userToken, 'refreshable', 'false');
`;
db.prepare(sql).run({ userToken, disabledAt, reason });
},
/**
* Restores quotas for a user by adding the provided token counts to their
* existing counts.
*/
refreshQuotas(
userToken: string,
tokensByFamily: Record<ModelFamily, number>
): void {
const db = getDatabase();
if (!db.inTransaction) {
return db.transaction(() =>
UsersRepo.refreshQuotas(userToken, tokensByFamily)
)();
}
// for each provided family, increment the tokenLimit to equal inputTokens + outputTokens + refresh amount
const sql = `
INSERT INTO user_token_counts (userToken, modelFamily, inputTokens, outputTokens, tokenLimit, prompts)
VALUES (:userToken, :modelFamily, 0, 0, :refreshAmount, 0)
ON CONFLICT(userToken, modelFamily) DO UPDATE SET tokenLimit = inputTokens + outputTokens + :refreshAmount;
`;
for (const [family, tokens] of Object.entries(tokensByFamily)) {
db.prepare(sql).run({
userToken,
modelFamily: family,
refreshAmount: tokens,
});
}
},
/**
* Resets token usage counters for a given user to zero.
*/
resetUsage(userToken: string) {
const db = getDatabase();
const sql = `
DELETE
FROM user_token_counts
WHERE userToken = :token
`;
db.prepare(sql).run({ token: userToken });
},
};
function marshalUser(row: any): User {
const user: Partial<User> = {
token: row.token,
nickname: row.nickname,
type: row.type,
createdAt: row.createdAt,
lastUsedAt: row.lastUsedAt,
disabledAt: row.disabledAt,
disabledReason: row.disabledReason,
expiresAt: row.expiresAt,
maxIps: row.maxIps,
adminNote: row.adminNote,
};
user.ip = row.ip ? JSON.parse(row.ip) : [];
user.meta = row.meta ? JSON.parse(row.meta) : {};
user.modelTokenCounts = JSON.parse(row.tokenCounts ?? "{}") as z.infer<
typeof tokenCountsSchema
>;
// legacy token fields
user.promptCount = 0;
user.tokenCount = 0;
user.tokenCounts = {} as z.infer<typeof tokenCountsSchemaOld>;
if (row.tokenCounts) {
// initialize missing model families
for (const family of MODEL_FAMILIES) {
if (!user.modelTokenCounts[family]) {
user.modelTokenCounts[family] = {
input: 0,
output: 0,
limit: 0,
prompts: 0,
};
}
// aggregate legacy fields
user.promptCount += user.modelTokenCounts[family].prompts;
user.tokenCount +=
user.modelTokenCounts[family].input +
user.modelTokenCounts[family].output;
user.tokenCounts[family] =
user.modelTokenCounts[family].input +
user.modelTokenCounts[family].output;
}
}
return user as User;
}
+7
View File
@@ -34,3 +34,10 @@ export class TooManyRequestsError extends HttpError {
super(429, message);
}
}
export class RetryableError extends Error {
constructor(message: string) {
super(message);
this.name = "RetryableError";
}
}
+32 -12
View File
@@ -1,9 +1,9 @@
import axios, { AxiosError } from "axios";
import axios, { AxiosError, AxiosResponse } from "axios";
import { KeyCheckerBase } from "../key-checker-base";
import type { AnthropicKey, AnthropicKeyProvider } from "./provider";
const MIN_CHECK_INTERVAL = 3 * 1000; // 3 seconds
const KEY_CHECK_PERIOD = 60 * 60 * 1000; // 1 hour
const KEY_CHECK_PERIOD = 1000 * 60 * 60 * 6; // 6 hours
const POST_MESSAGES_URL = "https://api.anthropic.com/v1/messages";
const TEST_MODEL = "claude-3-sonnet-20240229";
const SYSTEM = "Obey all instructions from the user.";
@@ -52,10 +52,13 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
}
protected async testKeyOrFail(key: AnthropicKey) {
const [{ pozzed }] = await Promise.all([this.testLiveness(key)]);
const updates = { isPozzed: pozzed };
const [{ pozzed, tier }] = await Promise.all([this.testLiveness(key)]);
const updates = { isPozzed: pozzed, tier };
this.updateKey(key.hash, updates);
this.log.info({ key: key.hash, models: key.modelFamilies }, "Checked key.");
this.log.info(
{ key: key.hash, tier, models: key.modelFamilies },
"Checked key."
);
}
protected handleAxiosError(key: AnthropicKey, error: AxiosError) {
@@ -124,7 +127,9 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
this.updateKey(key.hash, { lastChecked: next });
}
private async testLiveness(key: AnthropicKey): Promise<{ pozzed: boolean }> {
private async testLiveness(
key: AnthropicKey
): Promise<{ pozzed: boolean; tier: AnthropicKey["tier"] }> {
const payload = {
model: TEST_MODEL,
max_tokens: 40,
@@ -133,24 +138,27 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
system: SYSTEM,
messages: DETECTION_PROMPT,
};
const { data } = await axios.post<MessageResponse>(
const { data, headers } = await axios.post<MessageResponse>(
POST_MESSAGES_URL,
payload,
{ headers: AnthropicKeyChecker.getHeaders(key) }
{ headers: AnthropicKeyChecker.getRequestHeaders(key) }
);
this.log.debug({ data }, "Response from Anthropic");
const tier = AnthropicKeyChecker.detectTier(headers);
const completion = data.content.map((part) => part.text).join("");
if (POZZ_PROMPT.some((re) => re.test(completion))) {
this.log.info({ key: key.hash, response: completion }, "Key is pozzed.");
return { pozzed: true };
return { pozzed: true, tier };
} else if (COPYRIGHT_PROMPT.some((re) => re.test(completion))) {
this.log.info(
{ key: key.hash, response: completion },
"Key has copyright CYA prompt."
);
return { pozzed: true };
return { pozzed: true, tier };
} else {
return { pozzed: false };
return { pozzed: false, tier };
}
}
@@ -161,7 +169,19 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
return data?.error?.type;
}
static getHeaders(key: AnthropicKey) {
static getRequestHeaders(key: AnthropicKey) {
return { "X-API-Key": key.key, "anthropic-version": "2023-06-01" };
}
static detectTier(headers: AxiosResponse["headers"]) {
const tokensLimit = headers["anthropic-ratelimit-tokens-limit"];
const intTokensLimit = parseInt(tokensLimit, 10);
if (!tokensLimit || isNaN(intTokensLimit)) return "unknown";
if (intTokensLimit <= 25000) return "free";
if (intTokensLimit <= 50000) return "build_1";
if (intTokensLimit <= 100000) return "build_2";
if (intTokensLimit <= 200000) return "build_3";
if (intTokensLimit <= 400000) return "build_4";
return "scale";
}
}
+66 -21
View File
@@ -4,7 +4,7 @@ import { config } from "../../../config";
import { logger } from "../../../logger";
import { AnthropicModelFamily, getClaudeModelFamily } from "../../models";
import { AnthropicKeyChecker } from "./checker";
import { HttpError, PaymentRequiredError } from "../../errors";
import { PaymentRequiredError } from "../../errors";
export type AnthropicKeyUpdate = Omit<
Partial<AnthropicKey>,
@@ -45,13 +45,40 @@ export interface AnthropicKey extends Key, AnthropicKeyUsage {
*/
isPozzed: boolean;
isOverQuota: boolean;
allowsMultimodality: boolean;
/**
* Key billing tier (https://docs.anthropic.com/claude/reference/rate-limits)
**/
tier: (typeof TIER_PRIORITY)[number];
}
/**
* Upon being rate limited, a key will be locked out for this many milliseconds
* while we wait for other concurrent requests to finish.
* Selection priority for Anthropic keys. Aims to maximize throughput by
* saturating concurrency-limited keys first, then trying keys with increasingly
* strict rate limits. Free keys have very limited throughput and are used last.
*/
const RATE_LIMIT_LOCKOUT = 2000;
const TIER_PRIORITY = [
"unknown",
"scale",
"build_4",
"build_3",
"build_2",
"build_1",
"free",
] as const;
/**
* Upon being rate limited, a Scale-tier key will be locked out for this many
* milliseconds while we wait for other concurrent requests to finish.
*/
const SCALE_RATE_LIMIT_LOCKOUT = 2000;
/**
* Upon being rate limited, a Build-tier key will be locked out for this many
* milliseconds while we wait for the per-minute rate limit to reset. Because
* the reset provided in the headers specifies the time for the full quota to
* become available, the key may become available before that time.
*/
const BUILD_RATE_LIMIT_LOCKOUT = 10000;
/**
* Upon assigning a key, we will wait this many milliseconds before allowing it
* to be used again. This is to prevent the queue from flooding a key with too
@@ -85,6 +112,7 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
isOverQuota: false,
isRevoked: false,
isPozzed: false,
allowsMultimodality: true,
promptCount: 0,
lastUsed: 0,
rateLimitedAt: 0,
@@ -98,6 +126,7 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
lastChecked: 0,
claudeTokens: 0,
"claude-opusTokens": 0,
tier: "unknown",
};
this.keys.push(newKey);
}
@@ -115,33 +144,43 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
return this.keys.map((k) => Object.freeze({ ...k, key: undefined }));
}
public get(_model: string) {
// Currently, all Anthropic keys have access to all models. This will almost
// certainly change when they move out of beta later this year.
const availableKeys = this.keys.filter((k) => !k.isDisabled);
public get(rawModel: string) {
this.log.debug({ model: rawModel }, "Selecting key");
const needsMultimodal = rawModel.endsWith("-multimodal");
const availableKeys = this.keys.filter((k) => {
return !k.isDisabled && (!needsMultimodal || k.allowsMultimodality);
});
if (availableKeys.length === 0) {
throw new PaymentRequiredError("No Anthropic keys available.");
throw new PaymentRequiredError(
needsMultimodal
? "No multimodal Anthropic keys available. Please disable multimodal input (such as inline images) and try again."
: "No Anthropic keys available."
);
}
// (largely copied from the OpenAI provider, without trial key support)
// Select a key, from highest priority to lowest priority:
// 1. Keys which are not rate limited
// a. If all keys were rate limited recently, select the least-recently
// rate limited key.
// 2. Keys which are not pozzed
// 3. Keys which have not been used in the longest time
// 1. Keys which are not rate limit locked
// 2. Keys with the highest tier
// 3. Keys which are not pozzed
// 4. Keys which have not been used in the longest time
const now = Date.now();
const keysByPriority = availableKeys.sort((a, b) => {
const aRateLimited = now - a.rateLimitedAt < RATE_LIMIT_LOCKOUT;
const bRateLimited = now - b.rateLimitedAt < RATE_LIMIT_LOCKOUT;
const aLockoutPeriod = getKeyLockout(a);
const bLockoutPeriod = getKeyLockout(b);
const aRateLimited = now - a.rateLimitedAt < aLockoutPeriod;
const bRateLimited = now - b.rateLimitedAt < bLockoutPeriod;
if (aRateLimited && !bRateLimited) return 1;
if (!aRateLimited && bRateLimited) return -1;
if (aRateLimited && bRateLimited) {
return a.rateLimitedAt - b.rateLimitedAt;
}
const aTierIndex = TIER_PRIORITY.indexOf(a.tier);
const bTierIndex = TIER_PRIORITY.indexOf(b.tier);
if (aTierIndex > bTierIndex) return -1;
if (a.isPozzed && !b.isPozzed) return 1;
if (!a.isPozzed && b.isPozzed) return -1;
@@ -207,7 +246,7 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
const key = this.keys.find((k) => k.hash === keyHash)!;
const now = Date.now();
key.rateLimitedAt = now;
key.rateLimitedUntil = now + RATE_LIMIT_LOCKOUT;
key.rateLimitedUntil = now + SCALE_RATE_LIMIT_LOCKOUT;
}
public recheck() {
@@ -239,3 +278,9 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
key.rateLimitedUntil = Math.max(currentRateLimit, nextRateLimit);
}
}
function getKeyLockout(key: AnthropicKey) {
return ["scale", "unknown"].includes(key.tier)
? SCALE_RATE_LIMIT_LOCKOUT
: BUILD_RATE_LIMIT_LOCKOUT;
}
+46 -14
View File
@@ -5,9 +5,11 @@ import axios, { AxiosError, AxiosRequestConfig, AxiosHeaders } from "axios";
import { URL } from "url";
import { KeyCheckerBase } from "../key-checker-base";
import type { AwsBedrockKey, AwsBedrockKeyProvider } from "./provider";
import { AwsBedrockModelFamily } from "../../models";
import { config } from "../../../config";
const MIN_CHECK_INTERVAL = 3 * 1000; // 3 seconds
const KEY_CHECK_PERIOD = 30 * 60 * 1000; // 30 minutes
const KEY_CHECK_PERIOD = 90 * 60 * 1000; // 90 minutes
const AMZ_HOST =
process.env.AMZ_HOST || "bedrock-runtime.%REGION%.amazonaws.com";
const GET_CALLER_IDENTITY_URL = `https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15`;
@@ -54,18 +56,41 @@ export class AwsKeyChecker extends KeyCheckerBase<AwsBedrockKey> {
this.invokeModel("anthropic.claude-v2", key),
this.invokeModel("anthropic.claude-3-sonnet-20240229-v1:0", key),
this.invokeModel("anthropic.claude-3-haiku-20240307-v1:0", key),
this.invokeModel("anthropic.claude-3-opus-20240229-v1:0", key),
];
}
checks.unshift(this.checkLoggingConfiguration(key));
const [_logging, _claudeV2, sonnet, haiku] = await Promise.all(checks);
const [_logging, claudeV2, sonnet, haiku, opus] = await Promise.all(checks);
if (isInitialCheck) {
this.updateKey(key.hash, { sonnetEnabled: sonnet, haikuEnabled: haiku });
const families: AwsBedrockModelFamily[] = [];
if (claudeV2 || sonnet || haiku) families.push("aws-claude");
if (opus) families.push("aws-claude-opus");
if (families.length === 0) {
this.log.warn(
{ key: key.hash },
"Key does not have access to any models; disabling."
);
return this.updateKey(key.hash, { isDisabled: true });
}
this.updateKey(key.hash, {
sonnetEnabled: sonnet,
haikuEnabled: haiku,
modelFamilies: families,
});
}
this.log.info(
{ key: key.hash, sonnet, haiku, logged: key.awsLoggingStatus },
{
key: key.hash,
sonnet,
haiku,
families: key.modelFamilies,
logged: key.awsLoggingStatus,
},
"Checked key."
);
}
@@ -175,13 +200,14 @@ export class AwsKeyChecker extends KeyCheckerBase<AwsBedrockKey> {
const correctErrorType = errorType === "ValidationException";
const correctErrorMessage = errorMessage?.match(/max_tokens/);
if (!correctErrorType || !correctErrorMessage) {
throw new AxiosError(
`Unexpected error when invoking model ${model}: ${errorMessage}`,
"AWS_ERROR",
response.config,
response.request,
response
);
return false;
// throw new AxiosError(
// `Unexpected error when invoking model ${model}: ${errorMessage}`,
// "AWS_ERROR",
// response.config,
// response.request,
// response
// );
}
this.log.debug(
@@ -192,16 +218,22 @@ export class AwsKeyChecker extends KeyCheckerBase<AwsBedrockKey> {
}
private async checkLoggingConfiguration(key: AwsBedrockKey) {
if (config.allowAwsLogging) {
// Don't check logging status if we're allowing it to reduce API calls.
this.updateKey(key.hash, { awsLoggingStatus: "unknown" });
return true;
}
const creds = AwsKeyChecker.getCredentialsFromKey(key);
const config: AxiosRequestConfig = {
const req: AxiosRequestConfig = {
method: "GET",
url: GET_INVOCATION_LOGGING_CONFIG_URL(creds.region),
headers: { accept: "application/json" },
validateStatus: () => true,
};
await AwsKeyChecker.signRequestForAws(config, key);
await AwsKeyChecker.signRequestForAws(req, key);
const { data, status, headers } =
await axios.request<GetLoggingConfigResponse>(config);
await axios.request<GetLoggingConfigResponse>(req);
let result: AwsBedrockKey["awsLoggingStatus"] = "unknown";
+13 -8
View File
@@ -2,7 +2,7 @@ import crypto from "crypto";
import { Key, KeyProvider } from "..";
import { config } from "../../../config";
import { logger } from "../../../logger";
import type { AwsBedrockModelFamily } from "../../models";
import { AwsBedrockModelFamily, getAwsBedrockModelFamily } from "../../models";
import { AwsKeyChecker } from "./checker";
import { PaymentRequiredError } from "../../errors";
@@ -78,6 +78,7 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
sonnetEnabled: true,
haikuEnabled: false,
["aws-claudeTokens"]: 0,
["aws-claude-opusTokens"]: 0,
};
this.keys.push(newKey);
}
@@ -97,14 +98,18 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
public get(model: string) {
const availableKeys = this.keys.filter((k) => {
const isNotLogged = k.awsLoggingStatus === "disabled";
const needsSonnet = model.includes("sonnet");
const needsHaiku = model.includes("haiku");
const isNotLogged = k.awsLoggingStatus !== "enabled";
const neededFamily = getAwsBedrockModelFamily(model);
const needsSonnet =
model.includes("sonnet") && neededFamily === "aws-claude";
const needsHaiku =
model.includes("haiku") && neededFamily === "aws-claude";
return (
!k.isDisabled &&
(isNotLogged || config.allowAwsLogging) &&
(k.sonnetEnabled || !needsSonnet) &&
(k.haikuEnabled || !needsHaiku)
(k.sonnetEnabled || !needsSonnet) && // sonnet and haiku are both under aws-claude, while opus is not
(k.haikuEnabled || !needsHaiku) &&
k.modelFamilies.includes(neededFamily)
);
});
if (availableKeys.length === 0) {
@@ -157,11 +162,11 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
return this.keys.filter((k) => !k.isDisabled).length;
}
public incrementUsage(hash: string, _model: string, tokens: number) {
public incrementUsage(hash: string, model: string, tokens: number) {
const key = this.keys.find((k) => k.hash === hash);
if (!key) return;
key.promptCount++;
key["aws-claudeTokens"] += tokens;
key[`${getAwsBedrockModelFamily(model)}Tokens`] += tokens;
}
public getLockoutPeriod() {
@@ -72,6 +72,7 @@ export class AzureOpenAIKeyProvider implements KeyProvider<AzureOpenAIKey> {
"azure-gpt4Tokens": 0,
"azure-gpt4-32kTokens": 0,
"azure-gpt4-turboTokens": 0,
"azure-gpt4oTokens": 0,
"azure-dall-eTokens": 0,
};
this.keys.push(newKey);
+17 -15
View File
@@ -13,15 +13,15 @@ type KeyCheckerOptions<TKey extends Key = Key> = {
export abstract class KeyCheckerBase<TKey extends Key> {
protected readonly service: string;
protected readonly RECURRING_CHECKS_ENABLED: boolean;
protected readonly recurringChecksEnabled: boolean;
/** Minimum time in between any two key checks. */
protected readonly MIN_CHECK_INTERVAL: number;
protected readonly minCheckInterval: number;
/**
* Minimum time in between checks for a given key. Because we can no longer
* read quota usage, there is little reason to check a single key more often
* than this.
*/
protected readonly KEY_CHECK_PERIOD: number;
protected readonly keyCheckPeriod: number;
protected readonly updateKey: (hash: string, props: Partial<TKey>) => void;
protected readonly keys: TKey[] = [];
protected log: pino.Logger;
@@ -29,14 +29,13 @@ export abstract class KeyCheckerBase<TKey extends Key> {
protected lastCheck = 0;
protected constructor(keys: TKey[], opts: KeyCheckerOptions<TKey>) {
const { service, keyCheckPeriod, minCheckInterval } = opts;
this.keys = keys;
this.KEY_CHECK_PERIOD = keyCheckPeriod;
this.MIN_CHECK_INTERVAL = minCheckInterval;
this.RECURRING_CHECKS_ENABLED = opts.recurringChecksEnabled ?? true;
this.keyCheckPeriod = opts.keyCheckPeriod;
this.minCheckInterval = opts.minCheckInterval;
this.recurringChecksEnabled = opts.recurringChecksEnabled ?? true;
this.updateKey = opts.updateKey;
this.service = service;
this.log = logger.child({ module: "key-checker", service });
this.service = opts.service;
this.log = logger.child({ module: "key-checker", service: opts.service });
}
public start() {
@@ -102,7 +101,7 @@ export abstract class KeyCheckerBase<TKey extends Key> {
return;
}
if (!this.RECURRING_CHECKS_ENABLED) {
if (!this.recurringChecksEnabled) {
checkLog.info(
"Initial checks complete and recurring checks are disabled for this service. Stopping."
);
@@ -117,17 +116,20 @@ export abstract class KeyCheckerBase<TKey extends Key> {
// Don't check any individual key too often.
// Don't check anything at all at a rate faster than once per 3 seconds.
const nextCheck = Math.max(
oldestKey.lastChecked + this.KEY_CHECK_PERIOD,
this.lastCheck + this.MIN_CHECK_INTERVAL
oldestKey.lastChecked + this.keyCheckPeriod,
this.lastCheck + this.minCheckInterval
);
const delay = nextCheck - Date.now();
const baseDelay = nextCheck - Date.now();
const jitter = (Math.random() - 0.5) * baseDelay * 0.5;
const jitteredDelay = Math.max(1000, baseDelay + jitter);
this.timeout = setTimeout(
() => this.checkKey(oldestKey).then(() => this.scheduleNextCheck()),
delay
jitteredDelay
);
checkLog.debug(
{ key: oldestKey.hash, nextCheck: new Date(nextCheck), delay },
{ key: oldestKey.hash, nextCheck: new Date(nextCheck), jitteredDelay },
"Scheduled next recurring check."
);
}
+7 -1
View File
@@ -41,7 +41,13 @@ export class KeyPool {
this.scheduleRecheck();
}
public get(model: string, service?: LLMService): Key {
public get(model: string, service?: LLMService, multimodal?: boolean): Key {
// hack for some claude requests needing keys with particular permissions
// even though they use the same models as the non-multimodal requests
if (multimodal) {
model += "-multimodal";
}
const queryService = service || this.getServiceForModel(model);
return this.getKeyProvider(queryService).get(model);
}
@@ -96,6 +96,7 @@ export class OpenAIKeyProvider implements KeyProvider<OpenAIKey> {
"turbo" as const,
"gpt4" as const,
"gpt4-turbo" as const,
"gpt4o" as const,
],
isTrial: false,
isDisabled: false,
@@ -116,6 +117,7 @@ export class OpenAIKeyProvider implements KeyProvider<OpenAIKey> {
gpt4Tokens: 0,
"gpt4-32kTokens": 0,
"gpt4-turboTokens": 0,
gpt4oTokens: 0,
"dall-eTokens": 0,
gpt4Rpm: 0,
modelSnapshots: [],
+12 -3
View File
@@ -21,6 +21,7 @@ export type OpenAIModelFamily =
| "gpt4"
| "gpt4-32k"
| "gpt4-turbo"
| "gpt4o"
| "dall-e";
export type AnthropicModelFamily = "claude" | "claude-opus";
export type GoogleAIModelFamily = "gemini-pro";
@@ -29,7 +30,7 @@ export type MistralAIModelFamily =
| "mistral-small"
| "mistral-medium"
| "mistral-large";
export type AwsBedrockModelFamily = "aws-claude";
export type AwsBedrockModelFamily = "aws-claude" | "aws-claude-opus";
export type AzureOpenAIModelFamily = `azure-${OpenAIModelFamily}`;
export type ModelFamily =
| OpenAIModelFamily
@@ -46,6 +47,7 @@ export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>(
"gpt4",
"gpt4-32k",
"gpt4-turbo",
"gpt4o",
"dall-e",
"claude",
"claude-opus",
@@ -55,10 +57,12 @@ export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>(
"mistral-medium",
"mistral-large",
"aws-claude",
"aws-claude-opus",
"azure-turbo",
"azure-gpt4",
"azure-gpt4-32k",
"azure-gpt4-turbo",
"azure-gpt4o",
"azure-dall-e",
] as const);
@@ -74,6 +78,8 @@ export const LLM_SERVICES = (<A extends readonly LLMService[]>(
] as const);
export const OPENAI_MODEL_FAMILY_MAP: { [regex: string]: OpenAIModelFamily } = {
"^gpt-4o": "gpt4o",
"^gpt-4-turbo(-\\d{4}-\\d{2}-\\d{2})?$": "gpt4-turbo",
"^gpt-4-turbo(-preview)?$": "gpt4-turbo",
"^gpt-4-(0125|1106)(-preview)?$": "gpt4-turbo",
"^gpt-4(-\\d{4})?-vision(-preview)?$": "gpt4-turbo",
@@ -93,14 +99,17 @@ export const MODEL_FAMILY_SERVICE: {
gpt4: "openai",
"gpt4-turbo": "openai",
"gpt4-32k": "openai",
"gpt4o": "openai",
"dall-e": "openai",
claude: "anthropic",
"claude-opus": "anthropic",
"aws-claude": "aws",
"aws-claude-opus": "aws",
"azure-turbo": "azure",
"azure-gpt4": "azure",
"azure-gpt4-32k": "azure",
"azure-gpt4-turbo": "azure",
"azure-gpt4o": "azure",
"azure-dall-e": "azure",
"gemini-pro": "google-ai",
"mistral-tiny": "mistral-ai",
@@ -149,8 +158,8 @@ export function getMistralAIModelFamily(model: string): MistralAIModelFamily {
}
}
export function getAwsBedrockModelFamily(model: string): ModelFamily {
if (model.includes("opus")) return "claude-opus";
export function getAwsBedrockModelFamily(model: string): AwsBedrockModelFamily {
if (model.includes("opus")) return "aws-claude-opus";
return "aws-claude";
}
@@ -0,0 +1,95 @@
// stolen from https://gitgud.io/fiz1/oai-reverse-proxy
import { promises as fs } from "fs";
import * as path from "path";
import { USER_ASSETS_DIR, config } from "../../../config";
import { logger } from "../../../logger";
import { LogBackend, PromptLogEntry } from "../index";
import { glob } from "glob";
const MAX_FILE_SIZE = 100 * 1024 * 1024;
let currentFileNumber = 0;
let currentFilePath = "";
let currentFileSize = 0;
export { currentFileNumber };
export const fileBackend: LogBackend = {
init: async (_onStop: () => void) => {
try {
await createNewLogFile();
} catch (error) {
logger.error("Error initializing file backend", error);
throw error;
}
const files = glob.sync(
path.join(USER_ASSETS_DIR, `${config.promptLoggingFilePrefix}*.jsonl`),
{ windowsPathsNoEscape: true }
);
const sorted = files.sort((a, b) => {
const aNum = parseInt(path.basename(a).replace(/[^0-9]/g, ""), 10);
const bNum = parseInt(path.basename(b).replace(/[^0-9]/g, ""), 10);
return aNum - bNum;
});
if (sorted.length > 0) {
const latestFile = sorted[sorted.length - 1];
const stats = await fs.stat(latestFile);
currentFileNumber = parseInt(
path.basename(latestFile).replace(/[^0-9]/g, ""),
10
);
currentFilePath = latestFile;
currentFileSize = stats.size;
}
logger.info(
{ currentFileNumber, currentFilePath, currentFileSize },
"File backend initialized"
);
},
appendBatch: async (batch: PromptLogEntry[]) => {
try {
if (currentFileSize > MAX_FILE_SIZE) {
await createNewLogFile();
}
const batchString =
batch
.map((entry) =>
JSON.stringify({
endpoint: entry.endpoint,
model: entry.model,
prompt: entry.promptRaw,
response: entry.response,
})
)
.join("\n") + "\n";
const batchSizeBytes = Buffer.byteLength(batchString);
const batchLines = batch.length;
logger.debug(
{ batchLines, batchSizeBytes, currentFileSize, file: currentFilePath },
"Appending batch to file"
);
await fs.appendFile(currentFilePath, batchString);
currentFileSize += Buffer.byteLength(batchString);
} catch (error) {
logger.error("Error appending batch to file", error);
throw error;
}
},
};
async function createNewLogFile() {
currentFileNumber++;
currentFilePath = path.join(
USER_ASSETS_DIR,
`${config.promptLoggingFilePrefix}${currentFileNumber}.jsonl`
);
currentFileSize = 0;
await fs.writeFile(currentFilePath, "");
logger.info(`Created new log file: ${currentFilePath}`);
}
@@ -1 +1,2 @@
export * as sheets from "./sheets";
export { fileBackend as file } from "./file";
+10
View File
@@ -0,0 +1,10 @@
import { config } from "../../config";
import type { EventLogEntry } from "../database";
import { eventsRepo } from "../database/repos/events";
export const logEvent = (payload: Omit<EventLogEntry, "date">) => {
if (!config.eventLogging) {
return;
}
eventsRepo.logEvent({ ...payload, date: new Date().toISOString() });
};
+6
View File
@@ -17,4 +17,10 @@ export interface PromptLogEntry {
// TODO: temperature, top_p, top_k, etc.
}
export interface LogBackend {
init: (onStop: () => void) => Promise<void>;
appendBatch: (batch: PromptLogEntry[]) => Promise<void>;
}
export * as logQueue from "./log-queue";
export * as eventLogger from "./event-logger";
+18 -3
View File
@@ -2,8 +2,10 @@
* logging backend. */
import { logger } from "../../logger";
import { PromptLogEntry } from ".";
import { sheets } from "./backends";
import { LogBackend, PromptLogEntry } from ".";
import { sheets, file } from "./backends";
import { config } from "../../config";
import { assertNever } from "../utils";
const FLUSH_INTERVAL = 1000 * 10;
const MAX_BATCH_SIZE = 25;
@@ -15,6 +17,7 @@ let started = false;
let timeoutId: NodeJS.Timeout | null = null;
let retrying = false;
let consecutiveFailedBatches = 0;
let backend: LogBackend;
export const enqueue = (payload: PromptLogEntry) => {
if (!started) {
@@ -34,7 +37,7 @@ export const flush = async () => {
const nextBatch = queue.splice(0, batchSize);
log.info({ size: nextBatch.length }, "Submitting new batch.");
try {
await sheets.appendBatch(nextBatch);
await backend.appendBatch(nextBatch);
retrying = false;
consecutiveFailedBatches = 0;
} catch (e: any) {
@@ -64,8 +67,20 @@ export const flush = async () => {
};
export const start = async () => {
const type = config.promptLoggingBackend!;
try {
switch (type) {
case "google_sheets":
backend = sheets;
await sheets.init(() => stop());
break;
case "file":
backend = file;
await file.init(() => stop());
break;
default:
assertNever(type)
}
log.info("Logging backend initialized.");
started = true;
} catch (e) {
+5
View File
@@ -6,6 +6,10 @@ import { ModelFamily } from "./models";
export function getTokenCostUsd(model: ModelFamily, tokens: number) {
let cost = 0;
switch (model) {
case "gpt4o":
case "azure-gpt4o":
cost = 0.000005;
break;
case "azure-gpt4-turbo":
case "gpt4-turbo":
cost = 0.00001;
@@ -29,6 +33,7 @@ export function getTokenCostUsd(model: ModelFamily, tokens: number) {
case "claude":
cost = 0.000008;
break;
case "aws-claude-opus":
case "claude-opus":
cost = 0.000015;
break;
+12 -2
View File
@@ -19,7 +19,9 @@ export function init() {
return true;
}
export async function getTokenCount(prompt: string | AnthropicChatMessage[]) {
export async function getTokenCount(
prompt: string | { system: string; messages: AnthropicChatMessage[] }
) {
if (typeof prompt !== "string") {
return getTokenCountForMessages(prompt);
}
@@ -34,9 +36,17 @@ export async function getTokenCount(prompt: string | AnthropicChatMessage[]) {
};
}
async function getTokenCountForMessages(messages: AnthropicChatMessage[]) {
async function getTokenCountForMessages({
system,
messages,
}: {
system: string;
messages: AnthropicChatMessage[];
}) {
let numTokens = 0;
numTokens += (await getTokenCount(system)).token_count;
for (const message of messages) {
const { content, role } = message;
numTokens += role === "user" ? userRoleCount : assistantRoleCount;
+1 -1
View File
@@ -35,7 +35,7 @@ type OpenAIChatTokenCountRequest = {
};
type AnthropicChatTokenCountRequest = {
prompt: AnthropicChatMessage[];
prompt: { system: string; messages: AnthropicChatMessage[] };
completion?: never;
service: "anthropic-chat";
};
-70
View File
@@ -1,70 +0,0 @@
import { ZodType, z } from "zod";
import { MODEL_FAMILIES, ModelFamily } from "../models";
import { makeOptionalPropsNullable } from "../utils";
// This just dynamically creates a Zod object type with a key for each model
// family and an optional number value.
export const tokenCountsSchema: ZodType<UserTokenCounts> = z.object(
MODEL_FAMILIES.reduce(
(acc, family) => ({ ...acc, [family]: z.number().optional().default(0) }),
{} as Record<ModelFamily, ZodType<number>>
)
);
export const UserSchema = z
.object({
/** User's personal access token. */
token: z.string(),
/** IP addresses the user has connected from. */
ip: z.array(z.string()),
/** User's nickname. */
nickname: z.string().max(80).optional(),
/**
* The user's privilege level.
* - `normal`: Default role. Subject to usual rate limits and quotas.
* - `special`: Special role. Higher quotas and exempt from
* auto-ban/lockout.
**/
type: z.enum(["normal", "special", "temporary"]),
/** Number of prompts the user has made. */
promptCount: z.number(),
/**
* @deprecated Use `tokenCounts` instead.
* Never used; retained for backwards compatibility.
*/
tokenCount: z.any().optional(),
/** Number of tokens the user has consumed, by model family. */
tokenCounts: tokenCountsSchema,
/** Maximum number of tokens the user can consume, by model family. */
tokenLimits: tokenCountsSchema,
/** Time at which the user was created. */
createdAt: z.number(),
/** Time at which the user last connected. */
lastUsedAt: z.number().optional(),
/** Time at which the user was disabled, if applicable. */
disabledAt: z.number().optional(),
/** Reason for which the user was disabled, if applicable. */
disabledReason: z.string().optional(),
/** Time at which the user will expire and be disabled (for temp users). */
expiresAt: z.number().optional(),
/** The user's maximum number of IP addresses; supercedes global max. */
maxIps: z.coerce.number().int().min(0).optional(),
/** Private note about the user. */
adminNote: z.string().optional(),
})
.strict();
/**
* Variant of `UserSchema` which allows for partial updates, and makes any
* optional properties on the base schema nullable. Null values are used to
* indicate that the property should be deleted from the user object.
*/
export const UserPartialSchema = makeOptionalPropsNullable(UserSchema)
.partial()
.extend({ token: z.string() });
export type UserTokenCounts = {
[K in ModelFamily]: number | undefined;
};
export type User = z.infer<typeof UserSchema>;
export type UserUpdate = z.infer<typeof UserPartialSchema>;
+13 -2
View File
@@ -22,9 +22,9 @@ import {
ModelFamily,
} from "../models";
import { logger } from "../../logger";
import { User, UserTokenCounts, UserUpdate } from "./schema";
import { APIFormat } from "../key-management";
import { assertNever } from "../utils";
import { User, UserTokenCounts, UserUpdate } from "../database/repos/users";
const log = logger.child({ module: "users" });
@@ -80,6 +80,7 @@ export function createUser(createOptions?: {
tokenCounts: { ...INITIAL_TOKENS },
tokenLimits: createOptions?.tokenLimits ?? { ...config.tokenQuota },
createdAt: Date.now(),
meta: {},
};
if (createOptions?.type === "temporary") {
@@ -123,6 +124,7 @@ export function upsertUser(user: UserUpdate) {
tokenCounts: { ...INITIAL_TOKENS },
tokenLimits: { ...config.tokenQuota },
createdAt: Date.now(),
meta: {},
};
const updates: Partial<User> = {};
@@ -274,6 +276,10 @@ export function disableUser(token: string, reason?: string) {
if (!user) return;
user.disabledAt = Date.now();
user.disabledReason = reason;
if (user.meta) {
// manually banned tokens cannot be refreshed
user.meta.refreshable = false;
}
usersToFlush.add(token);
}
@@ -295,9 +301,14 @@ function cleanupExpiredTokens() {
if (user.type !== "temporary") continue;
if (user.expiresAt && user.expiresAt < now && !user.disabledAt) {
disableUser(user.token, "Temporary token expired.");
if (!user.meta) {
user.meta = {};
}
user.meta.refreshable = config.captchaMode !== "none";
disabled++;
}
if (user.disabledAt && user.disabledAt + 72 * 60 * 60 * 1000 < now) {
const purgeTimeout = config.powTokenPurgeHours * 60 * 60 * 1000;
if (user.disabledAt && user.disabledAt + purgeTimeout < now) {
users.delete(user.token);
usersToFlush.add(user.token);
deleted++;
+10 -1
View File
@@ -57,7 +57,7 @@ export function makeOptionalPropsNullable<Schema extends z.AnyZodObject>(
) {
const entries = Object.entries(schema.shape) as [
keyof Schema["shape"],
z.ZodTypeAny
z.ZodTypeAny,
][];
const newProps = entries.reduce(
(acc, [key, value]) => {
@@ -84,3 +84,12 @@ export function redactIp(ip: string) {
export function assertNever(x: never): never {
throw new Error(`Called assertNever with argument ${x}.`);
}
export function encodeCursor(v: string) {
return Buffer.from(JSON.stringify(v)).toString("base64");
}
export function decodeCursor(cursor?: string) {
if (!cursor) return null;
return JSON.parse(Buffer.from(cursor, "base64").toString("utf-8"));
}
+34 -38
View File
@@ -1,22 +1,26 @@
<!DOCTYPE html>
<html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="<%= csrfToken %>">
<meta charset="utf-8" />
<meta name="csrf-token" content="<%= csrfToken %>" />
<title><%= title %></title>
<link rel="stylesheet" href="/res/css/reset.css" media="screen" />
<link rel="stylesheet" href="/res/css/sakura.css" media="screen" />
<link rel="stylesheet" href="/res/css/sakura-dark.css" media="screen and (prefers-color-scheme: dark)" />
<style>
body {
font-family: sans-serif;
background-color: #f0f0f0;
padding: 1em;
max-width: 800px;
}
a:hover {
background-color: #e0e6f6;
details summary {
cursor: pointer;
font-weight: bold;
}
a:visited:hover {
background-color: #e7e0f6;
details > *:not(summary) {
margin: 0.5em;
}
.pagination {
@@ -29,6 +33,7 @@
.pagination li a {
display: block;
padding: 0.5em 1em;
border-bottom: none;
text-decoration: none;
}
.pagination li.active a {
@@ -36,17 +41,18 @@
color: #fff;
}
table {
border-collapse: collapse;
border: 1px solid #ccc;
}
table.striped tr:nth-child(even) {
background-color: #eaeaea
background-color: #eaeaea;
}
table td, table th {
border: 1px solid #ccc;
padding: 0.25em 0.5em;
table.full-width {
width: calc(100vw - 4em);
position: relative;
left: 50%;
right: 50%;
margin-left: calc(-50vw + 2em);
margin-right: calc(-50vw + 2em);
}
th.active {
background-color: #e0e6f6;
}
@@ -66,30 +72,22 @@
background-color: #e0e6f6;
}
@media (max-width: 600px) {
table {
width: 100%;
@media (max-width: 800px) {
body {
padding: 0.5em;
}
table td, table th {
display: block;
table.full-width {
width: 100%;
position: static;
left: auto;
right: auto;
margin-left: 0;
margin-right: 0;
}
}
@media (prefers-color-scheme: dark) {
body {
background-color: #222;
color: #eee;
}
a:link, a:visited {
color: #bbe;
}
a:link:hover, a:visited:hover {
background-color: #446;
}
table.striped tr:nth-child(even) {
background-color: #333;
}
@@ -102,5 +100,3 @@
</head>
<body>
<%- include("partials/shared_flash", { flashData: flash }) %>
@@ -12,7 +12,7 @@
<script>
function getPageSize() {
var match = window.location.search.match(/perPage=(\d+)/);
const match = window.location.search.match(/perPage=(\d+)/);
if (match) return parseInt(match[1]); else return document.cookie.match(/perPage=(\d+)/)?.[1] ?? 10;
}
function setPageSize(size) {
@@ -1,5 +1,5 @@
<a href="#" id="ip-list-toggle">Show all (<%- user.ip.length %>)</a>
<ol id="ip-list" style="display: none; padding-left: 1em; margin: 0">
<ol id="ip-list" style="display: none">
<% user.ip.forEach((ip) => { %>
<li><code><%- shouldRedact ? redactIp(ip) : ip %></code></li>
<% }) %>
+16 -2
View File
@@ -2,6 +2,7 @@ import express, { Router } from "express";
import { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf";
import { browseImagesRouter } from "./web/browse-images";
import { selfServiceRouter } from "./web/self-service";
import { powRouter } from "./web/pow-captcha";
import { injectLocals } from "../shared/inject-locals";
import { withSession } from "../shared/with-session";
import { config } from "../config";
@@ -18,17 +19,30 @@ userRouter.use(injectLocals);
if (config.showRecentImages) {
userRouter.use(browseImagesRouter);
}
if (config.captchaMode !== "none") {
userRouter.use("/captcha", powRouter);
}
userRouter.use(selfServiceRouter);
userRouter.use(
(
err: Error,
_req: express.Request,
req: express.Request,
res: express.Response,
_next: express.NextFunction
) => {
const data: any = { message: err.message, stack: err.stack, status: 500 };
res.status(500).render("user_error", { ...data, flash: null });
if (req.accepts("json", "html") === "json") {
const isCsrfError = err.message === "invalid csrf token";
const message = isCsrfError
? "CSRF token mismatch; try refreshing the page"
: err.message;
return res.status(500).json({ error: message });
} else {
return res.status(500).render("user_error", { ...data, flash: null });
}
}
);
+370
View File
@@ -0,0 +1,370 @@
import crypto from "crypto";
import express from "express";
import argon2 from "@node-rs/argon2";
import { z } from "zod";
import {
authenticate,
createUser,
getUser,
upsertUser,
} from "../../shared/users/user-store";
import { config } from "../../config";
/** Lockout time after verification in milliseconds */
const LOCKOUT_TIME = 1000 * 60; // 60 seconds
/** HMAC key for signing challenges; regenerated on startup */
let hmacSecret = crypto.randomBytes(32).toString("hex");
/**
* Regenerate the HMAC key used for signing challenges. Calling this function
* will invalidate all existing challenges.
*/
export function invalidatePowHmacKey() {
hmacSecret = crypto.randomBytes(32).toString("hex");
}
const argon2Params = {
ARGON2_TIME_COST: parseInt(process.env.ARGON2_TIME_COST || "8"),
ARGON2_MEMORY_KB: parseInt(process.env.ARGON2_MEMORY_KB || String(1024 * 64)),
ARGON2_PARALLELISM: parseInt(process.env.ARGON2_PARALLELISM || "1"),
ARGON2_HASH_LENGTH: parseInt(process.env.ARGON2_HASH_LENGTH || "32"),
};
/**
* Work factor for each difficulty. This is the expected number of hashes that
* will be computed to solve the challenge, on average. The actual number of
* hashes will vary due to randomness.
*/
const workFactors = { extreme: 4000, high: 1900, medium: 900, low: 200 };
type Challenge = {
/** Salt */
s: string;
/** Argon2 hash length */
hl: number;
/** Argon2 time cost */
t: number;
/** Argon2 memory cost */
m: number;
/** Argon2 parallelism */
p: number;
/** Challenge target value (difficulty) */
d: string;
/** Expiry time in milliseconds */
e: number;
/** IP address of the client */
ip?: string;
/** Challenge version */
v?: number;
/** Usertoken for refreshing */
token?: string;
};
const verifySchema = z.object({
challenge: z.object({
s: z
.string()
.min(1)
.max(64)
.regex(/^[0-9a-f]+$/),
hl: z.number().int().positive().max(64),
t: z.number().int().positive().min(2).max(10),
m: z
.number()
.int()
.positive()
.max(1024 * 1024 * 2),
p: z.number().int().positive().max(16),
d: z.string().regex(/^[0-9]+n$/),
e: z.number().int().positive(),
ip: z.string().min(1).max(64).optional(),
v: z.literal(1).optional(),
token: z.string().min(1).max(64).optional(),
}),
solution: z.string().min(1).max(64),
signature: z.string().min(1),
proxyKey: z.string().min(1).max(1024).optional(),
});
const challengeSchema = z.object({
action: z.union([z.literal("new"), z.literal("refresh")]),
refreshToken: z.string().min(1).max(64).optional(),
proxyKey: z.string().min(1).max(1024).optional(),
});
/** Solutions by timestamp */
const solves = new Map<string, number>();
/** Recent attempts by IP address */
const recentAttempts = new Map<string, number>();
setInterval(() => {
const now = Date.now();
for (const [ip, timestamp] of recentAttempts) {
if (now - timestamp > LOCKOUT_TIME) {
recentAttempts.delete(ip);
}
}
for (const [key, timestamp] of solves) {
if (now - timestamp > config.powChallengeTimeout * 1000 * 60) {
solves.delete(key);
}
}
}, 1000);
function generateChallenge(clientIp?: string, token?: string): Challenge {
let workFactor =
(typeof config.powDifficultyLevel === "number"
? config.powDifficultyLevel
: workFactors[config.powDifficultyLevel]) || 1000;
// If this is a token refresh, halve the work factor
if (token) {
workFactor = Math.floor(workFactor / 2);
}
const hashBits = BigInt(argon2Params.ARGON2_HASH_LENGTH) * 8n;
const hashMax = 2n ** hashBits;
const targetValue = hashMax / BigInt(workFactor);
return {
s: crypto.randomBytes(32).toString("hex"),
hl: argon2Params.ARGON2_HASH_LENGTH,
t: argon2Params.ARGON2_TIME_COST,
m: argon2Params.ARGON2_MEMORY_KB,
p: argon2Params.ARGON2_PARALLELISM,
d: targetValue.toString() + "n",
e: Date.now() + config.powChallengeTimeout * 1000 * 60,
ip: clientIp,
token,
};
}
function signMessage(msg: any): string {
const hmac = crypto.createHmac("sha256", hmacSecret);
if (typeof msg === "object") {
hmac.update(JSON.stringify(msg));
} else {
hmac.update(msg);
}
return hmac.digest("hex");
}
async function verifySolution(
challenge: Challenge,
solution: string,
logger: any
): Promise<boolean> {
logger.info({ solution, challenge }, "Verifying solution");
const hash = await argon2.hashRaw(String(solution), {
salt: Buffer.from(challenge.s, "hex"),
outputLen: challenge.hl,
timeCost: challenge.t,
memoryCost: challenge.m,
parallelism: challenge.p,
algorithm: argon2.Algorithm.Argon2id,
});
const hashStr = hash.toString("hex");
const target = BigInt(challenge.d.slice(0, -1));
const hashValue = BigInt("0x" + hashStr);
const result = hashValue <= target;
logger.info({ hashStr, target, hashValue, result }, "Solution verified");
return result;
}
function verifyTokenRefreshable(token: string, req: express.Request) {
const ip = req.ip;
const user = getUser(token);
if (!user) {
req.log.warn({ token }, "Cannot refresh token - not found");
return false;
}
if (user.type !== "temporary") {
req.log.warn({ token }, "Cannot refresh token - wrong token type");
return false;
}
if (!user.meta?.refreshable) {
req.log.warn({ token }, "Cannot refresh token - not refreshable");
return false;
}
if (!user.ip.includes(ip)) {
// If there are available slots, add the IP to the list
const { result } = authenticate(token, ip);
if (result === "limited") {
req.log.warn({ token, ip }, "Cannot refresh token - IP limit reached");
return false;
}
}
req.log.info({ token }, "Allowing token refresh");
return true;
}
const router = express.Router();
router.post("/challenge", (req, res) => {
const data = challengeSchema.safeParse(req.body);
if (!data.success) {
res
.status(400)
.json({ error: "Invalid challenge request", details: data.error });
return;
}
const { action, refreshToken, proxyKey } = data.data;
if (config.proxyKey && proxyKey !== config.proxyKey) {
res.status(400).json({ error: "Invalid proxy password" });
return;
}
if (action === "refresh") {
if (!refreshToken || !verifyTokenRefreshable(refreshToken, req)) {
res.status(400).json({
error: "Not allowed to refresh that token; request a new one",
});
return;
}
const challenge = generateChallenge(req.ip, refreshToken);
const signature = signMessage(challenge);
res.json({ challenge, signature });
} else {
const challenge = generateChallenge(req.ip);
const signature = signMessage(challenge);
res.json({ challenge, signature });
}
});
router.post("/verify", async (req, res) => {
const ip = req.ip;
req.log.info("Got verification request");
if (recentAttempts.has(ip)) {
res
.status(429)
.json({ error: "Rate limited; wait a minute before trying again" });
return;
}
const result = verifySchema.safeParse(req.body);
if (!result.success) {
res
.status(400)
.json({ error: "Invalid verify request", details: result.error });
return;
}
const { challenge, signature, solution } = result.data;
if (signMessage(challenge) !== signature) {
res.status(400).json({
error:
"Invalid signature; server may have restarted since challenge was issued. Please request a new challenge.",
});
return;
}
if (config.proxyKey && result.data.proxyKey !== config.proxyKey) {
res.status(401).json({ error: "Invalid proxy password" });
return;
}
if (challenge.ip && challenge.ip !== ip) {
req.log.warn("Attempt to verify from different IP address");
res.status(400).json({
error: "Solution must be verified from original IP address",
});
return;
}
if (solves.has(signature)) {
req.log.warn("Attempt to reuse signature");
res.status(400).json({ error: "Reused signature" });
return;
}
if (Date.now() > challenge.e) {
req.log.warn("Verification took too long");
res.status(400).json({ error: "Verification took too long" });
return;
}
if (challenge.token && !verifyTokenRefreshable(challenge.token, req)) {
res.status(400).json({ error: "Not allowed to refresh that usertoken" });
return;
}
recentAttempts.set(ip, Date.now());
try {
const success = await verifySolution(challenge, solution, req.log);
if (!success) {
recentAttempts.set(ip, Date.now() + 1000 * 60 * 60 * 6);
req.log.warn("Solution failed verification");
res.status(400).json({ error: "Solution failed verification" });
return;
}
solves.set(signature, Date.now());
} catch (err) {
req.log.error(err, "Error verifying proof-of-work");
res.status(500).json({ error: "Internal error" });
return;
}
if (challenge.token) {
const user = getUser(challenge.token);
if (user) {
user.expiresAt = Date.now() + config.powTokenHours * 60 * 60 * 1000;
upsertUser(user);
req.log.info(
{ token: `...${challenge.token.slice(-5)}` },
"Token refreshed"
);
return res.json({ success: true, token: challenge.token });
}
} else {
const newToken = issueToken(req);
return res.json({ success: true, token: newToken });
}
});
router.get("/", (_req, res) => {
res.render("user_request_token", {
keyRequired: !!config.proxyKey,
difficultyLevel: config.powDifficultyLevel,
tokenLifetime: config.powTokenHours,
tokenMaxIps: config.powTokenMaxIps,
challengeTimeout: config.powChallengeTimeout,
});
});
// const ipTokenCache = new Map<string, Set<string>>();
//
// function buildIpTokenCountCache() {
// ipTokenCache.clear();
// const users = getUsers().filter((u) => u.type === "temporary");
// for (const user of users) {
// for (const ip of user.ip) {
// if (!ipTokenCache.has(ip)) {
// ipTokenCache.set(ip, new Set());
// }
// ipTokenCache.get(ip)?.add(user.token);
// }
// }
// }
function issueToken(req: express.Request) {
const token = createUser({
type: "temporary",
expiresAt: Date.now() + config.powTokenHours * 60 * 60 * 1000,
});
upsertUser({
token,
ip: [req.ip],
maxIps: config.powTokenMaxIps,
meta: { refreshable: true },
});
req.log.info(
{ ip: req.ip, token: `...${token.slice(-5)}` },
"Proof-of-work token issued"
);
return token;
}
export { router as powRouter };
+1 -1
View File
@@ -1,9 +1,9 @@
import { Router } from "express";
import { UserPartialSchema } from "../../shared/users/schema";
import * as userStore from "../../shared/users/user-store";
import { ForbiddenError, BadRequestError } from "../../shared/errors";
import { sanitizeAndTrim } from "../../shared/utils";
import { config } from "../../config";
import { UserPartialSchema } from "../../shared/database/repos/users";
const router = Router();
@@ -0,0 +1,376 @@
<noscript>
<p style="color: darkorange; background-color: #ffeecc; padding: 1em">
JavaScript needs to be enabled to complete verification.
</p>
</noscript>
<style>
#captcha-container {
max-width: 500px;
margin: 50px auto;
}
@media (max-width: 1000px) {
#captcha-container {
max-width: unset;
margin: 30px;
}
}
#captcha-container details {
margin: 10px 0;
}
#captcha-container details p {
margin-left: 20px;
}
#captcha-container details li {
margin: 2px 0 0 20px;
line-height: 1.5;
}
#captcha-control {
display: flex;
flex-direction: column;
justify-content: space-between;
}
#captcha-control button {
flex-grow: 1;
margin: 10px;
padding: 10px 20px;
}
#captcha-progress-text {
width: 100%;
height: 18rem;
resize: vertical;
font-family: monospace;
}
#captcha-progress-container {
margin: 20px 0;
}
#captcha-progress-container textarea {
margin-top: 5px;
background-color: transparent;
color: inherit;
}
.progress-bar {
width: 100%;
height: 20px;
background-color: #e0e6f6;
border-radius: 5px;
overflow: hidden;
}
.progress {
width: 0;
height: 100%;
background-color: #76c7c0;
}
</style>
<div style="display: none" id="captcha-container">
<p>
Your device needs to perform a verification task before you can receive a token. This might take anywhere from a few
seconds to a few minutes, depending on your device and the proxy's security settings.
</p>
<p>Click the button below to start.</p>
<details>
<summary>What is this?</summary>
<p>
This is a <a href="https://en.wikipedia.org/wiki/Proof_of_work" target="_blank">proof-of-work</a> verification
task designed to slow down automated abuse. It requires your device's CPU to find a solution to a cryptographic
puzzle, after which a user token will be issued.
</p>
</details>
<details>
<summary>How long does verification take?</summary>
<p>
It depends on the device you're using and the current difficulty level (<code><%= difficultyLevel %></code>). The
faster your device, the quicker it will solve the task.
</p>
<p>
An estimate will be displayed once verification starts. Because the task is probabilistic, your device could solve
it more quickly or take longer than the estimate.
</p>
</details>
<details>
<summary>How often do I need to do this?</summary>
<p>
Once you've earned a user token, you can use it for <strong><%= `${tokenLifetime} hours` %></strong> before it
expires.
</p>
<p>
You can refresh an expired token by returning to this page and verifying again. Subsequent verifications will go
faster than the first one.
</p>
</details>
<details>
<summary>What is the "Workers" setting?</summary>
<p>
This controls how many CPU cores will be used to solve the verification task. If your device gets too hot or slows
down too much during verification, reduce the number of workers.
</p>
<p>
For fastest verification, set this to the number of physical CPU cores in your device. Setting more workers than
you have actual cores will generally only slow down verification.
</p>
<p>If you don't understand what this means, leave it at the default setting.</p>
</details>
<details>
<summary>Other important information</summary>
<ul>
<li>Don't change your IP address during verification.</li>
<li>Don't close this tab until verification is complete.</li>
<li>
Verification must be finished within <strong><%= `${challengeTimeout} minutes` %></strong>.
</li>
<li>Your user token will be registered to your current IP address.</li>
<li>
Up to <strong><%= tokenMaxIps || "unlimited" %></strong> IP addresses total can be registered to your user
token.
</li>
</ul>
</details>
<form id="captcha-form" style="display: none">
<input type="hidden" name="_csrf" value="<%= csrfToken %>" />
<input type="hidden" name="tokenLifetime" value="<%= tokenLifetime %>" />
</form>
<div id="captcha-control">
<div>
<label for="workers">Workers:</label>
<input type="number" id="workers" value="1" min="1" max="32" onchange="spawnWorkers()" />
</div>
<button id="worker-control" onclick="toggleWorker()">Start verification</button>
</div>
<div id="captcha-progress-container" style="display: none">
<label for="captcha-progress-text">Status:</label>
<div id="captcha-progress" class="progress-bar">
<div class="progress"></div>
</div>
<textarea disabled id="captcha-progress-text"></textarea>
</div>
<div id="captcha-result"></div>
</div>
<script>
let workers = [];
let challenge = null;
let signature = null;
let solution = null;
let totalHashes = 0;
let startTime = 0;
let lastUpdateTime = 0;
let reports = 0;
let elapsedTime = 0;
let workFactor = 0;
let active = false;
// Safari is all kinds of fucked and throws WASM Memory errors when memory
// pressure is high. Batch size and worker count need to be reduced to prevent
// this.
function isIOSiPadOSWebKit() {
const userAgent = navigator.userAgent;
const isWebKit = userAgent.includes("Safari") && !userAgent.includes("Chrome") && !userAgent.includes("Android");
const isIOS =
/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
return isWebKit && isIOS;
}
let isMobileWebkit = isIOSiPadOSWebKit();
function handleWorkerMessage(e) {
switch (e.data.type) {
case "progress":
totalHashes += e.data.hashes;
reports++;
break;
case "started":
active = true;
document.getElementById("worker-control").textContent = "Pause verification";
startTime = Date.now();
lastUpdateTime = startTime;
document.getElementById("captcha-progress-container").style.display = "block";
break;
case "paused":
active = false;
document.getElementById("worker-control").textContent = "Start verification";
document.getElementById("workers").disabled = false;
break;
case "solved":
if (solution) {
return;
}
workers.forEach((w, i) => {
w.postMessage({ type: "stop" });
setTimeout(() => w.terminate(), 1000 + i * 100)
});
workers = [];
active = false;
solution = e.data.nonce;
document.getElementById("captcha-result").textContent =
"Verification completed. Submitting solution for verification...";
document.getElementById("captcha-control").style.display = "none";
submitVerification();
break;
case "error":
workers.forEach((w) => w.postMessage({ type: "stop" }));
active = false;
const msg = e.data.error || "An unknown error occurred.";
const debug = e.data.debug || "";
document.getElementById("captcha-result").innerHTML = `
<p style="color:red">Error: ${msg}</p>
<pre style="color: red">${debug.stack}</pre>
<pre style="color: red">${debug.lastNonce}, ${String(debug.targetValue)}</pre>
<p>Refresh the page and try again. Use another device or browser if the problem persists, or lower the number of workers.</p>
`;
break;
}
estimateProgress();
}
function loadNewChallenge(c, s) {
const btn = document.getElementById("worker-control");
btn.textContent = "Start verification";
document.getElementById("captcha-container").style.display = "block";
document.getElementById("workers").disabled = false;
const maxWorkers = isMobileWebkit ? 6 : 16;
document.getElementById("workers").value = Math.min(maxWorkers, navigator.hardwareConcurrency || 4).toString();
challenge = c;
signature = s;
solution = null;
nonce = 0;
startTime = 0;
lastUpdateTime = 0;
elapsedTime = 0;
const targetValue = challenge.d.slice(0, -1);
const hashLength = challenge.hl;
workFactor = Number(BigInt(2) ** BigInt(8 * hashLength) / BigInt(targetValue));
spawnWorkers();
}
function spawnWorkers() {
for (const worker of workers) {
worker.terminate();
}
workers = [];
const selectedWorkers = document.getElementById("workers").value;
const workerCount = Math.min(32, Math.max(1, parseInt(selectedWorkers)));
for (let i = 0; i < workerCount; i++) {
const worker = new Worker("/res/js/hash-worker.js");
worker.onmessage = handleWorkerMessage;
workers.push(worker);
}
}
function toggleWorker() {
if (active) {
workers.forEach((w) => w.postMessage({ type: "stop" }));
} else {
const workerCount = workers.length;
const hashSpace = BigInt(challenge.hl * 8) ** BigInt(2);
const workerSpace = hashSpace / BigInt(workerCount);
const alreadyHashed = Math.floor(totalHashes / workerCount);
document.getElementById("workers").disabled = true;
for (let i = 0; i < workerCount; i++) {
const startNonce = workerSpace * BigInt(i) + BigInt(alreadyHashed);
workers[i].postMessage({
type: "start",
challenge: challenge,
signature: signature,
nonce: startNonce,
isMobileWebkit,
});
}
}
}
function submitVerification() {
if (!solution) {
return;
}
const body = {
challenge: challenge,
signature: signature,
solution: String(solution),
_csrf: document.querySelector("meta[name=csrf-token]").getAttribute("content"),
};
fetch("/user/captcha/verify", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
.then((res) => res.json())
.then((data) => {
if (data.error) {
document.getElementById("captcha-result").textContent = "Error: " + data.error;
} else {
const lifetime = document.getElementById("captcha-form").querySelector('input[name="tokenLifetime"]').value;
window.localStorage.setItem(
"captcha-temp-token",
JSON.stringify({
token: data.token,
expires: Date.now() + lifetime * 3600 * 1000,
})
);
document.getElementById("captcha-progress").style.display = "none";
document.getElementById("captcha-result").innerHTML = `
<p style="color: green">Verification complete</p>
<p>Your user token is: <code>${data.token}</code></p>
<p>Valid until: ${new Date(Date.now() + lifetime * 3600 * 1000).toLocaleString()}</p>
`;
}
});
}
function estimateProgress() {
if (reports % workers.length !== 0) {
return;
}
elapsedTime += (Date.now() - lastUpdateTime) / 1000;
lastUpdateTime = Date.now();
const hashRate = totalHashes / elapsedTime;
const timeRemaining = (workFactor - totalHashes) / hashRate;
const progress = 100 * (1 - Math.exp(-totalHashes / workFactor));
const formatTime = (time) => {
if (time < 60) {
return time.toFixed(1) + "s";
} else if (time < 3600) {
const minutes = Math.floor(time / 60);
const seconds = Math.floor(time % 60);
return minutes + "m " + seconds + "s";
} else {
const hours = Math.floor(time / 3600);
const minutes = Math.floor((time % 3600) / 60);
return hours + "h " + minutes + "m";
}
};
const p = 1 / workFactor;
const odds = ((1 - p) ** totalHashes * 100).toFixed(2);
let note = "";
if (odds < 33) {
note = " (" + odds + "% odds of no solution yet)";
}
document.getElementById("captcha-progress").style.width = Math.min(progress, 100) + "%";
document.getElementById("captcha-progress-text").value = `
Solution probability: 1 in ${workFactor.toLocaleString()} hashes
Hashes computed: ${totalHashes.toLocaleString()}${note}
Elapsed time: ${formatTime(elapsedTime)}
Hash rate: ${hashRate.toFixed(2)} H/s
Workers: ${workers.length}${isMobileWebkit ? " (iOS/iPadOS detected)" : ""}
${active ? `Average time remaining: ${formatTime(timeRemaining)}` : "Verification task stopped"}`.trim();
}
</script>
+4 -1
View File
@@ -1,8 +1,11 @@
<%- include("partials/shared_header", { title: "Error" }) %>
<div id="error-content" style="color: red; background-color: #eedddd; padding: 1em">
<p><strong>⚠️ Error <%= status %>:</strong> <%= message %></p>
<% if (message.includes('csrf')) { %>
<p>️ Refresh the previous page and then try again. If the problem persists, clear cookies for this site.</p>
<% } %>
<pre><%= stack %></pre>
<a href="#" onclick="window.history.back()">Go Back</a>
<a href="#" onclick="window.history.back()" style="color:unset">Go Back</a>
</div>
</body>
</html>
+104
View File
@@ -0,0 +1,104 @@
<%- include("partials/shared_header", { title: "Request User Token" }) %>
<style>
#request-buttons {
display: flex;
justify-content: space-between;
margin-top: 20px;
width: 400px;
}
#request-buttons button {
margin: 0 10px;
flex: 1;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
<h1>Request User Token</h1>
<p>You can request a temporary user token to use this proxy. The token will be valid for <%= tokenLifetime %> hours.</p>
<% if (keyRequired) { %>
<div>
<p>You need to supply the proxy password to request or refresh a token.</p>
<div>
<label for="proxy-key">Proxy password:</label>
<input type="password" id="proxy-key" />
</div>
</div>
<% } %>
<div id="existing-token" style="display: none">
<p>It looks like you might have an older temporary user token. If it has expired, you can try to refresh it.</p>
<strong id="existing-token-value">Existing token:</strong>
</div>
<div id="request-buttons">
<button disabled id="refresh-token" onclick="requestChallenge('refresh')">Refresh old token</button>
<button id="request_token" onclick="requestChallenge('new')">Request new token</button>
</div>
<%- include("partials/user_challenge_widget") %>
<script>
function requestChallenge(action) {
const token = localStorage.getItem("captcha-temp-token");
if (token && action === "new") {
const data = JSON.parse(token);
const { expires } = data;
const expiresDate = new Date(expires);
const now = new Date();
if (expiresDate > now) {
if (!confirm("You already have an existing token. Are you sure you want to request a new one?")) {
return;
}
localStorage.removeItem("captcha-temp-token");
document.getElementById("existing-token").style.display = "none";
document.getElementById("refresh-token").disabled = true;
}
} else if (!token && action === "refresh") {
alert("You don't have an existing token to refresh");
return;
}
const refreshToken = token && action === "refresh" ? JSON.parse(token).token : undefined;
const keyInput = document.getElementById("proxy-key");
const proxyKey = (keyInput && keyInput.value) || undefined;
localStorage.setItem("captcha-proxy-key", proxyKey);
fetch("/user/captcha/challenge", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action, proxyKey, refreshToken, _csrf: "<%= csrfToken %>" }),
})
.then((response) => response.json())
.then(function (data) {
if (data.error) {
throw new Error(data.error);
}
const { challenge, signature } = data;
loadNewChallenge(challenge, signature);
document.getElementById("request-buttons").style.display = "none";
})
.catch(function (error) {
console.error(error);
alert(`Error getting verification - ${error.message}`);
});
}
const existingToken = localStorage.getItem("captcha-temp-token");
if (existingToken) {
const data = JSON.parse(existingToken);
const { token, expires } = data;
const expiresDate = new Date(expires);
document.getElementById(
"existing-token-value"
).textContent = `Your token: ${token} (valid until ${expiresDate.toLocaleString()})`;
document.getElementById("existing-token").style.display = "block";
document.getElementById("refresh-token").disabled = false;
}
const proxyKey = localStorage.getItem("captcha-proxy-key");
if (proxyKey && document.getElementById("proxy-key")) {
document.getElementById("proxy-key").value = proxyKey;
}
</script>
<%- include("partials/user_footer") %>