easytopaste-mcp 0.0.0-stage → 0.1.0
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/LICENSE.md +21 -0
- package/README.md +96 -3
- package/bin/easytopaste-mcp.js +16 -0
- package/package.json +39 -6
- package/src/api.js +169 -0
- package/src/server.js +162 -0
- package/src/tools.js +167 -0
- package/src/vendor/crypto.js +328 -0
- package/src/vendor/link.js +115 -0
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 EasyToPaste
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,96 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# EasyToPaste MCP server
|
|
2
|
+
|
|
3
|
+
Hand a credential to a human **without putting it in the chat log**.
|
|
4
|
+
|
|
5
|
+
> **Not on npm yet.** `npx -y easytopaste-mcp` resolves the day the package is
|
|
6
|
+
> published; publishing is the owner's call and is pending. Until then, install
|
|
7
|
+
> from source — clone this repository and point the `command` at
|
|
8
|
+
> `node /path/to/easytopaste-mcp/bin/easytopaste-mcp.js`. Everything below is
|
|
9
|
+
> true of both.
|
|
10
|
+
|
|
11
|
+
```jsonc
|
|
12
|
+
// Claude Desktop: claude_desktop_config.json
|
|
13
|
+
{
|
|
14
|
+
"mcpServers": {
|
|
15
|
+
"easytopaste": {
|
|
16
|
+
"command": "npx",
|
|
17
|
+
"args": ["-y", "easytopaste-mcp"]
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Then, in the conversation:
|
|
24
|
+
|
|
25
|
+
> **agent:** The deploy key is `AKIA…` — I'll send it as a one-time link instead.
|
|
26
|
+
> *(calls `create_secret`)*
|
|
27
|
+
> `https://app.easytopaste.com/s/MFRG…#k=…`
|
|
28
|
+
|
|
29
|
+
## Why this exists
|
|
30
|
+
|
|
31
|
+
An agent that has to pass a password, an API key or a token to a person has
|
|
32
|
+
nowhere safe to put it today, so it pastes it into the conversation — where it
|
|
33
|
+
stays, searchable, for as long as the transcript does, in whatever tool the
|
|
34
|
+
transcript syncs to. A one-time link does not fix that completely. It shrinks
|
|
35
|
+
it to one read and a known expiry, and it moves the value out of the log.
|
|
36
|
+
|
|
37
|
+
## The two tools, and the one that is deliberately missing
|
|
38
|
+
|
|
39
|
+
| tool | what it does |
|
|
40
|
+
| --- | --- |
|
|
41
|
+
| `create_secret` | encrypts a text here and returns a one-time link |
|
|
42
|
+
| `get_secret_status` | says whether a link is still live — status, expiry, size |
|
|
43
|
+
|
|
44
|
+
There is **no tool that reads a secret back**. That is the design, not an
|
|
45
|
+
omission: a read tool would put the plaintext into the transcript the
|
|
46
|
+
credential was being taken out of. `get_secret_status` never returns content,
|
|
47
|
+
and the server could not decrypt it if it tried — it does not have the key.
|
|
48
|
+
|
|
49
|
+
## What leaves this process
|
|
50
|
+
|
|
51
|
+
The text is encrypted here with AES-256-GCM and a fresh 32-byte key. **Only
|
|
52
|
+
ciphertext is sent.** The key goes into the link's URL fragment — the part
|
|
53
|
+
after the `#`, which no HTTP client transmits — so the service stores a blob
|
|
54
|
+
it cannot read.
|
|
55
|
+
|
|
56
|
+
The request carries the ciphertext, its size, the expiry and the one-time
|
|
57
|
+
flag, and nothing else: no plaintext, no key, no conversation, no model name,
|
|
58
|
+
no telemetry. `test/server.test.js` asserts the arguments handed to the API client
|
|
59
|
+
field by field, including that the plaintext does not appear in them —
|
|
60
|
+
one layer above the HTTP body, which `src/api.js` builds. The property
|
|
61
|
+
holds on the wire; the test watches the layer above it.
|
|
62
|
+
|
|
63
|
+
Being precise about the rest, because a request is never only its body: the
|
|
64
|
+
service sees what any server sees — your machine's outgoing IP address, which
|
|
65
|
+
is what the daily anonymous allowance is counted against — and a `User-Agent`
|
|
66
|
+
of `easytopaste-mcp/<version>`.
|
|
67
|
+
|
|
68
|
+
## The limit you will meet first
|
|
69
|
+
|
|
70
|
+
There is no long-lived API key for machines yet. Anonymous callers share a
|
|
71
|
+
daily allowance of **10 creates per outgoing IP address**, and an office, a VPN
|
|
72
|
+
or a hosted agent platform can be one address for everybody on it. When it is
|
|
73
|
+
gone, `create_secret` answers `quota_exceeded` and says so in words rather than
|
|
74
|
+
failing silently. Set `EASYTOPASTE_TOKEN` if you have a bearer token from an
|
|
75
|
+
earlier step; access tokens last 15 minutes, which is why there is no way to
|
|
76
|
+
configure a permanent one.
|
|
77
|
+
|
|
78
|
+
## Configuration
|
|
79
|
+
|
|
80
|
+
| variable | default | meaning |
|
|
81
|
+
| --- | --- | --- |
|
|
82
|
+
| `EASYTOPASTE_TOKEN` | *(empty)* | optional bearer access token |
|
|
83
|
+
| `EASYTOPASTE_API_BASE` | `https://api.easytopaste.com` | override for self-hosting |
|
|
84
|
+
| `EASYTOPASTE_APP_BASE` | `https://app.easytopaste.com` | origin used to build links |
|
|
85
|
+
| `EASYTOPASTE_CHANNEL` | *(empty)* | where this copy was installed from, reported in the User-Agent |
|
|
86
|
+
|
|
87
|
+
## No dependencies
|
|
88
|
+
|
|
89
|
+
The protocol is JSON-RPC 2.0 over line-delimited stdio, and the whole server
|
|
90
|
+
is readable in one sitting. This installs into an agent that is already
|
|
91
|
+
holding your credentials; every dependency would be one more thing you have to
|
|
92
|
+
trust on our word.
|
|
93
|
+
|
|
94
|
+
What it is: <https://easytopaste.com/?utm_source=mcp&utm_medium=server&utm_campaign=launch-2026-11>
|
|
95
|
+
· how the encryption works: <https://easytopaste.com/how-it-works/?utm_source=mcp&utm_medium=server&utm_campaign=launch-2026-11>
|
|
96
|
+
· the same thing from a terminal: `npm i -g easytopaste`
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Entry point. Keep this file boring: the protocol forbids anything on stdout
|
|
4
|
+
* that is not a JSON-RPC message, so there is no banner, no version line and
|
|
5
|
+
* no "listening" notice here. Diagnostics go to stderr.
|
|
6
|
+
*/
|
|
7
|
+
import { readFileSync } from 'node:fs';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
import { dirname, join } from 'node:path';
|
|
10
|
+
|
|
11
|
+
import { serve } from '../src/server.js';
|
|
12
|
+
|
|
13
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
14
|
+
const pkg = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8'));
|
|
15
|
+
|
|
16
|
+
serve({ version: pkg.version });
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "easytopaste-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "easytopaste-mcp",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "MCP server for EasyToPaste \u2014 hand a credential to a human as a one-time, client-encrypted link instead of pasting it into the chat",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mcp",
|
|
7
|
+
"modelcontextprotocol",
|
|
8
|
+
"secrets",
|
|
9
|
+
"one-time",
|
|
10
|
+
"encryption",
|
|
11
|
+
"zero-knowledge"
|
|
12
|
+
],
|
|
13
|
+
"homepage": "https://easytopaste.com/?utm_source=mcp&utm_medium=server&utm_campaign=launch-2026-11",
|
|
14
|
+
"bugs": {
|
|
15
|
+
"email": "support@easytopaste.com"
|
|
16
|
+
},
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"type": "module",
|
|
19
|
+
"bin": {
|
|
20
|
+
"easytopaste-mcp": "bin/easytopaste-mcp.js"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"bin",
|
|
24
|
+
"src",
|
|
25
|
+
"README.md",
|
|
26
|
+
"LICENSE.md"
|
|
27
|
+
],
|
|
28
|
+
"engines": {
|
|
29
|
+
"node": ">=20"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"test": "node --test test/"
|
|
33
|
+
},
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "https://github.com/Nemet360/easytopaste-mcp"
|
|
37
|
+
},
|
|
38
|
+
"mcpName": "io.github.nemet360/easytopaste"
|
|
39
|
+
}
|
package/src/api.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP half of the MCP server: two calls against the public secrets API.
|
|
3
|
+
*
|
|
4
|
+
* Adapted from the CLI's `src/api.js`, and the differences are deliberate and
|
|
5
|
+
* small — the User-Agent prefix, and `retrieveStatus`, which throws away the
|
|
6
|
+
* envelope the API returns. `vendor/crypto.js` and `vendor/link.js` are
|
|
7
|
+
* byte-identical copies of the CLI's, so a link made by an agent opens in the
|
|
8
|
+
* browser and in the terminal.
|
|
9
|
+
*
|
|
10
|
+
* What this module is allowed to send matters as much as what it does send.
|
|
11
|
+
* It posts ciphertext and metadata, and nothing else: no plaintext, no key, no
|
|
12
|
+
* conversation, no model name, no telemetry. An MCP server sits inside an
|
|
13
|
+
* agent's context, which is the most tempting place in this product to leak
|
|
14
|
+
* something by accident, so the arguments are asserted field-by-field in
|
|
15
|
+
* test/server.test.js rather than trusted. The body itself is built below;
|
|
16
|
+
* an acceptance reviewer confirmed it on the wire, and nothing watches it yet.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { DEFAULT_API_BASE } from './vendor/link.js';
|
|
20
|
+
|
|
21
|
+
const USER_AGENT_PREFIX = 'easytopaste-mcp';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Which host installed this server, if the installer said so.
|
|
25
|
+
*
|
|
26
|
+
* Same reasoning as the CLI's: a `utm` tag measures a click on a link, and an
|
|
27
|
+
* agent that creates a secret never loads a page. The MCP directories set
|
|
28
|
+
* EASYTOPASTE_CHANNEL so a Smithery install is distinguishable from a manual
|
|
29
|
+
* one. Sanitised rather than trusted: the value comes from the environment and
|
|
30
|
+
* goes into a header, where a stray newline is a request-splitting bug.
|
|
31
|
+
*/
|
|
32
|
+
export function channelTag(env = process.env) {
|
|
33
|
+
const raw = String(env.EASYTOPASTE_CHANNEL ?? '').trim().toLowerCase();
|
|
34
|
+
return raw.replace(/[^a-z0-9-]/g, '').slice(0, 16);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `easytopaste-mcp/0.1.0` or `easytopaste-mcp/0.1.0 (smithery)`. */
|
|
38
|
+
export function userAgent(version, env = process.env) {
|
|
39
|
+
const channel = channelTag(env);
|
|
40
|
+
return channel
|
|
41
|
+
? `${USER_AGENT_PREFIX}/${version} (${channel})`
|
|
42
|
+
: `${USER_AGENT_PREFIX}/${version}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export class ApiError extends Error {
|
|
46
|
+
constructor(message, info = {}) {
|
|
47
|
+
super(message);
|
|
48
|
+
this.name = 'ApiError';
|
|
49
|
+
this.code = info.code ?? 'unknown';
|
|
50
|
+
this.status = info.status ?? 0;
|
|
51
|
+
this.requestId = info.requestId ?? null;
|
|
52
|
+
this.retryAfter = info.retryAfter ?? null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export class NetworkError extends Error {
|
|
57
|
+
constructor(message, cause) {
|
|
58
|
+
super(message);
|
|
59
|
+
this.name = 'NetworkError';
|
|
60
|
+
this.code = 'network';
|
|
61
|
+
this.cause = cause;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export class ApiClient {
|
|
66
|
+
constructor({
|
|
67
|
+
baseUrl = DEFAULT_API_BASE,
|
|
68
|
+
version = '0.0.0',
|
|
69
|
+
token = '',
|
|
70
|
+
timeoutMs = 15000,
|
|
71
|
+
fetchImpl = globalThis.fetch,
|
|
72
|
+
env = process.env,
|
|
73
|
+
} = {}) {
|
|
74
|
+
this.baseUrl = String(baseUrl).replace(/\/+$/, '');
|
|
75
|
+
this.version = version;
|
|
76
|
+
this.token = token;
|
|
77
|
+
this.timeoutMs = timeoutMs;
|
|
78
|
+
this.fetchImpl = fetchImpl;
|
|
79
|
+
this.env = env;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** POST /v1/secrets — the create body, identical in shape to the CLI's. */
|
|
83
|
+
async createSecret({ ciphertextB64, sizeBytes, oneTime, expiresInDays }) {
|
|
84
|
+
const body = {
|
|
85
|
+
type: 'text',
|
|
86
|
+
mode: 'link',
|
|
87
|
+
envelopeVersion: 1,
|
|
88
|
+
sizeBytes,
|
|
89
|
+
oneTime,
|
|
90
|
+
expiresInDays,
|
|
91
|
+
requiresRecipientLogin: false,
|
|
92
|
+
mimeHint: 'text/plain',
|
|
93
|
+
ciphertext: ciphertextB64,
|
|
94
|
+
};
|
|
95
|
+
const json = await this.#request('POST', '/v1/secrets', body);
|
|
96
|
+
if (!json || typeof json.locator !== 'string') {
|
|
97
|
+
throw new ApiError('the API accepted the secret but returned no locator');
|
|
98
|
+
}
|
|
99
|
+
return json;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* GET /v1/secrets/{locator}, reduced to status.
|
|
104
|
+
*
|
|
105
|
+
* The endpoint returns the envelope alongside the metadata. An agent asking
|
|
106
|
+
* "is it still there" must not receive ciphertext it did not ask for and
|
|
107
|
+
* cannot read — it would end up in a transcript, which is the exact place
|
|
108
|
+
* this product exists to keep secrets out of. So the envelope is dropped
|
|
109
|
+
* here, in the one function that sees it, rather than filtered later.
|
|
110
|
+
*
|
|
111
|
+
* It does NOT burn: that is POST /burn, which this server does not call.
|
|
112
|
+
*/
|
|
113
|
+
async retrieveStatus(locator) {
|
|
114
|
+
const json = await this.#request(
|
|
115
|
+
'GET', `/v1/secrets/${encodeURIComponent(locator)}`,
|
|
116
|
+
) ?? {};
|
|
117
|
+
return {
|
|
118
|
+
locator: json.locator ?? locator,
|
|
119
|
+
status: json.status ?? 'unknown',
|
|
120
|
+
oneTime: json.oneTime ?? null,
|
|
121
|
+
expiresAt: json.expiresAt ?? null,
|
|
122
|
+
sizeBytes: json.sizeBytes ?? null,
|
|
123
|
+
createdAt: json.createdAt ?? null,
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async #request(method, path, body) {
|
|
128
|
+
const headers = {
|
|
129
|
+
accept: 'application/json',
|
|
130
|
+
'user-agent': userAgent(this.version, this.env),
|
|
131
|
+
};
|
|
132
|
+
if (body !== undefined) headers['content-type'] = 'application/json';
|
|
133
|
+
if (this.token) headers.authorization = `Bearer ${this.token}`;
|
|
134
|
+
|
|
135
|
+
const controller = new AbortController();
|
|
136
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
137
|
+
let response;
|
|
138
|
+
try {
|
|
139
|
+
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
140
|
+
method,
|
|
141
|
+
headers,
|
|
142
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
143
|
+
signal: controller.signal,
|
|
144
|
+
});
|
|
145
|
+
} catch (cause) {
|
|
146
|
+
throw new NetworkError(`could not reach ${this.baseUrl}: ${cause?.message ?? cause}`, cause);
|
|
147
|
+
} finally {
|
|
148
|
+
clearTimeout(timer);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
let json = null;
|
|
152
|
+
try {
|
|
153
|
+
json = await response.json();
|
|
154
|
+
} catch {
|
|
155
|
+
json = null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (!response.ok) {
|
|
159
|
+
const err = json?.error ?? {};
|
|
160
|
+
throw new ApiError(err.message || `the API answered ${response.status}`, {
|
|
161
|
+
code: err.code,
|
|
162
|
+
status: response.status,
|
|
163
|
+
requestId: err.request_id ?? err.requestId,
|
|
164
|
+
retryAfter: response.headers?.get?.('retry-after') ?? null,
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return json;
|
|
168
|
+
}
|
|
169
|
+
}
|
package/src/server.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP over stdio, JSON-RPC 2.0, with no dependencies.
|
|
3
|
+
*
|
|
4
|
+
* Why no SDK: the same reason the GitHub Action ships its dependencies as
|
|
5
|
+
* committed JavaScript. The protocol this wraps is four methods and a
|
|
6
|
+
* line-delimited JSON framing, the audience installs it with `npx` into an
|
|
7
|
+
* agent that is already holding their credentials, and every dependency is
|
|
8
|
+
* something that audience has to trust on our word. The whole server is
|
|
9
|
+
* readable in one sitting, which is the point.
|
|
10
|
+
*
|
|
11
|
+
* Framing: one JSON object per line on stdin, one per line on stdout.
|
|
12
|
+
* **Nothing else may ever be written to stdout** — a stray `console.log` is
|
|
13
|
+
* not a cosmetic bug here, it is a protocol error that breaks the client's
|
|
14
|
+
* parse. Diagnostics go to stderr, which the host shows in its logs.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { createInterface } from 'node:readline';
|
|
18
|
+
|
|
19
|
+
import { ApiClient, ApiError, NetworkError } from './api.js';
|
|
20
|
+
import {
|
|
21
|
+
TOOLS, ToolError, createSecret, getSecretStatus, describeCreate,
|
|
22
|
+
} from './tools.js';
|
|
23
|
+
import { DEFAULT_API_BASE, DEFAULT_APP_BASE } from './vendor/link.js';
|
|
24
|
+
|
|
25
|
+
export const PROTOCOL_VERSION = '2024-11-05';
|
|
26
|
+
export const SERVER_NAME = 'easytopaste';
|
|
27
|
+
|
|
28
|
+
/** Build the response for one request object. Returns null for a notification. */
|
|
29
|
+
export async function handle(message, ctx) {
|
|
30
|
+
const { id, method, params } = message ?? {};
|
|
31
|
+
const isNotification = id === undefined || id === null;
|
|
32
|
+
|
|
33
|
+
const reply = (result) => (isNotification ? null : { jsonrpc: '2.0', id, result });
|
|
34
|
+
const fail = (code, msg, data) =>
|
|
35
|
+
(isNotification ? null : { jsonrpc: '2.0', id, error: { code, message: msg, ...(data ? { data } : {}) } });
|
|
36
|
+
|
|
37
|
+
switch (method) {
|
|
38
|
+
case 'initialize':
|
|
39
|
+
return reply({
|
|
40
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
41
|
+
capabilities: { tools: { listChanged: false } },
|
|
42
|
+
serverInfo: { name: SERVER_NAME, version: ctx.version },
|
|
43
|
+
instructions:
|
|
44
|
+
'Use create_secret whenever you are about to put a password, an API ' +
|
|
45
|
+
'key or any other credential into the conversation, a file or a ' +
|
|
46
|
+
'ticket. It returns a one-time link you can paste instead. There is ' +
|
|
47
|
+
'no tool that reads a secret back: that would put the value into the ' +
|
|
48
|
+
'transcript, which is what this exists to avoid.',
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
case 'notifications/initialized':
|
|
52
|
+
case 'initialized':
|
|
53
|
+
return null;
|
|
54
|
+
|
|
55
|
+
case 'ping':
|
|
56
|
+
return reply({});
|
|
57
|
+
|
|
58
|
+
case 'tools/list':
|
|
59
|
+
return reply({ tools: TOOLS });
|
|
60
|
+
|
|
61
|
+
case 'tools/call': {
|
|
62
|
+
const name = params?.name;
|
|
63
|
+
const args = params?.arguments ?? {};
|
|
64
|
+
try {
|
|
65
|
+
if (name === 'create_secret') {
|
|
66
|
+
const result = await createSecret({ args, client: ctx.client, appBase: ctx.appBase });
|
|
67
|
+
return reply({
|
|
68
|
+
content: [{ type: 'text', text: describeCreate(result) }],
|
|
69
|
+
structuredContent: result,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
if (name === 'get_secret_status') {
|
|
73
|
+
const result = await getSecretStatus({ args, client: ctx.client });
|
|
74
|
+
return reply({
|
|
75
|
+
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
76
|
+
structuredContent: result,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return fail(-32602, `unknown tool: ${String(name)}`);
|
|
80
|
+
} catch (err) {
|
|
81
|
+
// A tool failure is reported INSIDE the result, not as a JSON-RPC
|
|
82
|
+
// error: the agent is supposed to read it, decide, and try something
|
|
83
|
+
// else. A protocol-level error would just end the call.
|
|
84
|
+
return reply({
|
|
85
|
+
content: [{ type: 'text', text: toolFailureText(err) }],
|
|
86
|
+
isError: true,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
default:
|
|
92
|
+
return fail(-32601, `method not found: ${String(method)}`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function toolFailureText(err) {
|
|
97
|
+
if (err instanceof ToolError) return `${err.code}: ${err.message}`;
|
|
98
|
+
if (err instanceof ApiError) {
|
|
99
|
+
if (err.code === 'quota_exceeded') {
|
|
100
|
+
return (
|
|
101
|
+
'quota_exceeded: this host has used its daily allowance of anonymous ' +
|
|
102
|
+
'secrets. The allowance is counted per outgoing IP address, which ' +
|
|
103
|
+
'several machines can share. It resets at midnight UTC.'
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
if (err.code === 'rate_limited') {
|
|
107
|
+
return `rate_limited: too many requests. Retry after ${err.retryAfter ?? 'a minute'}.`;
|
|
108
|
+
}
|
|
109
|
+
return `${err.code}: ${err.message}`;
|
|
110
|
+
}
|
|
111
|
+
if (err instanceof NetworkError) return `network: ${err.message}`;
|
|
112
|
+
return `unexpected: ${err?.message ?? String(err)}`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Read line-delimited JSON from stdin and answer on stdout. */
|
|
116
|
+
export function serve({
|
|
117
|
+
input = process.stdin,
|
|
118
|
+
output = process.stdout,
|
|
119
|
+
errorOut = process.stderr,
|
|
120
|
+
version = '0.0.0',
|
|
121
|
+
env = process.env,
|
|
122
|
+
} = {}) {
|
|
123
|
+
const client = new ApiClient({
|
|
124
|
+
baseUrl: env.EASYTOPASTE_API_BASE || DEFAULT_API_BASE,
|
|
125
|
+
token: env.EASYTOPASTE_TOKEN || '',
|
|
126
|
+
version,
|
|
127
|
+
env,
|
|
128
|
+
});
|
|
129
|
+
const ctx = { client, version, appBase: env.EASYTOPASTE_APP_BASE || DEFAULT_APP_BASE };
|
|
130
|
+
|
|
131
|
+
const rl = createInterface({ input, crlfDelay: Infinity });
|
|
132
|
+
const write = (obj) => output.write(`${JSON.stringify(obj)}\n`);
|
|
133
|
+
|
|
134
|
+
rl.on('line', (line) => {
|
|
135
|
+
const text = line.trim();
|
|
136
|
+
if (!text) return;
|
|
137
|
+
let message;
|
|
138
|
+
try {
|
|
139
|
+
message = JSON.parse(text);
|
|
140
|
+
} catch {
|
|
141
|
+
write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
// Each line is answered on its own; a slow create must not block a ping.
|
|
145
|
+
handle(message, ctx)
|
|
146
|
+
.then((response) => {
|
|
147
|
+
if (response) write(response);
|
|
148
|
+
})
|
|
149
|
+
.catch((err) => {
|
|
150
|
+
errorOut.write(`easytopaste-mcp: ${err?.stack ?? err}\n`);
|
|
151
|
+
if (message?.id !== undefined && message?.id !== null) {
|
|
152
|
+
write({
|
|
153
|
+
jsonrpc: '2.0',
|
|
154
|
+
id: message.id,
|
|
155
|
+
error: { code: -32603, message: 'internal error' },
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
return rl;
|
|
162
|
+
}
|
package/src/tools.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The two tools this server exposes, and the rules they enforce.
|
|
3
|
+
*
|
|
4
|
+
* The product reason for this server, in one sentence: an agent that has to
|
|
5
|
+
* hand a credential to a human has nowhere safe to put it today, so it pastes
|
|
6
|
+
* it into the chat log — where it stays, searchable, for as long as the log
|
|
7
|
+
* does. A one-time link does not fix that completely; it shrinks it to one
|
|
8
|
+
* read and a known expiry.
|
|
9
|
+
*
|
|
10
|
+
* Which means the dangerous direction here is INWARD, not outward. A tool that
|
|
11
|
+
* returned a secret's plaintext to an agent would put the thing back in the
|
|
12
|
+
* transcript it was taken out of, so there is no read tool. `create_secret`
|
|
13
|
+
* takes plaintext and returns a link; `get_secret_status` returns whether a
|
|
14
|
+
* link is still live and nothing else.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
encryptTextToEnvelope, generateKey, toBase64Url, zeroize, MAX_INLINE_BYTES,
|
|
19
|
+
} from './vendor/crypto.js';
|
|
20
|
+
import { buildLink, DEFAULT_APP_BASE } from './vendor/link.js';
|
|
21
|
+
|
|
22
|
+
export const MAX_DAYS = 30;
|
|
23
|
+
export const MIN_DAYS = 1;
|
|
24
|
+
|
|
25
|
+
export const TOOLS = [
|
|
26
|
+
{
|
|
27
|
+
name: 'create_secret',
|
|
28
|
+
description:
|
|
29
|
+
'Encrypt a short text (a password, an API key, a note) and return a ' +
|
|
30
|
+
'one-time link to it. The text is encrypted here; the key travels only ' +
|
|
31
|
+
'inside the link and is never sent to the service, which stores ' +
|
|
32
|
+
'ciphertext it cannot read. Use this instead of writing a credential ' +
|
|
33
|
+
'into the conversation, a file or a ticket. The link is the secret: ' +
|
|
34
|
+
'anyone holding it can read it once.',
|
|
35
|
+
inputSchema: {
|
|
36
|
+
type: 'object',
|
|
37
|
+
properties: {
|
|
38
|
+
text: {
|
|
39
|
+
type: 'string',
|
|
40
|
+
description: 'The value to share. UTF-8, up to 256 KB.',
|
|
41
|
+
},
|
|
42
|
+
days: {
|
|
43
|
+
type: 'integer',
|
|
44
|
+
minimum: MIN_DAYS,
|
|
45
|
+
maximum: MAX_DAYS,
|
|
46
|
+
default: 1,
|
|
47
|
+
description: 'Whole days until the link expires on its own.',
|
|
48
|
+
},
|
|
49
|
+
one_time: {
|
|
50
|
+
type: 'boolean',
|
|
51
|
+
default: true,
|
|
52
|
+
description:
|
|
53
|
+
'true (default) destroys the secret the first time it is read.',
|
|
54
|
+
},
|
|
55
|
+
},
|
|
56
|
+
required: ['text'],
|
|
57
|
+
additionalProperties: false,
|
|
58
|
+
},
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
name: 'get_secret_status',
|
|
62
|
+
description:
|
|
63
|
+
'Report whether a one-time link is still live, by its locator. Returns ' +
|
|
64
|
+
'status, expiry and size only — never the content, which this server ' +
|
|
65
|
+
'cannot decrypt because it never had the key. Does not read or destroy ' +
|
|
66
|
+
'the secret.',
|
|
67
|
+
inputSchema: {
|
|
68
|
+
type: 'object',
|
|
69
|
+
properties: {
|
|
70
|
+
locator: {
|
|
71
|
+
type: 'string',
|
|
72
|
+
description: 'The secret id, as returned by create_secret.',
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
required: ['locator'],
|
|
76
|
+
additionalProperties: false,
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
export class ToolError extends Error {
|
|
82
|
+
constructor(message, code = 'invalid_input') {
|
|
83
|
+
super(message);
|
|
84
|
+
this.name = 'ToolError';
|
|
85
|
+
this.code = code;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function normaliseDays(value) {
|
|
90
|
+
if (value === undefined || value === null) return 1;
|
|
91
|
+
if (!Number.isInteger(value)) {
|
|
92
|
+
throw new ToolError(`days must be a whole number, got ${JSON.stringify(value)}`);
|
|
93
|
+
}
|
|
94
|
+
if (value < MIN_DAYS || value > MAX_DAYS) {
|
|
95
|
+
throw new ToolError(`days must be between ${MIN_DAYS} and ${MAX_DAYS}, got ${value}`);
|
|
96
|
+
}
|
|
97
|
+
return value;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Encrypt and create. Returns the link, the locator and the expiry.
|
|
102
|
+
*
|
|
103
|
+
* The key is zeroized after the link is built. It is a best-effort gesture in
|
|
104
|
+
* a garbage-collected runtime and is done anyway, for the same reason the CLI
|
|
105
|
+
* does it: the window in which a key sits in a long-lived agent process is
|
|
106
|
+
* longer than the window in which it sits in a command that exits.
|
|
107
|
+
*/
|
|
108
|
+
export async function createSecret({ args, client, appBase = DEFAULT_APP_BASE }) {
|
|
109
|
+
const text = args?.text;
|
|
110
|
+
if (typeof text !== 'string' || text.length === 0) {
|
|
111
|
+
throw new ToolError('text is required and must be a non-empty string');
|
|
112
|
+
}
|
|
113
|
+
const bytes = new TextEncoder().encode(text).length;
|
|
114
|
+
if (bytes > MAX_INLINE_BYTES) {
|
|
115
|
+
throw new ToolError(
|
|
116
|
+
`text is ${bytes} bytes; this server takes up to ${MAX_INLINE_BYTES}. ` +
|
|
117
|
+
'A file that size belongs in the web app, which uploads it in chunks.',
|
|
118
|
+
'too_large',
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
const days = normaliseDays(args?.days);
|
|
122
|
+
const oneTime = args?.one_time === undefined ? true : Boolean(args.one_time);
|
|
123
|
+
|
|
124
|
+
const key = generateKey();
|
|
125
|
+
try {
|
|
126
|
+
const envelope = await encryptTextToEnvelope(text, key);
|
|
127
|
+
const created = await client.createSecret({
|
|
128
|
+
ciphertextB64: toBase64Url(envelope),
|
|
129
|
+
sizeBytes: bytes,
|
|
130
|
+
oneTime,
|
|
131
|
+
expiresInDays: days,
|
|
132
|
+
});
|
|
133
|
+
const link = buildLink({ locator: created.locator, key, appBase });
|
|
134
|
+
return {
|
|
135
|
+
link,
|
|
136
|
+
locator: created.locator,
|
|
137
|
+
one_time: oneTime,
|
|
138
|
+
expires_at: created.expiresAt ?? null,
|
|
139
|
+
size_bytes: bytes,
|
|
140
|
+
};
|
|
141
|
+
} finally {
|
|
142
|
+
zeroize(key);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export async function getSecretStatus({ args, client }) {
|
|
147
|
+
const locator = args?.locator;
|
|
148
|
+
if (typeof locator !== 'string' || locator.trim() === '') {
|
|
149
|
+
throw new ToolError('locator is required and must be a non-empty string');
|
|
150
|
+
}
|
|
151
|
+
return client.retrieveStatus(locator.trim());
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** What the agent is told, in words, after a successful create. */
|
|
155
|
+
export function describeCreate(result) {
|
|
156
|
+
const life = result.one_time
|
|
157
|
+
? 'It dies the first time it is read'
|
|
158
|
+
: 'It stays readable until it expires';
|
|
159
|
+
const until = result.expires_at ? `, and expires at ${result.expires_at}` : '';
|
|
160
|
+
return (
|
|
161
|
+
`${result.link}\n\n${life}${until}. Give this link to the person who needs ` +
|
|
162
|
+
'the value, through whatever channel you would have used anyway — the ' +
|
|
163
|
+
'link is the secret, so treat it as one. The service cannot read the ' +
|
|
164
|
+
'content: the key is in the part of the URL after the # and was never ' +
|
|
165
|
+
`sent to it. Locator: ${result.locator}`
|
|
166
|
+
);
|
|
167
|
+
}
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-side cryptography for the EasyToPaste clients.
|
|
3
|
+
*
|
|
4
|
+
* This file is the non-browser half of a contract the browser client already
|
|
5
|
+
* implements (frontend/src/app/crypto/crypto.utils.ts and
|
|
6
|
+
* frontend/src/app/components/create-secret/create-secret.component.ts).
|
|
7
|
+
* A secret created here must open in the web app, and a secret created in the
|
|
8
|
+
* web app must open here, so every constant below is a copy of a decision made
|
|
9
|
+
* there — not a new one:
|
|
10
|
+
*
|
|
11
|
+
* - AES-256-GCM, 96-bit IV, 128-bit tag, no additional authenticated data.
|
|
12
|
+
* - A fresh 32-byte key per secret, generated locally and never transmitted.
|
|
13
|
+
* - Inline text envelope byte layout: [iv 12][tag 16][ciphertext N].
|
|
14
|
+
* - The envelope travels base64url (RFC 4648 §5, no padding).
|
|
15
|
+
*
|
|
16
|
+
* test/compat.test.js re-reads those two frontend files and fails if the
|
|
17
|
+
* numbers drift apart, because a silent drift means every link this CLI prints
|
|
18
|
+
* is undecryptable in a browser and nothing else would notice.
|
|
19
|
+
*
|
|
20
|
+
* **There is no Node-only API in this file, deliberately.** It is vendored
|
|
21
|
+
* byte-identical into every client (`mcp/`, `vscode/`, `action/`, `chrome/`)
|
|
22
|
+
* and `work/ops/tests/test_distribution_channels.py` fails if a copy drifts.
|
|
23
|
+
* The Chrome extension runs it inside a browser service worker, where
|
|
24
|
+
* `node:crypto` cannot be imported and `Buffer` does not exist, so the two
|
|
25
|
+
* Node-isms this file used to carry are gone: WebCrypto is read from the
|
|
26
|
+
* global `crypto` object (a global in browsers, in service workers, and in
|
|
27
|
+
* Node since 18) and base64url is encoded here instead of delegated to
|
|
28
|
+
* `Buffer`. One crypto file across five clients is worth more than the few
|
|
29
|
+
* lines it saves — the envelope layout is this product's interop contract, and
|
|
30
|
+
* a second copy of it is a second place for it to drift.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/** Key size in bytes (AES-256). */
|
|
34
|
+
export const KEY_BYTES = 32;
|
|
35
|
+
/** IV size in bytes (96-bit GCM nonce). */
|
|
36
|
+
export const IV_BYTES = 12;
|
|
37
|
+
/** GCM authentication tag size in bytes (128-bit). */
|
|
38
|
+
export const TAG_BYTES = 16;
|
|
39
|
+
/** Offset of the ciphertext inside the inline envelope. */
|
|
40
|
+
export const CIPHERTEXT_OFFSET = IV_BYTES + TAG_BYTES;
|
|
41
|
+
/**
|
|
42
|
+
* Largest inline envelope the API accepts (API_SPEC §4.1: 256 KB).
|
|
43
|
+
* Anything larger is a file secret and goes through the presigned-upload path,
|
|
44
|
+
* which these clients deliberately do not implement (see README).
|
|
45
|
+
*/
|
|
46
|
+
export const MAX_INLINE_BYTES = 256 * 1024;
|
|
47
|
+
|
|
48
|
+
/** A failed GCM authentication: wrong key, or tampered ciphertext. */
|
|
49
|
+
export class DecryptionError extends Error {
|
|
50
|
+
constructor(message = 'decryption failed — wrong key, or the data was altered') {
|
|
51
|
+
super(message);
|
|
52
|
+
this.name = 'DecryptionError';
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Malformed base64url, envelope or key material. */
|
|
57
|
+
export class EnvelopeError extends Error {
|
|
58
|
+
constructor(message) {
|
|
59
|
+
super(message);
|
|
60
|
+
this.name = 'EnvelopeError';
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The host's WebCrypto, resolved lazily and loudly.
|
|
66
|
+
*
|
|
67
|
+
* Not resolved at module load: a module that throws while loading takes the
|
|
68
|
+
* whole client down with a stack trace nobody can act on. A missing `crypto`
|
|
69
|
+
* global means Node older than 18, or a page served from an insecure origin,
|
|
70
|
+
* and both deserve a sentence that says which.
|
|
71
|
+
*
|
|
72
|
+
* @returns {Crypto}
|
|
73
|
+
*/
|
|
74
|
+
function webcrypto() {
|
|
75
|
+
const host = globalThis.crypto;
|
|
76
|
+
if (!host || !host.subtle || typeof host.getRandomValues !== 'function') {
|
|
77
|
+
throw new EnvelopeError(
|
|
78
|
+
'this runtime has no WebCrypto (globalThis.crypto.subtle). ' +
|
|
79
|
+
'Node 18+ provides it; a browser provides it only on a secure origin.',
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
return host;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** @returns {SubtleCrypto} */
|
|
86
|
+
function subtleCrypto() {
|
|
87
|
+
return webcrypto().subtle;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Fill a typed array with cryptographically strong random bytes.
|
|
92
|
+
*
|
|
93
|
+
* Called as a method on the Crypto object rather than detached: WebCrypto's
|
|
94
|
+
* `getRandomValues` checks its receiver and throws when it is not — Node
|
|
95
|
+
* raises ERR_INVALID_THIS, a browser raises an illegal-invocation TypeError.
|
|
96
|
+
*
|
|
97
|
+
* @template {Uint8Array} T
|
|
98
|
+
* @param {T} buf
|
|
99
|
+
* @returns {T}
|
|
100
|
+
*/
|
|
101
|
+
function fillRandom(buf) {
|
|
102
|
+
const host = webcrypto();
|
|
103
|
+
return host.getRandomValues(buf);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The base64url alphabet (RFC 4648 §5), used for output. */
|
|
107
|
+
const B64URL = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Reverse lookup for decoding, built once.
|
|
111
|
+
*
|
|
112
|
+
* URL-safe alphabet only, with no entry for `+` or `/`. That is not a second
|
|
113
|
+
* guard bolted onto the regex below — the two must agree, and the regex is the
|
|
114
|
+
* one that produces the error message, so a standard-base64 string is refused
|
|
115
|
+
* there with "is not valid base64url" before this table is ever consulted.
|
|
116
|
+
* Adding `+`/`/` here would be code that can never run, which is worse than
|
|
117
|
+
* strictness: it reads as support the client does not have.
|
|
118
|
+
*/
|
|
119
|
+
const B64URL_INDEX = (() => {
|
|
120
|
+
const table = new Int16Array(128).fill(-1);
|
|
121
|
+
for (let i = 0; i < B64URL.length; i += 1) table[B64URL.charCodeAt(i)] = i;
|
|
122
|
+
return table;
|
|
123
|
+
})();
|
|
124
|
+
|
|
125
|
+
/** @returns {Uint8Array} 32 cryptographically random bytes. */
|
|
126
|
+
export function generateKey() {
|
|
127
|
+
return fillRandom(new Uint8Array(KEY_BYTES));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* base64url-encode bytes, unpadded — the alphabet the URL fragment and the
|
|
132
|
+
* API both expect.
|
|
133
|
+
*
|
|
134
|
+
* Written out rather than delegated, because `Buffer` does not exist in a
|
|
135
|
+
* browser service worker and `btoa` takes a string, which would mean building
|
|
136
|
+
* a 256 KB intermediate string out of the very bytes we are trying not to
|
|
137
|
+
* copy around.
|
|
138
|
+
*
|
|
139
|
+
* @param {Uint8Array} bytes
|
|
140
|
+
* @returns {string}
|
|
141
|
+
*/
|
|
142
|
+
export function toBase64Url(bytes) {
|
|
143
|
+
if (!(bytes instanceof Uint8Array)) {
|
|
144
|
+
throw new EnvelopeError('toBase64Url expects bytes');
|
|
145
|
+
}
|
|
146
|
+
const parts = [];
|
|
147
|
+
let chunk = '';
|
|
148
|
+
let i = 0;
|
|
149
|
+
// Three bytes in, four characters out.
|
|
150
|
+
for (; i + 2 < bytes.length; i += 3) {
|
|
151
|
+
const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
|
|
152
|
+
chunk +=
|
|
153
|
+
B64URL[(n >>> 18) & 63] + B64URL[(n >>> 12) & 63] + B64URL[(n >>> 6) & 63] + B64URL[n & 63];
|
|
154
|
+
// Flushed in blocks: appending to one string for a 256 KB envelope is
|
|
155
|
+
// ~350k concatenations, and V8's rope representation makes the final read
|
|
156
|
+
// the expensive part rather than the appends.
|
|
157
|
+
if (chunk.length >= 4096) {
|
|
158
|
+
parts.push(chunk);
|
|
159
|
+
chunk = '';
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// The tail, emitted unpadded.
|
|
163
|
+
const left = bytes.length - i;
|
|
164
|
+
if (left === 1) {
|
|
165
|
+
const n = bytes[i] << 16;
|
|
166
|
+
chunk += B64URL[(n >>> 18) & 63] + B64URL[(n >>> 12) & 63];
|
|
167
|
+
} else if (left === 2) {
|
|
168
|
+
const n = (bytes[i] << 16) | (bytes[i + 1] << 8);
|
|
169
|
+
chunk += B64URL[(n >>> 18) & 63] + B64URL[(n >>> 12) & 63] + B64URL[(n >>> 6) & 63];
|
|
170
|
+
}
|
|
171
|
+
parts.push(chunk);
|
|
172
|
+
return parts.join('');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Decode unpadded base64url back to bytes, strictly.
|
|
177
|
+
*
|
|
178
|
+
* A lenient decoder — which is what `Buffer.from(value, 'base64url')` is, and
|
|
179
|
+
* what this used to delegate to — silently skips characters outside the
|
|
180
|
+
* alphabet, so a truncated or corrupted fragment decodes to plausible garbage
|
|
181
|
+
* and surfaces later as a confusing GCM failure. The shape is checked first
|
|
182
|
+
* and rejected loudly instead, and the loop below reads every character it was
|
|
183
|
+
* given rather than skipping any.
|
|
184
|
+
*
|
|
185
|
+
* @param {string} value
|
|
186
|
+
* @param {string} what Label used in the error message.
|
|
187
|
+
* @returns {Uint8Array}
|
|
188
|
+
*/
|
|
189
|
+
export function fromBase64Url(value, what = 'value') {
|
|
190
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
191
|
+
throw new EnvelopeError(`${what} is empty`);
|
|
192
|
+
}
|
|
193
|
+
if (!/^[A-Za-z0-9_-]+={0,2}$/.test(value)) {
|
|
194
|
+
throw new EnvelopeError(`${what} is not valid base64url`);
|
|
195
|
+
}
|
|
196
|
+
const body = value.replace(/=+$/, '');
|
|
197
|
+
// A base64 quantum is four characters. A remainder of one cannot be produced
|
|
198
|
+
// by any encoder, so it means the string lost characters on the way here.
|
|
199
|
+
if (body.length % 4 === 1) {
|
|
200
|
+
throw new EnvelopeError(`${what} is truncated base64url`);
|
|
201
|
+
}
|
|
202
|
+
const out = new Uint8Array(Math.floor((body.length * 3) / 4));
|
|
203
|
+
let written = 0;
|
|
204
|
+
let acc = 0;
|
|
205
|
+
let bits = 0;
|
|
206
|
+
for (let i = 0; i < body.length; i += 1) {
|
|
207
|
+
const code = body.charCodeAt(i);
|
|
208
|
+
const digit = code < 128 ? B64URL_INDEX[code] : -1;
|
|
209
|
+
if (digit < 0) {
|
|
210
|
+
throw new EnvelopeError(`${what} is not valid base64url`);
|
|
211
|
+
}
|
|
212
|
+
acc = ((acc << 6) | digit) & 0xffffff;
|
|
213
|
+
bits += 6;
|
|
214
|
+
if (bits >= 8) {
|
|
215
|
+
bits -= 8;
|
|
216
|
+
out[written] = (acc >>> bits) & 0xff;
|
|
217
|
+
written += 1;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return out.subarray(0, written);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Encrypt UTF-8 text and pack it into the inline envelope the API stores.
|
|
225
|
+
*
|
|
226
|
+
* @param {string} plaintext
|
|
227
|
+
* @param {Uint8Array} key 32 bytes.
|
|
228
|
+
* @returns {Promise<Uint8Array>} [iv 12][tag 16][ciphertext N]
|
|
229
|
+
*/
|
|
230
|
+
export async function encryptTextToEnvelope(plaintext, key) {
|
|
231
|
+
assertKey(key);
|
|
232
|
+
const iv = fillRandom(new Uint8Array(IV_BYTES));
|
|
233
|
+
const cryptoKey = await subtleCrypto().importKey(
|
|
234
|
+
'raw',
|
|
235
|
+
key,
|
|
236
|
+
{ name: 'AES-GCM', length: 256 },
|
|
237
|
+
false,
|
|
238
|
+
['encrypt'],
|
|
239
|
+
);
|
|
240
|
+
const raw = new Uint8Array(
|
|
241
|
+
await subtleCrypto().encrypt(
|
|
242
|
+
{ name: 'AES-GCM', iv, tagLength: TAG_BYTES * 8 },
|
|
243
|
+
cryptoKey,
|
|
244
|
+
new TextEncoder().encode(plaintext),
|
|
245
|
+
),
|
|
246
|
+
);
|
|
247
|
+
|
|
248
|
+
// WebCrypto appends the tag to the ciphertext; the envelope carries it in
|
|
249
|
+
// front, exactly as the browser client packs it.
|
|
250
|
+
const ciphertext = raw.subarray(0, raw.length - TAG_BYTES);
|
|
251
|
+
const tag = raw.subarray(raw.length - TAG_BYTES);
|
|
252
|
+
|
|
253
|
+
const envelope = new Uint8Array(CIPHERTEXT_OFFSET + ciphertext.length);
|
|
254
|
+
envelope.set(iv, 0);
|
|
255
|
+
envelope.set(tag, IV_BYTES);
|
|
256
|
+
envelope.set(ciphertext, CIPHERTEXT_OFFSET);
|
|
257
|
+
return envelope;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/**
|
|
261
|
+
* Unpack an inline envelope and decrypt it back to UTF-8 text.
|
|
262
|
+
*
|
|
263
|
+
* @param {Uint8Array} envelope [iv 12][tag 16][ciphertext N]
|
|
264
|
+
* @param {Uint8Array} key 32 bytes.
|
|
265
|
+
* @returns {Promise<string>}
|
|
266
|
+
*/
|
|
267
|
+
export async function decryptEnvelopeToText(envelope, key) {
|
|
268
|
+
assertKey(key);
|
|
269
|
+
if (!(envelope instanceof Uint8Array) || envelope.length < CIPHERTEXT_OFFSET) {
|
|
270
|
+
throw new EnvelopeError(
|
|
271
|
+
`envelope is too short: ${envelope?.length ?? 0} bytes, minimum ${CIPHERTEXT_OFFSET}`,
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
const iv = envelope.subarray(0, IV_BYTES);
|
|
275
|
+
const tag = envelope.subarray(IV_BYTES, CIPHERTEXT_OFFSET);
|
|
276
|
+
const ciphertext = envelope.subarray(CIPHERTEXT_OFFSET);
|
|
277
|
+
|
|
278
|
+
const combined = new Uint8Array(ciphertext.length + TAG_BYTES);
|
|
279
|
+
combined.set(ciphertext, 0);
|
|
280
|
+
combined.set(tag, ciphertext.length);
|
|
281
|
+
|
|
282
|
+
const cryptoKey = await subtleCrypto().importKey(
|
|
283
|
+
'raw',
|
|
284
|
+
key,
|
|
285
|
+
{ name: 'AES-GCM', length: 256 },
|
|
286
|
+
false,
|
|
287
|
+
['decrypt'],
|
|
288
|
+
);
|
|
289
|
+
let plaintext;
|
|
290
|
+
try {
|
|
291
|
+
plaintext = await subtleCrypto().decrypt(
|
|
292
|
+
{ name: 'AES-GCM', iv, tagLength: TAG_BYTES * 8 },
|
|
293
|
+
cryptoKey,
|
|
294
|
+
combined,
|
|
295
|
+
);
|
|
296
|
+
} catch {
|
|
297
|
+
// No byte-level detail, for the same reason the web client gives none.
|
|
298
|
+
throw new DecryptionError();
|
|
299
|
+
}
|
|
300
|
+
// Strict, for the same reason the input side is strict: a lenient decoder
|
|
301
|
+
// turns bytes it cannot read into U+FFFD, and `--raw` promises the caller
|
|
302
|
+
// the exact bytes that were encrypted. A text secret created by this CLI or
|
|
303
|
+
// by the browser is always valid UTF-8; anything else did not come from
|
|
304
|
+
// either, and silently replacing bytes would be the worst possible answer.
|
|
305
|
+
try {
|
|
306
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(plaintext);
|
|
307
|
+
} catch {
|
|
308
|
+
throw new EnvelopeError(
|
|
309
|
+
'the secret decrypted correctly but is not UTF-8 text, so the client will not print it',
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Overwrite key material in place. A garbage-collected runtime cannot promise
|
|
316
|
+
* the bytes were never copied, so this shortens the window rather than
|
|
317
|
+
* closing it.
|
|
318
|
+
* @param {Uint8Array} bytes
|
|
319
|
+
*/
|
|
320
|
+
export function zeroize(bytes) {
|
|
321
|
+
if (bytes instanceof Uint8Array) bytes.fill(0);
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function assertKey(key) {
|
|
325
|
+
if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES) {
|
|
326
|
+
throw new EnvelopeError(`key must be ${KEY_BYTES} bytes, got ${key?.length ?? 'none'}`);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Share-link construction and parsing.
|
|
3
|
+
*
|
|
4
|
+
* The link shape is the browser client's (result-screen.component.ts):
|
|
5
|
+
*
|
|
6
|
+
* https://app.easytopaste.com/s/<locator>#k=<base64url key>&v=1
|
|
7
|
+
*
|
|
8
|
+
* Everything after `#` is a URL fragment, which browsers and HTTP clients do
|
|
9
|
+
* not transmit — that is the whole reason the key lives there. This module
|
|
10
|
+
* never logs or forwards the fragment; it only moves it between the link and
|
|
11
|
+
* the local crypto calls.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { EnvelopeError, KEY_BYTES, fromBase64Url, toBase64Url } from './crypto.js';
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_APP_BASE = 'https://app.easytopaste.com';
|
|
17
|
+
export const DEFAULT_API_BASE = 'https://api.easytopaste.com';
|
|
18
|
+
|
|
19
|
+
/** Locators are base32 (A-Z2-7); the wider class is what we will *accept*. */
|
|
20
|
+
const LOCATOR_RE = /^[A-Za-z0-9_-]{8,128}$/;
|
|
21
|
+
|
|
22
|
+
export class LinkError extends Error {
|
|
23
|
+
constructor(message) {
|
|
24
|
+
super(message);
|
|
25
|
+
this.name = 'LinkError';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {{locator: string, key: Uint8Array, appBase?: string}} args
|
|
31
|
+
* @returns {string} The full one-time link, fragment included.
|
|
32
|
+
*/
|
|
33
|
+
export function buildLink({ locator, key, appBase = DEFAULT_APP_BASE }) {
|
|
34
|
+
assertLocator(locator);
|
|
35
|
+
if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES) {
|
|
36
|
+
throw new LinkError(`key must be ${KEY_BYTES} bytes`);
|
|
37
|
+
}
|
|
38
|
+
const base = String(appBase).replace(/\/+$/, '');
|
|
39
|
+
return `${base}/s/${locator}#k=${toBase64Url(key)}&v=1`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Parse a share link back into its locator and key.
|
|
44
|
+
*
|
|
45
|
+
* Accepts the full URL, or the short `<locator>#k=<key>` form that is easier
|
|
46
|
+
* to paste between terminals.
|
|
47
|
+
*
|
|
48
|
+
* @param {string} input
|
|
49
|
+
* @returns {{locator: string, key: Uint8Array}}
|
|
50
|
+
*/
|
|
51
|
+
export function parseLink(input) {
|
|
52
|
+
if (typeof input !== 'string' || input.trim() === '') {
|
|
53
|
+
throw new LinkError('no link given');
|
|
54
|
+
}
|
|
55
|
+
const raw = input.trim();
|
|
56
|
+
const hashAt = raw.indexOf('#');
|
|
57
|
+
if (hashAt === -1) {
|
|
58
|
+
throw new LinkError(
|
|
59
|
+
'that link carries no "#k=" fragment, so it holds no key. ' +
|
|
60
|
+
'Copy the whole link, including everything after the "#".',
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const before = raw.slice(0, hashAt);
|
|
65
|
+
const fragment = raw.slice(hashAt + 1);
|
|
66
|
+
|
|
67
|
+
const params = new URLSearchParams(fragment);
|
|
68
|
+
const keyPart = params.get('k');
|
|
69
|
+
if (!keyPart) {
|
|
70
|
+
throw new LinkError('the link fragment has no "k=" key parameter');
|
|
71
|
+
}
|
|
72
|
+
const version = params.get('v');
|
|
73
|
+
if (version !== null && version !== '1') {
|
|
74
|
+
throw new LinkError(
|
|
75
|
+
`link envelope version ${version} is newer than this CLI understands (expected 1)`,
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
let key;
|
|
80
|
+
try {
|
|
81
|
+
key = fromBase64Url(keyPart, 'key fragment');
|
|
82
|
+
} catch (err) {
|
|
83
|
+
throw new LinkError(err.message);
|
|
84
|
+
}
|
|
85
|
+
if (key.length !== KEY_BYTES) {
|
|
86
|
+
throw new LinkError(
|
|
87
|
+
`key fragment decodes to ${key.length} bytes, expected ${KEY_BYTES} — the link is truncated`,
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const locator = extractLocator(before);
|
|
92
|
+
return { locator, key };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function extractLocator(before) {
|
|
96
|
+
// A link that travelled through Slack or an email client arrives with a
|
|
97
|
+
// tracking query attached: /s/<locator>?utm_source=slack#k=... The browser
|
|
98
|
+
// opens that fine, so refusing it here would be the CLI inventing a rule the
|
|
99
|
+
// product does not have. The query is not part of the locator and is dropped.
|
|
100
|
+
const trimmed = before.split('?')[0].replace(/\/+$/, '');
|
|
101
|
+
if (trimmed === '') {
|
|
102
|
+
throw new LinkError('the link has no locator before the "#"');
|
|
103
|
+
}
|
|
104
|
+
// Full URL form: .../s/<locator>. Bare form: <locator>.
|
|
105
|
+
const segments = trimmed.split('/');
|
|
106
|
+
const candidate = segments[segments.length - 1];
|
|
107
|
+
assertLocator(candidate);
|
|
108
|
+
return candidate;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function assertLocator(locator) {
|
|
112
|
+
if (typeof locator !== 'string' || !LOCATOR_RE.test(locator)) {
|
|
113
|
+
throw new LinkError(`"${locator}" is not a valid secret locator`);
|
|
114
|
+
}
|
|
115
|
+
}
|