@jimmiewang/message-broker 0.0.0-stage → 0.0.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/README.md +78 -2
- package/bin/mb.js +273 -0
- package/lib/config.js +49 -0
- package/lib/crypto.js +54 -0
- package/lib/pack.js +30 -0
- package/lib/registry.js +80 -0
- package/message.dat +2 -0
- package/package.json +19 -4
package/README.md
CHANGED
|
@@ -1,3 +1,79 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @jimmiewang/message-broker
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
One-way message relay over the npm registry. The sender publishes a new
|
|
4
|
+
package version containing an AES-256-GCM-encrypted message; the receiver
|
|
5
|
+
polls the registry on a schedule, downloads new versions, decrypts and
|
|
6
|
+
appends them to a local inbox. Use case: driving an agent on an internal
|
|
7
|
+
machine that can only reach the npm registry, from anywhere (including a
|
|
8
|
+
phone via SSH on the sender).
|
|
9
|
+
|
|
10
|
+
## Why a new version per message
|
|
11
|
+
|
|
12
|
+
npm refuses to overwrite a published version, and `npm view <pkg> version`
|
|
13
|
+
is a cheap metadata call that does not download the tarball. So the version
|
|
14
|
+
number doubles as a message cursor: the receiver only downloads a tarball
|
|
15
|
+
when the remote version differs from its last-seen version.
|
|
16
|
+
|
|
17
|
+
## Threat model / limits
|
|
18
|
+
|
|
19
|
+
- Payloads are encrypted with AES-256-GCM using a pre-shared 32-byte key
|
|
20
|
+
stored only on the two machines (`~/.message-broker/key`, mode 0600).
|
|
21
|
+
The key never enters the package or git.
|
|
22
|
+
- Package metadata (name, version numbers, publish timestamps) is public on
|
|
23
|
+
the npm registry. Observers can see that messages exist and how often,
|
|
24
|
+
just not what they say.
|
|
25
|
+
- Treat the shared key like a credential: if it leaks, every message is
|
|
26
|
+
readable. Rotating the key means future messages use the new key; old
|
|
27
|
+
tarballs remain decryptable by anyone holding the old key.
|
|
28
|
+
- npm publish cannot be undone after the 72h unpublish window. Do not send
|
|
29
|
+
secrets you cannot accept living in the registry forever.
|
|
30
|
+
|
|
31
|
+
## Setup
|
|
32
|
+
|
|
33
|
+
Requires Node.js >= 18. No runtime dependencies (Node built-ins only).
|
|
34
|
+
|
|
35
|
+
### Sender machine (this checkout)
|
|
36
|
+
|
|
37
|
+
# 1. point the CLI at this package
|
|
38
|
+
mb init @jimmiewang/message-broker --dir /path/to/messsage-broker-sender
|
|
39
|
+
|
|
40
|
+
# 2. generate the shared key
|
|
41
|
+
mb keygen
|
|
42
|
+
|
|
43
|
+
# 3. authenticate with npm (interactive, do once)
|
|
44
|
+
npm login
|
|
45
|
+
|
|
46
|
+
# 4. rename the package in package.json to your real scope/name, then:
|
|
47
|
+
npm publish --access public
|
|
48
|
+
|
|
49
|
+
### Receiver machine (internal, registry-only)
|
|
50
|
+
|
|
51
|
+
npm install -g @jimmiewang/message-broker
|
|
52
|
+
mb init @jimmiewang/message-broker # no --dir needed
|
|
53
|
+
# install the same key printed by "mb keygen" on the sender:
|
|
54
|
+
mkdir -p ~/.message-broker && chmod 700 ~/.message-broker
|
|
55
|
+
printf '%s\n' '<key-base64>' > ~/.message-broker/key
|
|
56
|
+
chmod 600 ~/.message-broker/key
|
|
57
|
+
|
|
58
|
+
mb poll # safe to run repeatedly; no-op when version unchanged
|
|
59
|
+
mb inbox # list decrypted messages
|
|
60
|
+
|
|
61
|
+
Schedule `mb poll` with cron or launchd, e.g. every 5 minutes:
|
|
62
|
+
|
|
63
|
+
*/5 * * * * /usr/local/bin/mb poll >> ~/.message-broker/poll.log 2>&1
|
|
64
|
+
|
|
65
|
+
## Daily use
|
|
66
|
+
|
|
67
|
+
mb send "run the daily cardhobby check and fix any dirty players"
|
|
68
|
+
mb send -f ./instructions.txt
|
|
69
|
+
|
|
70
|
+
Each send: encrypts into `message.dat`, bumps the patch version
|
|
71
|
+
(0.0.7 -> 0.0.8, based on the higher of local/remote version), publishes.
|
|
72
|
+
If publish fails, the local version is rolled back automatically.
|
|
73
|
+
|
|
74
|
+
## Files on each machine
|
|
75
|
+
|
|
76
|
+
~/.message-broker/config.json package name, sender checkout dir
|
|
77
|
+
~/.message-broker/key shared AES-256 key (0600)
|
|
78
|
+
~/.message-broker/state.json receiver cursor (last seen version)
|
|
79
|
+
~/.message-broker/inbox.jsonl decrypted messages, one JSON per line
|
package/bin/mb.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const fs = require('node:fs');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
const cfgLib = require('../lib/config');
|
|
7
|
+
const reg = require('../lib/registry');
|
|
8
|
+
const { extractFile, withTempPack } = require('../lib/pack');
|
|
9
|
+
const { generateKey, encrypt, decrypt } = require('../lib/crypto');
|
|
10
|
+
|
|
11
|
+
const HELP = `mb — one-way message relay over the npm registry
|
|
12
|
+
|
|
13
|
+
Usage:
|
|
14
|
+
mb init <package-name> [--dir <package-dir>]
|
|
15
|
+
Save the npm package name (e.g. @scope/message-broker).
|
|
16
|
+
--dir is required on the SENDER: local checkout of this package.
|
|
17
|
+
mb keygen
|
|
18
|
+
Generate an AES-256 key at ~/.message-broker/key (mode 0600).
|
|
19
|
+
Copy the SAME key to the receiver machine at the same path.
|
|
20
|
+
mb send "<message>"
|
|
21
|
+
mb send -f <file>
|
|
22
|
+
Encrypt the message into message.dat, bump the patch version,
|
|
23
|
+
and run "npm publish". Requires "npm login" on this machine.
|
|
24
|
+
mb poll
|
|
25
|
+
Cheap "npm view" version check; on a new version, download the
|
|
26
|
+
tarball, decrypt message.dat and append it to the inbox.
|
|
27
|
+
Designed to be run from cron/launchd. Exit code stays 0 when
|
|
28
|
+
there is simply nothing new.
|
|
29
|
+
mb inbox [--tail N]
|
|
30
|
+
Print received messages (newest last).
|
|
31
|
+
mb status
|
|
32
|
+
Show local config, remote/latest and last-seen versions.
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
function die(msg) {
|
|
36
|
+
console.error(`Error: ${msg}`);
|
|
37
|
+
process.exit(1);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function parseFlags(argv) {
|
|
41
|
+
const flags = {};
|
|
42
|
+
const positional = [];
|
|
43
|
+
for (let i = 0; i < argv.length; i++) {
|
|
44
|
+
const tok = argv[i];
|
|
45
|
+
if (tok.startsWith('-')) {
|
|
46
|
+
const name = tok.replace(/^-+/, '');
|
|
47
|
+
const next = argv[i + 1];
|
|
48
|
+
if (next && !next.startsWith('-')) {
|
|
49
|
+
flags[name] = next;
|
|
50
|
+
i++;
|
|
51
|
+
} else {
|
|
52
|
+
flags[name] = true;
|
|
53
|
+
}
|
|
54
|
+
} else {
|
|
55
|
+
positional.push(tok);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return { flags, positional };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function bumpPatch(version) {
|
|
62
|
+
const m = /^(\d+)\.(\d+)\.(\d+)$/.exec(version);
|
|
63
|
+
if (!m) throw new Error(`Unexpected version format: ${version}`);
|
|
64
|
+
return `${m[1]}.${m[2]}.${Number(m[3]) + 1}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function compareSemver(a, b) {
|
|
68
|
+
const pa = a.split('.').map(Number);
|
|
69
|
+
const pb = b.split('.').map(Number);
|
|
70
|
+
for (let i = 0; i < 3; i++) {
|
|
71
|
+
if (pa[i] !== pb[i]) return pa[i] - pb[i];
|
|
72
|
+
}
|
|
73
|
+
return 0;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function statePath() {
|
|
77
|
+
return path.join(cfgLib.paths().dir, 'state.json');
|
|
78
|
+
}
|
|
79
|
+
function inboxPath() {
|
|
80
|
+
return path.join(cfgLib.paths().dir, 'inbox.jsonl');
|
|
81
|
+
}
|
|
82
|
+
function readState() {
|
|
83
|
+
const p = statePath();
|
|
84
|
+
return fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, 'utf8')) : { lastVersion: null };
|
|
85
|
+
}
|
|
86
|
+
function writeState(s) {
|
|
87
|
+
fs.writeFileSync(statePath(), JSON.stringify(s, null, 2) + '\n', { mode: 0o600 });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function cmdInit(args) {
|
|
91
|
+
const { flags, positional } = parseFlags(args);
|
|
92
|
+
const packageName = positional[0];
|
|
93
|
+
if (!packageName) die('usage: mb init <package-name> [--dir <package-dir>]');
|
|
94
|
+
const cfg = { packageName, packageDir: flags.dir || null };
|
|
95
|
+
cfgLib.writeConfig(cfg);
|
|
96
|
+
console.log(`Saved config to ${cfgLib.paths().config}`);
|
|
97
|
+
console.log(JSON.stringify(cfg, null, 2));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function cmdKeygen() {
|
|
101
|
+
const key = generateKey();
|
|
102
|
+
cfgLib.writeKey(key);
|
|
103
|
+
console.log(`Key written to ${cfgLib.paths().key} (mode 0600)`);
|
|
104
|
+
console.log('Copy this exact key to the receiver machine (same path), e.g.:');
|
|
105
|
+
console.log(` mkdir -p ~/.message-broker && chmod 700 ~/.message-broker`);
|
|
106
|
+
console.log(` printf '%s\\n' '${key}' > ~/.message-broker/key && chmod 600 ~/.message-broker/key`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function cmdSend(args) {
|
|
110
|
+
const { flags, positional } = parseFlags(args);
|
|
111
|
+
const cfg = cfgLib.readConfig();
|
|
112
|
+
if (!cfg.packageDir) die('config has no packageDir. Re-run: mb init <package-name> --dir <package-dir>');
|
|
113
|
+
const pkgJsonPath = path.join(cfg.packageDir, 'package.json');
|
|
114
|
+
if (!fs.existsSync(pkgJsonPath)) die(`package.json not found under ${cfg.packageDir}`);
|
|
115
|
+
|
|
116
|
+
let message;
|
|
117
|
+
if (flags.f || flags.file) {
|
|
118
|
+
message = fs.readFileSync(flags.f || flags.file, 'utf8');
|
|
119
|
+
} else {
|
|
120
|
+
message = positional.join(' ');
|
|
121
|
+
}
|
|
122
|
+
if (!message || !message.trim()) die('empty message. Use: mb send "..." or mb send -f <file>');
|
|
123
|
+
|
|
124
|
+
const key = cfgLib.readKey();
|
|
125
|
+
const sentAt = new Date().toISOString();
|
|
126
|
+
const envelope = encrypt(key, message, sentAt);
|
|
127
|
+
|
|
128
|
+
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
|
|
129
|
+
if (pkg.name !== cfg.packageName) {
|
|
130
|
+
die(`package name mismatch: config=${cfg.packageName} package.json=${pkg.name}`);
|
|
131
|
+
}
|
|
132
|
+
const previousVersion = pkg.version;
|
|
133
|
+
const remoteVersion = reg.getRemoteVersion(cfg.packageName);
|
|
134
|
+
const base = remoteVersion && compareSemver(remoteVersion, previousVersion) > 0
|
|
135
|
+
? remoteVersion
|
|
136
|
+
: previousVersion;
|
|
137
|
+
let nextVersion = bumpPatch(base);
|
|
138
|
+
|
|
139
|
+
const maxAttempts = 3;
|
|
140
|
+
let lastErr;
|
|
141
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
142
|
+
pkg.version = nextVersion;
|
|
143
|
+
fs.writeFileSync(pkgJsonPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
144
|
+
fs.writeFileSync(path.join(cfg.packageDir, 'message.dat'), envelope + '\n', { mode: 0o644 });
|
|
145
|
+
try {
|
|
146
|
+
const out = reg.publish(cfg.packageDir);
|
|
147
|
+
if (out) process.stdout.write(out);
|
|
148
|
+
console.log(`Published ${cfg.packageName}@${nextVersion} (${message.length} chars, encrypted)`);
|
|
149
|
+
return;
|
|
150
|
+
} catch (err) {
|
|
151
|
+
lastErr = err;
|
|
152
|
+
// Race with another publish (or stale remote metadata): try the next number.
|
|
153
|
+
if (/EPUBLISHCONFLICT|already exists|cannot publish over/.test(err.message) && attempt < maxAttempts) {
|
|
154
|
+
console.warn(`Version ${nextVersion} already taken, retrying with ${bumpPatch(nextVersion)}...`);
|
|
155
|
+
nextVersion = bumpPatch(nextVersion);
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
break;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// All attempts failed: roll the version back so state stays auditable.
|
|
163
|
+
pkg.version = previousVersion;
|
|
164
|
+
fs.writeFileSync(pkgJsonPath, JSON.stringify(pkg, null, 2) + '\n');
|
|
165
|
+
die(`npm publish failed after ${maxAttempts} attempt(s) (version rolled back to ${previousVersion}):\n${lastErr.message}`);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function cmdPoll() {
|
|
169
|
+
const cfg = cfgLib.readConfig();
|
|
170
|
+
const key = cfgLib.readKey();
|
|
171
|
+
const state = readState();
|
|
172
|
+
|
|
173
|
+
const allVersions = reg.listVersions(cfg.packageName);
|
|
174
|
+
if (allVersions.length === 0) {
|
|
175
|
+
console.log('No published version found yet.');
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const sorted = [...allVersions].sort(compareSemver);
|
|
179
|
+
|
|
180
|
+
// First run: anchor the cursor at the latest version without backfilling
|
|
181
|
+
// whatever was published before this receiver existed.
|
|
182
|
+
if (!state.lastVersion) {
|
|
183
|
+
const latest = sorted[sorted.length - 1];
|
|
184
|
+
writeState({ lastVersion: latest });
|
|
185
|
+
console.log(`Initialized cursor at ${cfg.packageName}@${latest} (no backfill).`);
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const unseen = sorted.filter((v) => compareSemver(v, state.lastVersion) > 0);
|
|
190
|
+
if (unseen.length === 0) {
|
|
191
|
+
console.log(`No new messages (latest ${state.lastVersion}, already seen).`);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Backfill every unseen version in order, so messages sent between two
|
|
196
|
+
// poll cycles are never skipped.
|
|
197
|
+
for (const version of unseen) {
|
|
198
|
+
const spec = `${cfg.packageName}@${version}`;
|
|
199
|
+
withTempPack(spec, (tgz) => {
|
|
200
|
+
const envelope = extractFile(tgz, 'message.dat');
|
|
201
|
+
const { text, sentAt } = decrypt(key, envelope);
|
|
202
|
+
const record = {
|
|
203
|
+
version,
|
|
204
|
+
sentAt,
|
|
205
|
+
receivedAt: new Date().toISOString(),
|
|
206
|
+
text,
|
|
207
|
+
};
|
|
208
|
+
fs.appendFileSync(inboxPath(), JSON.stringify(record) + '\n', { mode: 0o600 });
|
|
209
|
+
writeState({ lastVersion: version });
|
|
210
|
+
console.log(`New message ${spec} (sent ${sentAt || 'unknown'}):`);
|
|
211
|
+
console.log(text);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function cmdInbox(args) {
|
|
217
|
+
const { flags } = parseFlags(args);
|
|
218
|
+
const p = inboxPath();
|
|
219
|
+
if (!fs.existsSync(p)) {
|
|
220
|
+
console.log('Inbox is empty.');
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
let lines = fs.readFileSync(p, 'utf8').split('\n').filter(Boolean);
|
|
224
|
+
if (flags.tail) lines = lines.slice(-Number(flags.tail));
|
|
225
|
+
for (const line of lines) {
|
|
226
|
+
const r = JSON.parse(line);
|
|
227
|
+
console.log(`--- ${r.version} | sent ${r.sentAt || '?'} | received ${r.receivedAt}`);
|
|
228
|
+
console.log(r.text);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function cmdStatus() {
|
|
233
|
+
const cfg = cfgLib.readConfig();
|
|
234
|
+
const state = readState();
|
|
235
|
+
let remote = null;
|
|
236
|
+
try {
|
|
237
|
+
remote = reg.getRemoteVersion(cfg.packageName);
|
|
238
|
+
} catch (err) {
|
|
239
|
+
remote = `unreachable (${err.message.split('\n')[0]})`;
|
|
240
|
+
}
|
|
241
|
+
console.log(JSON.stringify({
|
|
242
|
+
configPath: cfgLib.paths().config,
|
|
243
|
+
keyPath: cfgLib.paths().key,
|
|
244
|
+
keyPresent: fs.existsSync(cfgLib.paths().key),
|
|
245
|
+
packageName: cfg.packageName,
|
|
246
|
+
packageDir: cfg.packageDir,
|
|
247
|
+
remoteVersion: remote,
|
|
248
|
+
lastSeenVersion: state.lastVersion,
|
|
249
|
+
inboxPath: inboxPath(),
|
|
250
|
+
}, null, 2));
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function main() {
|
|
254
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
255
|
+
switch (cmd) {
|
|
256
|
+
case 'init': return cmdInit(rest);
|
|
257
|
+
case 'keygen': return cmdKeygen();
|
|
258
|
+
case 'send': return cmdSend(rest);
|
|
259
|
+
case 'poll': return cmdPoll();
|
|
260
|
+
case 'inbox': return cmdInbox(rest);
|
|
261
|
+
case 'status': return cmdStatus();
|
|
262
|
+
case '--help':
|
|
263
|
+
case '-h':
|
|
264
|
+
case 'help':
|
|
265
|
+
case undefined:
|
|
266
|
+
console.log(HELP);
|
|
267
|
+
break;
|
|
268
|
+
default:
|
|
269
|
+
die(`unknown command "${cmd}". Run "mb help".`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
main();
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const os = require('node:os');
|
|
5
|
+
const path = require('node:path');
|
|
6
|
+
|
|
7
|
+
const DIR = path.join(os.homedir(), '.message-broker');
|
|
8
|
+
const CONFIG_PATH = path.join(DIR, 'config.json');
|
|
9
|
+
const KEY_PATH = path.join(DIR, 'key');
|
|
10
|
+
|
|
11
|
+
function ensureDir() {
|
|
12
|
+
fs.mkdirSync(DIR, { recursive: true, mode: 0o700 });
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function readConfig() {
|
|
16
|
+
if (!fs.existsSync(CONFIG_PATH)) {
|
|
17
|
+
throw new Error(
|
|
18
|
+
`Config not found at ${CONFIG_PATH}. Run "mb init <package-name>" first.`
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function writeConfig(cfg) {
|
|
25
|
+
ensureDir();
|
|
26
|
+
fs.writeFileSync(CONFIG_PATH, JSON.stringify(cfg, null, 2) + '\n', {
|
|
27
|
+
mode: 0o600,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function readKey() {
|
|
32
|
+
if (!fs.existsSync(KEY_PATH)) {
|
|
33
|
+
throw new Error(
|
|
34
|
+
`Key not found at ${KEY_PATH}. Run "mb keygen" here, then copy the same key to the receiver (same path).`
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
return fs.readFileSync(KEY_PATH, 'utf8').trim();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function writeKey(keyB64) {
|
|
41
|
+
ensureDir();
|
|
42
|
+
fs.writeFileSync(KEY_PATH, keyB64 + '\n', { mode: 0o600 });
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function paths() {
|
|
46
|
+
return { dir: DIR, config: CONFIG_PATH, key: KEY_PATH };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
module.exports = { ensureDir, readConfig, writeConfig, readKey, writeKey, paths };
|
package/lib/crypto.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('node:crypto');
|
|
4
|
+
|
|
5
|
+
const ALGO = 'aes-256-gcm';
|
|
6
|
+
|
|
7
|
+
function generateKey() {
|
|
8
|
+
return crypto.randomBytes(32).toString('base64');
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function keyToBuffer(keyB64) {
|
|
12
|
+
const buf = Buffer.from(keyB64, 'base64');
|
|
13
|
+
if (buf.length !== 32) {
|
|
14
|
+
throw new Error('Invalid key: expected 32 bytes (base64-encoded). Run "mb keygen".');
|
|
15
|
+
}
|
|
16
|
+
return buf;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Payload envelope (JSON, base64 fields):
|
|
20
|
+
// { v: 1, iv, tag, data, sentAt }
|
|
21
|
+
function encrypt(keyB64, plaintext, sentAt) {
|
|
22
|
+
const key = keyToBuffer(keyB64);
|
|
23
|
+
const iv = crypto.randomBytes(12);
|
|
24
|
+
const cipher = crypto.createCipheriv(ALGO, key, iv);
|
|
25
|
+
const data = Buffer.concat([
|
|
26
|
+
cipher.update(Buffer.from(plaintext, 'utf8')),
|
|
27
|
+
cipher.final(),
|
|
28
|
+
]);
|
|
29
|
+
const tag = cipher.getAuthTag();
|
|
30
|
+
return JSON.stringify({
|
|
31
|
+
v: 1,
|
|
32
|
+
iv: iv.toString('base64'),
|
|
33
|
+
tag: tag.toString('base64'),
|
|
34
|
+
data: data.toString('base64'),
|
|
35
|
+
sentAt,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function decrypt(keyB64, envelopeJson) {
|
|
40
|
+
const key = keyToBuffer(keyB64);
|
|
41
|
+
const env = JSON.parse(envelopeJson);
|
|
42
|
+
if (env.v !== 1 || !env.iv || !env.tag || !env.data) {
|
|
43
|
+
throw new Error('Unrecognized or malformed message envelope.');
|
|
44
|
+
}
|
|
45
|
+
const decipher = crypto.createDecipheriv(ALGO, key, Buffer.from(env.iv, 'base64'));
|
|
46
|
+
decipher.setAuthTag(Buffer.from(env.tag, 'base64'));
|
|
47
|
+
const plaintext = Buffer.concat([
|
|
48
|
+
decipher.update(Buffer.from(env.data, 'base64')),
|
|
49
|
+
decipher.final(),
|
|
50
|
+
]).toString('utf8');
|
|
51
|
+
return { text: plaintext, sentAt: env.sentAt || null };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
module.exports = { generateKey, encrypt, decrypt };
|
package/lib/pack.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const os = require('node:os');
|
|
6
|
+
const { execFileSync } = require('node:child_process');
|
|
7
|
+
|
|
8
|
+
// Extract a single file from an npm tarball without third-party deps.
|
|
9
|
+
// npm tarballs always contain a top-level "package/" directory.
|
|
10
|
+
function extractFile(tgzPath, relativeFile) {
|
|
11
|
+
const tarMember = `package/${relativeFile}`;
|
|
12
|
+
const out = execFileSync(
|
|
13
|
+
'tar',
|
|
14
|
+
['-xzOf', tgzPath, tarMember],
|
|
15
|
+
{ encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 }
|
|
16
|
+
);
|
|
17
|
+
return out;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function withTempPack(packageSpec, fn) {
|
|
21
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mb-pack-'));
|
|
22
|
+
try {
|
|
23
|
+
const tgz = require('./registry').pack(packageSpec, dir);
|
|
24
|
+
return fn(tgz);
|
|
25
|
+
} finally {
|
|
26
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
module.exports = { extractFile, withTempPack };
|
package/lib/registry.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { execFileSync } = require('node:child_process');
|
|
4
|
+
|
|
5
|
+
// All registry access goes through the npm CLI itself, so registry URL,
|
|
6
|
+
// proxy and auth settings are inherited from the machine's npm config.
|
|
7
|
+
|
|
8
|
+
function view(packageName, field) {
|
|
9
|
+
const args = ['view', packageName];
|
|
10
|
+
if (field) args.push(field);
|
|
11
|
+
try {
|
|
12
|
+
const out = execFileSync('npm', args, {
|
|
13
|
+
encoding: 'utf8',
|
|
14
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
15
|
+
}).trim();
|
|
16
|
+
return out;
|
|
17
|
+
} catch (err) {
|
|
18
|
+
// E404 on first use (no version published yet) is a normal state.
|
|
19
|
+
const stderr = (err.stderr || '') + (err.stdout || '');
|
|
20
|
+
if (/E404|code E404|404/.test(stderr)) {
|
|
21
|
+
const e = new Error(`NPM_E404: ${packageName} has no published versions yet`);
|
|
22
|
+
e.code = 'NPM_E404';
|
|
23
|
+
throw e;
|
|
24
|
+
}
|
|
25
|
+
throw new Error(`npm view failed: ${stderr || err.message}`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function getRemoteVersion(packageName) {
|
|
30
|
+
try {
|
|
31
|
+
return view(packageName, 'version');
|
|
32
|
+
} catch (err) {
|
|
33
|
+
if (err.code === 'NPM_E404') return null;
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function getTarballUrl(packageName, version) {
|
|
39
|
+
const out = view(packageName, 'dist.tarball');
|
|
40
|
+
// npm view dist.tarball prints one URL; when a version arg is needed we
|
|
41
|
+
// pass it via the name@version form handled by the caller.
|
|
42
|
+
void version;
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function listVersions(packageName) {
|
|
47
|
+
try {
|
|
48
|
+
const out = execFileSync(
|
|
49
|
+
'npm',
|
|
50
|
+
['view', packageName, 'versions', '--json'],
|
|
51
|
+
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }
|
|
52
|
+
).trim();
|
|
53
|
+
const parsed = JSON.parse(out);
|
|
54
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
55
|
+
} catch (err) {
|
|
56
|
+
const stderr = (err.stderr || '') + (err.stdout || '');
|
|
57
|
+
if (/E404|404/.test(stderr)) return [];
|
|
58
|
+
throw new Error(`npm view versions failed: ${stderr || err.message}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function pack(packageSpec, destDir) {
|
|
63
|
+
const out = execFileSync('npm', ['pack', packageSpec, '--pack-destination', destDir], {
|
|
64
|
+
encoding: 'utf8',
|
|
65
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
66
|
+
}).trim();
|
|
67
|
+
// npm pack prints the generated tgz filename on the last line.
|
|
68
|
+
const lines = out.split('\n').filter(Boolean);
|
|
69
|
+
return require('node:path').join(destDir, lines[lines.length - 1]);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function publish(cwd) {
|
|
73
|
+
return execFileSync('npm', ['publish'], {
|
|
74
|
+
cwd,
|
|
75
|
+
encoding: 'utf8',
|
|
76
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = { view, getRemoteVersion, listVersions, getTarballUrl, pack, publish };
|
package/message.dat
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jimmiewang/message-broker",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "One-way message relay over the npm registry (AES-256-GCM encrypted payloads)",
|
|
5
|
+
"bin": {
|
|
6
|
+
"mb": "bin/mb.js"
|
|
7
|
+
},
|
|
8
|
+
"files": [
|
|
9
|
+
"bin",
|
|
10
|
+
"lib",
|
|
11
|
+
"message.dat"
|
|
12
|
+
],
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=18"
|
|
15
|
+
},
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public"
|
|
18
|
+
},
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"private": false
|
|
21
|
+
}
|