42 Commits

Author SHA1 Message Date
nai-degen 8d5059534a starts adding cohere api format and schemas 2024-06-09 12:46:02 -05:00
nai-degen 0ea43f61c2 fixes incorrect variable name in .env.example docs 2024-06-09 11:36:20 -05:00
nai-degen ca4321b4cb adjusts openai schema validation to allow
ull stop sequence
2024-06-07 14:29:18 -05:00
nai-degen 7660ed8b94 allows enabling vision prompts on a per-service basis 2024-06-07 12:09:43 -05:00
nai-degen 55f1bbed3b adds ipv6 mask to default ADMIN_WHITELIST 2024-06-02 20:49:18 -05:00
nai-degen 57fd17ede0 makes it easier for clients to detect proxy errors programatically 2024-05-27 15:30:28 -05:00
nai-degen 9d00b8a9de adjusts max IP error message wording 2024-05-27 08:24:56 -05:00
nai-degen 155e185c6e fixes shutdown handler fuckup 2024-05-26 15:36:54 -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
87 changed files with 5589 additions and 1197 deletions
+30 -8
View File
@@ -40,12 +40,22 @@ NODE_ENV=production
# Which model types users are allowed to access. # Which model types users are allowed to access.
# The following model families are recognized: # 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'. # 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 # 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. # '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
# Which services can be used to process prompts containing images via multimodal
# models. The following services are recognized:
# openai | anthropic | aws | azure | google-ai | mistral-ai
# Do not enable this feature unless all users are trusted, as you will be liable
# for any user-submitted images containing illegal content.
# By default, no image services are allowed and image prompts are rejected.
# ALLOWED_VISION_SERVICES=
# 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. # URLs from which requests will be blocked.
# BLOCKED_ORIGINS=reddit.com,9gag.com # BLOCKED_ORIGINS=reddit.com,9gag.com
# Message to show when requests are blocked. # Message to show when requests are blocked.
@@ -58,7 +68,7 @@ NODE_ENV=production
# Avoid short or common phrases as this tests the entire prompt. # Avoid short or common phrases as this tests the entire prompt.
# REJECT_PHRASES="phrase one,phrase two,"phrase three, which has a comma",phrase four" # REJECT_PHRASES="phrase one,phrase two,"phrase three, which has a comma",phrase four"
# Message to show when requests are rejected. # Message to show when requests are rejected.
# REJECT_MESSAGE="This content violates /aicg/'s acceptable use policy." # REJECT_MESSAGE="You can't say that here."
# Whether prompts should be logged to Google Sheets. # Whether prompts should be logged to Google Sheets.
# Requires additional setup. See `docs/google-sheets.md` for more information. # Requires additional setup. See `docs/google-sheets.md` for more information.
@@ -74,6 +84,13 @@ NODE_ENV=production
# Detail level of logging. (trace | debug | info | warn | error) # Detail level of logging. (trace | debug | info | warn | error)
# LOG_LEVEL=info # 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: # Optional settings for user management, access control, and quota enforcement:
# See `docs/user-management.md` for more information and setup instructions. # See `docs/user-management.md` for more information and setup instructions.
@@ -93,18 +110,19 @@ NODE_ENV=production
# ALLOW_NICKNAME_CHANGES=true # ALLOW_NICKNAME_CHANGES=true
# Default token quotas for each model family. (0 for unlimited) # Default token quotas for each model family. (0 for unlimited)
# DALL-E "tokens" are counted at a rate of 100000 tokens per US$1.00 generated, # Specify as TOKEN_QUOTA_MODEL_FAMILY=value, replacing dashes with underscores.
# which is similar to the cost of GPT-4 Turbo.
# DALL-E 3 costs around US$0.10 per image (10000 tokens).
# See `docs/dall-e-configuration.md` for more information.
# TOKEN_QUOTA_TURBO=0 # TOKEN_QUOTA_TURBO=0
# TOKEN_QUOTA_GPT4=0 # TOKEN_QUOTA_GPT4=0
# TOKEN_QUOTA_GPT4_32K=0 # TOKEN_QUOTA_GPT4_32K=0
# TOKEN_QUOTA_GPT4_TURBO=0 # TOKEN_QUOTA_GPT4_TURBO=0
# TOKEN_QUOTA_DALL_E=0
# TOKEN_QUOTA_CLAUDE=0 # TOKEN_QUOTA_CLAUDE=0
# TOKEN_QUOTA_GEMINI_PRO=0 # TOKEN_QUOTA_GEMINI_PRO=0
# TOKEN_QUOTA_AWS_CLAUDE=0 # TOKEN_QUOTA_AWS_CLAUDE=0
# "Tokens" for image-generation models are counted at a rate of 100000 tokens
# per US$1.00 generated, which is similar to the cost of GPT-4 Turbo.
# DALL-E 3 costs around US$0.10 per image (10000 tokens).
# See `docs/dall-e-configuration.md` for more information.
# TOKEN_QUOTA_DALL_E=0
# How often to refresh token quotas. (hourly | daily) # How often to refresh token quotas. (hourly | daily)
# Leave unset to never automatically refresh quotas. # Leave unset to never automatically refresh quotas.
@@ -136,6 +154,10 @@ AZURE_CREDENTIALS=azure-resource-name:deployment-id:api-key,another-azure-resour
# With user_token gatekeeper, the admin password used to manage users. # With user_token gatekeeper, the admin password used to manage users.
# ADMIN_KEY=your-very-secret-key # 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. # With firebase_rtdb gatekeeper storage, the Firebase project credentials.
# FIREBASE_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx # FIREBASE_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+3 -4
View File
@@ -1,11 +1,10 @@
{ {
"plugins": ["prettier-plugin-ejs"],
"overrides": [ "overrides": [
{ {
"files": [ "files": "*.ejs",
"*.ejs"
],
"options": { "options": {
"printWidth": 160, "printWidth": 120,
"bracketSameLine": true "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) - [Memory](#memory)
- [Firebase Realtime Database](#firebase-realtime-database) - [Firebase Realtime Database](#firebase-realtime-database)
- [Firebase setup instructions](#firebase-setup-instructions) - [Firebase setup instructions](#firebase-setup-instructions)
- [Whitelisting admin IP addresses](#whitelisting-admin-ip-addresses)
## No user management (`GATEKEEPER=none`) ## 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. 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. 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,::0`, which will allow access from any IPv4 or IPv6 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", "description": "Reverse proxy for the OpenAI API",
"scripts": { "scripts": {
"build": "tsc && copyfiles -u 1 src/**/*.ejs build", "build": "tsc && copyfiles -u 1 src/**/*.ejs build",
"database:migrate": "ts-node scripts/migrate.ts",
"prepare": "husky install", "prepare": "husky install",
"start": "node build/server.js", "start": "node build/server.js",
"start:dev": "nodemon --watch src --exec ts-node --transpile-only src/server.ts", "start:dev": "nodemon --watch src --exec ts-node --transpile-only src/server.ts",
@@ -19,6 +20,7 @@
"dependencies": { "dependencies": {
"@anthropic-ai/tokenizer": "^0.0.4", "@anthropic-ai/tokenizer": "^0.0.4",
"@aws-crypto/sha256-js": "^5.2.0", "@aws-crypto/sha256-js": "^5.2.0",
"@node-rs/argon2": "^1.8.3",
"@smithy/eventstream-codec": "^2.1.3", "@smithy/eventstream-codec": "^2.1.3",
"@smithy/eventstream-serde-node": "^2.1.3", "@smithy/eventstream-serde-node": "^2.1.3",
"@smithy/protocol-http": "^3.2.1", "@smithy/protocol-http": "^3.2.1",
@@ -26,18 +28,21 @@
"@smithy/types": "^2.10.1", "@smithy/types": "^2.10.1",
"@smithy/util-utf8": "^2.1.1", "@smithy/util-utf8": "^2.1.1",
"axios": "^1.3.5", "axios": "^1.3.5",
"better-sqlite3": "^10.0.0",
"check-disk-space": "^3.4.0", "check-disk-space": "^3.4.0",
"cookie-parser": "^1.4.6", "cookie-parser": "^1.4.6",
"copyfiles": "^2.4.1", "copyfiles": "^2.4.1",
"cors": "^2.8.5", "cors": "^2.8.5",
"csrf-csrf": "^2.3.0", "csrf-csrf": "^2.3.0",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"ejs": "^3.1.9", "ejs": "^3.1.10",
"express": "^4.18.2", "express": "^4.18.2",
"express-session": "^1.17.3", "express-session": "^1.17.3",
"firebase-admin": "^11.10.1", "firebase-admin": "^12.1.0",
"glob": "^10.3.12",
"googleapis": "^122.0.0", "googleapis": "^122.0.0",
"http-proxy-middleware": "^3.0.0-beta.1", "http-proxy-middleware": "^3.0.0-beta.1",
"ipaddr.js": "^2.1.0",
"memorystore": "^1.6.7", "memorystore": "^1.6.7",
"multer": "^1.4.5-lts.1", "multer": "^1.4.5-lts.1",
"node-schedule": "^2.1.1", "node-schedule": "^2.1.1",
@@ -55,6 +60,7 @@
"zod-error": "^1.5.0" "zod-error": "^1.5.0"
}, },
"devDependencies": { "devDependencies": {
"@types/better-sqlite3": "^7.6.10",
"@types/cookie-parser": "^1.4.3", "@types/cookie-parser": "^1.4.3",
"@types/cors": "^2.8.13", "@types/cors": "^2.8.13",
"@types/express": "^4.17.17", "@types/express": "^4.17.17",
@@ -72,11 +78,11 @@
"nodemon": "^3.0.1", "nodemon": "^3.0.1",
"pino-pretty": "^10.2.3", "pino-pretty": "^10.2.3",
"prettier": "^3.0.3", "prettier": "^3.0.3",
"prettier-plugin-ejs": "^1.0.3",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"typescript": "^5.4.2" "typescript": "^5.4.2"
}, },
"overrides": { "overrides": {
"google-gax": "^3.6.1",
"postcss": "^8.4.31", "postcss": "^8.4.31",
"follow-redirects": "^1.15.4" "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/event";
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 };
+19 -4
View File
@@ -1,17 +1,31 @@
import express, { Router } from "express"; import express, { Router } from "express";
import { authorize } from "./auth"; import { createWhitelistMiddleware } from "../shared/cidr";
import { HttpError } from "../shared/errors"; import { HttpError } from "../shared/errors";
import { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf";
import { injectLocals } from "../shared/inject-locals"; import { injectLocals } from "../shared/inject-locals";
import { withSession } from "../shared/with-session"; import { withSession } from "../shared/with-session";
import { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf"; import { config } from "../config";
import { renderPage } from "../info-page"; import { renderPage } from "../info-page";
import { buildInfo } from "../service-info"; import { buildInfo } from "../service-info";
import { authorize } from "./auth";
import { loginRouter } from "./login"; 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 { usersWebRouter as webRouter } from "./web/manage";
import { logger } from "../logger";
const adminRouter = Router(); 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( adminRouter.use(
express.json({ limit: "20mb" }), express.json({ limit: "20mb" }),
express.urlencoded({ extended: true, limit: "20mb" }) express.urlencoded({ extended: true, limit: "20mb" })
@@ -19,7 +33,8 @@ adminRouter.use(
adminRouter.use(withSession); adminRouter.use(withSession);
adminRouter.use(injectCsrfToken); 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(checkCsrfToken);
adminRouter.use(injectLocals); adminRouter.use(injectLocals);
+193 -5
View File
@@ -1,4 +1,5 @@
import { Router } from "express"; import { Router } from "express";
import ipaddr from "ipaddr.js";
import multer from "multer"; import multer from "multer";
import { z } from "zod"; import { z } from "zod";
import { config } from "../../config"; import { config } from "../../config";
@@ -15,6 +16,8 @@ import {
UserTokenCounts, UserTokenCounts,
} from "../../shared/users/schema"; } from "../../shared/users/schema";
import { getLastNImages } from "../../shared/file-storage/image-history"; import { getLastNImages } from "../../shared/file-storage/image-history";
import { blacklists, parseCidrs, whitelists } from "../../shared/cidr";
import { invalidatePowHmacKey } from "../../user/web/pow-captcha";
const router = Router(); const router = Router();
@@ -40,6 +43,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) => { router.post("/create-user", (req, res) => {
const body = req.body; const body = req.body;
@@ -223,10 +294,14 @@ router.post("/maintenance", (req, res) => {
break; break;
} }
case "downloadImageMetadata": { case "downloadImageMetadata": {
const data = JSON.stringify({ const data = JSON.stringify(
exportedAt: new Date().toISOString(), {
generations: getLastNImages() exportedAt: new Date().toISOString(),
}, null, 2); generations: getLastNImages(),
},
null,
2
);
res.setHeader( res.setHeader(
"Content-Disposition", "Content-Disposition",
`attachment; filename=image-metadata-${new Date().toISOString()}.json` `attachment; filename=image-metadata-${new Date().toISOString()}.json`
@@ -234,14 +309,127 @@ router.post("/maintenance", (req, res) => {
res.setHeader("Content-Type", "application/json"); res.setHeader("Content-Type", "application/json");
return res.send(data); 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: { default: {
throw new HttpError(400, "Invalid action"); throw new HttpError(400, "Invalid action");
} }
} }
req.session.flash = flash; 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) => { 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> <legend>Temporary User Options</legend>
<div class="temporary-user-fieldset"> <div class="temporary-user-fieldset">
<p class="full-width"> <p class="full-width">
Temporary users will be disabled after the specified duration, and their records will be deleted 72 hours after that. 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 These options apply only to new temporary users; existing ones use whatever options were in effect when they were created.
temporary users; existing ones use whatever options were in effect when they were created.
</p> </p>
<label for="temporaryUserDuration" class="full-width">Access duration (in minutes)</label> <label for="temporaryUserDuration" class="full-width">Access duration (in minutes)</label>
<input type="number" name="temporaryUserDuration" id="temporaryUserDuration" value="60" class="full-width" /> <input type="number" name="temporaryUserDuration" id="temporaryUserDuration" value="60" class="full-width" />
+27 -36
View File
@@ -5,18 +5,6 @@
flex-direction: column; 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 { #statsForm ul {
margin: 0; margin: 0;
padding-left: 2em; padding-left: 2em;
@@ -33,17 +21,17 @@
} }
</style> </style>
<h1>Download Stats</h1> <h1>Download Stats</h1>
<p> <p>Download usage statistics to a Markdown document. You can paste this into a service like Rentry.org to share it.</p>
Download usage statistics to a Markdown document. You can paste this into a service like Rentry.org to share it.
</p>
<div> <div>
<h3>Options</h3> <h3>Options</h3>
<form id="statsForm" action="/admin/manage/generate-stats" method="post" <form
style="display: flex; flex-direction: column;"> id="statsForm"
action="/admin/manage/generate-stats"
method="post"
style="display: flex; flex-direction: column">
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" /> <input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
<div> <div>
<label for="anon">Anonymize</label> <label for="anon"><input id="anon" type="checkbox" name="anon" value="true" /> <span>Anonymize</span></label>
<input id="anon" type="checkbox" name="anon" value="true" />
</div> </div>
<div> <div>
<label for="sort">Sort</label> <label for="sort">Sort</label>
@@ -64,11 +52,12 @@
</select> </select>
</div> </div>
<div> <div>
<label for="format">Custom Format <ul> <label for="format">Custom Format</label>
<li><code>{{header}}</code></li> <ul>
<li><code>{{stats}}</code></li> <li><code>{{header}}</code></li>
<li><code>{{time}}</code></li> <li><code>{{stats}}</code></li>
</ul></label> <li><code>{{time}}</code></li>
</ul>
<textarea id="format" name="format" rows="10" cols="50" placeholder="{{stats}}"> <textarea id="format" name="format" rows="10" cols="50" placeholder="{{stats}}">
# Stats # Stats
{{header}} {{header}}
@@ -115,33 +104,35 @@
loadDefaults(); loadDefaults();
async function fetchAndCopy() { async function fetchAndCopy() {
const form = document.getElementById('statsForm'); const form = document.getElementById("statsForm");
const formData = new FormData(form); const formData = new FormData(form);
const response = await fetch(form.action, { const response = await fetch(form.action, {
method: 'POST', method: "POST",
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, headers: { "Content-Type": "application/x-www-form-urlencoded" },
credentials: 'same-origin', credentials: "same-origin",
body: new URLSearchParams(formData), body: new URLSearchParams(formData),
}); });
if (response.ok) { if (response.ok) {
const content = await response.text(); const content = await response.text();
copyToClipboard(content); copyToClipboard(content);
} else { } 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) { function copyToClipboard(text) {
navigator.clipboard.writeText(text).then(() => { navigator.clipboard
alert('Copied to clipboard'); .writeText(text)
}).catch(err => { .then(() => {
alert('Failed to copy to clipboard. Try downloading the file instead.'); 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> </script>
<%- include("partials/admin-footer") %> <%- 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/import-users">Import Users</a></li>
<li><a href="/admin/manage/export-users">Export 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/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> <li><a href="/admin/service-info">Service Info</a></li>
</ul> </ul>
<h3>Maintenance</h3> <h3>Maintenance</h3>
<form id="maintenanceForm" action="/admin/manage/maintenance" method="post"> <form id="maintenanceForm" action="/admin/manage/maintenance" method="post">
<input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" /> <input id="_csrf" type="hidden" name="_csrf" value="<%= csrfToken %>" />
<input id="hiddenAction" type="hidden" name="action" value="" /> <input id="hiddenAction" type="hidden" name="action" value="" />
<div display="flex" flex-direction="column"> <div>
<fieldset> <fieldset>
<legend>Key Recheck</legend> <legend>Key Recheck</legend>
<button id="recheck-keys" type="button" onclick="submitForm('recheck')">Force Key Recheck</button> <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) { %> <% if (users.length === 0) { %>
<p>No users found.</p> <p>No users found.</p>
<% } else { %> <% } else { %>
<input type="checkbox" id="toggle-nicknames" onchange="toggleNicknames()" /> <label for="toggle-nicknames"><input type="checkbox" id="toggle-nicknames" onchange="toggleNicknames()" /> Show Nicknames</label>
<label for="toggle-nicknames">Show Nicknames</label> <table class="striped full-width">
<table class="striped">
<thead> <thead>
<tr> <tr>
<th>User</th> <th>User</th>
+16 -6
View File
@@ -55,8 +55,9 @@
<td><%- user.disabledReason %></td> <td><%- user.disabledReason %></td>
<% if (user.disabledAt) { %> <% if (user.disabledAt) { %>
<td class="actions"> <td class="actions">
<a title="Edit" id="edit-disabledReason" href="#" data-field="disabledReason" <a title="Edit" id="edit-disabledReason" href="#" data-field="disabledReason" data-token="<%= user.token %>"
data-token="<%= user.token %>">✏️</a> >✏️</a
>
</td> </td>
<% } %> <% } %>
</tr> </tr>
@@ -72,7 +73,8 @@
<td colspan="2"><%- include("partials/shared_user_ip_list", { user, shouldRedact: false }) %></td> <td colspan="2"><%- include("partials/shared_user_ip_list", { user, shouldRedact: false }) %></td>
</tr> </tr>
<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> </th>
<td><%- user.adminNote ?? "none" %></td> <td><%- user.adminNote ?? "none" %></td>
<td class="actions"> <td class="actions">
@@ -85,10 +87,16 @@
<td colspan="2"><%- user.expiresAt %></td> <td colspan="2"><%- user.expiresAt %></td>
</tr> </tr>
<% } %> <% } %>
<% if (user.meta) { %>
<tr>
<th scope="row">Meta</th>
<td colspan="2"><%- JSON.stringify(user.meta) %></td>
</tr>
<% } %>
</tbody> </tbody>
</table> </table>
<form style="display:none" id="current-values"> <form style="display: none" id="current-values">
<input type="hidden" name="token" value="<%- user.token %>" /> <input type="hidden" name="token" value="<%- user.token %>" />
<% ["nickname", "type", "disabledAt", "disabledReason", "maxIps", "adminNote"].forEach(function (key) { %> <% ["nickname", "type", "disabledAt", "disabledReason", "maxIps", "adminNote"].forEach(function (key) { %>
<input type="hidden" name="<%- key %>" value="<%- user[key] %>" /> <input type="hidden" name="<%- key %>" value="<%- user[key] %>" />
@@ -102,7 +110,8 @@
<input type="hidden" name="_csrf" value="<%- csrfToken %>" /> <input type="hidden" name="_csrf" value="<%- csrfToken %>" />
<button type="submit" class="btn btn-primary">Refresh Quotas for User</button> <button type="submit" class="btn btn-primary">Refresh Quotas for User</button>
</form> </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> <p><a href="/admin/manage/list-users">Back to User List</a></p>
@@ -144,4 +153,5 @@
}); });
</script> </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>
+221 -14
View File
@@ -1,8 +1,9 @@
import crypto from "crypto";
import dotenv from "dotenv"; import dotenv from "dotenv";
import type firebase from "firebase-admin"; import type firebase from "firebase-admin";
import path from "path"; import path from "path";
import pino from "pino"; import pino from "pino";
import type { ModelFamily } from "./shared/models"; import type { LLMService, ModelFamily } from "./shared/models";
import { MODEL_FAMILIES } from "./shared/models"; import { MODEL_FAMILIES } from "./shared/models";
dotenv.config(); dotenv.config();
@@ -107,9 +108,70 @@ type Config = {
* `maxIpsPerUser` limit, or if only connections from new IPs are be rejected. * `maxIpsPerUser` limit, or if only connections from new IPs are be rejected.
*/ */
maxIpsAutoBan: boolean; 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; 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; imageModelRateLimit: number;
/** /**
* For OpenAI, the maximum number of context tokens (prompt + max output) a * 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. * key and can't attach the policy, you can set this to true.
*/ */
allowAwsLogging?: boolean; 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. */ /** Whether prompts and responses should be logged to persistent storage. */
promptLogging?: boolean; promptLogging?: boolean;
/** Which prompt logging backend to use. */ /** 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. */ /** Base64-encoded Google Sheets API key. */
googleSheetsKey?: string; googleSheetsKey?: string;
/** Google Sheets spreadsheet ID. */ /** Google Sheets spreadsheet ID. */
@@ -249,11 +339,38 @@ type Config = {
* risk. * risk.
*/ */
allowOpenAIToolUsage?: boolean; allowOpenAIToolUsage?: boolean;
/**
* Which services will accept prompts containing images, for use with
* multimodal models. Users with `special` role are exempt from this
* restriction.
*
* Do not enable this feature for untrusted users, as malicious users could
* send images which violate your provider's terms of service or local laws.
*
* Defaults to no services, meaning image prompts are disabled. Use a comma-
* separated list. Available services are:
* openai,anthropic,google-ai,mistral-ai,aws,azure
*/
allowedVisionServices: LLMService[];
/** /**
* Allows overriding the default proxy endpoint route. Defaults to /proxy. * Allows overriding the default proxy endpoint route. Defaults to /proxy.
* A leading slash is required. * A leading slash is required.
*/ */
proxyEndpointRoute: string; 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. // To change configs, create a file called .env in the root directory.
@@ -270,10 +387,22 @@ export const config: Config = {
proxyKey: getEnvWithDefault("PROXY_KEY", ""), proxyKey: getEnvWithDefault("PROXY_KEY", ""),
adminKey: getEnvWithDefault("ADMIN_KEY", ""), adminKey: getEnvWithDefault("ADMIN_KEY", ""),
serviceInfoPassword: getEnvWithDefault("SERVICE_INFO_PASSWORD", ""), 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"), gatekeeper: getEnvWithDefault("GATEKEEPER", "none"),
gatekeeperStore: getEnvWithDefault("GATEKEEPER_STORE", "memory"), gatekeeperStore: getEnvWithDefault("GATEKEEPER_STORE", "memory"),
maxIpsPerUser: getEnvWithDefault("MAX_IPS_PER_USER", 0), 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), firebaseRtdbUrl: getEnvWithDefault("FIREBASE_RTDB_URL", undefined),
firebaseKey: getEnvWithDefault("FIREBASE_KEY", undefined), firebaseKey: getEnvWithDefault("FIREBASE_KEY", undefined),
textModelRateLimit: getEnvWithDefault("TEXT_MODEL_RATE_LIMIT", 4), textModelRateLimit: getEnvWithDefault("TEXT_MODEL_RATE_LIMIT", 4),
@@ -296,6 +425,7 @@ export const config: Config = {
"gpt4", "gpt4",
"gpt4-32k", "gpt4-32k",
"gpt4-turbo", "gpt4-turbo",
"gpt4o",
"claude", "claude",
"claude-opus", "claude-opus",
"gemini-pro", "gemini-pro",
@@ -304,10 +434,12 @@ export const config: Config = {
"mistral-medium", "mistral-medium",
"mistral-large", "mistral-large",
"aws-claude", "aws-claude",
"aws-claude-opus",
"azure-turbo", "azure-turbo",
"azure-gpt4", "azure-gpt4",
"azure-gpt4-turbo",
"azure-gpt4-32k", "azure-gpt4-32k",
"azure-gpt4-turbo",
"azure-gpt4o",
]), ]),
rejectPhrases: parseCsv(getEnvWithDefault("REJECT_PHRASES", "")), rejectPhrases: parseCsv(getEnvWithDefault("REJECT_PHRASES", "")),
rejectMessage: getEnvWithDefault( rejectMessage: getEnvWithDefault(
@@ -320,6 +452,10 @@ export const config: Config = {
allowAwsLogging: getEnvWithDefault("ALLOW_AWS_LOGGING", false), allowAwsLogging: getEnvWithDefault("ALLOW_AWS_LOGGING", false),
promptLogging: getEnvWithDefault("PROMPT_LOGGING", false), promptLogging: getEnvWithDefault("PROMPT_LOGGING", false),
promptLoggingBackend: getEnvWithDefault("PROMPT_LOGGING_BACKEND", undefined), promptLoggingBackend: getEnvWithDefault("PROMPT_LOGGING_BACKEND", undefined),
promptLoggingFilePrefix: getEnvWithDefault(
"PROMPT_LOGGING_FILE_PREFIX",
"prompt-logs"
),
googleSheetsKey: getEnvWithDefault("GOOGLE_SHEETS_KEY", undefined), googleSheetsKey: getEnvWithDefault("GOOGLE_SHEETS_KEY", undefined),
googleSheetsSpreadsheetId: getEnvWithDefault( googleSheetsSpreadsheetId: getEnvWithDefault(
"GOOGLE_SHEETS_SPREADSHEET_ID", "GOOGLE_SHEETS_SPREADSHEET_ID",
@@ -348,20 +484,50 @@ export const config: Config = {
staticServiceInfo: getEnvWithDefault("STATIC_SERVICE_INFO", false), staticServiceInfo: getEnvWithDefault("STATIC_SERVICE_INFO", false),
trustedProxies: getEnvWithDefault("TRUSTED_PROXIES", 1), trustedProxies: getEnvWithDefault("TRUSTED_PROXIES", 1),
allowOpenAIToolUsage: getEnvWithDefault("ALLOW_OPENAI_TOOL_USAGE", false), allowOpenAIToolUsage: getEnvWithDefault("ALLOW_OPENAI_TOOL_USAGE", false),
allowedVisionServices: parseCsv(
getEnvWithDefault("ALLOWED_VISION_SERVICES", "")
) as LLMService[],
proxyEndpointRoute: getEnvWithDefault("PROXY_ENDPOINT_ROUTE", "/proxy"), proxyEndpointRoute: getEnvWithDefault("PROXY_ENDPOINT_ROUTE", "/proxy"),
adminWhitelist: parseCsv(
getEnvWithDefault("ADMIN_WHITELIST", "0.0.0.0/0,::/0")
),
ipBlacklist: parseCsv(getEnvWithDefault("IP_BLACKLIST", "")),
} as const; } as const;
function generateCookieSecret() { function generateSigningKey() {
if (process.env.COOKIE_SECRET !== undefined) { if (process.env.COOKIE_SECRET !== undefined) {
// legacy, replaced by SIGNING_KEY
return process.env.COOKIE_SECRET; 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 secrets = [
const crypto = require("crypto"); 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"); 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() { export async function assertConfigIsValid() {
if (process.env.MODEL_RATE_LIMIT !== undefined) { if (process.env.MODEL_RATE_LIMIT !== undefined) {
@@ -377,6 +543,23 @@ export async function assertConfigIsValid() {
); );
} }
if (process.env.ALLOW_IMAGE_PROMPTS === "true") {
const hasAllowedServices = config.allowedVisionServices.length > 0;
if (!hasAllowedServices) {
config.allowedVisionServices = ["openai", "anthropic"];
startupLogger.warn(
{ allowedVisionServices: config.allowedVisionServices },
"ALLOW_IMAGE_PROMPTS is deprecated. Use ALLOWED_VISION_SERVICES instead."
);
}
}
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)) { if (!["none", "proxy_key", "user_token"].includes(config.gatekeeper)) {
throw new Error( throw new Error(
`Invalid gatekeeper mode: ${config.gatekeeper}. Must be one of: none, proxy_key, user_token.` `Invalid gatekeeper mode: ${config.gatekeeper}. Must be one of: none, proxy_key, user_token.`
@@ -389,15 +572,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( 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(
"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( throw new Error(
"`PROXY_KEY` is set, but gatekeeper mode is not `proxy_key`. Make sure to set `GATEKEEPER=proxy_key`." "`proxy_key` gatekeeper mode requires a `PROXY_KEY` to be set."
); );
} }
@@ -453,9 +653,13 @@ export const OMITTED_KEYS = [
"rejectPhrases", "rejectPhrases",
"rejectMessage", "rejectMessage",
"showTokenCosts", "showTokenCosts",
"promptLoggingFilePrefix",
"googleSheetsKey", "googleSheetsKey",
"firebaseKey", "firebaseKey",
"firebaseRtdbUrl", "firebaseRtdbUrl",
"sqliteDataPath",
"eventLogging",
"eventLoggingTrim",
"gatekeeperStore", "gatekeeperStore",
"maxIpsPerUser", "maxIpsPerUser",
"blockedOrigins", "blockedOrigins",
@@ -469,6 +673,9 @@ export const OMITTED_KEYS = [
"allowedModelFamilies", "allowedModelFamilies",
"trustedProxies", "trustedProxies",
"proxyEndpointRoute", "proxyEndpointRoute",
"adminWhitelist",
"ipBlacklist",
"powTokenPurgeHours",
] satisfies (keyof Config)[]; ] satisfies (keyof Config)[];
type OmitKeys = (typeof OMITTED_KEYS)[number]; type OmitKeys = (typeof OMITTED_KEYS)[number];
+33 -14
View File
@@ -16,6 +16,7 @@ const MODEL_FAMILY_FRIENDLY_NAME: { [f in ModelFamily]: string } = {
gpt4: "GPT-4", gpt4: "GPT-4",
"gpt4-32k": "GPT-4 32k", "gpt4-32k": "GPT-4 32k",
"gpt4-turbo": "GPT-4 Turbo", "gpt4-turbo": "GPT-4 Turbo",
gpt4o: "GPT-4o",
"dall-e": "DALL-E", "dall-e": "DALL-E",
claude: "Claude (Sonnet)", claude: "Claude (Sonnet)",
"claude-opus": "Claude (Opus)", "claude-opus": "Claude (Opus)",
@@ -25,10 +26,12 @@ const MODEL_FAMILY_FRIENDLY_NAME: { [f in ModelFamily]: string } = {
"mistral-medium": "Mistral Medium", "mistral-medium": "Mistral Medium",
"mistral-large": "Mistral Large", "mistral-large": "Mistral Large",
"aws-claude": "AWS Claude (Sonnet)", "aws-claude": "AWS Claude (Sonnet)",
"aws-claude-opus": "AWS Claude (Opus)",
"azure-turbo": "Azure GPT-3.5 Turbo", "azure-turbo": "Azure GPT-3.5 Turbo",
"azure-gpt4": "Azure GPT-4", "azure-gpt4": "Azure GPT-4",
"azure-gpt4-32k": "Azure GPT-4 32k", "azure-gpt4-32k": "Azure GPT-4 32k",
"azure-gpt4-turbo": "Azure GPT-4 Turbo", "azure-gpt4-turbo": "Azure GPT-4 Turbo",
"azure-gpt4o": "Azure GPT-4o",
"azure-dall-e": "Azure DALL-E", "azure-dall-e": "Azure DALL-E",
}; };
@@ -60,36 +63,42 @@ export function renderPage(info: ServiceInfo) {
const title = getServerTitle(); const title = getServerTitle();
const headerHtml = buildInfoPageHeader(info); const headerHtml = buildInfoPageHeader(info);
return `<!DOCTYPE html> return `<!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="robots" content="noindex" /> <meta name="robots" content="noindex" />
<title>${title}</title> <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> <style>
body { body {
font-family: sans-serif; font-family: sans-serif;
background-color: #f0f0f0;
padding: 1em; padding: 1em;
max-width: 900px;
margin: 0;
} }
@media (prefers-color-scheme: dark) {
body {
background-color: #222;
color: #eee;
}
a:link, a:visited { .self-service-links {
color: #bbe; display: flex;
} justify-content: center;
margin-bottom: 1em;
padding: 0.5em;
font-size: 0.8em;
}
.self-service-links a {
margin: 0 0.5em;
} }
</style> </style>
</head> </head>
<body> <body>
${headerHtml} ${headerHtml}
<hr /> <hr />
${getSelfServiceLinks()}
<h2>Service Info</h2> <h2>Service Info</h2>
<pre>${JSON.stringify(info, null, 2)}</pre> <pre>${JSON.stringify(info, null, 2)}</pre>
${getSelfServiceLinks()}
</body> </body>
</html>`; </html>`;
} }
@@ -143,7 +152,15 @@ This proxy keeps full logs of all prompts and AI responses. Prompt logs are anon
function getSelfServiceLinks() { function getSelfServiceLinks() {
if (config.gatekeeper !== "user_token") return ""; 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() { function getServerTitle() {
@@ -190,7 +207,7 @@ function buildRecentImageSection() {
</div>`; </div>`;
} }
html += `</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; return html;
} }
@@ -201,7 +218,9 @@ function escapeHtml(unsafe: string) {
.replace(/</g, "&lt;") .replace(/</g, "&lt;")
.replace(/>/g, "&gt;") .replace(/>/g, "&gt;")
.replace(/"/g, "&quot;") .replace(/"/g, "&quot;")
.replace(/'/g, "&#39;"); .replace(/'/g, "&#39;")
.replace(/\[/g, "&#91;")
.replace(/]/g, "&#93;");
} }
function getExternalUrlForHuggingfaceSpaceId(spaceId: string) { function getExternalUrlForHuggingfaceSpaceId(spaceId: string) {
+1 -1
View File
@@ -156,7 +156,7 @@ function transformAnthropicTextResponseToOpenAI(
}; };
} }
function transformAnthropicChatResponseToOpenAI( export function transformAnthropicChatResponseToOpenAI(
anthropicBody: Record<string, any> anthropicBody: Record<string, any>
): Record<string, any> { ): Record<string, any> {
return { return {
+40 -12
View File
@@ -16,7 +16,7 @@ import {
ProxyResHandlerWithBody, ProxyResHandlerWithBody,
createOnProxyResHandler, createOnProxyResHandler,
} from "./middleware/response"; } from "./middleware/response";
import { transformAnthropicChatResponseToAnthropicText } from "./anthropic"; import { transformAnthropicChatResponseToAnthropicText, transformAnthropicChatResponseToOpenAI } from "./anthropic";
import { sendErrorToClient } from "./middleware/response/error-generator"; import { sendErrorToClient } from "./middleware/response/error-generator";
const LATEST_AWS_V2_MINOR_VERSION = "1"; const LATEST_AWS_V2_MINOR_VERSION = "1";
@@ -37,6 +37,7 @@ const getModelsResponse = () => {
"anthropic.claude-v2:1", "anthropic.claude-v2:1",
"anthropic.claude-3-haiku-20240307-v1:0", "anthropic.claude-3-haiku-20240307-v1:0",
"anthropic.claude-3-sonnet-20240229-v1:0", "anthropic.claude-3-sonnet-20240229-v1:0",
"anthropic.claude-3-opus-20240229-v1:0",
]; ];
const models = variants.map((id) => ({ const models = variants.map((id) => ({
@@ -76,8 +77,10 @@ const awsResponseHandler: ProxyResHandlerWithBody = async (
req.log.info("Transforming Anthropic Text back to OpenAI format"); req.log.info("Transforming Anthropic Text back to OpenAI format");
newBody = transformAwsTextResponseToOpenAI(body, req); newBody = transformAwsTextResponseToOpenAI(body, req);
break; break;
// case "openai<-anthropic-chat": case "openai<-anthropic-chat":
// todo: implement this req.log.info("Transforming AWS Anthropic Chat back to OpenAI format");
newBody = transformAnthropicChatResponseToOpenAI(body);
break;
case "anthropic-text<-anthropic-chat": case "anthropic-text<-anthropic-chat":
req.log.info("Transforming AWS Anthropic Chat back to Text format"); req.log.info("Transforming AWS Anthropic Chat back to Text format");
newBody = transformAnthropicChatResponseToAnthropicText(body); newBody = transformAnthropicChatResponseToAnthropicText(body);
@@ -159,7 +162,7 @@ const textToChatPreprocessor = createPreprocessorMiddleware(
* Routes text completion prompts to aws anthropic-chat if they need translation * Routes text completion prompts to aws anthropic-chat if they need translation
* (claude-3 based models do not support the old text completion endpoint). * (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")) { if (req.body.model?.includes("claude-3")) {
textToChatPreprocessor(req, res, next); textToChatPreprocessor(req, res, next);
} else { } 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(); const awsRouter = Router();
awsRouter.get("/v1/models", handleModelRequest); awsRouter.get("/v1/models", handleModelRequest);
// Native(ish) Anthropic text completion endpoint. // 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. // Native Anthropic chat completion endpoint.
awsRouter.post( awsRouter.post(
"/v1/messages", "/v1/messages",
@@ -198,10 +223,7 @@ awsRouter.post(
awsRouter.post( awsRouter.post(
"/v1/chat/completions", "/v1/chat/completions",
ipLimiter, ipLimiter,
createPreprocessorMiddleware( preprocessOpenAICompatRequest,
{ inApi: "openai", outApi: "anthropic-text", service: "aws" },
{ afterTransform: [maybeReassignModel] }
),
awsProxy awsProxy
); );
@@ -222,7 +244,7 @@ function maybeReassignModel(req: Request) {
} }
const pattern = 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); const match = model.match(pattern);
// If there's no match, return the latest v2 model // 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. // 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]; const variantVersion = match[9];
if (major === "3") { if (major === "3") {
req.body.model = "anthropic.claude-3-sonnet-20240229-v1:0"; 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; return;
} }
+44 -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 { config } from "../config";
import { authenticate, getUser } from "../shared/users/user-store"; import { authenticate, getUser } from "../shared/users/user-store";
import { sendErrorToClient } from "./middleware/response/error-generator";
const GATEKEEPER = config.gatekeeper; const GATEKEEPER = config.gatekeeper;
const PROXY_KEY = config.proxyKey; 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. // IP alone to distinguish between them and prevent usertoken sharing.
// Risu sends a signed token in the request headers with an anonymous user // 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. // ID that we can instead use to associate requests with an individual.
const ip = req.risuToken?.length ? const ip = req.risuToken?.length
`risu${req.risuToken}-${req.ip}` : ? `risu${req.risuToken}-${req.ip}`
req.ip; : req.ip;
const { user, result } = authenticate(token, ip); const { user, result } = authenticate(token, ip);
@@ -61,17 +62,50 @@ export const gatekeeper: RequestHandler = (req, res, next) => {
req.user = user; req.user = user;
return next(); return next();
case "limited": case "limited":
return res.status(403).json({ return sendError(
error: `Forbidden: no more IPs can authenticate with this token`, req,
}); res,
403,
`Forbidden: no more IP addresses allowed for this user token`,
{ currentIp: ip, maxIps: user?.maxIps }
);
case "disabled": case "disabled":
const bannedUser = getUser(token); const bannedUser = getUser(token);
if (bannedUser?.disabledAt) { if (bannedUser?.disabledAt) {
const reason = bannedUser.disabledReason || "Token disabled"; const reason = bannedUser.disabledReason || "User token disabled";
return res.status(403).json({ error: `Forbidden: ${reason}` }); 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,
data: any = {}
) {
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,
obj: data,
},
});
}
+3 -3
View File
@@ -3,10 +3,10 @@ import http from "http";
import httpProxy from "http-proxy"; import httpProxy from "http-proxy";
import { ZodError } from "zod"; import { ZodError } from "zod";
import { generateErrorMessage } from "zod-error"; import { generateErrorMessage } from "zod-error";
import { HttpError } from "../../shared/errors";
import { assertNever } from "../../shared/utils"; import { assertNever } from "../../shared/utils";
import { QuotaExceededError } from "./request/preprocessors/apply-quota-limits"; import { QuotaExceededError } from "./request/preprocessors/apply-quota-limits";
import { sendErrorToClient } from "./response/error-generator"; import { sendErrorToClient } from "./response/error-generator";
import { HttpError } from "../../shared/errors";
const OPENAI_CHAT_COMPLETION_ENDPOINT = "/v1/chat/completions"; const OPENAI_CHAT_COMPLETION_ENDPOINT = "/v1/chat/completions";
const OPENAI_TEXT_COMPLETION_ENDPOINT = "/v1/completions"; const OPENAI_TEXT_COMPLETION_ENDPOINT = "/v1/completions";
@@ -54,13 +54,13 @@ export function sendProxyError(
const msg = const msg =
statusCode === 500 statusCode === 500
? `The proxy encountered an error while trying to process your prompt.` ? `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({ sendErrorToClient({
options: { options: {
format: req.inboundApi, format: req.inboundApi,
title: `Proxy error (HTTP ${statusCode} ${statusMessage})`, title: `Proxy error (HTTP ${statusCode} ${statusMessage})`,
message: `${msg} Further technical details are provided below.`, message: `${msg} Further details are provided below.`,
obj: errorPayload, obj: errorPayload,
reqId: req.id, reqId: req.id,
model: req.body?.model, model: req.body?.model,
+3 -2
View File
@@ -11,16 +11,17 @@ export {
// Express middleware (runs before http-proxy-middleware, can be async) // Express middleware (runs before http-proxy-middleware, can be async)
export { addAzureKey } from "./preprocessors/add-azure-key"; export { addAzureKey } from "./preprocessors/add-azure-key";
export { applyQuotaLimits } from "./preprocessors/apply-quota-limits"; export { applyQuotaLimits } from "./preprocessors/apply-quota-limits";
export { validateContextSize } from "./preprocessors/validate-context-size";
export { countPromptTokens } from "./preprocessors/count-prompt-tokens"; export { countPromptTokens } from "./preprocessors/count-prompt-tokens";
export { languageFilter } from "./preprocessors/language-filter"; export { languageFilter } from "./preprocessors/language-filter";
export { setApiFormat } from "./preprocessors/set-api-format"; export { setApiFormat } from "./preprocessors/set-api-format";
export { signAwsRequest } from "./preprocessors/sign-aws-request"; export { signAwsRequest } from "./preprocessors/sign-aws-request";
export { transformOutboundPayload } from "./preprocessors/transform-outbound-payload"; 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) // 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 { addAnthropicPreamble } from "./onproxyreq/add-anthropic-preamble";
export { addKey, addKeyForEmbeddingsRequest } from "./onproxyreq/add-key";
export { blockZoomerOrigins } from "./onproxyreq/block-zoomer-origins"; export { blockZoomerOrigins } from "./onproxyreq/block-zoomer-origins";
export { checkModelFamily } from "./onproxyreq/check-model-family"; export { checkModelFamily } from "./onproxyreq/check-model-family";
export { finalizeBody } from "./onproxyreq/finalize-body"; 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 { Key, OpenAIKey, keyPool } from "../../../../shared/key-management";
import { isEmbeddingsRequest } from "../../common"; import { isEmbeddingsRequest } from "../../common";
import { HPMRequestCallback } from "../index"; 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."); 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) { if (inboundApi === outboundApi) {
assignedKey = keyPool.get(body.model, service); assignedKey = keyPool.get(body.model, service, needsMultimodal);
} else { } else {
switch (outboundApi) { switch (outboundApi) {
// If we are translating between API formats we may need to select a model // 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. // for the user, because the provided model is for the inbound API.
// TODO: This whole else condition is probably no longer needed since API // TODO: This whole else condition is probably no longer needed since API
// translation now reassigns the model earlier in the request pipeline. // translation now reassigns the model earlier in the request pipeline.
case "anthropic-chat":
case "anthropic-text": case "anthropic-text":
assignedKey = keyPool.get("claude-v1", service); case "anthropic-chat":
assignedKey = keyPool.get("claude-v1", service, needsMultimodal);
break; break;
case "openai-text": case "openai-text":
assignedKey = keyPool.get("gpt-3.5-turbo-instruct", service); assignedKey = keyPool.get("gpt-3.5-turbo-instruct", service);
@@ -7,10 +7,15 @@ import { HPMRequestCallback } from "../index";
export const stripHeaders: HPMRequestCallback = (proxyReq) => { export const stripHeaders: HPMRequestCallback = (proxyReq) => {
proxyReq.setHeader("origin", ""); proxyReq.setHeader("origin", "");
proxyReq.setHeader("referer", ""); 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("cf-connecting-ip");
proxyReq.removeHeader("forwarded"); proxyReq.removeHeader("forwarded");
proxyReq.removeHeader("true-client-ip"); proxyReq.removeHeader("true-client-ip");
proxyReq.removeHeader("x-forwarded-for"); proxyReq.removeHeader("x-forwarded-for");
proxyReq.removeHeader("x-forwarded-host");
proxyReq.removeHeader("x-forwarded-proto");
proxyReq.removeHeader("x-real-ip"); proxyReq.removeHeader("x-real-ip");
}; };
@@ -4,11 +4,12 @@ import { initializeSseStream } from "../../../shared/streaming";
import { classifyErrorAndSend } from "../common"; import { classifyErrorAndSend } from "../common";
import { import {
RequestPreprocessor, RequestPreprocessor,
validateContextSize,
countPromptTokens, countPromptTokens,
languageFilter,
setApiFormat, setApiFormat,
transformOutboundPayload, transformOutboundPayload,
languageFilter, validateContextSize,
validateVision,
} from "."; } from ".";
type RequestPreprocessorOptions = { type RequestPreprocessorOptions = {
@@ -50,6 +51,7 @@ export const createPreprocessorMiddleware = (
languageFilter, languageFilter,
...(afterTransform ?? []), ...(afterTransform ?? []),
validateContextSize, validateContextSize,
validateVision,
]; ];
return async (...args) => executePreprocessors(preprocessors, args); return async (...args) => executePreprocessors(preprocessors, args);
}; };
@@ -31,7 +31,10 @@ export const countPromptTokens: RequestPreprocessor = async (req) => {
} }
case "anthropic-chat": { case "anthropic-chat": {
req.outputTokens = req.body.max_tokens; 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 }); result = await countTokens({ req, prompt, service });
break; break;
} }
@@ -38,6 +38,7 @@ export const signAwsRequest: RequestPreprocessor = async (req) => {
if (req.outboundApi === "anthropic-chat") { if (req.outboundApi === "anthropic-chat") {
strippedParams = AnthropicV1MessagesSchema.pick({ strippedParams = AnthropicV1MessagesSchema.pick({
messages: true, messages: true,
system: true,
max_tokens: true, max_tokens: true,
stop_sequences: true, stop_sequences: true,
temperature: true, temperature: true,
@@ -46,9 +46,18 @@ export const validateContextSize: RequestPreprocessor = async (req) => {
} }
proxyMax ||= Number.MAX_SAFE_INTEGER; 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; let modelMax: number;
if (model.match(/gpt-3.5-turbo-16k/)) { if (model.match(/gpt-3.5-turbo-16k/)) {
modelMax = 16384; 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)?$/)) { } else if (model.match(/gpt-4-turbo(-preview)?$/)) {
modelMax = 131072; modelMax = 131072;
} else if (model.match(/gpt-4-(0125|1106)(-preview)?$/)) { } 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)?$/)) { } else if (model.match(/^gpt-4(-\d{4})?-vision(-preview)?$/)) {
modelMax = 131072; modelMax = 131072;
} else if (model.match(/gpt-3.5-turbo/)) { } else if (model.match(/gpt-3.5-turbo/)) {
modelMax = 4096; modelMax = 16384;
} else if (model.match(/gpt-4-32k/)) { } else if (model.match(/gpt-4-32k/)) {
modelMax = 32768; modelMax = 32768;
} else if (model.match(/gpt-4/)) { } else if (model.match(/gpt-4/)) {
@@ -75,7 +84,7 @@ export const validateContextSize: RequestPreprocessor = async (req) => {
modelMax = GOOGLE_AI_MAX_CONTEXT; modelMax = GOOGLE_AI_MAX_CONTEXT;
} else if (model.match(/^mistral-(tiny|small|medium)$/)) { } else if (model.match(/^mistral-(tiny|small|medium)$/)) {
modelMax = MISTRAL_AI_MAX_CONTENT; modelMax = MISTRAL_AI_MAX_CONTENT;
} else if (model.match(/^anthropic\.claude-3-sonnet/)) { } else if (model.match(/^anthropic\.claude-3/)) {
modelMax = 200000; modelMax = 200000;
} else if (model.match(/^anthropic\.claude-v2:\d/)) { } else if (model.match(/^anthropic\.claude-v2:\d/)) {
modelMax = 200000; modelMax = 200000;
@@ -0,0 +1,43 @@
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 (req.service === undefined) {
throw new Error("Request service must be set before validateVision");
}
if (req.user?.type === "special") return;
if (config.allowedVisionServices.includes(req.service)) return;
// vision not allowed for req's service, block prompts with images
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,34 @@ function getMessageContent({
} }
``` ```
*/ */
const note = obj?.proxy_note || obj?.error?.message || ""; const note = obj?.proxy_note || obj?.error?.message || "";
const friendlyMessage = note ? `${message}\n\n***\n\n*${note}*` : message; const header = `### **${title}**`;
const details = JSON.parse(JSON.stringify(obj ?? {})); const friendlyMessage = note ? `${message}\n\n----\n\n*${note}*` : message;
let stack = "";
if (details.stack) { const serializedObj = obj
stack = `\n\nInclude this trace when reporting an issue.\n\`\`\`\n${details.stack}\n\`\`\``; ? ["```", JSON.stringify(obj, null, 2), "```"].join("\n")
delete details.stack; : "";
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,
"<!-- oai-proxy-error -->",
].join("\n\n");
} }
type ErrorGeneratorOptions = { type ErrorGeneratorOptions = {
@@ -105,6 +122,11 @@ export function sendErrorToClient({
const isStreaming = const isStreaming =
req.isStreaming || req.body.stream === true || req.body.stream === "true"; req.isStreaming || req.body.stream === true || req.body.stream === "true";
if (!res.headersSent) {
res.setHeader("x-oai-proxy-error", options.title);
res.setHeader("x-oai-proxy-error-status", options.statusCode || 500);
}
if (isStreaming) { if (isStreaming) {
if (!res.headersSent) { if (!res.headersSent) {
initializeSseStream(res); initializeSseStream(res);
@@ -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 StreamArray from "stream-json/streamers/StreamArray";
import { StringDecoder } from "string_decoder"; import { StringDecoder } from "string_decoder";
import { promisify } from "util"; import { promisify } from "util";
import type { logger } from "../../../logger";
import { BadRequestError, RetryableError } from "../../../shared/errors";
import { APIFormat, keyPool } from "../../../shared/key-management"; import { APIFormat, keyPool } from "../../../shared/key-management";
import { import {
copySseResponseHeaders, copySseResponseHeaders,
initializeSseStream, initializeSseStream,
} from "../../../shared/streaming"; } from "../../../shared/streaming";
import type { logger } from "../../../logger"; import { reenqueueRequest } from "../../queue";
import { enqueue } from "../../queue"; import type { RawResponseBodyHandler } from ".";
import { decodeResponseBody, RawResponseBodyHandler, RetryableError } from "."; import { handleBlockingResponse } from "./handle-blocking-response";
import { buildSpoofedSSE, sendErrorToClient } from "./error-generator";
import { getAwsEventStreamDecoder } from "./streaming/aws-event-stream-decoder"; import { getAwsEventStreamDecoder } from "./streaming/aws-event-stream-decoder";
import { EventAggregator } from "./streaming/event-aggregator"; import { EventAggregator } from "./streaming/event-aggregator";
import { SSEMessageTransformer } from "./streaming/sse-message-transformer"; import { SSEMessageTransformer } from "./streaming/sse-message-transformer";
import { SSEStreamAdapter } from "./streaming/sse-stream-adapter"; import { SSEStreamAdapter } from "./streaming/sse-stream-adapter";
import { buildSpoofedSSE, sendErrorToClient } from "./error-generator";
import { BadRequestError } from "../../../shared/errors";
const pipelineAsync = promisify(pipeline); const pipelineAsync = promisify(pipeline);
@@ -50,7 +51,7 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
{ statusCode: proxyRes.statusCode, key: hash }, { statusCode: proxyRes.statusCode, key: hash },
`Streaming request returned error status code. Falling back to non-streaming response handler.` `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.`); req.log.debug({ headers: proxyRes.headers }, `Starting to proxy SSE stream.`);
@@ -105,12 +106,7 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
} catch (err) { } catch (err) {
if (err instanceof RetryableError) { if (err instanceof RetryableError) {
keyPool.markRateLimited(req.key!); keyPool.markRateLimited(req.key!);
req.log.warn( await reenqueueRequest(req);
{ key: req.key!.hash, retryCount: req.retryCount },
`Re-enqueueing request due to retryable error during streaming response.`
);
req.retryCount++;
await enqueue(req);
} else if (err instanceof BadRequestError) { } else if (err instanceof BadRequestError) {
sendErrorToClient({ sendErrorToClient({
req, req,
@@ -138,7 +134,17 @@ export const handleStreamedResponse: RawResponseBodyHandler = async (
res.write(`data: [DONE]\n\n`); res.write(`data: [DONE]\n\n`);
res.end(); res.end();
} }
throw err;
// 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;
}
} }
}; };
+73 -144
View File
@@ -1,10 +1,8 @@
/* This file is fucking horrendous, sorry */ /* This file is fucking horrendous, sorry */
import { Request, Response } from "express"; import { Request, Response } from "express";
import * as http from "http"; import * as http from "http";
import util from "util"; import { config } from "../../../config";
import zlib from "zlib"; import { HttpError, RetryableError } from "../../../shared/errors";
import { enqueue, trackWaitTime } from "../../queue";
import { HttpError } from "../../../shared/errors";
import { keyPool } from "../../../shared/key-management"; import { keyPool } from "../../../shared/key-management";
import { getOpenAIModelFamily } from "../../../shared/models"; import { getOpenAIModelFamily } from "../../../shared/models";
import { countTokens } from "../../../shared/tokenization"; import { countTokens } from "../../../shared/tokenization";
@@ -13,6 +11,7 @@ import {
incrementTokenCount, incrementTokenCount,
} from "../../../shared/users/user-store"; } from "../../../shared/users/user-store";
import { assertNever } from "../../../shared/utils"; import { assertNever } from "../../../shared/utils";
import { reenqueueRequest, trackWaitTime } from "../../queue";
import { refundLastAttempt } from "../../rate-limit"; import { refundLastAttempt } from "../../rate-limit";
import { import {
getCompletionFromBody, getCompletionFromBody,
@@ -20,39 +19,23 @@ import {
isTextGenerationRequest, isTextGenerationRequest,
sendProxyError, sendProxyError,
} from "../common"; } from "../common";
import { handleBlockingResponse } from "./handle-blocking-response";
import { handleStreamedResponse } from "./handle-streamed-response"; import { handleStreamedResponse } from "./handle-streamed-response";
import { logPrompt } from "./log-prompt"; import { logPrompt } from "./log-prompt";
import { logEvent } from "./log-event";
import { saveImage } from "./save-image"; 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 * Either decodes or streams the entire response body and then resolves with it.
* last argument to the rest of the middleware stack. * @returns The response body as a string or parsed JSON object depending on the
* response's content-type.
*/ */
export type RawResponseBodyHandler = ( export type RawResponseBodyHandler = (
proxyRes: http.IncomingMessage, proxyRes: http.IncomingMessage,
req: Request, req: Request,
res: Response res: Response
) => Promise<string | Record<string, any>>; ) => Promise<string | Record<string, any>>;
export type ProxyResHandlerWithBody = ( export type ProxyResHandlerWithBody = (
proxyRes: http.IncomingMessage, proxyRes: http.IncomingMessage,
req: Request, req: Request,
@@ -76,6 +59,10 @@ export type ProxyResMiddleware = ProxyResHandlerWithBody[];
* middleware from executing as it consumes the stream and forwards events to * 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 * the client. Once the stream is closed, the finalized body will be attached
* to res.body and the remaining middleware will execute. * 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) => { export const createOnProxyResHandler = (apiMiddleware: ProxyResMiddleware) => {
return async ( return async (
@@ -83,36 +70,35 @@ export const createOnProxyResHandler = (apiMiddleware: ProxyResMiddleware) => {
req: Request, req: Request,
res: Response res: Response
) => { ) => {
const initialHandler = req.isStreaming const initialHandler: RawResponseBodyHandler = req.isStreaming
? handleStreamedResponse ? handleStreamedResponse
: decodeResponseBody; : handleBlockingResponse;
let lastMiddleware = initialHandler.name; let lastMiddleware = initialHandler.name;
try { try {
const body = await initialHandler(proxyRes, req, res); const body = await initialHandler(proxyRes, req, res);
const middlewareStack: ProxyResMiddleware = []; const middlewareStack: ProxyResMiddleware = [];
if (req.isStreaming) { if (req.isStreaming) {
// `handleStreamedResponse` writes to the response and ends it, so // Handlers for streaming requests must never write to the response.
// we can only execute middleware that doesn't write to the response.
middlewareStack.push( middlewareStack.push(
trackRateLimit, trackKeyRateLimit,
countResponseTokens, countResponseTokens,
incrementUsage, incrementUsage,
logPrompt logPrompt,
logEvent
); );
} else { } else {
middlewareStack.push( middlewareStack.push(
trackRateLimit, trackKeyRateLimit,
addProxyInfo, injectProxyInfo,
handleUpstreamErrors, handleUpstreamErrors,
countResponseTokens, countResponseTokens,
incrementUsage, incrementUsage,
copyHttpHeaders, copyHttpHeaders,
saveImage, saveImage,
logPrompt, logPrompt,
logEvent,
...apiMiddleware ...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 = { type ProxiedErrorPayload = {
error?: Record<string, any>; error?: Record<string, any>;
message?: string; message?: string;
@@ -242,15 +162,9 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
) => { ) => {
const statusCode = proxyRes.statusCode || 500; const statusCode = proxyRes.statusCode || 500;
const statusMessage = proxyRes.statusMessage || "Internal Server Error"; const statusMessage = proxyRes.statusMessage || "Internal Server Error";
if (statusCode < 400) {
return;
}
let errorPayload: ProxiedErrorPayload; 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.` if (statusCode < 400) return;
: "There are no more keys available for this model.";
try { try {
assertJsonResponse(body); assertJsonResponse(body);
@@ -281,6 +195,9 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
`Received error response from upstream. (${proxyRes.statusMessage})` `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; const service = req.key!.service;
if (service === "aws") { if (service === "aws") {
// Try to standardize the error format for AWS // Try to standardize the error format for AWS
@@ -289,8 +206,6 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
} }
if (statusCode === 400) { 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) { switch (service) {
case "openai": case "openai":
case "google-ai": case "google-ai":
@@ -303,7 +218,7 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
} else if (errorPayload.error?.code === "billing_hard_limit_reached") { } else if (errorPayload.error?.code === "billing_hard_limit_reached") {
// For some reason, some models return this 400 error instead of the // For some reason, some models return this 400 error instead of the
// same 429 billing error that other models return. // same 429 billing error that other models return.
await handleOpenAIRateLimitError(req, tryAgainMessage, errorPayload); await handleOpenAIRateLimitError(req, errorPayload);
} else { } else {
errorPayload.proxy_note = `The upstream API rejected the request. Your prompt may be too long for ${req.body?.model}.`; errorPayload.proxy_note = `The upstream API rejected the request. Your prompt may be too long for ${req.body?.model}.`;
} }
@@ -318,38 +233,53 @@ const handleUpstreamErrors: ProxyResHandlerWithBody = async (
} else if (statusCode === 401) { } else if (statusCode === 401) {
// Key is invalid or was revoked // Key is invalid or was revoked
keyPool.disable(req.key!, "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) { } else if (statusCode === 403) {
if (service === "anthropic") { switch (service) {
keyPool.disable(req.key!, "revoked"); case "anthropic":
errorPayload.proxy_note = `API key is invalid or revoked. ${tryAgainMessage}`; if (
return; errorType === "permission_error" &&
} errorPayload.error?.message?.toLowerCase().includes("multimodal")
switch (errorType) { ) {
case "UnrecognizedClientException": req.log.warn(
// Key is invalid. { key: req.key?.hash },
keyPool.disable(req.key!, "revoked"); "This Anthropic key does not support multimodal prompts."
errorPayload.proxy_note = `API key is invalid or revoked. ${tryAgainMessage}`;
break;
case "AccessDeniedException":
const isModelAccessError =
errorPayload.error?.message?.includes(`specified model ID`);
if (!isModelAccessError) {
req.log.error(
{ key: req.key?.hash, model: req.body?.model },
"Disabling key due to AccessDeniedException when invoking model. If credentials are valid, check IAM permissions."
); );
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"); keyPool.disable(req.key!, "revoked");
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 = `Assigned API key is invalid or revoked, please try again.`;
break;
case "AccessDeniedException":
const isModelAccessError =
errorPayload.error?.message?.includes(`specified model ID`);
if (!isModelAccessError) {
req.log.error(
{ key: req.key?.hash, model: req.body?.model },
"Disabling key due to AccessDeniedException when invoking model. If credentials are valid, check IAM permissions."
);
keyPool.disable(req.key!, "revoked");
}
errorPayload.proxy_note = `API key doesn't have access to the requested resource. Model ID: ${req.body?.model}`;
break;
default:
errorPayload.proxy_note = `Received 403 error. Key may be invalid.`;
} }
errorPayload.proxy_note = `API key doesn't have access to the requested resource. Model ID: ${req.body?.model}`;
break;
default:
errorPayload.proxy_note = `Received 403 error. Key may be invalid.`;
} }
} else if (statusCode === 429) { } else if (statusCode === 429) {
switch (service) { switch (service) {
case "openai": case "openai":
await handleOpenAIRateLimitError(req, tryAgainMessage, errorPayload); await handleOpenAIRateLimitError(req, errorPayload);
break; break;
case "anthropic": case "anthropic":
await handleAnthropicRateLimitError(req, errorPayload); await handleAnthropicRateLimitError(req, errorPayload);
@@ -459,7 +389,7 @@ async function handleAnthropicBadRequestError(
"Anthropic key has been disabled." "Anthropic key has been disabled."
); );
keyPool.disable(req.key!, "revoked"); 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; return;
} }
@@ -499,7 +429,6 @@ async function handleAwsRateLimitError(
async function handleOpenAIRateLimitError( async function handleOpenAIRateLimitError(
req: Request, req: Request,
tryAgainMessage: string,
errorPayload: ProxiedErrorPayload errorPayload: ProxiedErrorPayload
): Promise<Record<string, any>> { ): Promise<Record<string, any>> {
const type = errorPayload.error?.type; 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 case "invalid_request_error": // this is the billing_hard_limit_reached error seen in some cases
// Billing quota exceeded (key is dead, disable it) // Billing quota exceeded (key is dead, disable it)
keyPool.disable(req.key!, "quota"); 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; break;
case "access_terminated": case "access_terminated":
// Account banned (key is dead, disable it) // Account banned (key is dead, disable it)
keyPool.disable(req.key!, "revoked"); 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; break;
case "billing_not_active": case "billing_not_active":
// Key valid but account billing is delinquent // Key valid but account billing is delinquent
keyPool.disable(req.key!, "quota"); 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; break;
case "requests": case "requests":
case "tokens": 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); keyPool.updateRateLimits(req.key!, proxyRes.headers);
}; };
@@ -714,7 +643,7 @@ const copyHttpHeaders: ProxyResHandlerWithBody = async (
* or transformed. * or transformed.
* Only used for non-streaming requests. * Only used for non-streaming requests.
*/ */
const addProxyInfo: ProxyResHandlerWithBody = async ( const injectProxyInfo: ProxyResHandlerWithBody = async (
_proxyRes, _proxyRes,
req, req,
res, 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 { assertNever } from "../../../shared/utils";
import { import {
AnthropicChatMessage, AnthropicChatMessage,
flattenAnthropicMessages, flattenAnthropicMessages, GoogleAIChatMessage,
MistralAIChatMessage, MistralAIChatMessage,
OpenAIChatMessage, OpenAIChatMessage,
} from "../../../shared/api-schemas"; } from "../../../shared/api-schemas";
import { APIFormat } from "../../../shared/key-management";
/** If prompt logging is enabled, enqueues the prompt for logging. */ /** If prompt logging is enabled, enqueues the prompt for logging. */
export const logPrompt: ProxyResHandlerWithBody = async ( export const logPrompt: ProxyResHandlerWithBody = async (
@@ -36,7 +35,7 @@ export const logPrompt: ProxyResHandlerWithBody = async (
if (!loggable) return; if (!loggable) return;
const promptPayload = getPromptForRequest(req, responseBody); const promptPayload = getPromptForRequest(req, responseBody);
const promptFlattened = flattenMessages(promptPayload, req.outboundApi); const promptFlattened = flattenMessages(promptPayload);
const response = getCompletionFromBody(req, responseBody); const response = getCompletionFromBody(req, responseBody);
const model = getModelFromBody(req, responseBody); const model = getModelFromBody(req, responseBody);
@@ -63,7 +62,8 @@ const getPromptForRequest = (
): ):
| string | string
| OpenAIChatMessage[] | OpenAIChatMessage[]
| AnthropicChatMessage[] | { contents: GoogleAIChatMessage[] }
| { system: string; messages: AnthropicChatMessage[] }
| MistralAIChatMessage[] | MistralAIChatMessage[]
| OaiImageResult => { | OaiImageResult => {
// Since the prompt logger only runs after the request has been proxied, we // Since the prompt logger only runs after the request has been proxied, we
@@ -72,8 +72,9 @@ const getPromptForRequest = (
switch (req.outboundApi) { switch (req.outboundApi) {
case "openai": case "openai":
case "mistral-ai": case "mistral-ai":
case "anthropic-chat":
return req.body.messages; return req.body.messages;
case "anthropic-chat":
return { system: req.body.system, messages: req.body.messages };
case "openai-text": case "openai-text":
return req.body.prompt; return req.body.prompt;
case "openai-image": case "openai-image":
@@ -87,7 +88,7 @@ const getPromptForRequest = (
case "anthropic-text": case "anthropic-text":
return req.body.prompt; return req.body.prompt;
case "google-ai": case "google-ai":
return req.body.prompt.text; return { contents: req.body.contents };
default: default:
assertNever(req.outboundApi); assertNever(req.outboundApi);
} }
@@ -98,15 +99,26 @@ const flattenMessages = (
| string | string
| OaiImageResult | OaiImageResult
| OpenAIChatMessage[] | OpenAIChatMessage[]
| AnthropicChatMessage[] | { contents: GoogleAIChatMessage[] }
| MistralAIChatMessage[], | { system: string; messages: AnthropicChatMessage[] }
format: APIFormat | MistralAIChatMessage[]
): string => { ): string => {
if (typeof val === "string") { if (typeof val === "string") {
return val.trim(); return val.trim();
} }
if (format === "anthropic-chat") { if (isAnthropicChatPrompt(val)) {
return flattenAnthropicMessages(val as AnthropicChatMessage[]); 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)) { if (Array.isArray(val)) {
return val return val
@@ -127,3 +139,24 @@ const flattenMessages = (
} }
return val.prompt.trim(); 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); assertNever(this.format);
} }
} }
hasEvents() {
return this.events.length > 0;
}
} }
function eventIsOpenAIEvent( function eventIsOpenAIEvent(
@@ -2,9 +2,8 @@ import pino from "pino";
import { Transform, TransformOptions } from "stream"; import { Transform, TransformOptions } from "stream";
import { Message } from "@smithy/eventstream-codec"; import { Message } from "@smithy/eventstream-codec";
import { APIFormat } from "../../../../shared/key-management"; import { APIFormat } from "../../../../shared/key-management";
import { RetryableError } from "../index";
import { buildSpoofedSSE } from "../error-generator"; import { buildSpoofedSSE } from "../error-generator";
import { BadRequestError } from "../../../../shared/errors"; import { BadRequestError, RetryableError } from "../../../../shared/errors";
type SSEStreamAdapterOptions = TransformOptions & { type SSEStreamAdapterOptions = TransformOptions & {
contentType?: string; contentType?: string;
@@ -117,7 +116,7 @@ export class SSEStreamAdapter extends Transform {
try { try {
const hasParts = candidates[0].content?.parts?.length > 0; const hasParts = candidates[0].content?.parts?.length > 0;
if (hasParts) { if (hasParts) {
return `data: ${JSON.stringify(data)}`; return `data: ${JSON.stringify(data.value ?? data)}\n`;
} else { } else {
this.log.error({ event: data }, "Received bad Google AI event"); this.log.error({ event: data }, "Received bad Google AI event");
return `data: ${buildSpoofedSSE({ return `data: ${buildSpoofedSSE({
+1 -1
View File
@@ -70,7 +70,7 @@ export function generateModelList(models = KNOWN_MISTRAL_AI_MODELS) {
} }
const handleModelRequest: RequestHandler = (_req, res) => { 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); return res.status(200).json(modelsCache);
} }
const result = generateModelList(); const result = generateModelList();
+8 -4
View File
@@ -28,10 +28,14 @@ import {
// https://platform.openai.com/docs/models/overview // https://platform.openai.com/docs/models/overview
export const KNOWN_OPENAI_MODELS = [ export const KNOWN_OPENAI_MODELS = [
"gpt-4-turbo-preview", "gpt-4o",
"gpt-4-0125-preview", "gpt-4o-2024-05-13",
"gpt-4-1106-preview", "gpt-4-turbo", // alias for latest gpt4-turbo stable
"gpt-4-vision-preview", "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",
"gpt-4-0613", "gpt-4-0613",
"gpt-4-0314", // EOL 2024-06-13 "gpt-4-0314", // EOL 2024-06-13
+11 -2
View File
@@ -12,7 +12,7 @@
*/ */
import crypto from "crypto"; import crypto from "crypto";
import type { Handler, Request } from "express"; import { Handler, Request } from "express";
import { BadRequestError, TooManyRequestsError } from "../shared/errors"; import { BadRequestError, TooManyRequestsError } from "../shared/errors";
import { keyPool } from "../shared/key-management"; import { keyPool } from "../shared/key-management";
import { import {
@@ -67,7 +67,7 @@ const sharesIdentifierWith = (incoming: Request) => (queued: Request) =>
const isFromSharedIp = (req: Request) => SHARED_IP_ADDRESSES.has(req.ip); 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; const enqueuedRequestCount = queue.filter(sharesIdentifierWith(req)).length;
let isGuest = req.user?.token === undefined; 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[] { function getQueueForPartition(partition: ModelFamily): Request[] {
return queue return queue
.filter((req) => getModelFamilyForRequest(req) === partition) .filter((req) => getModelFamilyForRequest(req) === partition)
+36 -1
View File
@@ -8,6 +8,7 @@ import pinoHttp from "pino-http";
import os from "os"; import os from "os";
import childProcess from "child_process"; import childProcess from "child_process";
import { logger } from "./logger"; import { logger } from "./logger";
import { createBlacklistMiddleware } from "./shared/cidr";
import { setupAssetsDir } from "./shared/file-storage/setup-assets-dir"; import { setupAssetsDir } from "./shared/file-storage/setup-assets-dir";
import { keyPool } from "./shared/key-management"; import { keyPool } from "./shared/key-management";
import { adminRouter } from "./admin/routes"; 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 { init as initTokenizers } from "./shared/tokenization";
import { checkOrigin } from "./proxy/check-origin"; import { checkOrigin } from "./proxy/check-origin";
import { sendErrorToClient } from "./proxy/middleware/response/error-generator"; import { sendErrorToClient } from "./proxy/middleware/response/error-generator";
import { initializeDatabase, getDatabase } from "./shared/database";
const PORT = config.port; const PORT = config.port;
const BIND_ADDRESS = config.bindAddress; const BIND_ADDRESS = config.bindAddress;
@@ -31,13 +33,19 @@ app.use(
pinoHttp({ pinoHttp({
quietReqLogger: true, quietReqLogger: true,
logger, 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: { redact: {
paths: [ paths: [
"req.headers.cookie", "req.headers.cookie",
'res.headers["set-cookie"]', 'res.headers["set-cookie"]',
"req.headers.authorization", "req.headers.authorization",
'req.headers["x-api-key"]', 'req.headers["x-api-key"]',
'req.headers["api-key"]',
// Don't log the prompt text on transform errors // Don't log the prompt text on transform errors
"body.messages", "body.messages",
"body.prompt", "body.prompt",
@@ -62,9 +70,20 @@ app.set("views", [
]); ]);
app.use("/user_content", express.static(USER_ASSETS_DIR, { maxAge: "2h" })); 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.get("/health", (_req, res) => res.sendStatus(200));
app.use(cors()); app.use(cors());
const blacklist = createBlacklistMiddleware("IP_BLACKLIST", config.ipBlacklist);
app.use(blacklist);
app.use(checkOrigin); app.use(checkOrigin);
app.use("/admin", adminRouter); app.use("/admin", adminRouter);
@@ -125,6 +144,8 @@ async function start() {
await logQueue.start(); await logQueue.start();
} }
await initializeDatabase();
logger.info("Starting request queue..."); logger.info("Starting request queue...");
startRequestQueue(); startRequestQueue();
@@ -146,6 +167,20 @@ 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("SIGINT", cleanup);
function registerUncaughtExceptionHandler() { function registerUncaughtExceptionHandler() {
process.on("uncaughtException", (err: any) => { process.on("uncaughtException", (err: any) => {
logger.error( logger.error(
+26 -22
View File
@@ -80,6 +80,7 @@ type OpenAIInfo = BaseFamilyInfo & {
overQuotaKeys?: number; overQuotaKeys?: number;
}; };
type AnthropicInfo = BaseFamilyInfo & { type AnthropicInfo = BaseFamilyInfo & {
trialKeys?: number;
prefilledKeys?: number; prefilledKeys?: number;
overQuotaKeys?: number; overQuotaKeys?: number;
}; };
@@ -140,8 +141,6 @@ const SERVICE_ENDPOINTS: { [s in LLMService]: Record<string, string> } = {
}, },
anthropic: { anthropic: {
anthropic: `%BASE%/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": {
"google-ai": `%BASE%/google-ai`, "google-ai": `%BASE%/google-ai`,
@@ -151,7 +150,6 @@ const SERVICE_ENDPOINTS: { [s in LLMService]: Record<string, string> } = {
}, },
aws: { aws: {
aws: `%BASE%/aws/claude`, aws: `%BASE%/aws/claude`,
"aws-sonnet (⚠️Temporary: for AWS Claude 3 Sonnet)": `%BASE%/aws/claude/sonnet`,
}, },
azure: { azure: {
azure: `%BASE%/azure/openai`, azure: `%BASE%/azure/openai`,
@@ -211,7 +209,8 @@ export function buildInfo(baseUrl: string, forAdmin = false): ServiceInfo {
} }
function getStatus() { 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; let unchecked = 0;
for (const service of LLM_SERVICES) { for (const service of LLM_SERVICES) {
@@ -349,6 +348,7 @@ function addKeyToAggregates(k: KeyPoolKey) {
sumTokens += tokens; sumTokens += tokens;
sumCost += getTokenCostUsd(f, tokens); sumCost += getTokenCostUsd(f, tokens);
increment(modelStats, `${f}__tokens`, 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}__revoked`, k.isRevoked ? 1 : 0);
increment(modelStats, `${f}__active`, k.isDisabled ? 0 : 1); increment(modelStats, `${f}__active`, k.isDisabled ? 0 : 1);
increment(modelStats, `${f}__overQuota`, k.isOverQuota ? 1 : 0); increment(modelStats, `${f}__overQuota`, k.isOverQuota ? 1 : 0);
@@ -385,21 +385,22 @@ function addKeyToAggregates(k: KeyPoolKey) {
} }
case "aws": { case "aws": {
if (!keyIsAwsKey(k)) throw new Error("Invalid key type"); if (!keyIsAwsKey(k)) throw new Error("Invalid key type");
const family = "aws-claude"; k.modelFamilies.forEach((f) => {
sumTokens += k["aws-claudeTokens"]; const tokens = k[`${f}Tokens`];
sumCost += getTokenCostUsd(family, k["aws-claudeTokens"]); sumTokens += tokens;
increment(modelStats, `${family}__active`, k.isDisabled ? 0 : 1); sumCost += getTokenCostUsd(f, tokens);
increment(modelStats, `${family}__revoked`, k.isRevoked ? 1 : 0); increment(modelStats, `${f}__tokens`, tokens);
increment(modelStats, `${family}__tokens`, k["aws-claudeTokens"]); increment(modelStats, `${f}__revoked`, k.isRevoked ? 1 : 0);
increment(modelStats, `${family}__awsSonnet`, k.sonnetEnabled ? 1 : 0); increment(modelStats, `${f}__active`, k.isDisabled ? 0 : 1);
increment(modelStats, `${family}__awsHaiku`, k.haikuEnabled ? 1 : 0); });
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 // Ignore revoked keys for aws logging stats, but include keys where the
// logging status is unknown. // logging status is unknown.
const countAsLogged = const countAsLogged =
k.lastChecked && !k.isDisabled && k.awsLoggingStatus !== "disabled"; k.lastChecked && !k.isDisabled && k.awsLoggingStatus === "enabled";
increment(modelStats, `${family}__awsLogged`, countAsLogged ? 1 : 0); increment(modelStats, `aws-claude__awsLogged`, countAsLogged ? 1 : 0);
break; break;
} }
default: default:
@@ -437,16 +438,19 @@ function getInfoForFamily(family: ModelFamily): BaseFamilyInfo {
break; break;
case "anthropic": case "anthropic":
info.overQuotaKeys = modelStats.get(`${family}__overQuota`) || 0; info.overQuotaKeys = modelStats.get(`${family}__overQuota`) || 0;
info.trialKeys = modelStats.get(`${family}__trial`) || 0;
info.prefilledKeys = modelStats.get(`${family}__pozzed`) || 0; info.prefilledKeys = modelStats.get(`${family}__pozzed`) || 0;
break; break;
case "aws": case "aws":
info.sonnetKeys = modelStats.get(`${family}__awsSonnet`) || 0; if (family === "aws-claude") {
info.haikuKeys = modelStats.get(`${family}__awsHaiku`) || 0; info.sonnetKeys = modelStats.get(`${family}__awsSonnet`) || 0;
const logged = modelStats.get(`${family}__awsLogged`) || 0; info.haikuKeys = modelStats.get(`${family}__awsHaiku`) || 0;
if (logged > 0) { const logged = modelStats.get(`${family}__awsLogged`) || 0;
info.privacy = config.allowAwsLogging if (logged > 0) {
? `${logged} active keys are potentially logged.` info.privacy = config.allowAwsLogging
: `${logged} active keys are potentially logged and can't be used. Set ALLOW_AWS_LOGGING=true to override.`; ? `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; break;
} }
+10 -2
View File
@@ -119,7 +119,8 @@ export const transformOpenAIToAnthropicChat: APIFormatTransformer<
stream: rest.stream, stream: rest.stream,
temperature: rest.temperature, temperature: rest.temperature,
top_p: rest.top_p, top_p: rest.top_p,
stop_sequences: typeof rest.stop === "string" ? [rest.stop] : rest.stop, stop_sequences:
typeof rest.stop === "string" ? [rest.stop] : rest.stop || undefined,
...(rest.user ? { metadata: { user_id: rest.user } } : {}), ...(rest.user ? { metadata: { user_id: rest.user } } : {}),
// Anthropic supports top_k, but OpenAI does not // Anthropic supports top_k, but OpenAI does not
// OpenAI supports frequency_penalty, presence_penalty, logit_bias, n, seed, // OpenAI supports frequency_penalty, presence_penalty, logit_bias, n, seed,
@@ -260,7 +261,7 @@ export function flattenAnthropicMessages(
): string { ): string {
return messages return messages
.map((msg) => { .map((msg) => {
const name = msg.role === "user" ? "\n\nHuman: " : "\n\nAssistant: "; const name = msg.role === "user" ? "Human" : "Assistant";
const parts = Array.isArray(msg.content) const parts = Array.isArray(msg.content)
? msg.content ? msg.content
: [{ type: "text", text: msg.content }]; : [{ type: "text", text: msg.content }];
@@ -438,3 +439,10 @@ function convertOpenAIContent(
} }
}); });
} }
export function containsImageContent(messages: AnthropicChatMessage[]) {
return messages.some(
({ content }) =>
typeof content !== "string" && content.some((c) => c.type === "image")
);
}
+181
View File
@@ -0,0 +1,181 @@
import { z } from "zod";
import {
OPENAI_OUTPUT_MAX,
OpenAIV1ChatCompletionSchema,
flattenOpenAIMessageContent,
} from "./openai";
import { APIFormatTransformer } from ".";
// https://docs.cohere.com/reference/chat
export const CohereV1ChatSchema = z
.object({
message: z.string(),
model: z.string().default("command-r-plus"),
stream: z.boolean().default(false).optional(),
preamble: z.string().optional(),
chat_history: z
.array(
// Either a message from a chat participant, or a past tool call
z.union([
z.object({
role: z.enum(["CHATBOT", "SYSTEM", "USER"]),
message: z.string(),
tool_calls: z
.array(z.object({ name: z.string(), parameters: z.any() }))
.optional(),
}),
z.object({
role: z.enum(["TOOL"]),
tool_results: z.array(
z.object({
call: z.object({ name: z.string(), parameters: z.any() }),
outputs: z.array(z.any()),
})
),
}),
])
)
.optional(),
// Don't allow conversation_id as it causes calls to be stateful and we don't
// offer guarantees about which key a user's request will be routed to.
conversation_id: z.literal(undefined).optional(),
prompt_truncation: z
.enum(["AUTO", "AUTO_PRESERVE_ORDER", "OFF"])
.optional(),
/*
Supporting RAG is complex because documents can be arbitrary size and have
to have embeddings generated, which incurs a cost that is not trivial to
estimate. We don't support it for now.
connectors: z
.array(
z.object({
id: z.string(),
user_access_token: z.string().optional(),
continue_on_failure: z.boolean().default(false).optional(),
options: z.any().optional(),
})
)
.optional(),
search_queries_only: z.boolean().default(false).optional(),
documents: z
.array(
z.object({
id: z.string().optional(),
title: z.string().optional(),
text: z.string(),
_excludes: z.array(z.string()).optional(),
})
)
.optional(),
citation_quality: z.enum(["accurate", "fast"]).optional(),
*/
temperature: z.number().default(0.3).optional(),
max_tokens: z
.number()
.int()
.nullish()
.default(Math.min(OPENAI_OUTPUT_MAX, 4096))
.transform((v) => Math.min(v ?? OPENAI_OUTPUT_MAX, OPENAI_OUTPUT_MAX)),
max_input_tokens: z.number().int().optional(),
k: z.number().int().min(0).max(500).default(0).optional(),
p: z.number().min(0.01).max(0.99).default(0.75).optional(),
seed: z.number().int().optional(),
stop_sequences: z.array(z.string()).max(5).optional(),
frequency_penalty: z.number().min(0).max(1).default(0).optional(),
presence_penalty: z.number().min(0).max(1).default(0).optional(),
tools: z
.array(
z.object({
name: z.string(),
description: z.string(),
parameter_definitions: z.record(
z.object({
description: z.string().optional(),
type: z.string(),
required: z.boolean().optional().default(false),
})
),
})
)
.optional(),
tool_results: z
.array(
z.object({
call: z.object({
name: z.string(),
parameters: z.record(z.any()),
}),
outputs: z.array(z.record(z.any())),
})
)
.optional(),
// We always force single step to avoid stateful calls or expensive multi-step
// generations when tools are involved.
force_single_step: z.literal(true).default(true).optional(),
})
.strip();
export type CohereChatMessage = NonNullable<
z.infer<typeof CohereV1ChatSchema>["chat_history"]
>[number];
export function flattenCohereMessageContent(
message: CohereChatMessage
): string {
return message.role === "TOOL"
? message.tool_results.map((r) => r.outputs[0].text).join("\n")
: message.message;
}
export const transformOpenAIToCohere: APIFormatTransformer<
typeof CohereV1ChatSchema
> = async (req) => {
const { body } = req;
const result = OpenAIV1ChatCompletionSchema.safeParse({
...body,
model: "gpt-3.5-turbo",
});
if (!result.success) {
req.log.warn(
{ issues: result.error.issues, body },
"Invalid OpenAI-to-Cohere request"
);
throw result.error;
}
const { messages, ...rest } = result.data;
// Final OAI message becomes the `message` field in Cohere
const message = messages[messages.length - 1];
// If the first message has system role, use it as preamble.
const hasSystemPreamble = messages[0]?.role === "system";
const preamble = hasSystemPreamble
? flattenOpenAIMessageContent(messages[0].content)
: undefined;
const chatHistory = messages.slice(0, -1).map((m) => {
const role: Exclude<CohereChatMessage["role"], "TOOL"> =
m.role === "assistant"
? "CHATBOT"
: m.role === "system"
? "SYSTEM"
: "USER";
const content = flattenOpenAIMessageContent(m.content);
const message = m.name ? `${m.name}: ${content}` : content;
return { role, message };
});
return {
model: rest.model,
preamble,
chat_history: chatHistory,
message: flattenOpenAIMessageContent(message.content),
stop_sequences:
typeof rest.stop === "string" ? [rest.stop] : rest.stop ?? undefined,
max_tokens: rest.max_tokens,
temperature: rest.temperature,
p: rest.top_p,
frequency_penalty: rest.frequency_penalty,
presence_penalty: rest.presence_penalty,
seed: rest.seed,
stream: rest.stream,
};
};
+20
View File
@@ -22,6 +22,7 @@ import {
transformOpenAIToGoogleAI, transformOpenAIToGoogleAI,
} from "./google-ai"; } from "./google-ai";
import { MistralAIV1ChatCompletionsSchema } from "./mistral-ai"; import { MistralAIV1ChatCompletionsSchema } from "./mistral-ai";
import { CohereV1ChatSchema, transformOpenAIToCohere } from "./cohere";
export { OpenAIChatMessage } from "./openai"; export { OpenAIChatMessage } from "./openai";
export { export {
@@ -33,15 +34,29 @@ export {
export { GoogleAIChatMessage } from "./google-ai"; export { GoogleAIChatMessage } from "./google-ai";
export { MistralAIChatMessage } from "./mistral-ai"; export { MistralAIChatMessage } from "./mistral-ai";
/** Represents a pair of API formats that can be transformed between. */
type APIPair = `${APIFormat}->${APIFormat}`; type APIPair = `${APIFormat}->${APIFormat}`;
/** Represents a map of API format pairs to transformer functions. */
type TransformerMap = { type TransformerMap = {
[key in APIPair]?: APIFormatTransformer<any>; [key in APIPair]?: APIFormatTransformer<any>;
}; };
/**
* Represents a transformer function that takes a Request and returns a Promise
* resolving to a value of the specified Zod schema type.
*
* @template Z The Zod schema type to transform the request into (from api-schemas).
* @param req The incoming Request to transform.
* @returns A Promise resolving to the transformed request body.
*/
export type APIFormatTransformer<Z extends z.ZodType<any, any>> = ( export type APIFormatTransformer<Z extends z.ZodType<any, any>> = (
req: Request req: Request
) => Promise<z.infer<Z>>; ) => Promise<z.infer<Z>>;
/**
* Specifies possible translations between API formats and the corresponding
* transformer functions to apply them.
*/
export const API_REQUEST_TRANSFORMERS: TransformerMap = { export const API_REQUEST_TRANSFORMERS: TransformerMap = {
"anthropic-text->anthropic-chat": transformAnthropicTextToAnthropicChat, "anthropic-text->anthropic-chat": transformAnthropicTextToAnthropicChat,
"openai->anthropic-chat": transformOpenAIToAnthropicChat, "openai->anthropic-chat": transformOpenAIToAnthropicChat,
@@ -49,8 +64,12 @@ export const API_REQUEST_TRANSFORMERS: TransformerMap = {
"openai->openai-text": transformOpenAIToOpenAIText, "openai->openai-text": transformOpenAIToOpenAIText,
"openai->openai-image": transformOpenAIToOpenAIImage, "openai->openai-image": transformOpenAIToOpenAIImage,
"openai->google-ai": transformOpenAIToGoogleAI, "openai->google-ai": transformOpenAIToGoogleAI,
"openai->cohere-chat": transformOpenAIToCohere,
}; };
/**
* Specifies the schema for each API format to validate incoming requests.
*/
export const API_REQUEST_VALIDATORS: Record<APIFormat, z.ZodSchema<any>> = { export const API_REQUEST_VALIDATORS: Record<APIFormat, z.ZodSchema<any>> = {
"anthropic-chat": AnthropicV1MessagesSchema, "anthropic-chat": AnthropicV1MessagesSchema,
"anthropic-text": AnthropicV1TextSchema, "anthropic-text": AnthropicV1TextSchema,
@@ -59,4 +78,5 @@ export const API_REQUEST_VALIDATORS: Record<APIFormat, z.ZodSchema<any>> = {
"openai-image": OpenAIV1ImagesGenerationSchema, "openai-image": OpenAIV1ImagesGenerationSchema,
"google-ai": GoogleAIV1GenerateContentSchema, "google-ai": GoogleAIV1GenerateContentSchema,
"mistral-ai": MistralAIV1ChatCompletionsSchema, "mistral-ai": MistralAIV1ChatCompletionsSchema,
"cohere-chat": CohereV1ChatSchema,
}; };
+11 -1
View File
@@ -47,7 +47,7 @@ export const OpenAIV1ChatCompletionSchema = z
stream: z.boolean().optional().default(false), stream: z.boolean().optional().default(false),
stop: z stop: z
.union([z.string().max(500), z.array(z.string().max(500))]) .union([z.string().max(500), z.array(z.string().max(500))])
.optional(), .nullish(),
max_tokens: z.coerce max_tokens: z.coerce
.number() .number()
.int() .int()
@@ -131,3 +131,13 @@ export function flattenOpenAIChatMessages(messages: OpenAIChatMessage[]) {
throw new Error(`Unknown prompt version: ${PROMPT_VERSION}`); 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;
}
+89
View File
@@ -0,0 +1,89 @@
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);
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/event";
+61
View File
@@ -0,0 +1,61 @@
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;`
);
},
},
] 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),
};
}
+7
View File
@@ -34,3 +34,10 @@ export class TooManyRequestsError extends HttpError {
super(429, message); 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 { KeyCheckerBase } from "../key-checker-base";
import type { AnthropicKey, AnthropicKeyProvider } from "./provider"; import type { AnthropicKey, AnthropicKeyProvider } from "./provider";
const MIN_CHECK_INTERVAL = 3 * 1000; // 3 seconds 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 POST_MESSAGES_URL = "https://api.anthropic.com/v1/messages";
const TEST_MODEL = "claude-3-sonnet-20240229"; const TEST_MODEL = "claude-3-sonnet-20240229";
const SYSTEM = "Obey all instructions from the user."; const SYSTEM = "Obey all instructions from the user.";
@@ -52,10 +52,13 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
} }
protected async testKeyOrFail(key: AnthropicKey) { protected async testKeyOrFail(key: AnthropicKey) {
const [{ pozzed }] = await Promise.all([this.testLiveness(key)]); const [{ pozzed, tier }] = await Promise.all([this.testLiveness(key)]);
const updates = { isPozzed: pozzed }; const updates = { isPozzed: pozzed, tier };
this.updateKey(key.hash, updates); 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) { protected handleAxiosError(key: AnthropicKey, error: AxiosError) {
@@ -124,7 +127,9 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
this.updateKey(key.hash, { lastChecked: next }); 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 = { const payload = {
model: TEST_MODEL, model: TEST_MODEL,
max_tokens: 40, max_tokens: 40,
@@ -133,24 +138,27 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
system: SYSTEM, system: SYSTEM,
messages: DETECTION_PROMPT, messages: DETECTION_PROMPT,
}; };
const { data } = await axios.post<MessageResponse>( const { data, headers } = await axios.post<MessageResponse>(
POST_MESSAGES_URL, POST_MESSAGES_URL,
payload, payload,
{ headers: AnthropicKeyChecker.getHeaders(key) } { headers: AnthropicKeyChecker.getRequestHeaders(key) }
); );
this.log.debug({ data }, "Response from Anthropic"); this.log.debug({ data }, "Response from Anthropic");
const tier = AnthropicKeyChecker.detectTier(headers);
const completion = data.content.map((part) => part.text).join(""); const completion = data.content.map((part) => part.text).join("");
if (POZZ_PROMPT.some((re) => re.test(completion))) { if (POZZ_PROMPT.some((re) => re.test(completion))) {
this.log.info({ key: key.hash, response: completion }, "Key is pozzed."); 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))) { } else if (COPYRIGHT_PROMPT.some((re) => re.test(completion))) {
this.log.info( this.log.info(
{ key: key.hash, response: completion }, { key: key.hash, response: completion },
"Key has copyright CYA prompt." "Key has copyright CYA prompt."
); );
return { pozzed: true }; return { pozzed: true, tier };
} else { } else {
return { pozzed: false }; return { pozzed: false, tier };
} }
} }
@@ -161,7 +169,19 @@ export class AnthropicKeyChecker extends KeyCheckerBase<AnthropicKey> {
return data?.error?.type; return data?.error?.type;
} }
static getHeaders(key: AnthropicKey) { static getRequestHeaders(key: AnthropicKey) {
return { "X-API-Key": key.key, "anthropic-version": "2023-06-01" }; 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 { logger } from "../../../logger";
import { AnthropicModelFamily, getClaudeModelFamily } from "../../models"; import { AnthropicModelFamily, getClaudeModelFamily } from "../../models";
import { AnthropicKeyChecker } from "./checker"; import { AnthropicKeyChecker } from "./checker";
import { HttpError, PaymentRequiredError } from "../../errors"; import { PaymentRequiredError } from "../../errors";
export type AnthropicKeyUpdate = Omit< export type AnthropicKeyUpdate = Omit<
Partial<AnthropicKey>, Partial<AnthropicKey>,
@@ -45,13 +45,40 @@ export interface AnthropicKey extends Key, AnthropicKeyUsage {
*/ */
isPozzed: boolean; isPozzed: boolean;
isOverQuota: 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 * Selection priority for Anthropic keys. Aims to maximize throughput by
* while we wait for other concurrent requests to finish. * 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 * 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 * 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, isOverQuota: false,
isRevoked: false, isRevoked: false,
isPozzed: false, isPozzed: false,
allowsMultimodality: true,
promptCount: 0, promptCount: 0,
lastUsed: 0, lastUsed: 0,
rateLimitedAt: 0, rateLimitedAt: 0,
@@ -98,6 +126,7 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
lastChecked: 0, lastChecked: 0,
claudeTokens: 0, claudeTokens: 0,
"claude-opusTokens": 0, "claude-opusTokens": 0,
tier: "unknown",
}; };
this.keys.push(newKey); this.keys.push(newKey);
} }
@@ -115,33 +144,43 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
return this.keys.map((k) => Object.freeze({ ...k, key: undefined })); return this.keys.map((k) => Object.freeze({ ...k, key: undefined }));
} }
public get(_model: string) { public get(rawModel: string) {
// Currently, all Anthropic keys have access to all models. This will almost this.log.debug({ model: rawModel }, "Selecting key");
// certainly change when they move out of beta later this year. const needsMultimodal = rawModel.endsWith("-multimodal");
const availableKeys = this.keys.filter((k) => !k.isDisabled);
const availableKeys = this.keys.filter((k) => {
return !k.isDisabled && (!needsMultimodal || k.allowsMultimodality);
});
if (availableKeys.length === 0) { 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: // Select a key, from highest priority to lowest priority:
// 1. Keys which are not rate limited // 1. Keys which are not rate limit locked
// a. If all keys were rate limited recently, select the least-recently // 2. Keys with the highest tier
// rate limited key. // 3. Keys which are not pozzed
// 2. Keys which are not pozzed // 4. Keys which have not been used in the longest time
// 3. Keys which have not been used in the longest time
const now = Date.now(); const now = Date.now();
const keysByPriority = availableKeys.sort((a, b) => { const keysByPriority = availableKeys.sort((a, b) => {
const aRateLimited = now - a.rateLimitedAt < RATE_LIMIT_LOCKOUT; const aLockoutPeriod = getKeyLockout(a);
const bRateLimited = now - b.rateLimitedAt < RATE_LIMIT_LOCKOUT; 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 -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;
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 key = this.keys.find((k) => k.hash === keyHash)!;
const now = Date.now(); const now = Date.now();
key.rateLimitedAt = now; key.rateLimitedAt = now;
key.rateLimitedUntil = now + RATE_LIMIT_LOCKOUT; key.rateLimitedUntil = now + SCALE_RATE_LIMIT_LOCKOUT;
} }
public recheck() { public recheck() {
@@ -239,3 +278,9 @@ export class AnthropicKeyProvider implements KeyProvider<AnthropicKey> {
key.rateLimitedUntil = Math.max(currentRateLimit, nextRateLimit); 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 { URL } from "url";
import { KeyCheckerBase } from "../key-checker-base"; import { KeyCheckerBase } from "../key-checker-base";
import type { AwsBedrockKey, AwsBedrockKeyProvider } from "./provider"; import type { AwsBedrockKey, AwsBedrockKeyProvider } from "./provider";
import { AwsBedrockModelFamily } from "../../models";
import { config } from "../../../config";
const MIN_CHECK_INTERVAL = 3 * 1000; // 3 seconds 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 = const AMZ_HOST =
process.env.AMZ_HOST || "bedrock-runtime.%REGION%.amazonaws.com"; process.env.AMZ_HOST || "bedrock-runtime.%REGION%.amazonaws.com";
const GET_CALLER_IDENTITY_URL = `https://sts.amazonaws.com/?Action=GetCallerIdentity&Version=2011-06-15`; 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-v2", key),
this.invokeModel("anthropic.claude-3-sonnet-20240229-v1:0", 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-haiku-20240307-v1:0", key),
this.invokeModel("anthropic.claude-3-opus-20240229-v1:0", key),
]; ];
} }
checks.unshift(this.checkLoggingConfiguration(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) { 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( this.log.info(
{ key: key.hash, sonnet, haiku, logged: key.awsLoggingStatus }, {
key: key.hash,
sonnet,
haiku,
families: key.modelFamilies,
logged: key.awsLoggingStatus,
},
"Checked key." "Checked key."
); );
} }
@@ -175,13 +200,14 @@ export class AwsKeyChecker extends KeyCheckerBase<AwsBedrockKey> {
const correctErrorType = errorType === "ValidationException"; const correctErrorType = errorType === "ValidationException";
const correctErrorMessage = errorMessage?.match(/max_tokens/); const correctErrorMessage = errorMessage?.match(/max_tokens/);
if (!correctErrorType || !correctErrorMessage) { if (!correctErrorType || !correctErrorMessage) {
throw new AxiosError( return false;
`Unexpected error when invoking model ${model}: ${errorMessage}`, // throw new AxiosError(
"AWS_ERROR", // `Unexpected error when invoking model ${model}: ${errorMessage}`,
response.config, // "AWS_ERROR",
response.request, // response.config,
response // response.request,
); // response
// );
} }
this.log.debug( this.log.debug(
@@ -192,16 +218,22 @@ export class AwsKeyChecker extends KeyCheckerBase<AwsBedrockKey> {
} }
private async checkLoggingConfiguration(key: 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 creds = AwsKeyChecker.getCredentialsFromKey(key);
const config: AxiosRequestConfig = { const req: AxiosRequestConfig = {
method: "GET", method: "GET",
url: GET_INVOCATION_LOGGING_CONFIG_URL(creds.region), url: GET_INVOCATION_LOGGING_CONFIG_URL(creds.region),
headers: { accept: "application/json" }, headers: { accept: "application/json" },
validateStatus: () => true, validateStatus: () => true,
}; };
await AwsKeyChecker.signRequestForAws(config, key); await AwsKeyChecker.signRequestForAws(req, key);
const { data, status, headers } = const { data, status, headers } =
await axios.request<GetLoggingConfigResponse>(config); await axios.request<GetLoggingConfigResponse>(req);
let result: AwsBedrockKey["awsLoggingStatus"] = "unknown"; let result: AwsBedrockKey["awsLoggingStatus"] = "unknown";
+13 -8
View File
@@ -2,7 +2,7 @@ import crypto from "crypto";
import { Key, KeyProvider } from ".."; import { Key, KeyProvider } from "..";
import { config } from "../../../config"; import { config } from "../../../config";
import { logger } from "../../../logger"; import { logger } from "../../../logger";
import type { AwsBedrockModelFamily } from "../../models"; import { AwsBedrockModelFamily, getAwsBedrockModelFamily } from "../../models";
import { AwsKeyChecker } from "./checker"; import { AwsKeyChecker } from "./checker";
import { PaymentRequiredError } from "../../errors"; import { PaymentRequiredError } from "../../errors";
@@ -78,6 +78,7 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
sonnetEnabled: true, sonnetEnabled: true,
haikuEnabled: false, haikuEnabled: false,
["aws-claudeTokens"]: 0, ["aws-claudeTokens"]: 0,
["aws-claude-opusTokens"]: 0,
}; };
this.keys.push(newKey); this.keys.push(newKey);
} }
@@ -97,14 +98,18 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
public get(model: string) { public get(model: string) {
const availableKeys = this.keys.filter((k) => { const availableKeys = this.keys.filter((k) => {
const isNotLogged = k.awsLoggingStatus === "disabled"; const isNotLogged = k.awsLoggingStatus !== "enabled";
const needsSonnet = model.includes("sonnet"); const neededFamily = getAwsBedrockModelFamily(model);
const needsHaiku = model.includes("haiku"); const needsSonnet =
model.includes("sonnet") && neededFamily === "aws-claude";
const needsHaiku =
model.includes("haiku") && neededFamily === "aws-claude";
return ( return (
!k.isDisabled && !k.isDisabled &&
(isNotLogged || config.allowAwsLogging) && (isNotLogged || config.allowAwsLogging) &&
(k.sonnetEnabled || !needsSonnet) && (k.sonnetEnabled || !needsSonnet) && // sonnet and haiku are both under aws-claude, while opus is not
(k.haikuEnabled || !needsHaiku) (k.haikuEnabled || !needsHaiku) &&
k.modelFamilies.includes(neededFamily)
); );
}); });
if (availableKeys.length === 0) { if (availableKeys.length === 0) {
@@ -157,11 +162,11 @@ export class AwsBedrockKeyProvider implements KeyProvider<AwsBedrockKey> {
return this.keys.filter((k) => !k.isDisabled).length; 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); const key = this.keys.find((k) => k.hash === hash);
if (!key) return; if (!key) return;
key.promptCount++; key.promptCount++;
key["aws-claudeTokens"] += tokens; key[`${getAwsBedrockModelFamily(model)}Tokens`] += tokens;
} }
public getLockoutPeriod() { public getLockoutPeriod() {
@@ -72,6 +72,7 @@ export class AzureOpenAIKeyProvider implements KeyProvider<AzureOpenAIKey> {
"azure-gpt4Tokens": 0, "azure-gpt4Tokens": 0,
"azure-gpt4-32kTokens": 0, "azure-gpt4-32kTokens": 0,
"azure-gpt4-turboTokens": 0, "azure-gpt4-turboTokens": 0,
"azure-gpt4oTokens": 0,
"azure-dall-eTokens": 0, "azure-dall-eTokens": 0,
}; };
this.keys.push(newKey); this.keys.push(newKey);
+2 -1
View File
@@ -9,7 +9,8 @@ export type APIFormat =
| "anthropic-chat" // Anthropic's newer messages array format | "anthropic-chat" // Anthropic's newer messages array format
| "anthropic-text" // Legacy flat string prompt format | "anthropic-text" // Legacy flat string prompt format
| "google-ai" | "google-ai"
| "mistral-ai"; | "mistral-ai"
| "cohere-chat";
export interface Key { export interface Key {
/** The API key itself. Never log this, use `hash` instead. */ /** The API key itself. Never log this, use `hash` instead. */
+17 -15
View File
@@ -13,15 +13,15 @@ type KeyCheckerOptions<TKey extends Key = Key> = {
export abstract class KeyCheckerBase<TKey extends Key> { export abstract class KeyCheckerBase<TKey extends Key> {
protected readonly service: string; protected readonly service: string;
protected readonly RECURRING_CHECKS_ENABLED: boolean; protected readonly recurringChecksEnabled: boolean;
/** Minimum time in between any two key checks. */ /** 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 * 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 * read quota usage, there is little reason to check a single key more often
* than this. * than this.
*/ */
protected readonly KEY_CHECK_PERIOD: number; protected readonly keyCheckPeriod: number;
protected readonly updateKey: (hash: string, props: Partial<TKey>) => void; protected readonly updateKey: (hash: string, props: Partial<TKey>) => void;
protected readonly keys: TKey[] = []; protected readonly keys: TKey[] = [];
protected log: pino.Logger; protected log: pino.Logger;
@@ -29,14 +29,13 @@ export abstract class KeyCheckerBase<TKey extends Key> {
protected lastCheck = 0; protected lastCheck = 0;
protected constructor(keys: TKey[], opts: KeyCheckerOptions<TKey>) { protected constructor(keys: TKey[], opts: KeyCheckerOptions<TKey>) {
const { service, keyCheckPeriod, minCheckInterval } = opts;
this.keys = keys; this.keys = keys;
this.KEY_CHECK_PERIOD = keyCheckPeriod; this.keyCheckPeriod = opts.keyCheckPeriod;
this.MIN_CHECK_INTERVAL = minCheckInterval; this.minCheckInterval = opts.minCheckInterval;
this.RECURRING_CHECKS_ENABLED = opts.recurringChecksEnabled ?? true; this.recurringChecksEnabled = opts.recurringChecksEnabled ?? true;
this.updateKey = opts.updateKey; this.updateKey = opts.updateKey;
this.service = service; this.service = opts.service;
this.log = logger.child({ module: "key-checker", service }); this.log = logger.child({ module: "key-checker", service: opts.service });
} }
public start() { public start() {
@@ -102,7 +101,7 @@ export abstract class KeyCheckerBase<TKey extends Key> {
return; return;
} }
if (!this.RECURRING_CHECKS_ENABLED) { if (!this.recurringChecksEnabled) {
checkLog.info( checkLog.info(
"Initial checks complete and recurring checks are disabled for this service. Stopping." "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 any individual key too often.
// Don't check anything at all at a rate faster than once per 3 seconds. // Don't check anything at all at a rate faster than once per 3 seconds.
const nextCheck = Math.max( const nextCheck = Math.max(
oldestKey.lastChecked + this.KEY_CHECK_PERIOD, oldestKey.lastChecked + this.keyCheckPeriod,
this.lastCheck + this.MIN_CHECK_INTERVAL 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.timeout = setTimeout(
() => this.checkKey(oldestKey).then(() => this.scheduleNextCheck()), () => this.checkKey(oldestKey).then(() => this.scheduleNextCheck()),
delay jitteredDelay
); );
checkLog.debug( checkLog.debug(
{ key: oldestKey.hash, nextCheck: new Date(nextCheck), delay }, { key: oldestKey.hash, nextCheck: new Date(nextCheck), jitteredDelay },
"Scheduled next recurring check." "Scheduled next recurring check."
); );
} }
+7 -1
View File
@@ -41,7 +41,13 @@ export class KeyPool {
this.scheduleRecheck(); 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); const queryService = service || this.getServiceForModel(model);
return this.getKeyProvider(queryService).get(model); return this.getKeyProvider(queryService).get(model);
} }
@@ -96,6 +96,7 @@ export class OpenAIKeyProvider implements KeyProvider<OpenAIKey> {
"turbo" as const, "turbo" as const,
"gpt4" as const, "gpt4" as const,
"gpt4-turbo" as const, "gpt4-turbo" as const,
"gpt4o" as const,
], ],
isTrial: false, isTrial: false,
isDisabled: false, isDisabled: false,
@@ -116,6 +117,7 @@ export class OpenAIKeyProvider implements KeyProvider<OpenAIKey> {
gpt4Tokens: 0, gpt4Tokens: 0,
"gpt4-32kTokens": 0, "gpt4-32kTokens": 0,
"gpt4-turboTokens": 0, "gpt4-turboTokens": 0,
gpt4oTokens: 0,
"dall-eTokens": 0, "dall-eTokens": 0,
gpt4Rpm: 0, gpt4Rpm: 0,
modelSnapshots: [], modelSnapshots: [],
+30 -5
View File
@@ -14,13 +14,15 @@ export type LLMService =
| "google-ai" | "google-ai"
| "mistral-ai" | "mistral-ai"
| "aws" | "aws"
| "azure"; | "azure"
| "cohere";
export type OpenAIModelFamily = export type OpenAIModelFamily =
| "turbo" | "turbo"
| "gpt4" | "gpt4"
| "gpt4-32k" | "gpt4-32k"
| "gpt4-turbo" | "gpt4-turbo"
| "gpt4o"
| "dall-e"; | "dall-e";
export type AnthropicModelFamily = "claude" | "claude-opus"; export type AnthropicModelFamily = "claude" | "claude-opus";
export type GoogleAIModelFamily = "gemini-pro"; export type GoogleAIModelFamily = "gemini-pro";
@@ -29,15 +31,17 @@ export type MistralAIModelFamily =
| "mistral-small" | "mistral-small"
| "mistral-medium" | "mistral-medium"
| "mistral-large"; | "mistral-large";
export type AwsBedrockModelFamily = "aws-claude"; export type AwsBedrockModelFamily = "aws-claude" | "aws-claude-opus";
export type AzureOpenAIModelFamily = `azure-${OpenAIModelFamily}`; export type AzureOpenAIModelFamily = `azure-${OpenAIModelFamily}`;
export type CohereModelFamily = "command-r" | "command-r-plus";
export type ModelFamily = export type ModelFamily =
| OpenAIModelFamily | OpenAIModelFamily
| AnthropicModelFamily | AnthropicModelFamily
| GoogleAIModelFamily | GoogleAIModelFamily
| MistralAIModelFamily | MistralAIModelFamily
| AwsBedrockModelFamily | AwsBedrockModelFamily
| AzureOpenAIModelFamily; | AzureOpenAIModelFamily
| CohereModelFamily;
export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>( export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>(
arr: A & ([ModelFamily] extends [A[number]] ? unknown : never) arr: A & ([ModelFamily] extends [A[number]] ? unknown : never)
@@ -46,6 +50,7 @@ export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>(
"gpt4", "gpt4",
"gpt4-32k", "gpt4-32k",
"gpt4-turbo", "gpt4-turbo",
"gpt4o",
"dall-e", "dall-e",
"claude", "claude",
"claude-opus", "claude-opus",
@@ -55,11 +60,15 @@ export const MODEL_FAMILIES = (<A extends readonly ModelFamily[]>(
"mistral-medium", "mistral-medium",
"mistral-large", "mistral-large",
"aws-claude", "aws-claude",
"aws-claude-opus",
"azure-turbo", "azure-turbo",
"azure-gpt4", "azure-gpt4",
"azure-gpt4-32k", "azure-gpt4-32k",
"azure-gpt4-turbo", "azure-gpt4-turbo",
"azure-gpt4o",
"azure-dall-e", "azure-dall-e",
"command-r",
"command-r-plus",
] as const); ] as const);
export const LLM_SERVICES = (<A extends readonly LLMService[]>( export const LLM_SERVICES = (<A extends readonly LLMService[]>(
@@ -71,9 +80,12 @@ export const LLM_SERVICES = (<A extends readonly LLMService[]>(
"mistral-ai", "mistral-ai",
"aws", "aws",
"azure", "azure",
"cohere",
] as const); ] as const);
export const OPENAI_MODEL_FAMILY_MAP: { [regex: string]: OpenAIModelFamily } = { 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-turbo(-preview)?$": "gpt4-turbo",
"^gpt-4-(0125|1106)(-preview)?$": "gpt4-turbo", "^gpt-4-(0125|1106)(-preview)?$": "gpt4-turbo",
"^gpt-4(-\\d{4})?-vision(-preview)?$": "gpt4-turbo", "^gpt-4(-\\d{4})?-vision(-preview)?$": "gpt4-turbo",
@@ -93,20 +105,25 @@ export const MODEL_FAMILY_SERVICE: {
gpt4: "openai", gpt4: "openai",
"gpt4-turbo": "openai", "gpt4-turbo": "openai",
"gpt4-32k": "openai", "gpt4-32k": "openai",
"gpt4o": "openai",
"dall-e": "openai", "dall-e": "openai",
claude: "anthropic", claude: "anthropic",
"claude-opus": "anthropic", "claude-opus": "anthropic",
"aws-claude": "aws", "aws-claude": "aws",
"aws-claude-opus": "aws",
"azure-turbo": "azure", "azure-turbo": "azure",
"azure-gpt4": "azure", "azure-gpt4": "azure",
"azure-gpt4-32k": "azure", "azure-gpt4-32k": "azure",
"azure-gpt4-turbo": "azure", "azure-gpt4-turbo": "azure",
"azure-gpt4o": "azure",
"azure-dall-e": "azure", "azure-dall-e": "azure",
"gemini-pro": "google-ai", "gemini-pro": "google-ai",
"mistral-tiny": "mistral-ai", "mistral-tiny": "mistral-ai",
"mistral-small": "mistral-ai", "mistral-small": "mistral-ai",
"mistral-medium": "mistral-ai", "mistral-medium": "mistral-ai",
"mistral-large": "mistral-ai", "mistral-large": "mistral-ai",
"command-r": "cohere",
"command-r-plus": "cohere",
}; };
export const IMAGE_GEN_MODELS: ModelFamily[] = ["dall-e", "azure-dall-e"]; export const IMAGE_GEN_MODELS: ModelFamily[] = ["dall-e", "azure-dall-e"];
@@ -149,8 +166,8 @@ export function getMistralAIModelFamily(model: string): MistralAIModelFamily {
} }
} }
export function getAwsBedrockModelFamily(model: string): ModelFamily { export function getAwsBedrockModelFamily(model: string): AwsBedrockModelFamily {
if (model.includes("opus")) return "claude-opus"; if (model.includes("opus")) return "aws-claude-opus";
return "aws-claude"; return "aws-claude";
} }
@@ -172,6 +189,11 @@ export function getAzureOpenAIModelFamily(
return defaultFamily; return defaultFamily;
} }
export function getCohereModelFamily(model: string): CohereModelFamily {
if (model.includes("plus")) return "command-r-plus";
return "command-r";
}
export function assertIsKnownModelFamily( export function assertIsKnownModelFamily(
modelFamily: string modelFamily: string
): asserts modelFamily is ModelFamily { ): asserts modelFamily is ModelFamily {
@@ -211,6 +233,9 @@ export function getModelFamilyForRequest(req: Request): ModelFamily {
case "mistral-ai": case "mistral-ai":
modelFamily = getMistralAIModelFamily(model); modelFamily = getMistralAIModelFamily(model);
break; break;
case "cohere-chat":
modelFamily = getCohereModelFamily(model);
break;
default: default:
assertNever(req.outboundApi); assertNever(req.outboundApi);
} }
@@ -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 * 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/event";
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. // 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 logQueue from "./log-queue";
export * as eventLogger from "./event-logger";
+19 -4
View File
@@ -2,8 +2,10 @@
* logging backend. */ * logging backend. */
import { logger } from "../../logger"; import { logger } from "../../logger";
import { PromptLogEntry } from "."; import { LogBackend, PromptLogEntry } from ".";
import { sheets } from "./backends"; import { sheets, file } from "./backends";
import { config } from "../../config";
import { assertNever } from "../utils";
const FLUSH_INTERVAL = 1000 * 10; const FLUSH_INTERVAL = 1000 * 10;
const MAX_BATCH_SIZE = 25; const MAX_BATCH_SIZE = 25;
@@ -15,6 +17,7 @@ let started = false;
let timeoutId: NodeJS.Timeout | null = null; let timeoutId: NodeJS.Timeout | null = null;
let retrying = false; let retrying = false;
let consecutiveFailedBatches = 0; let consecutiveFailedBatches = 0;
let backend: LogBackend;
export const enqueue = (payload: PromptLogEntry) => { export const enqueue = (payload: PromptLogEntry) => {
if (!started) { if (!started) {
@@ -34,7 +37,7 @@ export const flush = async () => {
const nextBatch = queue.splice(0, batchSize); const nextBatch = queue.splice(0, batchSize);
log.info({ size: nextBatch.length }, "Submitting new batch."); log.info({ size: nextBatch.length }, "Submitting new batch.");
try { try {
await sheets.appendBatch(nextBatch); await backend.appendBatch(nextBatch);
retrying = false; retrying = false;
consecutiveFailedBatches = 0; consecutiveFailedBatches = 0;
} catch (e: any) { } catch (e: any) {
@@ -64,8 +67,20 @@ export const flush = async () => {
}; };
export const start = async () => { export const start = async () => {
const type = config.promptLoggingBackend!;
try { try {
await sheets.init(() => stop()); 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."); log.info("Logging backend initialized.");
started = true; started = true;
} catch (e) { } catch (e) {
+5
View File
@@ -6,6 +6,10 @@ import { ModelFamily } from "./models";
export function getTokenCostUsd(model: ModelFamily, tokens: number) { export function getTokenCostUsd(model: ModelFamily, tokens: number) {
let cost = 0; let cost = 0;
switch (model) { switch (model) {
case "gpt4o":
case "azure-gpt4o":
cost = 0.000005;
break;
case "azure-gpt4-turbo": case "azure-gpt4-turbo":
case "gpt4-turbo": case "gpt4-turbo":
cost = 0.00001; cost = 0.00001;
@@ -29,6 +33,7 @@ export function getTokenCostUsd(model: ModelFamily, tokens: number) {
case "claude": case "claude":
cost = 0.000008; cost = 0.000008;
break; break;
case "aws-claude-opus":
case "claude-opus": case "claude-opus":
cost = 0.000015; cost = 0.000015;
break; break;
+12 -2
View File
@@ -19,7 +19,9 @@ export function init() {
return true; return true;
} }
export async function getTokenCount(prompt: string | AnthropicChatMessage[]) { export async function getTokenCount(
prompt: string | { system: string; messages: AnthropicChatMessage[] }
) {
if (typeof prompt !== "string") { if (typeof prompt !== "string") {
return getTokenCountForMessages(prompt); 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; let numTokens = 0;
numTokens += (await getTokenCount(system)).token_count;
for (const message of messages) { for (const message of messages) {
const { content, role } = message; const { content, role } = message;
numTokens += role === "user" ? userRoleCount : assistantRoleCount; numTokens += role === "user" ? userRoleCount : assistantRoleCount;
+1 -1
View File
@@ -35,7 +35,7 @@ type OpenAIChatTokenCountRequest = {
}; };
type AnthropicChatTokenCountRequest = { type AnthropicChatTokenCountRequest = {
prompt: AnthropicChatMessage[]; prompt: { system: string; messages: AnthropicChatMessage[] };
completion?: never; completion?: never;
service: "anthropic-chat"; service: "anthropic-chat";
}; };
+1
View File
@@ -51,6 +51,7 @@ export const UserSchema = z
maxIps: z.coerce.number().int().min(0).optional(), maxIps: z.coerce.number().int().min(0).optional(),
/** Private note about the user. */ /** Private note about the user. */
adminNote: z.string().optional(), adminNote: z.string().optional(),
meta: z.record(z.any()).optional(),
}) })
.strict(); .strict();
+12 -1
View File
@@ -80,6 +80,7 @@ export function createUser(createOptions?: {
tokenCounts: { ...INITIAL_TOKENS }, tokenCounts: { ...INITIAL_TOKENS },
tokenLimits: createOptions?.tokenLimits ?? { ...config.tokenQuota }, tokenLimits: createOptions?.tokenLimits ?? { ...config.tokenQuota },
createdAt: Date.now(), createdAt: Date.now(),
meta: {},
}; };
if (createOptions?.type === "temporary") { if (createOptions?.type === "temporary") {
@@ -123,6 +124,7 @@ export function upsertUser(user: UserUpdate) {
tokenCounts: { ...INITIAL_TOKENS }, tokenCounts: { ...INITIAL_TOKENS },
tokenLimits: { ...config.tokenQuota }, tokenLimits: { ...config.tokenQuota },
createdAt: Date.now(), createdAt: Date.now(),
meta: {},
}; };
const updates: Partial<User> = {}; const updates: Partial<User> = {};
@@ -274,6 +276,10 @@ export function disableUser(token: string, reason?: string) {
if (!user) return; if (!user) return;
user.disabledAt = Date.now(); user.disabledAt = Date.now();
user.disabledReason = reason; user.disabledReason = reason;
if (user.meta) {
// manually banned tokens cannot be refreshed
user.meta.refreshable = false;
}
usersToFlush.add(token); usersToFlush.add(token);
} }
@@ -295,9 +301,14 @@ function cleanupExpiredTokens() {
if (user.type !== "temporary") continue; if (user.type !== "temporary") continue;
if (user.expiresAt && user.expiresAt < now && !user.disabledAt) { if (user.expiresAt && user.expiresAt < now && !user.disabledAt) {
disableUser(user.token, "Temporary token expired."); disableUser(user.token, "Temporary token expired.");
if (!user.meta) {
user.meta = {};
}
user.meta.refreshable = config.captchaMode !== "none";
disabled++; 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); users.delete(user.token);
usersToFlush.add(user.token); usersToFlush.add(user.token);
deleted++; deleted++;
+10 -1
View File
@@ -57,7 +57,7 @@ export function makeOptionalPropsNullable<Schema extends z.AnyZodObject>(
) { ) {
const entries = Object.entries(schema.shape) as [ const entries = Object.entries(schema.shape) as [
keyof Schema["shape"], keyof Schema["shape"],
z.ZodTypeAny z.ZodTypeAny,
][]; ][];
const newProps = entries.reduce( const newProps = entries.reduce(
(acc, [key, value]) => { (acc, [key, value]) => {
@@ -84,3 +84,12 @@ export function redactIp(ip: string) {
export function assertNever(x: never): never { export function assertNever(x: never): never {
throw new Error(`Called assertNever with argument ${x}.`); 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"));
}
+36 -40
View File
@@ -1,22 +1,26 @@
<!DOCTYPE html> <!doctype html>
<html> <html lang="en">
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8" />
<meta name="csrf-token" content="<%= csrfToken %>"> <meta name="csrf-token" content="<%= csrfToken %>" />
<title><%= title %></title> <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> <style>
body { body {
font-family: sans-serif; font-family: sans-serif;
background-color: #f0f0f0;
padding: 1em; padding: 1em;
max-width: 800px;
} }
a:hover { details summary {
background-color: #e0e6f6; cursor: pointer;
font-weight: bold;
} }
details > *:not(summary) {
a:visited:hover { margin: 0.5em;
background-color: #e7e0f6;
} }
.pagination { .pagination {
@@ -29,6 +33,7 @@
.pagination li a { .pagination li a {
display: block; display: block;
padding: 0.5em 1em; padding: 0.5em 1em;
border-bottom: none;
text-decoration: none; text-decoration: none;
} }
.pagination li.active a { .pagination li.active a {
@@ -36,17 +41,18 @@
color: #fff; color: #fff;
} }
table {
border-collapse: collapse;
border: 1px solid #ccc;
}
table.striped tr:nth-child(even) { table.striped tr:nth-child(even) {
background-color: #eaeaea background-color: #eaeaea;
} }
table td, table th { table.full-width {
border: 1px solid #ccc; width: calc(100vw - 4em);
padding: 0.25em 0.5em; position: relative;
left: 50%;
right: 50%;
margin-left: calc(-50vw + 2em);
margin-right: calc(-50vw + 2em);
} }
th.active { th.active {
background-color: #e0e6f6; background-color: #e0e6f6;
} }
@@ -66,30 +72,22 @@
background-color: #e0e6f6; background-color: #e0e6f6;
} }
@media (max-width: 600px) { @media (max-width: 800px) {
table { body {
width: 100%; padding: 0.5em;
}
table td, table th {
display: block;
width: 100%;
} }
table.full-width {
width: 100%;
position: static;
left: auto;
right: auto;
margin-left: 0;
margin-right: 0;
}
} }
@media (prefers-color-scheme: dark) { @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) { table.striped tr:nth-child(even) {
background-color: #333; background-color: #333;
} }
@@ -102,5 +100,3 @@
</head> </head>
<body> <body>
<%- include("partials/shared_flash", { flashData: flash }) %> <%- include("partials/shared_flash", { flashData: flash }) %>
@@ -12,7 +12,7 @@
<script> <script>
function getPageSize() { 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; if (match) return parseInt(match[1]); else return document.cookie.match(/perPage=(\d+)/)?.[1] ?? 10;
} }
function setPageSize(size) { function setPageSize(size) {
@@ -1,5 +1,5 @@
<a href="#" id="ip-list-toggle">Show all (<%- user.ip.length %>)</a> <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) => { %> <% user.ip.forEach((ip) => { %>
<li><code><%- shouldRedact ? redactIp(ip) : ip %></code></li> <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 { injectCsrfToken, checkCsrfToken } from "../shared/inject-csrf";
import { browseImagesRouter } from "./web/browse-images"; import { browseImagesRouter } from "./web/browse-images";
import { selfServiceRouter } from "./web/self-service"; import { selfServiceRouter } from "./web/self-service";
import { powRouter } from "./web/pow-captcha";
import { injectLocals } from "../shared/inject-locals"; import { injectLocals } from "../shared/inject-locals";
import { withSession } from "../shared/with-session"; import { withSession } from "../shared/with-session";
import { config } from "../config"; import { config } from "../config";
@@ -18,17 +19,30 @@ userRouter.use(injectLocals);
if (config.showRecentImages) { if (config.showRecentImages) {
userRouter.use(browseImagesRouter); userRouter.use(browseImagesRouter);
} }
if (config.captchaMode !== "none") {
userRouter.use("/captcha", powRouter);
}
userRouter.use(selfServiceRouter); userRouter.use(selfServiceRouter);
userRouter.use( userRouter.use(
( (
err: Error, err: Error,
_req: express.Request, req: express.Request,
res: express.Response, res: express.Response,
_next: express.NextFunction _next: express.NextFunction
) => { ) => {
const data: any = { message: err.message, stack: err.stack, status: 500 }; 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 };
@@ -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" }) %> <%- include("partials/shared_header", { title: "Error" }) %>
<div id="error-content" style="color: red; background-color: #eedddd; padding: 1em"> <div id="error-content" style="color: red; background-color: #eedddd; padding: 1em">
<p><strong>⚠️ Error <%= status %>:</strong> <%= message %></p> <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> <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> </div>
</body> </body>
</html> </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") %>