easytopaste 0.1.0 → 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.
Files changed (4) hide show
  1. package/LICENSE.md +21 -37
  2. package/package.json +4 -5
  3. package/src/api.js +219 -189
  4. package/src/crypto.js +165 -29
package/LICENSE.md CHANGED
@@ -1,37 +1,21 @@
1
- # EasyToPaste CLI — licence
2
-
3
- Copyright © 2026 EasyToPaste. All rights reserved.
4
-
5
- ## What you may do
6
-
7
- You are granted a free, worldwide, non-exclusive, revocable licence to
8
- **download, install and run** this package — personally, inside a company, and
9
- in automated systems such as CI — for any lawful purpose, including commercial
10
- use. No registration, payment or notice to us is required.
11
-
12
- You may read the source. It is published unminified on purpose: this tool
13
- encrypts your secrets on your own machine, and a client you cannot inspect is a
14
- client you cannot check.
15
-
16
- ## What you may not do
17
-
18
- You may not redistribute, republish, sublicense or sell this package or a
19
- derivative of it, and you may not modify it for distribution to others.
20
- Installing it from npm as a dependency of your own project is not
21
- redistribution and is expressly allowed.
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.0",
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,12 +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
- "url": "https://easytopaste.com/legal/contact"
39
+ "email": "support@easytopaste.com"
40
40
  },
