javascript-solid-server 0.0.197 → 0.0.198

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/bin/jss.js CHANGED
@@ -307,6 +307,31 @@ program
307
307
  }
308
308
  });
309
309
 
310
+ /**
311
+ * Install command — install a Solid app from the default registry
312
+ * (`github.com/solid-apps/<name>`) into a running pod.
313
+ *
314
+ * Phase 1 of #464 / scoped in #478. Hardcodes the default registry;
315
+ * later phases add <org>/<repo>, full URLs, refs, renames, did:nostr
316
+ * resolution, NIP-98 auth, curated default sets, and --bundle.
317
+ */
318
+ program
319
+ .command('install <names...>')
320
+ .description('Install a Solid app from github.com/solid-apps/<name> into a running pod')
321
+ .option('--pod <url>', 'Target pod URL', 'http://localhost:4443')
322
+ .option('--user <name>', 'Username for IDP auth', 'me')
323
+ .option('--password <pw>', 'Password (default: $JSS_SINGLE_USER_PASSWORD or "me")')
324
+ .option('--nostr-privkey <hex>', 'Sign install pushes with NIP-98 using this 64-char hex Nostr privkey instead of fetching a bearer token (default: $NOSTR_PRIVKEY)')
325
+ .action(async (names, options) => {
326
+ try {
327
+ const { runInstall } = await import('../src/cli/install.js');
328
+ await runInstall(names, options);
329
+ } catch (err) {
330
+ // runInstall prints its own per-app error lines; we just exit non-zero.
331
+ process.exit(1);
332
+ }
333
+ });
334
+
310
335
  /**
311
336
  * Init command - interactive configuration
312
337
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.197",
3
+ "version": "0.0.198",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -0,0 +1,283 @@
1
+ /**
2
+ * `jss install <name>` — install a Solid app into a running pod.
3
+ *
4
+ * Phase 1 of #464 (see #478 for the scoped issue). Hardcodes the
5
+ * default registry to `github.com/solid-apps/<name>`. Later phases
6
+ * add `<org>/<repo>` shorthand, full URLs, `#<ref>` pinning,
7
+ * `=<name>` rename, `--did` resolution, `--nostr-privkey` NIP-98
8
+ * auth, a curated default set, and `--bundle`.
9
+ *
10
+ * The install is a thin shell over the auto-init + updateInstead +
11
+ * regular-repo machinery already in `src/handlers/git.js`:
12
+ *
13
+ * 1. POST <pod>/idp/credentials with the supplied creds → bearer token
14
+ * 2. `git clone <source> /tmp/<name>` (full clone — shallow pushes
15
+ * are rejected by JSS git-receive)
16
+ * 3. Push the clone to `<pod>/public/apps/<name>` with the bearer
17
+ * header, on BOTH `HEAD:main` and `HEAD:gh-pages` so it works
18
+ * regardless of the operator's `init.defaultBranch`. Whichever
19
+ * matches server-side HEAD triggers `updateInstead` and extracts
20
+ * the working tree; the other creates a stranded ref.
21
+ *
22
+ * Idempotent on re-run (existing repo at the path accepts the push
23
+ * normally). Skip-on-existing-non-repo translates auto-init's
24
+ * "won't init a non-empty path" 404 into a friendly message.
25
+ */
26
+
27
+ import { spawnSync } from 'child_process';
28
+ import { existsSync } from 'fs';
29
+ import { join } from 'path';
30
+ import { nip98Token } from '../nostr/event.js';
31
+
32
+ // ANSI helpers — keep zero-dep so this works in any embedded usage.
33
+ const c = (n) => (s) => `\x1b[${n}m${s}\x1b[0m`;
34
+ const green = c(32);
35
+ const yellow = c(33);
36
+ const red = c(31);
37
+ const dim = c(2);
38
+ const bold = c(1);
39
+
40
+ /**
41
+ * Parse an app spec. Accepts (Phase 2 of #464):
42
+ * - bare name → github.com/solid-apps/<name> (default registry)
43
+ * - "<org>/<repo>" → github.com/<org>/<repo>
44
+ * - "https://..." full URL → as-is (must point at a git repo)
45
+ * Each form may carry an optional "#<ref>" suffix to pin a tag or branch:
46
+ * chrome#v1.2 / solid-apps/chrome#main / https://...#v2
47
+ * And an optional "=<name>" suffix to override the pod-path name:
48
+ * litecut/litecut.github.io=litecut
49
+ */
50
+ function parseAppSpec(input) {
51
+ // Pull off the rename suffix first, then the ref suffix.
52
+ let base = input;
53
+ let renameName = null;
54
+ const eqIx = base.lastIndexOf('=');
55
+ if (eqIx > 0) {
56
+ renameName = base.slice(eqIx + 1);
57
+ base = base.slice(0, eqIx);
58
+ }
59
+ let ref = null;
60
+ const hashIx = base.lastIndexOf('#');
61
+ if (hashIx > 0) {
62
+ ref = base.slice(hashIx + 1) || null;
63
+ base = base.slice(0, hashIx);
64
+ }
65
+ let source, name;
66
+ if (/^https?:\/\//.test(base)) {
67
+ source = base.replace(/\.git$/, '').replace(/\/$/, '');
68
+ name = source.split('/').pop();
69
+ } else if (base.includes('/')) {
70
+ const cleaned = base.replace(/\.git$/, '').replace(/^\/+|\/+$/g, '');
71
+ if (cleaned.split('/').length !== 2) {
72
+ return { error: 'expected <org>/<repo> shorthand' };
73
+ }
74
+ source = `https://github.com/${cleaned}`;
75
+ name = cleaned.split('/').pop();
76
+ } else {
77
+ source = `https://github.com/solid-apps/${base}`;
78
+ name = base;
79
+ }
80
+ if (renameName) name = renameName;
81
+ if (!/^[a-z0-9][a-z0-9_.-]*$/i.test(name)) {
82
+ return { error: `invalid pod-path name "${name}"` };
83
+ }
84
+ if (ref && !/^[a-z0-9][a-z0-9_./-]*$/i.test(ref)) {
85
+ return { error: `invalid ref "${ref}"` };
86
+ }
87
+ return { source, name, ref };
88
+ }
89
+
90
+ /**
91
+ * Fetch a bearer token from the pod's IDP, or null if the pod runs
92
+ * with `--public` (no auth required for writes).
93
+ */
94
+ async function fetchToken({ pod, user, password }) {
95
+ // First check whether the pod accepts unauthenticated writes — if so,
96
+ // we don't need a token. Probe with HEAD on /public/ (which any pod
97
+ // exposes); if writes there require auth, we'll need the token.
98
+ // For Phase 1 we just always try to fetch a token; if the IDP isn't
99
+ // running, we fall through with a clear error.
100
+ try {
101
+ const r = await fetch(`${pod}/idp/credentials`, {
102
+ method: 'POST',
103
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
104
+ body: new URLSearchParams({ username: user, password })
105
+ });
106
+ if (r.status === 404) {
107
+ // No IDP — pod is likely in --public mode. Proceed without a token.
108
+ return null;
109
+ }
110
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
111
+ const j = await r.json();
112
+ if (!j.access_token) throw new Error('no access_token in response');
113
+ return j.access_token;
114
+ } catch (e) {
115
+ throw new Error(`Could not authenticate against ${pod}: ${e.message}`);
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Install one app spec to one pod. Returns a status object the caller
121
+ * uses for per-app output + exit-code aggregation.
122
+ */
123
+ async function installOne({ spec, pod, token, nostrPrivkey }) {
124
+ const { source, name, ref } = spec;
125
+ const dest = `${pod}/public/apps/${name}`;
126
+ const tmp = join('/tmp', `jss-install-${name}-${process.pid}`);
127
+
128
+ // Clean any stale tmp from a prior failed run.
129
+ if (existsSync(tmp)) spawnSync('rm', ['-rf', tmp], { stdio: 'ignore' });
130
+
131
+ // Clone (no --depth: shallow pushes are rejected by JSS git-receive).
132
+ // --branch picks a tag or branch when pinned (e.g. `foo/bar#v2`).
133
+ const cloneArgs = ['clone', '--quiet'];
134
+ if (ref) cloneArgs.push('--branch', ref);
135
+ cloneArgs.push(source, tmp);
136
+ const clone = spawnSync('git', cloneArgs, {
137
+ stdio: ['ignore', 'pipe', 'pipe']
138
+ });
139
+ if (clone.status !== 0) {
140
+ const err = clone.stderr?.toString?.().trim() || '';
141
+ return { name, status: 'failed', reason: `clone failed${err ? `: ${err.slice(0, 300)}` : ''}` };
142
+ }
143
+
144
+ // Build the Authorization header for the push. NIP-98 (Phase 4)
145
+ // signs a Nostr event with the user's Schnorr key — no IDP creds
146
+ // needed; JSS verifies via src/auth/token.js and returns a
147
+ // did:nostr:<hex> identity for ACL matching.
148
+ //
149
+ // Git makes BOTH an advertise GET (`info/refs?service=git-receive-pack`)
150
+ // and a receive POST (`git-receive-pack`) on the same http.extraHeader.
151
+ // JSS is lenient for git clients (src/auth/nostr.js): it accepts a
152
+ // NIP-98 event whose `u` is a prefix of the request URL, and whose
153
+ // `method` is `*` as a wildcard. Sign the base URL with method `*`
154
+ // so the same event passes auth on both requests.
155
+ const authHeader = () => {
156
+ if (nostrPrivkey) {
157
+ const b64 = nip98Token(dest, '*', nostrPrivkey);
158
+ return `Authorization: Nostr ${b64}`;
159
+ }
160
+ if (token) return `Authorization: Bearer ${token}`;
161
+ return null;
162
+ };
163
+
164
+ // Dual push: HEAD:main and HEAD:gh-pages. Whichever matches server-
165
+ // side HEAD triggers updateInstead and extracts the working tree.
166
+ // The other just creates a stranded ref (harmless). Idempotent.
167
+ // Each push gets a freshly-signed NIP-98 event (the signature is
168
+ // tied to a specific u + method + timestamp window).
169
+ const pushArgs = (branch) => {
170
+ const args = ['-C', tmp];
171
+ const auth = authHeader();
172
+ if (auth) args.push('-c', `http.extraHeader=${auth}`);
173
+ args.push('push', dest, `HEAD:${branch}`);
174
+ return args;
175
+ };
176
+
177
+ const pushMain = spawnSync('git', pushArgs('main'), { stdio: ['ignore', 'pipe', 'pipe'] });
178
+ const errMain = pushMain.stderr?.toString?.() || '';
179
+
180
+ // Auto-init refuses on a non-empty target dir → 404 / "not found".
181
+ // Distinguish "path already in use" from real errors.
182
+ if (pushMain.status !== 0 && (errMain.includes('not found') || errMain.includes('404'))) {
183
+ spawnSync('rm', ['-rf', tmp], { stdio: 'ignore' });
184
+ return { name, status: 'skipped', reason: 'path already in use' };
185
+ }
186
+
187
+ const pushPages = spawnSync('git', pushArgs('gh-pages'), { stdio: ['ignore', 'pipe', 'pipe'] });
188
+
189
+ if (pushMain.status !== 0 && pushPages.status !== 0) {
190
+ const err = (errMain + '\n' + (pushPages.stderr?.toString?.() || '')).trim();
191
+ spawnSync('rm', ['-rf', tmp], { stdio: 'ignore' });
192
+ return { name, status: 'failed', reason: `push failed: ${err.slice(0, 400)}` };
193
+ }
194
+
195
+ spawnSync('rm', ['-rf', tmp], { stdio: 'ignore' });
196
+ return { name, status: 'installed', dest: `${dest}/` };
197
+ }
198
+
199
+ /**
200
+ * Public entry point. Called from bin/jss.js's `install` subcommand
201
+ * action. Throws to signal a non-zero exit; returns normally for
202
+ * partial success (per-app errors are reported but don't fail-fast).
203
+ */
204
+ export async function runInstall(names, options) {
205
+ const pod = (options.pod || 'http://localhost:4443').replace(/\/$/, '');
206
+ const user = options.user || 'me';
207
+ const password = options.password || process.env.JSS_SINGLE_USER_PASSWORD || 'me';
208
+ const nostrPrivkey = options.nostrPrivkey || process.env.NOSTR_PRIVKEY || null;
209
+
210
+ if (!names || names.length === 0) {
211
+ throw new Error('expected at least one app name. Try: `jss install chrome`');
212
+ }
213
+
214
+ // Validate Nostr privkey if supplied (64 lowercase-hex chars).
215
+ if (nostrPrivkey && !/^[0-9a-f]{64}$/i.test(nostrPrivkey)) {
216
+ console.error(red('✗ --nostr-privkey must be 64 hex chars'));
217
+ throw new Error('invalid --nostr-privkey');
218
+ }
219
+
220
+ // Validate every spec up front so we report invalid names before
221
+ // doing any network work.
222
+ const specs = [];
223
+ for (const n of names) {
224
+ const spec = parseAppSpec(n);
225
+ if (spec.error) {
226
+ console.error(red(`✗ ${n}: ${spec.error}`));
227
+ throw new Error(`invalid app spec: ${n}`);
228
+ }
229
+ specs.push(spec);
230
+ }
231
+
232
+ console.log(bold(`\nInstalling ${specs.length} app${specs.length === 1 ? '' : 's'} → `) + green(pod));
233
+ if (nostrPrivkey) console.log(dim(' (signing with Nostr privkey — NIP-98)'));
234
+ console.log('');
235
+
236
+ // With --nostr-privkey we sign each push as NIP-98; no bearer token
237
+ // needed. Otherwise fetch the bearer token from the pod's IDP.
238
+ let token = null;
239
+ if (!nostrPrivkey) try {
240
+ token = await fetchToken({ pod, user, password });
241
+ } catch (e) {
242
+ console.error(red(`✗ ${e.message}`));
243
+ console.error(dim(' Is the pod running? Try: `jss start`'));
244
+ throw e;
245
+ }
246
+
247
+ // Decode hex privkey once for installOne (nip98Token wants bytes).
248
+ const privkeyBytes = nostrPrivkey
249
+ ? Uint8Array.from(Buffer.from(nostrPrivkey, 'hex'))
250
+ : null;
251
+
252
+ let okCount = 0;
253
+ let failCount = 0;
254
+ for (const spec of specs) {
255
+ const result = await installOne({ spec, pod, token, nostrPrivkey: privkeyBytes });
256
+ switch (result.status) {
257
+ case 'installed':
258
+ console.log(green(`✓ ${result.name}`) + dim(` → ${result.dest}`));
259
+ okCount++;
260
+ break;
261
+ case 'skipped':
262
+ console.log(yellow(`⊘ ${result.name}`) + dim(`: skipped (${result.reason})`));
263
+ break;
264
+ case 'failed':
265
+ console.error(red(`✗ ${result.name}: ${result.reason.split(':')[0]}`));
266
+ if (result.reason.includes(':')) {
267
+ console.error(dim(` ${result.reason.slice(result.reason.indexOf(':') + 1).trim()}`));
268
+ }
269
+ failCount++;
270
+ break;
271
+ }
272
+ }
273
+
274
+ console.log('');
275
+ console.log(bold(`${okCount}/${specs.length} installed.`));
276
+ if (okCount > 0) {
277
+ console.log(dim('Open in browser: ') + `${pod}/public/apps/`);
278
+ }
279
+
280
+ if (failCount > 0) {
281
+ throw new Error(`${failCount} of ${specs.length} install(s) failed`);
282
+ }
283
+ }