@shelby-protocol/mcp 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +104 -2
- package/dist/config.js +67 -0
- package/dist/load-env.js +12 -0
- package/dist/resources/how_to_connect_to_a_shelby_bucket_with_s3.md +107 -0
- package/dist/server.js +29 -0
- package/dist/services/ShelbyAccount.js +50 -0
- package/dist/services/ShelbyAdmin.js +109 -0
- package/dist/services/ShelbyObjects.js +171 -0
- package/dist/services/agentKey.js +63 -0
- package/dist/services/catalog.js +135 -0
- package/dist/tools/buckets.js +175 -0
- package/dist/tools/guide.js +21 -0
- package/dist/tools/index.js +16 -0
- package/dist/tools/key.js +32 -0
- package/dist/tools/objects.js +69 -0
- package/dist/tools/run.js +25 -0
- package/dist/tools/schemas.js +74 -0
- package/dist/utils/bucketName.js +33 -0
- package/dist/utils/errors.js +58 -0
- package/dist/utils/paths.js +87 -0
- package/package.json +49 -4
package/README.md
CHANGED
|
@@ -1,3 +1,105 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Shelby MCP
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An MCP server that lets agents manage Shelby buckets and read and write their objects. It authenticates with an agent key, which you can limit to an organization, some projects, or specific buckets, and make read-only.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- Node.js `>= 22.12.0` (see `.nvmrc`)
|
|
8
|
+
- A Shelby agent key
|
|
9
|
+
|
|
10
|
+
### Get an agent key
|
|
11
|
+
|
|
12
|
+
1. Go to [https://console.shelby.xyz/](https://console.shelby.xyz/) and open **Integrations**.
|
|
13
|
+
2. Create an agent key. Choose what it can reach (the organization, some projects, or specific buckets), whether it's read-only, and when it expires (30, 60, 90 or 180 days).
|
|
14
|
+
3. Copy the key. It's shown once.
|
|
15
|
+
|
|
16
|
+
In the last 7 days before the key expires, every tool result carries a second text block warning about it, so the agent can tell you to create a new key and update `SHELBY_AGENT_KEY`.
|
|
17
|
+
|
|
18
|
+
Give the key the least it needs. A key limited to specific buckets can read and write those buckets but can't create new ones.
|
|
19
|
+
|
|
20
|
+
## Setup
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
npm install
|
|
24
|
+
npm run build
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The server reads the key from, in order:
|
|
28
|
+
|
|
29
|
+
1. `SHELBY_AGENT_KEY` in the environment, or in a `.env` file in this directory (`.env` is gitignored).
|
|
30
|
+
2. `SHELBY_BOT_KEY`, the older name.
|
|
31
|
+
3. The OS keychain, under service `shelby-mcp` and account `SHELBY_AGENT_KEY`:
|
|
32
|
+
- macOS: `security add-generic-password -s shelby-mcp -a SHELBY_AGENT_KEY -w`
|
|
33
|
+
- Linux (libsecret): `secret-tool store --label "Shelby agent key" service shelby-mcp account SHELBY_AGENT_KEY`
|
|
34
|
+
|
|
35
|
+
Uploads read and downloads write only inside the allowed directories. Pass `--allow-dir <dir>`, with more directories after it or repeated; without it, only the directory the server starts in is allowed. Paths are checked after resolving symlinks, so neither `..` nor a link can reach outside.
|
|
36
|
+
|
|
37
|
+
`SHELBY_ENV` selects the backend. It defaults to `beta`; `staging` points at staging. `SHELBY_ADMIN_URL`, `SHELBY_S3_ADMIN_URL` and `SHELBY_S3_ENDPOINT` override single endpoints.
|
|
38
|
+
|
|
39
|
+
## Use with Cursor
|
|
40
|
+
|
|
41
|
+
Add this to your user-level `~/.cursor/mcp.json`, and set `SHELBY_AGENT_KEY` in your shell profile or keychain rather than in the file:
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"mcpServers": {
|
|
46
|
+
"shelby": {
|
|
47
|
+
"command": "node",
|
|
48
|
+
"args": [
|
|
49
|
+
"<path-to-shelby-mcp>/dist/server.js",
|
|
50
|
+
"--allow-dir",
|
|
51
|
+
"<directory-with-your-files>"
|
|
52
|
+
],
|
|
53
|
+
"env": {
|
|
54
|
+
"SHELBY_AGENT_KEY": "${env:SHELBY_AGENT_KEY}"
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Don't put the key itself in a project-level `.cursor/mcp.json` or `.mcp.json`; those are easy to commit.
|
|
62
|
+
|
|
63
|
+
The server uses stdio. Restart the MCP client after changing the config.
|
|
64
|
+
|
|
65
|
+
## Use with Claude Desktop
|
|
66
|
+
|
|
67
|
+
`npm run bundle` builds two [MCP bundles](https://github.com/modelcontextprotocol/mcpb): `build/shelby.mcpb` for beta and `build/shelby-staging.mcpb` for staging. Open one to install it in Claude Desktop, which asks for the agent key (masked and stored securely) and the allowed directories.
|
|
68
|
+
|
|
69
|
+
## Tools
|
|
70
|
+
|
|
71
|
+
Tools take bucket and project **names**. The project is only needed when two reachable buckets share a name.
|
|
72
|
+
|
|
73
|
+
| Tool | What it does |
|
|
74
|
+
| --- | --- |
|
|
75
|
+
| `get_shelby_agent_key_info` | The key's name, expiry, permission, what it reaches, and the allowed directories. Never the key itself |
|
|
76
|
+
| `list_shelby_buckets` | Buckets the key reaches, with each one's S3 bucket name and account address, and where new buckets can be created |
|
|
77
|
+
| `get_shelby_bucket` | One bucket by name |
|
|
78
|
+
| `create_shelby_bucket` | Create a bucket and the managed account that owns its data |
|
|
79
|
+
| `rename_shelby_bucket` | Rename a bucket's display name. Its S3 bucket name and account address do not change |
|
|
80
|
+
| `delete_shelby_bucket` | Delete a bucket. This cannot be undone |
|
|
81
|
+
| `list_shelby_objects` | List objects, optionally under a prefix, a page at a time |
|
|
82
|
+
| `upload_shelby_object` | Upload a local file, streamed, with a multipart upload above 16 MiB |
|
|
83
|
+
| `download_shelby_object` | Download an object to a local file. Won't replace an existing file unless asked |
|
|
84
|
+
| `get_shelby_s3_connection_guide` | Sample code (boto3, AWS SDK v3, AWS CLI) for S3 clients |
|
|
85
|
+
| `get_mcp_version` | Return this server's version |
|
|
86
|
+
|
|
87
|
+
A bucket's name is also its S3 bucket name, so it must be 3–32 characters of lowercase letters, numbers, and dashes, start and end with a letter or number, and contain at least one letter. It also can't look like an account address (`0x` followed by hex) or use an AWS-reserved prefix or suffix, and `health`, `ready`, `metrics` and `internal` are reserved. API key names and renamed display names must be 3–32 characters: lowercase letters, numbers, dashes, and underscores.
|
|
88
|
+
|
|
89
|
+
S3 clients use the bucket's `s3_bucket`: the name it was created with, or its `account_address` for older buckets whose names aren't valid S3 bucket names. The account address always works too. Renaming a bucket only changes its display name, so S3 clients keep using the original `s3_bucket`.
|
|
90
|
+
|
|
91
|
+
## Unscoped bot keys
|
|
92
|
+
|
|
93
|
+
Bot keys created before agent keys aren't limited to anything. They still work for managing buckets: `create_shelby_bucket` then also creates an API key, the bucket's S3 credential, and `list_shelby_buckets` returns API keys. They can't use the object tools; use an agent key for those.
|
|
94
|
+
|
|
95
|
+
## Scripts
|
|
96
|
+
|
|
97
|
+
| Script | What it does |
|
|
98
|
+
| --- | --- |
|
|
99
|
+
| `npm run build` | Compile TypeScript to `dist/` |
|
|
100
|
+
| `npm start` | Build and run the server |
|
|
101
|
+
| `npm run dev` | Build and run the FastMCP dev inspector |
|
|
102
|
+
| `npm test` | Build, then run the unit and smoke tests |
|
|
103
|
+
| `npm run lint` | Biome and `tsc --noEmit` |
|
|
104
|
+
| `npm run format` | Format with Biome |
|
|
105
|
+
| `npm run bundle` | Build the Claude Desktop bundles in `build/` |
|
package/dist/config.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { resolve } from "node:path";
|
|
2
|
+
import { loadEnvFromFile } from "./load-env.js";
|
|
3
|
+
loadEnvFromFile();
|
|
4
|
+
const environments = {
|
|
5
|
+
beta: {
|
|
6
|
+
adminUrl: "https://admin.api.beta.shelby.xyz/api/rspc",
|
|
7
|
+
// JWT/bot-key authed control plane. Never send SigV4 requests here.
|
|
8
|
+
s3AdminUrl: "https://api.beta.shelby.xyz/s3/admin",
|
|
9
|
+
// S3 data plane. Agent keys use it with a Bearer token, S3 clients with SigV4.
|
|
10
|
+
s3EndpointUrl: "https://s3.beta.shelby.xyz",
|
|
11
|
+
},
|
|
12
|
+
staging: {
|
|
13
|
+
adminUrl: "https://admin.api.staging.beta.shelby.xyz/api/rspc",
|
|
14
|
+
s3AdminUrl: "https://api.staging.beta.shelby.xyz/s3/admin",
|
|
15
|
+
s3EndpointUrl: "https://s3.staging.beta.shelby.xyz",
|
|
16
|
+
},
|
|
17
|
+
};
|
|
18
|
+
function resolveEnvironment() {
|
|
19
|
+
const value = process.env.SHELBY_ENV ?? "beta";
|
|
20
|
+
if (!(value in environments)) {
|
|
21
|
+
throw new Error(`Unknown SHELBY_ENV "${value}". Expected one of: ${Object.keys(environments).join(", ")}`);
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Every `--allow-dir <dir>...` and `--allow-dir=<dir>` argument, resolved. `--allow-dir` takes
|
|
27
|
+
* each argument up to the next flag, since MCP bundle hosts expand a multi-directory picker into
|
|
28
|
+
* separate arguments.
|
|
29
|
+
*/
|
|
30
|
+
export function parseAllowedDirs(argv, cwd) {
|
|
31
|
+
const dirs = [];
|
|
32
|
+
for (let i = 0; i < argv.length; i++) {
|
|
33
|
+
const arg = argv[i];
|
|
34
|
+
if (arg === "--allow-dir") {
|
|
35
|
+
const start = dirs.length;
|
|
36
|
+
while (i + 1 < argv.length && !argv[i + 1].startsWith("--")) {
|
|
37
|
+
dirs.push(resolve(cwd, argv[++i]));
|
|
38
|
+
}
|
|
39
|
+
if (dirs.length === start)
|
|
40
|
+
throw new Error("--allow-dir needs a directory");
|
|
41
|
+
}
|
|
42
|
+
else if (arg.startsWith("--allow-dir=")) {
|
|
43
|
+
dirs.push(resolve(cwd, arg.slice("--allow-dir=".length)));
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return dirs.length > 0 ? dirs : [cwd];
|
|
47
|
+
}
|
|
48
|
+
const environment = resolveEnvironment();
|
|
49
|
+
const endpoints = environments[environment];
|
|
50
|
+
export const config = {
|
|
51
|
+
environment,
|
|
52
|
+
shelby: {
|
|
53
|
+
adminUrl: process.env.SHELBY_ADMIN_URL ?? endpoints.adminUrl,
|
|
54
|
+
s3AdminUrl: process.env.SHELBY_S3_ADMIN_URL ?? endpoints.s3AdminUrl,
|
|
55
|
+
s3EndpointUrl: process.env.SHELBY_S3_ENDPOINT ?? endpoints.s3EndpointUrl,
|
|
56
|
+
// api-gateway chain name for Shelby; the only network buckets can be created on.
|
|
57
|
+
network: "shelby-beta",
|
|
58
|
+
// api-gateway service type for Managed Shelby Accounts (buckets).
|
|
59
|
+
serviceType: "S3Gateway",
|
|
60
|
+
},
|
|
61
|
+
// Uploads read from and downloads write to these directories only.
|
|
62
|
+
allowedDirs: parseAllowedDirs(process.argv.slice(2), process.cwd()),
|
|
63
|
+
server: {
|
|
64
|
+
name: "Shelby MCP Server",
|
|
65
|
+
version: "0.1.0",
|
|
66
|
+
},
|
|
67
|
+
};
|
package/dist/load-env.js
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
# How to connect to a Shelby bucket with S3
|
|
2
|
+
|
|
3
|
+
Shelby buckets speak the S3 API. Any S3-compatible client (boto3, AWS SDK, AWS CLI, rclone, ...) works once it is configured with:
|
|
4
|
+
|
|
5
|
+
| Setting | Value |
|
|
6
|
+
| --- | --- |
|
|
7
|
+
| Endpoint | `{{S3_ENDPOINT}}` |
|
|
8
|
+
| Addressing style | Path-style (`forcePathStyle: true` / `addressing_style: "path"`) |
|
|
9
|
+
| Access key id | The bucket's API key secret |
|
|
10
|
+
| Secret access key | The same API key secret |
|
|
11
|
+
| Bucket | The bucket's S3 bucket name: `{{BUCKET}}` |
|
|
12
|
+
|
|
13
|
+
Rules:
|
|
14
|
+
|
|
15
|
+
- Use the API key secret as **both** the access key id and the secret access key.
|
|
16
|
+
- The S3 `Bucket` parameter is the bucket's `s3_bucket`: the name it was created with, or its account address for older buckets whose names aren't valid S3 bucket names. The account address always works too.
|
|
17
|
+
- Renaming a bucket changes only its display name, not its S3 bucket name.
|
|
18
|
+
- Never commit the API key secret. Load it from an environment variable (e.g. `SHELBY_API_KEY`).
|
|
19
|
+
- Only send S3 (SigV4) requests to `{{S3_ENDPOINT}}`.
|
|
20
|
+
|
|
21
|
+
## Python (boto3)
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
import os
|
|
25
|
+
|
|
26
|
+
import boto3
|
|
27
|
+
from botocore.config import Config
|
|
28
|
+
|
|
29
|
+
api_key = os.environ["SHELBY_API_KEY"]
|
|
30
|
+
|
|
31
|
+
s3 = boto3.client(
|
|
32
|
+
"s3",
|
|
33
|
+
aws_access_key_id=api_key,
|
|
34
|
+
aws_secret_access_key=api_key,
|
|
35
|
+
endpoint_url="{{S3_ENDPOINT}}",
|
|
36
|
+
config=Config(
|
|
37
|
+
s3={"addressing_style": "path"},
|
|
38
|
+
request_checksum_calculation="when_required",
|
|
39
|
+
),
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# List objects
|
|
43
|
+
response = s3.list_objects_v2(Bucket="{{BUCKET}}")
|
|
44
|
+
for obj in response.get("Contents", []):
|
|
45
|
+
print(obj["Key"])
|
|
46
|
+
|
|
47
|
+
# Upload an object
|
|
48
|
+
with open("my-file.txt", "rb") as f:
|
|
49
|
+
s3.put_object(Bucket="{{BUCKET}}", Key="my-file.txt", Body=f)
|
|
50
|
+
|
|
51
|
+
# Download an object
|
|
52
|
+
response = s3.get_object(Bucket="{{BUCKET}}", Key="my-file.txt")
|
|
53
|
+
with open("my-file.txt", "wb") as f:
|
|
54
|
+
f.write(response["Body"].read())
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## TypeScript (AWS SDK v3)
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import {
|
|
61
|
+
GetObjectCommand,
|
|
62
|
+
ListObjectsV2Command,
|
|
63
|
+
PutObjectCommand,
|
|
64
|
+
S3Client,
|
|
65
|
+
} from "@aws-sdk/client-s3";
|
|
66
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
67
|
+
|
|
68
|
+
const apiKey = process.env.SHELBY_API_KEY!;
|
|
69
|
+
|
|
70
|
+
const s3 = new S3Client({
|
|
71
|
+
endpoint: "{{S3_ENDPOINT}}",
|
|
72
|
+
region: "default",
|
|
73
|
+
credentials: { accessKeyId: apiKey, secretAccessKey: apiKey },
|
|
74
|
+
forcePathStyle: true,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// List objects
|
|
78
|
+
const list = await s3.send(new ListObjectsV2Command({ Bucket: "{{BUCKET}}" }));
|
|
79
|
+
list.Contents?.forEach((obj) => console.log(obj.Key));
|
|
80
|
+
|
|
81
|
+
// Upload an object
|
|
82
|
+
await s3.send(
|
|
83
|
+
new PutObjectCommand({
|
|
84
|
+
Bucket: "{{BUCKET}}",
|
|
85
|
+
Key: "my-file.txt",
|
|
86
|
+
Body: readFileSync("./my-file.txt"),
|
|
87
|
+
}),
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
// Download an object
|
|
91
|
+
const object = await s3.send(
|
|
92
|
+
new GetObjectCommand({ Bucket: "{{BUCKET}}", Key: "my-file.txt" }),
|
|
93
|
+
);
|
|
94
|
+
writeFileSync("./my-file.txt", await object.Body!.transformToByteArray());
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## AWS CLI
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
export AWS_ACCESS_KEY_ID="$SHELBY_API_KEY"
|
|
101
|
+
export AWS_SECRET_ACCESS_KEY="$SHELBY_API_KEY"
|
|
102
|
+
|
|
103
|
+
aws s3 ls "s3://{{BUCKET}}/" --endpoint-url {{S3_ENDPOINT}}
|
|
104
|
+
aws s3 cp ./my-file.txt "s3://{{BUCKET}}/my-file.txt" --endpoint-url {{S3_ENDPOINT}}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Full documentation: https://docs.shelby.xyz/
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { FastMCP } from "fastmcp";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { config } from "./config.js";
|
|
5
|
+
import { registerTools } from "./tools/index.js";
|
|
6
|
+
async function main() {
|
|
7
|
+
const server = new FastMCP({
|
|
8
|
+
name: config.server.name,
|
|
9
|
+
version: config.server.version,
|
|
10
|
+
});
|
|
11
|
+
registerTools(server);
|
|
12
|
+
server.addTool({
|
|
13
|
+
name: "get_mcp_version",
|
|
14
|
+
description: "Returns the version of the MCP server",
|
|
15
|
+
parameters: z.object({}),
|
|
16
|
+
execute: async () => ({
|
|
17
|
+
type: "text",
|
|
18
|
+
text: config.server.version,
|
|
19
|
+
}),
|
|
20
|
+
});
|
|
21
|
+
try {
|
|
22
|
+
await server.start({ transportType: "stdio" });
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
console.error("Error starting server:", error);
|
|
26
|
+
process.exit(1);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
main();
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { config } from "../config.js";
|
|
2
|
+
import { explainAgentKeyRejection } from "../utils/errors.js";
|
|
3
|
+
import { agentKeyHeaders } from "./agentKey.js";
|
|
4
|
+
/**
|
|
5
|
+
* Client for the S3 gateway admin plane (`/s3/admin`), which provisions the
|
|
6
|
+
* Managed Shelby Account (custodied keypair + fee payer) behind a bucket app.
|
|
7
|
+
*/
|
|
8
|
+
export class ShelbyAccount {
|
|
9
|
+
headers = agentKeyHeaders();
|
|
10
|
+
async createAccount(scope, name) {
|
|
11
|
+
return this.request("POST", scope, "createAccount", {
|
|
12
|
+
name,
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
async getAccount(scope) {
|
|
16
|
+
return this.request("GET", scope, "getAccount");
|
|
17
|
+
}
|
|
18
|
+
/** Soft-deletes the account. A 404 counts as success so retries are safe. */
|
|
19
|
+
async deleteAccount(scope) {
|
|
20
|
+
await this.request("DELETE", scope, "deleteAccount", undefined, {
|
|
21
|
+
treat404AsSuccess: true,
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
async request(method, scope, label, body, { treat404AsSuccess = false } = {}) {
|
|
25
|
+
const res = await fetch(`${config.shelby.s3AdminUrl}/account`, {
|
|
26
|
+
method,
|
|
27
|
+
headers: {
|
|
28
|
+
...this.headers,
|
|
29
|
+
"Content-Type": "application/json",
|
|
30
|
+
"x-jwt-organization-id": scope.organization_id,
|
|
31
|
+
"x-jwt-project-id": scope.project_id,
|
|
32
|
+
"x-jwt-application-id": scope.application_id,
|
|
33
|
+
},
|
|
34
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
35
|
+
});
|
|
36
|
+
if (res.status === 404) {
|
|
37
|
+
if (treat404AsSuccess)
|
|
38
|
+
return undefined;
|
|
39
|
+
throw new Error(`S3 gateway admin ${label}: not found`);
|
|
40
|
+
}
|
|
41
|
+
if (!res.ok) {
|
|
42
|
+
const text = await res.text().catch(() => "");
|
|
43
|
+
throw new Error(explainAgentKeyRejection(res.status, text) ??
|
|
44
|
+
`S3 gateway admin ${label} failed (${res.status}): ${text}`);
|
|
45
|
+
}
|
|
46
|
+
if (res.status === 204)
|
|
47
|
+
return undefined;
|
|
48
|
+
return (await res.json());
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createAdminApiClient, } from "@aptos-labs/api-gateway-admin-api-client";
|
|
2
|
+
import { config } from "../config.js";
|
|
3
|
+
import { explainAgentKeyRejection, formatError } from "../utils/errors.js";
|
|
4
|
+
import { agentKeyHeaders } from "./agentKey.js";
|
|
5
|
+
function describe(error) {
|
|
6
|
+
const message = formatError(error);
|
|
7
|
+
return explainAgentKeyRejection(0, message) ?? message;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Client for the Shelby API Gateway admin API (RSPC). A bucket is an
|
|
11
|
+
* application with service type "S3Gateway".
|
|
12
|
+
*/
|
|
13
|
+
export class ShelbyAdmin {
|
|
14
|
+
headers = agentKeyHeaders();
|
|
15
|
+
/** What the key reaches. `scope` is null for an unscoped (legacy) bot key. */
|
|
16
|
+
async getBotApiKeySelf() {
|
|
17
|
+
try {
|
|
18
|
+
return await this.createApiClient().query(["getBotApiKeySelf"]);
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
throw new Error(`Failed to read the agent key: ${describe(error)}`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** Only unscoped (legacy) bot keys may call this. */
|
|
25
|
+
async getOrganizationsRecursively() {
|
|
26
|
+
try {
|
|
27
|
+
return await this.createApiClient().query([
|
|
28
|
+
"getOrganizationsRecursively",
|
|
29
|
+
]);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
throw new Error(`Failed to get organizations: ${describe(error)}`);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async createBucketApplication({ name, organization_id, project_id, }) {
|
|
36
|
+
try {
|
|
37
|
+
return await this.createApiClient({
|
|
38
|
+
organization_id,
|
|
39
|
+
project_id,
|
|
40
|
+
}).mutation([
|
|
41
|
+
"createApplicationV2",
|
|
42
|
+
{
|
|
43
|
+
name,
|
|
44
|
+
network: config.shelby.network,
|
|
45
|
+
description: null,
|
|
46
|
+
service_type: config.shelby.serviceType,
|
|
47
|
+
},
|
|
48
|
+
]);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
throw new Error(`Failed to create application: ${describe(error)}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/** Only unscoped (legacy) bot keys may call this; agent keys can't make keys. */
|
|
55
|
+
async createApiKey({ name, ...scope }) {
|
|
56
|
+
try {
|
|
57
|
+
return await this.createApiClient(scope).mutation([
|
|
58
|
+
"createApiKeyV2",
|
|
59
|
+
{ name, frontend_args: null },
|
|
60
|
+
]);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
throw new Error(`Failed to create api key: ${describe(error)}`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async setApplicationName({ new_name, ...scope }) {
|
|
67
|
+
try {
|
|
68
|
+
await this.createApiClient(scope).mutation([
|
|
69
|
+
"setApplicationNameV2",
|
|
70
|
+
{ new_application_name: new_name },
|
|
71
|
+
]);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
throw new Error(`Failed to rename application: ${describe(error)}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async deleteApplication(scope) {
|
|
78
|
+
try {
|
|
79
|
+
await this.createApiClient(scope).mutation([
|
|
80
|
+
"deleteApplicationV2",
|
|
81
|
+
{ _dummy: "" },
|
|
82
|
+
]);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
throw new Error(`Failed to delete application: ${describe(error)}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
createApiClient(scope = {}) {
|
|
89
|
+
const scopeHeaders = {
|
|
90
|
+
"x-jwt-organization-id": scope.organization_id,
|
|
91
|
+
"x-jwt-project-id": scope.project_id,
|
|
92
|
+
"x-jwt-application-id": scope.application_id,
|
|
93
|
+
};
|
|
94
|
+
return createAdminApiClient({
|
|
95
|
+
apiUrl: config.shelby.adminUrl,
|
|
96
|
+
customFetch: async (input, init) => {
|
|
97
|
+
const headers = new Headers(init?.headers);
|
|
98
|
+
for (const [key, value] of Object.entries(this.headers)) {
|
|
99
|
+
headers.set(key, value);
|
|
100
|
+
}
|
|
101
|
+
for (const [key, value] of Object.entries(scopeHeaders)) {
|
|
102
|
+
if (value)
|
|
103
|
+
headers.set(key, value);
|
|
104
|
+
}
|
|
105
|
+
return fetch(input, { ...init, headers });
|
|
106
|
+
},
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { createReadStream, createWriteStream } from "node:fs";
|
|
3
|
+
import { rename, stat, unlink } from "node:fs/promises";
|
|
4
|
+
import { basename, dirname, join } from "node:path";
|
|
5
|
+
import { Readable } from "node:stream";
|
|
6
|
+
import { pipeline } from "node:stream/promises";
|
|
7
|
+
import { config } from "../config.js";
|
|
8
|
+
import { explainAgentKeyRejection } from "../utils/errors.js";
|
|
9
|
+
import { agentKeyHeaders } from "./agentKey.js";
|
|
10
|
+
/** Comfortably under the gateway's default 32 MiB request limit. */
|
|
11
|
+
export const DEFAULT_PART_SIZE = 16 * 1024 * 1024;
|
|
12
|
+
function decodeXml(value) {
|
|
13
|
+
return value
|
|
14
|
+
.replaceAll("<", "<")
|
|
15
|
+
.replaceAll(">", ">")
|
|
16
|
+
.replaceAll(""", '"')
|
|
17
|
+
.replaceAll("'", "'")
|
|
18
|
+
.replaceAll("&", "&");
|
|
19
|
+
}
|
|
20
|
+
function encodeXml(value) {
|
|
21
|
+
return value
|
|
22
|
+
.replaceAll("&", "&")
|
|
23
|
+
.replaceAll("<", "<")
|
|
24
|
+
.replaceAll(">", ">");
|
|
25
|
+
}
|
|
26
|
+
function tagValues(xml, tag) {
|
|
27
|
+
return [
|
|
28
|
+
...xml.matchAll(new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`, "g")),
|
|
29
|
+
].map((match) => decodeXml(match[1]));
|
|
30
|
+
}
|
|
31
|
+
function tagValue(xml, tag) {
|
|
32
|
+
return tagValues(xml, tag)[0];
|
|
33
|
+
}
|
|
34
|
+
function encodeKey(key) {
|
|
35
|
+
const segments = key.split("/");
|
|
36
|
+
// URL parsing collapses "." and ".." segments, even percent-encoded, so the request
|
|
37
|
+
// would reach a different key.
|
|
38
|
+
if (segments.some((segment) => segment === "." || segment === "..")) {
|
|
39
|
+
throw new Error(`Object key "${key}" can't be used: keys with "." or ".." path segments aren't supported.`);
|
|
40
|
+
}
|
|
41
|
+
return segments.map(encodeURIComponent).join("/");
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Reads and writes objects through the S3 data plane with the agent key. The
|
|
45
|
+
* gateway checks the key's scope and permission against the application in
|
|
46
|
+
* `x-jwt-application-id`, and the S3 gateway checks the bucket belongs to it.
|
|
47
|
+
*/
|
|
48
|
+
export class ShelbyObjects {
|
|
49
|
+
endpoint;
|
|
50
|
+
headers;
|
|
51
|
+
partSize;
|
|
52
|
+
constructor(options = {}) {
|
|
53
|
+
this.endpoint = options.endpoint ?? config.shelby.s3EndpointUrl;
|
|
54
|
+
this.headers = options.headers ?? agentKeyHeaders();
|
|
55
|
+
this.partSize = options.partSize ?? DEFAULT_PART_SIZE;
|
|
56
|
+
}
|
|
57
|
+
async list(target, { prefix, delimiter, continuationToken, maxKeys, } = {}) {
|
|
58
|
+
const query = new URLSearchParams({ "list-type": "2" });
|
|
59
|
+
if (prefix)
|
|
60
|
+
query.set("prefix", prefix);
|
|
61
|
+
if (delimiter)
|
|
62
|
+
query.set("delimiter", delimiter);
|
|
63
|
+
if (continuationToken)
|
|
64
|
+
query.set("continuation-token", continuationToken);
|
|
65
|
+
if (maxKeys)
|
|
66
|
+
query.set("max-keys", String(maxKeys));
|
|
67
|
+
const res = await this.send(target, "GET", "", query);
|
|
68
|
+
const xml = await res.text();
|
|
69
|
+
return {
|
|
70
|
+
objects: tagValues(xml, "Contents").map((contents) => ({
|
|
71
|
+
key: tagValue(contents, "Key") ?? "",
|
|
72
|
+
size: Number(tagValue(contents, "Size") ?? 0),
|
|
73
|
+
last_modified: tagValue(contents, "LastModified") ?? "",
|
|
74
|
+
})),
|
|
75
|
+
common_prefixes: tagValues(xml, "CommonPrefixes").flatMap((p) => tagValues(p, "Prefix")),
|
|
76
|
+
is_truncated: tagValue(xml, "IsTruncated") === "true",
|
|
77
|
+
next_continuation_token: tagValue(xml, "NextContinuationToken"),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
async upload(target, key, filePath, contentType = "application/octet-stream") {
|
|
81
|
+
const { size } = await stat(filePath);
|
|
82
|
+
if (size <= this.partSize) {
|
|
83
|
+
await this.send(target, "PUT", key, undefined, {
|
|
84
|
+
body: this.fileBody(filePath, 0, size),
|
|
85
|
+
headers: {
|
|
86
|
+
"Content-Type": contentType,
|
|
87
|
+
"Content-Length": String(size),
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
return { key, size, parts: 1 };
|
|
91
|
+
}
|
|
92
|
+
const created = await this.send(target, "POST", key, "uploads", {
|
|
93
|
+
headers: { "Content-Type": contentType },
|
|
94
|
+
});
|
|
95
|
+
const uploadId = tagValue(await created.text(), "UploadId");
|
|
96
|
+
if (!uploadId)
|
|
97
|
+
throw new Error("The S3 gateway didn't return an UploadId");
|
|
98
|
+
try {
|
|
99
|
+
const etags = [];
|
|
100
|
+
for (let start = 0; start < size; start += this.partSize) {
|
|
101
|
+
const end = Math.min(start + this.partSize, size);
|
|
102
|
+
const res = await this.send(target, "PUT", key, new URLSearchParams({
|
|
103
|
+
partNumber: String(etags.length + 1),
|
|
104
|
+
uploadId,
|
|
105
|
+
}), {
|
|
106
|
+
body: this.fileBody(filePath, start, end),
|
|
107
|
+
headers: { "Content-Length": String(end - start) },
|
|
108
|
+
});
|
|
109
|
+
const etag = res.headers.get("etag");
|
|
110
|
+
if (!etag)
|
|
111
|
+
throw new Error("The S3 gateway didn't return a part ETag");
|
|
112
|
+
etags.push(etag);
|
|
113
|
+
}
|
|
114
|
+
const parts = etags
|
|
115
|
+
.map((etag, i) => `<Part><PartNumber>${i + 1}</PartNumber><ETag>${encodeXml(etag)}</ETag></Part>`)
|
|
116
|
+
.join("");
|
|
117
|
+
await this.send(target, "POST", key, new URLSearchParams({ uploadId }), {
|
|
118
|
+
body: `<CompleteMultipartUpload>${parts}</CompleteMultipartUpload>`,
|
|
119
|
+
headers: { "Content-Type": "application/xml" },
|
|
120
|
+
});
|
|
121
|
+
return { key, size, parts: etags.length };
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
await this.send(target, "DELETE", key, new URLSearchParams({ uploadId })).catch(() => undefined);
|
|
125
|
+
throw error;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Writes to a temporary file next to `destPath`, then renames it into place. */
|
|
129
|
+
async download(target, key, destPath) {
|
|
130
|
+
const res = await this.send(target, "GET", key);
|
|
131
|
+
if (!res.body)
|
|
132
|
+
throw new Error("The S3 gateway returned no body");
|
|
133
|
+
const temp = join(dirname(destPath), `.${basename(destPath)}.shelby-${randomBytes(6).toString("hex")}`);
|
|
134
|
+
try {
|
|
135
|
+
await pipeline(Readable.fromWeb(res.body), createWriteStream(temp, { flags: "wx" }));
|
|
136
|
+
await rename(temp, destPath);
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
await unlink(temp).catch(() => undefined);
|
|
140
|
+
throw error;
|
|
141
|
+
}
|
|
142
|
+
return { key, size: (await stat(destPath)).size };
|
|
143
|
+
}
|
|
144
|
+
fileBody(filePath, start, end) {
|
|
145
|
+
if (end === start)
|
|
146
|
+
return "";
|
|
147
|
+
return Readable.toWeb(createReadStream(filePath, { start, end: end - 1 }));
|
|
148
|
+
}
|
|
149
|
+
async send(target, method, key, query, { body, headers, } = {}) {
|
|
150
|
+
const path = key ? `/${encodeKey(key)}` : "";
|
|
151
|
+
const search = query ? `?${query.toString()}` : "";
|
|
152
|
+
const res = await fetch(`${this.endpoint}/${target.bucketAddress}${path}${search}`, {
|
|
153
|
+
method,
|
|
154
|
+
headers: {
|
|
155
|
+
...this.headers,
|
|
156
|
+
"x-jwt-application-id": target.applicationId,
|
|
157
|
+
...headers,
|
|
158
|
+
},
|
|
159
|
+
body,
|
|
160
|
+
// Required by fetch for a streamed request body.
|
|
161
|
+
duplex: body instanceof ReadableStream ? "half" : undefined,
|
|
162
|
+
});
|
|
163
|
+
if (res.ok)
|
|
164
|
+
return res;
|
|
165
|
+
const text = await res.text().catch(() => "");
|
|
166
|
+
const code = tagValue(text, "Code");
|
|
167
|
+
const message = tagValue(text, "Message") ?? text;
|
|
168
|
+
throw new Error(explainAgentKeyRejection(res.status, text) ??
|
|
169
|
+
`${method} ${key || target.bucketAddress} failed (${res.status})${code ? ` ${code}` : ""}: ${message}`);
|
|
170
|
+
}
|
|
171
|
+
}
|