41
- "license": "SEE LICENSE IN LICENSE.md",
42
- "_private_why": "Published 2026-11-19 under the owner's standing instruction to release the CLI without asking. private:true was removed in the same edit as the licence, which is what that flag was guarding.",
41
+ "license": "MIT",
43
42
  "publishConfig": {
44
43
  "access": "public"
45
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
- /** An error the API itself reported, carrying its machine-readable code. */
16
- export class ApiError extends Error {
17
- /**
18
- * @param {string} message Human-readable, already suitable for stderr.
19
- * @param {{code?: string, status?: number, requestId?: string, retryAfter?: string}} info
20
- */
21
- constructor(message, info = {}) {
22
- super(message);
23
- this.name = 'ApiError';
24
- this.code = info.code ?? 'unknown';
25
- this.status = info.status ?? 0;
26
- this.requestId = info.requestId ?? null;
27
- this.retryAfter = info.retryAfter ?? null;
28
- }
29
- }
30
-
31
- /** The request never reached the API, or the API never answered. */
32
- export class NetworkError extends Error {
33
- constructor(message, cause) {
34
- super(message, { cause });
35
- this.name = 'NetworkError';
36
- }
37
- }
38
-
39
- export class ApiClient {
40
- /**
41
- * @param {{baseUrl?: string, version?: string, timeoutMs?: number, fetchImpl?: typeof fetch}} opts
42
- */
43
- constructor({ baseUrl = DEFAULT_API_BASE, version = '0.0.0', timeoutMs = 20_000, fetchImpl } = {}) {
44
- this.baseUrl = String(baseUrl).replace(/\/+$/, '');
45
- this.version = version;
46
- this.timeoutMs = timeoutMs;
47
- this.fetchImpl = fetchImpl ?? globalThis.fetch;
48
- }
49
-
50
- /**
51
- * POST /v1/secrets — store one inline ciphertext envelope.
52
- *
53
- * @param {{ciphertextB64: string, sizeBytes: number, oneTime: boolean, expiresInDays: number}} args
54
- * @returns {Promise<{locator: string, code?: string, expiresAt?: string}>}
55
- */
56
- async createSecret({ ciphertextB64, sizeBytes, oneTime, expiresInDays }) {
57
- const body = {
58
- type: 'text',
59
- mode: 'link',
60
- envelopeVersion: 1,
61
- sizeBytes,
62
- oneTime,
63
- expiresInDays,
64
- requiresRecipientLogin: false,
65
- mimeHint: 'text/plain',
66
- ciphertext: ciphertextB64,
67
- };
68
- const { json } = await this.#request('POST', '/v1/secrets', body);
69
- if (!json || typeof json.locator !== 'string') {
70
- throw new ApiError('the API accepted the secret but returned no locator');
71
- }
72
- return json;
73
- }
74
-
75
- /**
76
- * GET /v1/secrets/{locator} — metadata plus, for inline text, the envelope.
77
- * This call deliberately does not burn; see burnSecret.
78
- *
79
- * @param {string} locator
80
- */
81
- async retrieveSecret(locator) {
82
- const { json } = await this.#request('GET', `/v1/secrets/${encodeURIComponent(locator)}`);
83
- return json ?? {};
84
- }
85
-
86
- /**
87
- * POST /v1/secrets/{locator}/burn — destroy a one-time secret.
88
- *
89
- * Called only after a successful local decrypt, for the reason the web
90
- * client records: burning first would destroy a secret the reader never got.
91
- *
92
- * @param {string} locator
93
- */
94
- async burnSecret(locator) {
95
- const { json } = await this.#request(
96
- 'POST',
97
- `/v1/secrets/${encodeURIComponent(locator)}/burn`,
98
- {},
99
- );
100
- return json ?? {};
101
- }
102
-
103
- async #request(method, path, body) {
104
- const url = `${this.baseUrl}${path}`;
105
- const headers = {
106
- accept: 'application/json',
107
- 'user-agent': `${USER_AGENT_PREFIX}/${this.version}`,
108
- };
109
- if (body !== undefined) headers['content-type'] = 'application/json';
110
-
111
- const controller = new AbortController();
112
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
113
- let response;
114
- try {
115
- response = await this.fetchImpl(url, {
116
- method,
117
- headers,
118
- body: body === undefined ? undefined : JSON.stringify(body),
119
- signal: controller.signal,
120
- });
121
- } catch (cause) {
122
- if (cause?.name === 'AbortError') {
123
- throw new NetworkError(`${method} ${url} timed out after ${this.timeoutMs} ms`, cause);
124
- }
125
- throw new NetworkError(`cannot reach ${this.baseUrl} — ${cause?.message ?? cause}`, cause);
126
- } finally {
127
- clearTimeout(timer);
128
- }
129
-
130
- const text = await response.text();
131
- let json = null;
132
- if (text) {
133
- try {
134
- json = JSON.parse(text);
135
- } catch {
136
- json = null;
137
- }
138
- }
139
-
140
- if (!response.ok) {
141
- throw toApiError(response, json);
142
- }
143
- return { json, response };
144
- }
145
- }
146
-
147
- /**
148
- * Turn an API error envelope into a message a person can act on.
149
- * API_SPEC §1.2: `{ "error": { code, message, request_id, hint? } }`.
150
- */
151
- function toApiError(response, json) {
152
- const err = json && typeof json === 'object' ? json.error : null;
153
- const code = err?.code ?? `http_${response.status}`;
154
- const requestId = err?.request_id ?? err?.requestId ?? null;
155
- const base = err?.message || `the API answered ${response.status}`;
156
- const hint = err?.hint ? ` ${err.hint}` : '';
157
- return new ApiError(`${explain(code)}${base}${hint}`, {
158
- code,
159
- status: response.status,
160
- requestId,
161
- retryAfter: response.headers?.get?.('retry-after') ?? null,
162
- });
163
- }
164
-
165
- /** Short prefixes that say what the code means for *this* CLI's user. */
166
- function explain(code) {
167
- switch (code) {
168
- case 'not_found':
169
- return 'no such secret — it was burned, expired, or the link is wrong: ';
170
- case 'already_accessed':
171
- return 'this one-time secret has already been read: ';
172
- case 'expired':
173
- return 'this secret has expired: ';
174
- case 'revoked':
175
- return 'the sender revoked this secret: ';
176
- case 'rate_limited':
177
- return 'too many requests, wait a minute: ';
178
- case 'quota_exceeded':
179
- return 'daily quota reached: ';
180
- case 'payload_too_large':
181
- return 'the secret is too large for an inline link: ';
182
- case 'recipient_denied':
183
- case 'unauthorized':
184
- case 'forbidden':
185
- return 'this secret requires a signed-in recipient, open it in a browser: ';
186
- default:
187
- return '';
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 CLI.
2
+ * Client-side cryptography for the EasyToPaste clients.
3
3
  *
4
- * This file is the terminal half of a contract the browser client already
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 this CLI deliberately does not implement (see README).
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 getRandomValues(new Uint8Array(KEY_BYTES));
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
- return Buffer.from(bytes).toString('base64url');
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
- * Buffer's own base64url decoder silently skips characters outside the
78
- * alphabet, so a truncated or corrupted fragment would decode to plausible
79
- * garbage and surface later as a confusing GCM failure. The shape is checked
80
- * first and rejected loudly instead.
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
- return new Uint8Array(Buffer.from(value, 'base64url'));
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 = getRandomValues(new Uint8Array(IV_BYTES));
106
- const cryptoKey = await subtle.importKey('raw', key, { name: 'AES-GCM', length: 256 }, false, [
107
- 'encrypt',
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 subtle.encrypt(
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 subtle.importKey('raw', key, { name: 'AES-GCM', length: 256 }, false, [
152
- 'decrypt',
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 subtle.decrypt(
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 CLI will not print it',
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. Node cannot promise the bytes were never
181
- * copied by the GC, so this shortens the window rather than closing it.
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) {