easytopaste 0.1.1 → 0.1.2
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 -37
- package/package.json +4 -4
- package/src/api.js +219 -189
- package/src/crypto.js +165 -29
package/LICENSE.md
CHANGED
|
@@ -1,37 +1,21 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
Copyright
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
## No warranty
|
|
24
|
-
|
|
25
|
-
This package is provided "as is", without warranty of any kind, express or
|
|
26
|
-
implied, including the warranties of merchantability, fitness for a particular
|
|
27
|
-
purpose and non-infringement. To the fullest extent permitted by law, the
|
|
28
|
-
copyright holder is not liable for any claim, damages or other liability
|
|
29
|
-
arising from this package or its use.
|
|
30
|
-
|
|
31
|
-
## Not an open-source promise
|
|
32
|
-
|
|
33
|
-
This licence grants use, not stewardship. Publishing this package is not a
|
|
34
|
-
commitment to maintain it as an open-source project, to accept contributions,
|
|
35
|
-
or to keep publishing future versions.
|
|
36
|
-
|
|
37
|
-
Questions: https://easytopaste.com/legal/contact
|
|
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "easytopaste",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Pipe a secret in, get a one-time link out. Encrypted on your machine with AES-256-GCM; the key never leaves it.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -34,11 +34,11 @@
|
|
|
34
34
|
"devops",
|
|
35
35
|
"secrets-management"
|
|
36
36
|
],
|
|
37
|
-
"homepage": "https://easytopaste.com",
|
|
37
|
+
"homepage": "https://easytopaste.com/?utm_source=npm&utm_medium=cli&utm_campaign=launch-2026-11",
|
|
38
38
|
"bugs": {
|
|
39
|
-
"
|
|
39
|
+
"email": "support@easytopaste.com"
|
|
40
40
|
},
|
|
41
|
-
"license": "
|
|
41
|
+
"license": "MIT",
|
|
42
42
|
"publishConfig": {
|
|
43
43
|
"access": "public"
|
|
44
44
|
}
|
package/src/api.js
CHANGED
|
@@ -1,189 +1,219 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The HTTP half of the CLI: three calls against the public secrets API.
|
|
3
|
-
*
|
|
4
|
-
* What this module is allowed to send is as important as what it does send.
|
|
5
|
-
* It posts ciphertext and metadata, and nothing else — no plaintext, no key,
|
|
6
|
-
* no file path, no environment detail, no telemetry of any kind. The
|
|
7
|
-
* zero-knowledge posture is a product promise, so the request body built here
|
|
8
|
-
* is asserted field-by-field in test/api.test.js rather than trusted.
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
import { DEFAULT_API_BASE } from './link.js';
|
|
12
|
-
|
|
13
|
-
const USER_AGENT_PREFIX = 'easytopaste-cli';
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
)
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
1
|
+
/**
|
|
2
|
+
* The HTTP half of the CLI: three calls against the public secrets API.
|
|
3
|
+
*
|
|
4
|
+
* What this module is allowed to send is as important as what it does send.
|
|
5
|
+
* It posts ciphertext and metadata, and nothing else — no plaintext, no key,
|
|
6
|
+
* no file path, no environment detail, no telemetry of any kind. The
|
|
7
|
+
* zero-knowledge posture is a product promise, so the request body built here
|
|
8
|
+
* is asserted field-by-field in test/api.test.js rather than trusted.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { DEFAULT_API_BASE } from './link.js';
|
|
12
|
+
|
|
13
|
+
const USER_AGENT_PREFIX = 'easytopaste-cli';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Which registry this copy was installed from, if the installer said so.
|
|
17
|
+
*
|
|
18
|
+
* A `utm` tag measures a click on a link. It cannot measure this: somebody who
|
|
19
|
+
* runs `brew install easytopaste` and then `easytopaste send` never loads a
|
|
20
|
+
* page, so the only place the channel can appear is the one request we do
|
|
21
|
+
* make. The Homebrew formula and the Scoop manifest set EASYTOPASTE_CHANNEL;
|
|
22
|
+
* an npm install sets nothing and reports nothing, which is the honest
|
|
23
|
+
* default rather than a guess.
|
|
24
|
+
*
|
|
25
|
+
* Deliberately narrow: lower-case letters, digits and a hyphen, at most 16
|
|
26
|
+
* characters. This value goes into a header from an environment variable, so
|
|
27
|
+
* it is sanitised rather than trusted — a header is a place where a stray
|
|
28
|
+
* newline is a request-splitting bug, and the field is worth nothing if it
|
|
29
|
+
* can carry anything.
|
|
30
|
+
*/
|
|
31
|
+
export function channelTag(env = process.env) {
|
|
32
|
+
const raw = String(env.EASYTOPASTE_CHANNEL ?? '').trim().toLowerCase();
|
|
33
|
+
const clean = raw.replace(/[^a-z0-9-]/g, '');
|
|
34
|
+
return clean.slice(0, 16);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** `easytopaste-cli/0.1.1` or `easytopaste-cli/0.1.1 (brew)`. */
|
|
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
|
+
/** An error the API itself reported, carrying its machine-readable code. */
|
|
46
|
+
export class ApiError extends Error {
|
|
47
|
+
/**
|
|
48
|
+
* @param {string} message Human-readable, already suitable for stderr.
|
|
49
|
+
* @param {{code?: string, status?: number, requestId?: string, retryAfter?: string}} info
|
|
50
|
+
*/
|
|
51
|
+
constructor(message, info = {}) {
|
|
52
|
+
super(message);
|
|
53
|
+
this.name = 'ApiError';
|
|
54
|
+
this.code = info.code ?? 'unknown';
|
|
55
|
+
this.status = info.status ?? 0;
|
|
56
|
+
this.requestId = info.requestId ?? null;
|
|
57
|
+
this.retryAfter = info.retryAfter ?? null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The request never reached the API, or the API never answered. */
|
|
62
|
+
export class NetworkError extends Error {
|
|
63
|
+
constructor(message, cause) {
|
|
64
|
+
super(message, { cause });
|
|
65
|
+
this.name = 'NetworkError';
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export class ApiClient {
|
|
70
|
+
/**
|
|
71
|
+
* @param {{baseUrl?: string, version?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} opts
|
|
72
|
+
*/
|
|
73
|
+
constructor({ baseUrl = DEFAULT_API_BASE, version = '0.0.0', timeoutMs = 20_000, fetchImpl } = {}) {
|
|
74
|
+
this.baseUrl = String(baseUrl).replace(/\/+$/, '');
|
|
75
|
+
this.version = version;
|
|
76
|
+
this.timeoutMs = timeoutMs;
|
|
77
|
+
this.fetchImpl = fetchImpl ?? globalThis.fetch;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* POST /v1/secrets — store one inline ciphertext envelope.
|
|
82
|
+
*
|
|
83
|
+
* @param {{ciphertextB64: string, sizeBytes: number, oneTime: boolean, expiresInDays: number}} args
|
|
84
|
+
* @returns {Promise<{locator: string, code?: string, expiresAt?: string}>}
|
|
85
|
+
*/
|
|
86
|
+
async createSecret({ ciphertextB64, sizeBytes, oneTime, expiresInDays }) {
|
|
87
|
+
const body = {
|
|
88
|
+
type: 'text',
|
|
89
|
+
mode: 'link',
|
|
90
|
+
envelopeVersion: 1,
|
|
91
|
+
sizeBytes,
|
|
92
|
+
oneTime,
|
|
93
|
+
expiresInDays,
|
|
94
|
+
requiresRecipientLogin: false,
|
|
95
|
+
mimeHint: 'text/plain',
|
|
96
|
+
ciphertext: ciphertextB64,
|
|
97
|
+
};
|
|
98
|
+
const { json } = await this.#request('POST', '/v1/secrets', body);
|
|
99
|
+
if (!json || typeof json.locator !== 'string') {
|
|
100
|
+
throw new ApiError('the API accepted the secret but returned no locator');
|
|
101
|
+
}
|
|
102
|
+
return json;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* GET /v1/secrets/{locator} — metadata plus, for inline text, the envelope.
|
|
107
|
+
* This call deliberately does not burn; see burnSecret.
|
|
108
|
+
*
|
|
109
|
+
* @param {string} locator
|
|
110
|
+
*/
|
|
111
|
+
async retrieveSecret(locator) {
|
|
112
|
+
const { json } = await this.#request('GET', `/v1/secrets/${encodeURIComponent(locator)}`);
|
|
113
|
+
return json ?? {};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* POST /v1/secrets/{locator}/burn — destroy a one-time secret.
|
|
118
|
+
*
|
|
119
|
+
* Called only after a successful local decrypt, for the reason the web
|
|
120
|
+
* client records: burning first would destroy a secret the reader never got.
|
|
121
|
+
*
|
|
122
|
+
* @param {string} locator
|
|
123
|
+
*/
|
|
124
|
+
async burnSecret(locator) {
|
|
125
|
+
const { json } = await this.#request(
|
|
126
|
+
'POST',
|
|
127
|
+
`/v1/secrets/${encodeURIComponent(locator)}/burn`,
|
|
128
|
+
{},
|
|
129
|
+
);
|
|
130
|
+
return json ?? {};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async #request(method, path, body) {
|
|
134
|
+
const url = `${this.baseUrl}${path}`;
|
|
135
|
+
const headers = {
|
|
136
|
+
accept: 'application/json',
|
|
137
|
+
'user-agent': userAgent(this.version),
|
|
138
|
+
};
|
|
139
|
+
if (body !== undefined) headers['content-type'] = 'application/json';
|
|
140
|
+
|
|
141
|
+
const controller = new AbortController();
|
|
142
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
143
|
+
let response;
|
|
144
|
+
try {
|
|
145
|
+
response = await this.fetchImpl(url, {
|
|
146
|
+
method,
|
|
147
|
+
headers,
|
|
148
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
149
|
+
signal: controller.signal,
|
|
150
|
+
});
|
|
151
|
+
} catch (cause) {
|
|
152
|
+
if (cause?.name === 'AbortError') {
|
|
153
|
+
throw new NetworkError(`${method} ${url} timed out after ${this.timeoutMs} ms`, cause);
|
|
154
|
+
}
|
|
155
|
+
throw new NetworkError(`cannot reach ${this.baseUrl} — ${cause?.message ?? cause}`, cause);
|
|
156
|
+
} finally {
|
|
157
|
+
clearTimeout(timer);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const text = await response.text();
|
|
161
|
+
let json = null;
|
|
162
|
+
if (text) {
|
|
163
|
+
try {
|
|
164
|
+
json = JSON.parse(text);
|
|
165
|
+
} catch {
|
|
166
|
+
json = null;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
if (!response.ok) {
|
|
171
|
+
throw toApiError(response, json);
|
|
172
|
+
}
|
|
173
|
+
return { json, response };
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Turn an API error envelope into a message a person can act on.
|
|
179
|
+
* API_SPEC §1.2: `{ "error": { code, message, request_id, hint? } }`.
|
|
180
|
+
*/
|
|
181
|
+
function toApiError(response, json) {
|
|
182
|
+
const err = json && typeof json === 'object' ? json.error : null;
|
|
183
|
+
const code = err?.code ?? `http_${response.status}`;
|
|
184
|
+
const requestId = err?.request_id ?? err?.requestId ?? null;
|
|
185
|
+
const base = err?.message || `the API answered ${response.status}`;
|
|
186
|
+
const hint = err?.hint ? ` ${err.hint}` : '';
|
|
187
|
+
return new ApiError(`${explain(code)}${base}${hint}`, {
|
|
188
|
+
code,
|
|
189
|
+
status: response.status,
|
|
190
|
+
requestId,
|
|
191
|
+
retryAfter: response.headers?.get?.('retry-after') ?? null,
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Short prefixes that say what the code means for *this* CLI's user. */
|
|
196
|
+
function explain(code) {
|
|
197
|
+
switch (code) {
|
|
198
|
+
case 'not_found':
|
|
199
|
+
return 'no such secret — it was burned, expired, or the link is wrong: ';
|
|
200
|
+
case 'already_accessed':
|
|
201
|
+
return 'this one-time secret has already been read: ';
|
|
202
|
+
case 'expired':
|
|
203
|
+
return 'this secret has expired: ';
|
|
204
|
+
case 'revoked':
|
|
205
|
+
return 'the sender revoked this secret: ';
|
|
206
|
+
case 'rate_limited':
|
|
207
|
+
return 'too many requests, wait a minute: ';
|
|
208
|
+
case 'quota_exceeded':
|
|
209
|
+
return 'daily quota reached: ';
|
|
210
|
+
case 'payload_too_large':
|
|
211
|
+
return 'the secret is too large for an inline link: ';
|
|
212
|
+
case 'recipient_denied':
|
|
213
|
+
case 'unauthorized':
|
|
214
|
+
case 'forbidden':
|
|
215
|
+
return 'this secret requires a signed-in recipient, open it in a browser: ';
|
|
216
|
+
default:
|
|
217
|
+
return '';
|
|
218
|
+
}
|
|
219
|
+
}
|
package/src/crypto.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Client-side cryptography for the EasyToPaste
|
|
2
|
+
* Client-side cryptography for the EasyToPaste clients.
|
|
3
3
|
*
|
|
4
|
-
* This file is the
|
|
4
|
+
* This file is the non-browser half of a contract the browser client already
|
|
5
5
|
* implements (frontend/src/app/crypto/crypto.utils.ts and
|
|
6
6
|
* frontend/src/app/components/create-secret/create-secret.component.ts).
|
|
7
7
|
* A secret created here must open in the web app, and a secret created in the
|
|
@@ -16,15 +16,20 @@
|
|
|
16
16
|
* test/compat.test.js re-reads those two frontend files and fails if the
|
|
17
17
|
* numbers drift apart, because a silent drift means every link this CLI prints
|
|
18
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.
|
|
19
31
|
*/
|
|
20
32
|
|
|
21
|
-
import { webcrypto } from 'node:crypto';
|
|
22
|
-
|
|
23
|
-
const { subtle } = webcrypto;
|
|
24
|
-
// Bound, not destructured: webcrypto.getRandomValues checks its receiver and
|
|
25
|
-
// throws ERR_INVALID_THIS when it is called detached from the Crypto object.
|
|
26
|
-
const getRandomValues = webcrypto.getRandomValues.bind(webcrypto);
|
|
27
|
-
|
|
28
33
|
/** Key size in bytes (AES-256). */
|
|
29
34
|
export const KEY_BYTES = 32;
|
|
30
35
|
/** IV size in bytes (96-bit GCM nonce). */
|
|
@@ -36,7 +41,7 @@ export const CIPHERTEXT_OFFSET = IV_BYTES + TAG_BYTES;
|
|
|
36
41
|
/**
|
|
37
42
|
* Largest inline envelope the API accepts (API_SPEC §4.1: 256 KB).
|
|
38
43
|
* Anything larger is a file secret and goes through the presigned-upload path,
|
|
39
|
-
* which
|
|
44
|
+
* which these clients deliberately do not implement (see README).
|
|
40
45
|
*/
|
|
41
46
|
export const MAX_INLINE_BYTES = 256 * 1024;
|
|
42
47
|
|
|
@@ -56,28 +61,126 @@ export class EnvelopeError extends Error {
|
|
|
56
61
|
}
|
|
57
62
|
}
|
|
58
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
|
+
|
|
59
125
|
/** @returns {Uint8Array} 32 cryptographically random bytes. */
|
|
60
126
|
export function generateKey() {
|
|
61
|
-
return
|
|
127
|
+
return fillRandom(new Uint8Array(KEY_BYTES));
|
|
62
128
|
}
|
|
63
129
|
|
|
64
130
|
/**
|
|
65
131
|
* base64url-encode bytes, unpadded — the alphabet the URL fragment and the
|
|
66
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
|
+
*
|
|
67
139
|
* @param {Uint8Array} bytes
|
|
68
140
|
* @returns {string}
|
|
69
141
|
*/
|
|
70
142
|
export function toBase64Url(bytes) {
|
|
71
|
-
|
|
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('');
|
|
72
173
|
}
|
|
73
174
|
|
|
74
175
|
/**
|
|
75
176
|
* Decode unpadded base64url back to bytes, strictly.
|
|
76
177
|
*
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
*
|
|
80
|
-
*
|
|
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.
|
|
81
184
|
*
|
|
82
185
|
* @param {string} value
|
|
83
186
|
* @param {string} what Label used in the error message.
|
|
@@ -90,7 +193,31 @@ export function fromBase64Url(value, what = 'value') {
|
|
|
90
193
|
if (!/^[A-Za-z0-9_-]+={0,2}$/.test(value)) {
|
|
91
194
|
throw new EnvelopeError(`${what} is not valid base64url`);
|
|
92
195
|
}
|
|
93
|
-
|
|
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);
|
|
94
221
|
}
|
|
95
222
|
|
|
96
223
|
/**
|
|
@@ -102,12 +229,16 @@ export function fromBase64Url(value, what = 'value') {
|
|
|
102
229
|
*/
|
|
103
230
|
export async function encryptTextToEnvelope(plaintext, key) {
|
|
104
231
|
assertKey(key);
|
|
105
|
-
const iv =
|
|
106
|
-
const cryptoKey = await
|
|
107
|
-
'
|
|
108
|
-
|
|
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
|
+
);
|
|
109
240
|
const raw = new Uint8Array(
|
|
110
|
-
await
|
|
241
|
+
await subtleCrypto().encrypt(
|
|
111
242
|
{ name: 'AES-GCM', iv, tagLength: TAG_BYTES * 8 },
|
|
112
243
|
cryptoKey,
|
|
113
244
|
new TextEncoder().encode(plaintext),
|
|
@@ -148,12 +279,16 @@ export async function decryptEnvelopeToText(envelope, key) {
|
|
|
148
279
|
combined.set(ciphertext, 0);
|
|
149
280
|
combined.set(tag, ciphertext.length);
|
|
150
281
|
|
|
151
|
-
const cryptoKey = await
|
|
152
|
-
'
|
|
153
|
-
|
|
282
|
+
const cryptoKey = await subtleCrypto().importKey(
|
|
283
|
+
'raw',
|
|
284
|
+
key,
|
|
285
|
+
{ name: 'AES-GCM', length: 256 },
|
|
286
|
+
false,
|
|
287
|
+
['decrypt'],
|
|
288
|
+
);
|
|
154
289
|
let plaintext;
|
|
155
290
|
try {
|
|
156
|
-
plaintext = await
|
|
291
|
+
plaintext = await subtleCrypto().decrypt(
|
|
157
292
|
{ name: 'AES-GCM', iv, tagLength: TAG_BYTES * 8 },
|
|
158
293
|
cryptoKey,
|
|
159
294
|
combined,
|
|
@@ -171,14 +306,15 @@ export async function decryptEnvelopeToText(envelope, key) {
|
|
|
171
306
|
return new TextDecoder('utf-8', { fatal: true }).decode(plaintext);
|
|
172
307
|
} catch {
|
|
173
308
|
throw new EnvelopeError(
|
|
174
|
-
'the secret decrypted correctly but is not UTF-8 text, so the
|
|
309
|
+
'the secret decrypted correctly but is not UTF-8 text, so the client will not print it',
|
|
175
310
|
);
|
|
176
311
|
}
|
|
177
312
|
}
|
|
178
313
|
|
|
179
314
|
/**
|
|
180
|
-
* Overwrite key material in place.
|
|
181
|
-
*
|
|
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.
|
|
182
318
|
* @param {Uint8Array} bytes
|
|
183
319
|
*/
|
|
184
320
|
export function zeroize(bytes) {
|