@quadient/skillshare 1.21.0 → 1.23.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 +77 -0
- package/dist/help.js +13 -4
- package/dist/index.js +58 -0
- package/dist/pages-backups.js +168 -0
- package/dist/pages-tunnel.js +387 -0
- package/dist/service-manager.js +12 -11
- package/dist/tunnel-windows-service.js +145 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -385,6 +385,83 @@ printf %s "$TOKEN" | skillshare pages secrets set my-app API_TOKEN
|
|
|
385
385
|
skillshare pages secrets delete my-app API_TOKEN
|
|
386
386
|
```
|
|
387
387
|
|
|
388
|
+
## Page backups (1.22.0+)
|
|
389
|
+
|
|
390
|
+
Owners and administrators back up the data of a celld Page (D1, KV, R2, Durable
|
|
391
|
+
Objects, Workflows). The Page is stopped while a backup or restore runs; the
|
|
392
|
+
command waits for it unless `--no-wait`. Every backup is deleted automatically
|
|
393
|
+
when it expires: `create` keeps it for `--keep` days (default 30, at most 365),
|
|
394
|
+
and daily backups are kept for 7 days.
|
|
395
|
+
|
|
396
|
+
```bash
|
|
397
|
+
skillshare pages backups list my-app
|
|
398
|
+
skillshare pages backups create my-app --keep 7
|
|
399
|
+
skillshare pages backups daily my-app on
|
|
400
|
+
skillshare pages backups delete my-app 2
|
|
401
|
+
skillshare pages backups restore my-app 3
|
|
402
|
+
skillshare pages backups restore my-app 3 --confirm my-app # scripts without a terminal
|
|
403
|
+
```
|
|
404
|
+
|
|
405
|
+
`restore` replaces all current data of the Page; data written since the backup is
|
|
406
|
+
lost. It asks twice in a terminal; without one it needs the slug again in `--confirm`.
|
|
407
|
+
|
|
408
|
+
## Page tunnels (1.23.0+)
|
|
409
|
+
|
|
410
|
+
`skillshare pages tunnel` publishes an application running on your computer as a
|
|
411
|
+
SkillShare Page, without uploading it. The first run signs you in (if needed), asks
|
|
412
|
+
which local port to publish and the Page name, creates the Page and issues the
|
|
413
|
+
tunnel **its own secret**. It also downloads the **tunnel agent** for your OS and CPU
|
|
414
|
+
from SkillShare (`skillshare-tunnel`, a native executable built from
|
|
415
|
+
[tunnel-agent/](../tunnel-agent/README.md)) and checks it against the SHA-256 the
|
|
416
|
+
server lists. The agent holds the tunnel with its secret alone, without your login,
|
|
417
|
+
so it keeps working in a service, after your login expires and before anyone signs in.
|
|
418
|
+
|
|
419
|
+
```bash
|
|
420
|
+
skillshare pages tunnel # asks for the port and the name
|
|
421
|
+
skillshare pages tunnel my-tool --port 3000 # the same without questions
|
|
422
|
+
skillshare pages tunnel run # run the agent in the terminal
|
|
423
|
+
skillshare pages tunnel list
|
|
424
|
+
skillshare pages tunnel remove my-tool
|
|
425
|
+
skillshare pages tunnel service install | status | logs | uninstall
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
The secret is saved with the tunnel in `tunnels.json` in the CLI directory (readable
|
|
429
|
+
only by you) and SkillShare stores only its hash. Running `pages tunnel` for the same
|
|
430
|
+
Page again issues a new secret and disconnects whoever used the old one. An owner or an
|
|
431
|
+
administrator revokes it with **Revoke secret** on the Page's overview; the computer is
|
|
432
|
+
disconnected at once and stays out until an owner sets the tunnel up again. The tunnel
|
|
433
|
+
acts as the owner who created the secret and stops when they no longer own the Page.
|
|
434
|
+
|
|
435
|
+
Setup offers to keep the agent running in the background:
|
|
436
|
+
|
|
437
|
+
- **Windows:** the agent itself is the Windows service `SkillshareTunnels` (*Skillshare
|
|
438
|
+
Page tunnels*), started automatically with Windows, before anyone signs in, under the
|
|
439
|
+
virtual account `NT SERVICE\SkillshareTunnels`. Installing, updating and removing it
|
|
440
|
+
needs an administrator; from a normal terminal Windows asks for consent. The service
|
|
441
|
+
gets copies of the agent and of your tunnels with their secrets in
|
|
442
|
+
`%ProgramData%\Skillshare\Tunnels`, readable only by the service, SYSTEM and
|
|
443
|
+
administrators (`logs\` is readable by local users). Setting up or removing a tunnel
|
|
444
|
+
updates the service; uninstalling deletes the directory with the secrets.
|
|
445
|
+
- **macOS and Linux:** a launchd agent or systemd user service that starts at login and
|
|
446
|
+
runs a copy of the agent with your `tunnels.json`. A Linux user service keeps running
|
|
447
|
+
without an open session only after `loginctl enable-linger`. Linux needs glibc 2.34 or
|
|
448
|
+
newer (Ubuntu 22.04, Debian 12, RHEL 9).
|
|
449
|
+
|
|
450
|
+
A new tunnel Page opens **only for its owners**. Share it with other people in its
|
|
451
|
+
**Settings** on SkillShare (Access); everything else about the Page (co-owners,
|
|
452
|
+
comments, rename) works as for any Page. Like a celld app, the application receives
|
|
453
|
+
the viewer in `X-Skillshare-User` (Base64 JSON with `id`, `displayName`, `email`,
|
|
454
|
+
`isOwner`, `isAdmin`), plus `X-Skillshare-Page` and `X-Skillshare-Base-Url`, and is
|
|
455
|
+
served under `/p/<slug>/`, so configure its base path (for example Vite's `base`).
|
|
456
|
+
SkillShare's cookies and tokens are not forwarded. HTTP streaming and WebSockets work.
|
|
457
|
+
|
|
458
|
+
Only the port in the configuration is ever reached; SkillShare cannot ask for another
|
|
459
|
+
one. Let the application listen on `localhost` only: anyone who can reach the port
|
|
460
|
+
directly can send it a forged `X-Skillshare-User`. Only one computer serves a Page at
|
|
461
|
+
a time; while the Page is not connected, viewers get an offline notice. A service keeps
|
|
462
|
+
the agent it was installed with; `pages tunnel service install` updates it to the
|
|
463
|
+
server's current one.
|
|
464
|
+
|
|
388
465
|
## Page comments (1.13.0+)
|
|
389
466
|
|
|
390
467
|
Every Page is also served at `/pa/<slug>/` with an **Annotations** button. Signed-in
|
package/dist/help.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs';
|
|
2
2
|
export const GLOBAL_FLAGS = ['token', 'server', 'help'];
|
|
3
|
-
export const BOOLEAN_FLAGS = new Set(['all', 'digest', 'disabled', 'dry-run', 'force', 'headless', 'help', 'json', 'keep-unread', 'no-teams-watch', 'no-update', 'notify-again', 'original', 'always-on', 'owners-only', 'resolved', 'review', 'sandbox', 'unread']);
|
|
3
|
+
export const BOOLEAN_FLAGS = new Set(['all', 'digest', 'disabled', 'dry-run', 'force', 'headless', 'help', 'elevated', 'json', 'keep-unread', 'no-teams-watch', 'no-update', 'no-wait', 'notify-again', 'original', 'always-on', 'owners-only', 'resolved', 'review', 'sandbox', 'unread']);
|
|
4
4
|
export const COMMANDS = [
|
|
5
5
|
{
|
|
6
6
|
name: 'login',
|
|
@@ -87,6 +87,11 @@ export const COMMANDS = [
|
|
|
87
87
|
'pages show <slug> [--json]',
|
|
88
88
|
'pages runtime <slug> [--json]',
|
|
89
89
|
'pages runtime set <slug> [--min <MiB>] [--max <MiB>] [--always-on true|false] [--json]',
|
|
90
|
+
'pages backups list <slug> [--json]',
|
|
91
|
+
'pages backups create <slug> [--keep <days>] [--no-wait] [--json]',
|
|
92
|
+
'pages backups restore <slug> <id> [--confirm <slug>] [--no-wait] [--json]',
|
|
93
|
+
'pages backups delete <slug> <id> [--json]',
|
|
94
|
+
'pages backups daily <slug> on|off [--json]',
|
|
90
95
|
'pages upload <directory> [--slug <slug>] [--json]',
|
|
91
96
|
'pages rename <slug> <new-slug> [--json]',
|
|
92
97
|
'pages secrets list <slug> [--json]',
|
|
@@ -97,12 +102,16 @@ export const COMMANDS = [
|
|
|
97
102
|
'pages comments reply|edit <slug> <id> [text] [--json]',
|
|
98
103
|
'pages comments resolve|reopen|delete <slug> <id> [--json]',
|
|
99
104
|
'pages comments enable|disable <slug> [--json]',
|
|
105
|
+
'pages tunnel [setup] [<slug>] [--port <port>]',
|
|
106
|
+
'pages tunnel run | list | remove <slug>',
|
|
107
|
+
'pages tunnel service install | status | uninstall',
|
|
108
|
+
'pages tunnel service logs [--lines <count>]',
|
|
100
109
|
'pages dev [directory] [--slug <slug>] [--port <port>] [--build <command> --watch-dir <sources>]',
|
|
101
110
|
' [--celld <executable>] [--user-id <id>] [--user-name <name>] [--user-email <email>]',
|
|
102
111
|
],
|
|
103
|
-
description: 'An upload replaces all content of the page. Without --slug the directory name is used; build output folders such as dist need an explicit --slug. Pages owned by someone else are refused unless you are their co-owner or an admin. pages rename moves a page to a new slug with its versions, comments, secrets and app data (owner or admin only); the old address redirects to the new one and stays reserved. pages secrets manages the write-only secrets an app reads through SKILLSHARE_SECRETS (owner or admin only, at most 32 per page, 16 KiB each); set reads the value from piped stdin or a masked prompt, never from the command line. pages runtime set: each app runs in its own pod and gets memory automatically between --min and --max MiB, which the page owners or an admin set; only admins use --always-on to keep an app running without traffic. pages comments reads and writes the annotations reviewers leave on a Page at /pa/<slug>/ (enable and disable decide whether the regular /p/<slug>/ address shows them too); add creates a page note, text without an argument (or -) is read from stdin, and list hides resolved threads unless --resolved is given.',
|
|
104
|
-
examples: ['skillshare pages upload ./site --slug release-notes', 'skillshare pages dev . --slug my-app', 'skillshare pages secrets set my-app API_TOKEN', 'printf %s "$TOKEN" | skillshare pages secrets set my-app API_TOKEN', 'skillshare pages comments list my-app --author mine', 'skillshare pages comments reply my-app 12 "Fixed in revision 4"'],
|
|
105
|
-
flags: ['slug', 'path', 'author', 'resolved', 'min', 'max', 'always-on', 'json'],
|
|
112
|
+
description: 'An upload replaces all content of the page. Without --slug the directory name is used; build output folders such as dist need an explicit --slug. Pages owned by someone else are refused unless you are their co-owner or an admin. pages rename moves a page to a new slug with its versions, comments, secrets and app data (owner or admin only); the old address redirects to the new one and stays reserved. pages secrets manages the write-only secrets an app reads through SKILLSHARE_SECRETS (owner or admin only, at most 32 per page, 16 KiB each); set reads the value from piped stdin or a masked prompt, never from the command line. pages runtime set: each app runs in its own pod and gets memory automatically between --min and --max MiB, which the page owners or an admin set; only admins use --always-on to keep an app running without traffic. pages backups copies the data of a celld app (D1, KV, R2, Durable Objects, Workflows) for its owners or an admin; the app is stopped while a backup or restore runs and the command waits for it unless --no-wait. create keeps the backup for --keep days (default 30, at most 365), daily on takes a backup every day kept for 7 days, and every backup is deleted automatically when it expires. restore replaces all current data of the app: it asks twice, and without a terminal it needs --confirm <slug>. pages tunnel publishes a port of this computer as a Page: the first run signs you in, asks for the port and the Page name and creates the Page, which only you can open until you share it in its settings on SkillShare; the application gets the viewer in the X-Skillshare-User header like a celld app. Setting a tunnel up (again) issues the tunnel its own secret, saved with it, which replaces the previous one, and downloads the tunnel agent for this OS from SkillShare (a native executable, checked against its SHA-256). The agent serves the tunnels with their secrets alone, without your login; an owner can revoke a secret on SkillShare. Setup offers to keep the agent running in the background: on Windows as the Windows service SkillshareTunnels (starts with Windows under its own account and asks for administrator consent to install), on macOS and Linux as a launchd or systemd user service that starts at login; pages tunnel run runs it in the terminal. pages comments reads and writes the annotations reviewers leave on a Page at /pa/<slug>/ (enable and disable decide whether the regular /p/<slug>/ address shows them too); add creates a page note, text without an argument (or -) is read from stdin, and list hides resolved threads unless --resolved is given.',
|
|
113
|
+
examples: ['skillshare pages upload ./site --slug release-notes', 'skillshare pages dev . --slug my-app', 'skillshare pages tunnel my-tool --port 3000', 'skillshare pages backups create my-app --keep 7', 'skillshare pages backups restore my-app 3', 'skillshare pages secrets set my-app API_TOKEN', 'printf %s "$TOKEN" | skillshare pages secrets set my-app API_TOKEN', 'skillshare pages comments list my-app --author mine', 'skillshare pages comments reply my-app 12 "Fixed in revision 4"'],
|
|
114
|
+
flags: ['slug', 'path', 'author', 'resolved', 'min', 'max', 'always-on', 'keep', 'confirm', 'no-wait', 'port', 'lines', 'config', 'agent', 'elevated', 'json'],
|
|
106
115
|
},
|
|
107
116
|
{
|
|
108
117
|
name: 'teams',
|
package/dist/index.js
CHANGED
|
@@ -17,6 +17,9 @@ import { runPageDev } from './pages-dev.js';
|
|
|
17
17
|
import { runPageCommentsCommand } from './pages-comments.js';
|
|
18
18
|
import { runPageSecretsCommand } from './pages-secrets.js';
|
|
19
19
|
import { runPageRuntimeCommand } from './pages-runtime.js';
|
|
20
|
+
import { runPageBackupsCommand } from './pages-backups.js';
|
|
21
|
+
import { runPageTunnelCommand } from './pages-tunnel.js';
|
|
22
|
+
import { defaultWindowsServiceEnvironment } from './tunnel-windows-service.js';
|
|
20
23
|
import { waitForLoginCallback } from './login-callback.js';
|
|
21
24
|
import { createHash, randomBytes } from 'node:crypto';
|
|
22
25
|
import { spawn } from 'node:child_process';
|
|
@@ -129,6 +132,51 @@ async function main() {
|
|
|
129
132
|
await runPageDev(options.positionals[1] ?? '.', options.flags);
|
|
130
133
|
return;
|
|
131
134
|
}
|
|
135
|
+
if ((command === 'pages' || command === 'page') && options.positionals[0] === 'tunnel') {
|
|
136
|
+
const clients = new Map();
|
|
137
|
+
const clientFor = async (server) => {
|
|
138
|
+
const base = normalizeBaseUrl(server);
|
|
139
|
+
if (!clients.has(base))
|
|
140
|
+
clients.set(base, await createClient(base, options.token));
|
|
141
|
+
return clients.get(base);
|
|
142
|
+
};
|
|
143
|
+
await runPageTunnelCommand(options.positionals.slice(1), options.flags, {
|
|
144
|
+
appDir: APP_DIR,
|
|
145
|
+
service: { platform: process.platform, user: () => defaultServiceEnvironment(APP_DIR), windows: defaultWindowsServiceEnvironment },
|
|
146
|
+
pause: async () => {
|
|
147
|
+
if (!process.stdin.isTTY)
|
|
148
|
+
return;
|
|
149
|
+
process.stderr.write('Press Enter to close this window.');
|
|
150
|
+
await new Promise((resolve) => process.stdin.once('data', resolve));
|
|
151
|
+
},
|
|
152
|
+
signedInServer: async (server) => {
|
|
153
|
+
const base = normalizeBaseUrl(server ?? await resolveActiveBaseUrl());
|
|
154
|
+
assertCredentialDestination(base);
|
|
155
|
+
if (!options.token && !await loadSession(base))
|
|
156
|
+
await login(base);
|
|
157
|
+
return base;
|
|
158
|
+
},
|
|
159
|
+
api: clientFor,
|
|
160
|
+
pageUrl: async (api, slug) => {
|
|
161
|
+
const client = await clientFor(api.baseUrl);
|
|
162
|
+
const linkConfig = await client.get('/api/auth/config');
|
|
163
|
+
configurePageLinks(client.baseUrl, linkConfig.pageBaseDomain);
|
|
164
|
+
return pageUrl(client.baseUrl, slug);
|
|
165
|
+
},
|
|
166
|
+
interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
167
|
+
promptText: async (message, { initial, validate }) => {
|
|
168
|
+
const value = await text({ message, initialValue: initial, validate: (input) => validate((input ?? '').trim()) });
|
|
169
|
+
if (isCancel(value)) {
|
|
170
|
+
cancel('Cancelled.');
|
|
171
|
+
process.exit(0);
|
|
172
|
+
}
|
|
173
|
+
return value.trim();
|
|
174
|
+
},
|
|
175
|
+
promptConfirm,
|
|
176
|
+
log: (line) => console.log(line),
|
|
177
|
+
});
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
132
180
|
switch (command) {
|
|
133
181
|
case 'login': {
|
|
134
182
|
const baseUrl = options.flags.server ?? (options.positionals[0] === 'local' ? LOCAL_URL : DEFAULT_URL);
|
|
@@ -392,6 +440,16 @@ async function main() {
|
|
|
392
440
|
await runPageRuntimeCommand(client, options.positionals.slice(1), options.flags, print);
|
|
393
441
|
return;
|
|
394
442
|
}
|
|
443
|
+
if (action === 'backups' || action === 'backup') {
|
|
444
|
+
const backupStatus = spinner({ indicator: 'timer', output: statusOutput });
|
|
445
|
+
await runPageBackupsCommand(client, options.positionals.slice(1), options.flags, {
|
|
446
|
+
print,
|
|
447
|
+
interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
448
|
+
confirm: (message) => promptConfirm(message, false),
|
|
449
|
+
status: { start: (message) => backupStatus.start(message), stop: (message) => backupStatus.stop(message), clear: () => backupStatus.clear() },
|
|
450
|
+
});
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
395
453
|
if (action === 'show') {
|
|
396
454
|
const slug = options.positionals[1];
|
|
397
455
|
if (!slug)
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { formatByteSize, formatDateTime } from './output.js';
|
|
2
|
+
const POLL_MS = 2000;
|
|
3
|
+
/**
|
|
4
|
+
* `pages backups` lets the owners of a celld Page and administrators back up its data, keep daily backups and
|
|
5
|
+
* restore one. Backups and restores run on the server with the Page stopped; the command waits for them unless --no-wait.
|
|
6
|
+
*/
|
|
7
|
+
export async function runPageBackupsCommand(client, positionals, flags, deps) {
|
|
8
|
+
const [action = 'list', slug, argument] = positionals;
|
|
9
|
+
if (!slug)
|
|
10
|
+
throw new Error(`pages backups ${action} requires <slug>`);
|
|
11
|
+
const base = `/api/pages/${encodeURIComponent(slug)}/backups`;
|
|
12
|
+
const wait = !isTrue(flags['no-wait']);
|
|
13
|
+
if (action === 'list') {
|
|
14
|
+
const view = await expect(slug, await client.request(base, { method: 'GET' }));
|
|
15
|
+
deps.print(view, () => renderPageBackups(slug, view));
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (action === 'create') {
|
|
19
|
+
const body = flags.keep === undefined ? {} : { retentionDays: days(flags.keep) };
|
|
20
|
+
const started = await expect(slug, await client.request(base, json('POST', body)));
|
|
21
|
+
if (!wait) {
|
|
22
|
+
deps.print(started, () => `Backing up /p/${slug}/ as backup #${started.id}, kept until ${formatDateTime(started.expires)}. The Page is stopped until it finishes.`);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
deps.status.start(`Backing up /p/${slug}/ (the Page is stopped meanwhile)`);
|
|
26
|
+
const backup = await poll(client, slug, base, deps, (view) => {
|
|
27
|
+
const current = view.backups.find((candidate) => candidate.id === started.id);
|
|
28
|
+
return current && current.state !== 'creating' ? current : undefined;
|
|
29
|
+
});
|
|
30
|
+
if (backup.state === 'failed') {
|
|
31
|
+
deps.status.clear();
|
|
32
|
+
throw new Error(`Backup #${backup.id} of /p/${slug}/ failed: ${backup.error ?? 'unknown error'}`);
|
|
33
|
+
}
|
|
34
|
+
deps.status.stop(`Backed up /p/${slug}/ as backup #${backup.id} (${formatByteSize(backup.bytes)})`);
|
|
35
|
+
deps.print(backup, () => `Kept until ${formatDateTime(backup.expires)}.`);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
if (action === 'delete') {
|
|
39
|
+
const id = backupId(argument, 'delete');
|
|
40
|
+
await expect(slug, await client.request(`${base}/${id}`, { method: 'DELETE' }), id);
|
|
41
|
+
deps.print({ deleted: id }, () => `Deleted backup #${id} of /p/${slug}/.`);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (action === 'daily') {
|
|
45
|
+
if (argument !== 'on' && argument !== 'off')
|
|
46
|
+
throw new Error('pages backups daily requires <slug> on|off');
|
|
47
|
+
const view = await expect(slug, await client.request(`${base}/schedule`, json('PUT', { enabled: argument === 'on' })));
|
|
48
|
+
deps.print(view, () => `Daily backups of /p/${slug}/ are ${daily(view)}.`);
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
if (action === 'restore') {
|
|
52
|
+
const id = backupId(argument, 'restore');
|
|
53
|
+
const view = await expect(slug, await client.request(base, { method: 'GET' }));
|
|
54
|
+
const backup = view.backups.find((candidate) => candidate.id === id);
|
|
55
|
+
if (!backup)
|
|
56
|
+
throw new Error(`Backup #${id} of /p/${slug}/ was not found.`);
|
|
57
|
+
if (backup.state !== 'ready')
|
|
58
|
+
throw new Error(`Backup #${id} of /p/${slug}/ is ${backup.state}; only a completed backup can be restored.`);
|
|
59
|
+
const created = formatDateTime(backup.created);
|
|
60
|
+
if (flags.confirm !== undefined) {
|
|
61
|
+
if (flags.confirm !== slug)
|
|
62
|
+
throw new Error(`--confirm must repeat the Page slug ${slug}.`);
|
|
63
|
+
}
|
|
64
|
+
else if (!deps.interactive) {
|
|
65
|
+
throw new Error(`Restoring replaces all data of /p/${slug}/. Repeat its slug with --confirm ${slug} to proceed.`);
|
|
66
|
+
}
|
|
67
|
+
else if (!await deps.confirm(`Restore /p/${slug}/ from backup #${id} of ${created}? All data written since then will be lost.`) ||
|
|
68
|
+
!await deps.confirm(`Are you absolutely sure? All current data of /p/${slug}/ will be permanently replaced by the backup of ${created}. This cannot be undone.`)) {
|
|
69
|
+
deps.print({ restored: false }, () => 'Restore cancelled; nothing was changed.');
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const started = await expect(slug, await client.request(`${base}/${id}/restore`, json('POST', { confirm: slug })), id);
|
|
73
|
+
if (!wait) {
|
|
74
|
+
deps.print(started, () => `Restoring /p/${slug}/ from backup #${id}. The Page is stopped until it finishes.`);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
deps.status.start(`Restoring /p/${slug}/ from backup #${id} (the Page is stopped meanwhile)`);
|
|
78
|
+
const restore = await poll(client, slug, base, deps, (current) => current.lastRestore && current.lastRestore.backupId === id && current.lastRestore.state !== 'running' && !current.operation
|
|
79
|
+
? current.lastRestore : undefined);
|
|
80
|
+
if (restore.state === 'failed') {
|
|
81
|
+
deps.status.clear();
|
|
82
|
+
throw new Error(`Restoring /p/${slug}/ from backup #${id} failed: ${restore.error ?? 'unknown error'} The Page data may be incomplete; restore a backup again.`);
|
|
83
|
+
}
|
|
84
|
+
deps.status.stop(`Restored /p/${slug}/ from backup #${id} of ${created}`);
|
|
85
|
+
deps.print(restore, () => 'The Page starts again on its next request.');
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
throw new Error(`Unknown pages backups action "${action}". Use list, create, delete, daily or restore.`);
|
|
89
|
+
}
|
|
90
|
+
export function renderPageBackups(slug, view) {
|
|
91
|
+
const lines = [`${slug}: daily backups ${daily(view)}`];
|
|
92
|
+
if (view.operation === 'backingUp')
|
|
93
|
+
lines.push('A backup is running; the Page is stopped until it finishes.');
|
|
94
|
+
if (view.operation === 'restoring')
|
|
95
|
+
lines.push('A restore is running; the Page is stopped until it finishes.');
|
|
96
|
+
const restore = view.lastRestore;
|
|
97
|
+
if (restore) {
|
|
98
|
+
const from = `backup #${restore.backupId} of ${formatDateTime(restore.backupCreated)}`;
|
|
99
|
+
lines.push(restore.state === 'done' ? `Last restore: ${from} by ${restore.requestedBy}, ${formatDateTime(restore.finished)}`
|
|
100
|
+
: restore.state === 'running' ? `Restoring ${from}…`
|
|
101
|
+
: `Last restore of ${from} failed: ${restore.error ?? 'unknown error'} The Page data may be incomplete.`);
|
|
102
|
+
}
|
|
103
|
+
if (view.backups.length === 0) {
|
|
104
|
+
lines.push('No backups yet.');
|
|
105
|
+
return lines.join('\n');
|
|
106
|
+
}
|
|
107
|
+
lines.push('');
|
|
108
|
+
for (const backup of view.backups) {
|
|
109
|
+
const by = backup.scheduled ? 'daily' : backup.createdBy;
|
|
110
|
+
const size = backup.state === 'ready' ? formatByteSize(backup.bytes) : backup.state;
|
|
111
|
+
lines.push(`#${backup.id} ${formatDateTime(backup.created)} ${size.padEnd(9)} expires ${formatDateTime(backup.expires)} ${by}`);
|
|
112
|
+
if (backup.error)
|
|
113
|
+
lines.push(` ${backup.error}`);
|
|
114
|
+
}
|
|
115
|
+
return lines.join('\n');
|
|
116
|
+
}
|
|
117
|
+
function daily(view) {
|
|
118
|
+
return view.dailyEnabled
|
|
119
|
+
? `on at ${String(view.dailyHourUtc).padStart(2, '0')}:00 UTC, kept ${view.dailyRetentionDays} days${view.nextDailyRun ? ` (next ${formatDateTime(view.nextDailyRun)})` : ''}`
|
|
120
|
+
: 'off';
|
|
121
|
+
}
|
|
122
|
+
async function poll(client, slug, base, deps, done) {
|
|
123
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
124
|
+
for (;;) {
|
|
125
|
+
await sleep(POLL_MS);
|
|
126
|
+
let view;
|
|
127
|
+
try {
|
|
128
|
+
view = await expect(slug, await client.request(base, { method: 'GET' }));
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
deps.status.clear();
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
const result = done(view);
|
|
135
|
+
if (result !== undefined)
|
|
136
|
+
return result;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
function json(method, body) {
|
|
140
|
+
return { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) };
|
|
141
|
+
}
|
|
142
|
+
function backupId(value, action) {
|
|
143
|
+
if (!value || !/^\d+$/.test(value))
|
|
144
|
+
throw new Error(`pages backups ${action} requires <slug> <backup id>`);
|
|
145
|
+
return Number(value);
|
|
146
|
+
}
|
|
147
|
+
function days(value) {
|
|
148
|
+
if (!/^\d+$/.test(value) || Number(value) < 1)
|
|
149
|
+
throw new Error('--keep takes a whole number of days, for example --keep 30.');
|
|
150
|
+
return Number(value);
|
|
151
|
+
}
|
|
152
|
+
function isTrue(value) {
|
|
153
|
+
return value !== undefined && !['0', 'false', 'no', 'off'].includes(value.toLowerCase());
|
|
154
|
+
}
|
|
155
|
+
async function expect(slug, response, id) {
|
|
156
|
+
if (response.ok)
|
|
157
|
+
return (response.status === 204 ? undefined : await response.json());
|
|
158
|
+
if (response.status === 403)
|
|
159
|
+
throw new Error(`Only the owner or a co-owner of /p/${slug}/ or an administrator can manage its backups.`);
|
|
160
|
+
if (response.status === 404)
|
|
161
|
+
throw new Error(id === undefined ? `Page /p/${slug}/ was not found.` : `Page /p/${slug}/ or its backup #${id} was not found.`);
|
|
162
|
+
let error = {};
|
|
163
|
+
try {
|
|
164
|
+
error = await response.json();
|
|
165
|
+
}
|
|
166
|
+
catch { }
|
|
167
|
+
throw new Error(error.error ?? `Skillshare returned HTTP ${response.status} for the Page backups.`);
|
|
168
|
+
}
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { existsSync } from 'node:fs';
|
|
4
|
+
import { chmod, copyFile, mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
5
|
+
import { connect as connectTcp } from 'node:net';
|
|
6
|
+
import { hostname } from 'node:os';
|
|
7
|
+
import { basename, dirname, join } from 'node:path';
|
|
8
|
+
import { readCliVersion } from './help.js';
|
|
9
|
+
import { definitionPath, registerService, serviceIsRunning, serviceLogs, servicePaths, unregisterService, } from './service-manager.js';
|
|
10
|
+
import { installWindowsService, isElevated, runElevated, uninstallWindowsService, windowsServiceLogs, windowsServiceState, } from './tunnel-windows-service.js';
|
|
11
|
+
/**
|
|
12
|
+
* skillshare pages tunnel publishes a port of this computer as a SkillShare Page. The CLI sets a tunnel up with the
|
|
13
|
+
* owner's login, which issues the tunnel its own secret, and installs the tunnel agent: a Native AOT executable
|
|
14
|
+
* (tunnel-agent/, C#) that SkillShare serves for each OS. The agent holds the connection with only that secret, as a
|
|
15
|
+
* Windows service, a launchd agent or a systemd user service, or in the terminal with pages tunnel run.
|
|
16
|
+
*/
|
|
17
|
+
const SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;
|
|
18
|
+
export const tunnelConfigPath = (appDir) => join(appDir, 'tunnels.json');
|
|
19
|
+
export async function loadTunnelConfig(appDir, path = tunnelConfigPath(appDir)) {
|
|
20
|
+
try {
|
|
21
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
22
|
+
const tunnels = Array.isArray(parsed.tunnels) ? parsed.tunnels.filter(isEntry) : [];
|
|
23
|
+
return { hostId: typeof parsed.hostId === 'string' && /^[A-Za-z0-9-]{1,64}$/.test(parsed.hostId) ? parsed.hostId : randomUUID(), tunnels };
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error.code !== 'ENOENT')
|
|
27
|
+
throw new Error(`Could not read ${path}: ${error.message}`);
|
|
28
|
+
return { hostId: randomUUID(), tunnels: [] };
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function isEntry(value) {
|
|
32
|
+
const entry = value;
|
|
33
|
+
return typeof entry?.server === 'string' && typeof entry.slug === 'string' && Number.isInteger(entry.port)
|
|
34
|
+
&& typeof entry.secret === 'string' && entry.secret.length > 0;
|
|
35
|
+
}
|
|
36
|
+
export async function saveTunnelConfig(appDir, config) {
|
|
37
|
+
const path = tunnelConfigPath(appDir);
|
|
38
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
39
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
40
|
+
try {
|
|
41
|
+
await writeFile(temporary, JSON.stringify(config, null, 2), { mode: 0o600 });
|
|
42
|
+
await rename(temporary, path);
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
await rm(temporary, { force: true });
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export function parsePort(value) {
|
|
49
|
+
const port = Number(value);
|
|
50
|
+
if (!value || !Number.isInteger(port) || port < 1 || port > 65535)
|
|
51
|
+
throw new Error('The port must be a number between 1 and 65535.');
|
|
52
|
+
return port;
|
|
53
|
+
}
|
|
54
|
+
export function suggestSlug(directory) {
|
|
55
|
+
return basename(directory).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/-{2,}/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '');
|
|
56
|
+
}
|
|
57
|
+
export function validateSlug(slug) {
|
|
58
|
+
return SLUG_PATTERN.test(slug) && !slug.includes('--') ? undefined
|
|
59
|
+
: 'Use 1-40 lowercase letters, digits or single hyphens, starting and ending with a letter or digit.';
|
|
60
|
+
}
|
|
61
|
+
export class TunnelRegistrationError extends Error {
|
|
62
|
+
status;
|
|
63
|
+
constructor(message, status) {
|
|
64
|
+
super(message);
|
|
65
|
+
this.status = status;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** With the owner's login: creates the Page if needed and issues a new secret for the tunnel, replacing the previous one. */
|
|
69
|
+
export async function registerTunnel(api, entry, hostId, create) {
|
|
70
|
+
const response = await api.request(`/api/pages/${encodeURIComponent(entry.slug)}/tunnel`, {
|
|
71
|
+
method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
72
|
+
body: JSON.stringify({ create, hostId, host: hostname(), port: entry.port, cliVersion: readCliVersion() }),
|
|
73
|
+
});
|
|
74
|
+
const body = await response.json().catch(() => null);
|
|
75
|
+
if (!response.ok || !body?.secret)
|
|
76
|
+
throw new TunnelRegistrationError(body?.error ?? `SkillShare refused the tunnel (HTTP ${response.status}).`, response.status);
|
|
77
|
+
return body;
|
|
78
|
+
}
|
|
79
|
+
// ---- Tunnel agent ------------------------------------------------------------------------------------------------
|
|
80
|
+
/** The .NET runtime identifier of the agent build for this computer. */
|
|
81
|
+
export function agentRid(platform = process.platform, arch = process.arch) {
|
|
82
|
+
const os = platform === 'win32' ? 'win' : platform === 'darwin' ? 'osx' : platform === 'linux' ? 'linux' : undefined;
|
|
83
|
+
const cpu = arch === 'x64' || arch === 'arm64' ? arch : undefined;
|
|
84
|
+
if (!os || !cpu)
|
|
85
|
+
throw new Error(`The tunnel agent is not available for ${platform} on ${arch}.`);
|
|
86
|
+
return `${os}-${cpu}`;
|
|
87
|
+
}
|
|
88
|
+
export const agentFileName = (platform = process.platform) => platform === 'win32' ? 'skillshare-tunnel.exe' : 'skillshare-tunnel';
|
|
89
|
+
const agentCache = (appDir) => join(appDir, 'tunnel-agent');
|
|
90
|
+
const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex');
|
|
91
|
+
/**
|
|
92
|
+
* The agent for this computer, downloaded from SkillShare unless the same build is already here. The download is
|
|
93
|
+
* checked against the SHA-256 the server lists before it is ever run.
|
|
94
|
+
*/
|
|
95
|
+
export async function downloadAgent(api, appDir, rid = agentRid(), platform = process.platform) {
|
|
96
|
+
const manifestResponse = await api.request('/api/tunnel-agent', { method: 'GET', headers: { Accept: 'application/json' } });
|
|
97
|
+
const manifest = await manifestResponse.json().catch(() => null);
|
|
98
|
+
if (!manifestResponse.ok || !manifest?.files)
|
|
99
|
+
throw new Error(manifest?.error ?? `SkillShare did not list the tunnel agent (HTTP ${manifestResponse.status}).`);
|
|
100
|
+
const file = manifest.files.find(candidate => candidate.rid === rid);
|
|
101
|
+
if (!file || !/^[0-9a-f]{64}$/.test(file.sha256))
|
|
102
|
+
throw new Error(`SkillShare has no tunnel agent for ${rid}.`);
|
|
103
|
+
const directory = join(agentCache(appDir), file.sha256.slice(0, 16));
|
|
104
|
+
const path = join(directory, agentFileName(platform));
|
|
105
|
+
if (existsSync(path) && sha256(await readFile(path)) === file.sha256)
|
|
106
|
+
return { path, version: manifest.version };
|
|
107
|
+
const response = await api.request(`/api/tunnel-agent/${rid}`, { method: 'GET' });
|
|
108
|
+
if (!response.ok)
|
|
109
|
+
throw new Error(`Could not download the tunnel agent for ${rid} (HTTP ${response.status}).`);
|
|
110
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
111
|
+
if (bytes.length !== file.size || sha256(bytes) !== file.sha256)
|
|
112
|
+
throw new Error('The downloaded tunnel agent does not match its SHA-256; it was not saved.');
|
|
113
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
114
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
115
|
+
try {
|
|
116
|
+
await writeFile(temporary, bytes, { mode: 0o755 });
|
|
117
|
+
await rename(temporary, path);
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
await rm(temporary, { force: true });
|
|
121
|
+
}
|
|
122
|
+
return { path, version: manifest.version };
|
|
123
|
+
}
|
|
124
|
+
/** The most recently downloaded agent, for running without a connection to SkillShare. */
|
|
125
|
+
async function cachedAgent(appDir) {
|
|
126
|
+
let best;
|
|
127
|
+
try {
|
|
128
|
+
for (const name of await readdir(agentCache(appDir))) {
|
|
129
|
+
const path = join(agentCache(appDir), name, agentFileName());
|
|
130
|
+
if (!existsSync(path))
|
|
131
|
+
continue;
|
|
132
|
+
const time = (await stat(path)).mtimeMs;
|
|
133
|
+
if (!best || time > best.time)
|
|
134
|
+
best = { path, time };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
catch { }
|
|
138
|
+
return best?.path;
|
|
139
|
+
}
|
|
140
|
+
async function ensureAgent(deps, server) {
|
|
141
|
+
try {
|
|
142
|
+
return (await downloadAgent(await deps.api(server), deps.appDir)).path;
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
const cached = await cachedAgent(deps.appDir);
|
|
146
|
+
if (!cached)
|
|
147
|
+
throw error;
|
|
148
|
+
deps.log(`Using the tunnel agent downloaded before: ${error.message}`);
|
|
149
|
+
return cached;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
export async function tunnelServiceInstalled(host) {
|
|
153
|
+
return host.platform === 'win32' ? await windowsServiceState(host.windows().run) !== 'missing' : existsSync(definitionPath(host.user(), 'tunnel'));
|
|
154
|
+
}
|
|
155
|
+
async function tunnelServiceRunning(host) {
|
|
156
|
+
return host.platform === 'win32' ? await windowsServiceState(host.windows().run) === 'running' : serviceIsRunning(host.user(), 'tunnel');
|
|
157
|
+
}
|
|
158
|
+
/** macOS and Linux: the agent runs from a copy of its own, so clearing the download cache never breaks the service. */
|
|
159
|
+
export async function installUserService(env, agent, configPath) {
|
|
160
|
+
const paths = servicePaths(env.appDir, 'tunnel');
|
|
161
|
+
const program = join(env.appDir, 'tunnel-service', agentFileName(env.platform));
|
|
162
|
+
await mkdir(dirname(program), { recursive: true, mode: 0o700 });
|
|
163
|
+
await copyFile(agent, `${program}.tmp`);
|
|
164
|
+
await chmod(`${program}.tmp`, 0o755);
|
|
165
|
+
await rename(`${program}.tmp`, program);
|
|
166
|
+
await mkdir(dirname(paths.output), { recursive: true, mode: 0o700 });
|
|
167
|
+
await writeFile(paths.output, '', { flag: 'a', mode: 0o600 });
|
|
168
|
+
await registerService(env, 'tunnel', process.execPath, [program, 'run', '--config', configPath, '--log', paths.log]);
|
|
169
|
+
return program;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Installs or refreshes the background service with the agent and the tunnels of this user. On Windows the service gets
|
|
173
|
+
* copies of both (with the secrets) in its own protected directory; without administrator rights Windows asks for consent.
|
|
174
|
+
*/
|
|
175
|
+
async function applyTunnelService(host, configPath, agent, elevated) {
|
|
176
|
+
const config = await loadTunnelConfig('', configPath);
|
|
177
|
+
if (host.platform !== 'win32') {
|
|
178
|
+
if (config.tunnels.length === 0) {
|
|
179
|
+
await unregisterService(host.user(), 'tunnel');
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
await installUserService(host.user(), agent, configPath);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
const windows = host.windows();
|
|
186
|
+
if (elevated || await isElevated(windows.run)) {
|
|
187
|
+
if (config.tunnels.length === 0)
|
|
188
|
+
await uninstallWindowsService(windows);
|
|
189
|
+
else
|
|
190
|
+
await installWindowsService(windows, agent, config);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
console.log('Windows asks for administrator consent to change the Skillshare tunnel service.');
|
|
194
|
+
await runElevated(['pages', 'tunnel', 'service', 'install', '--config', configPath, ...(agent ? ['--agent', agent] : [])], windows.run);
|
|
195
|
+
}
|
|
196
|
+
function serviceDescription(platform) {
|
|
197
|
+
return platform === 'win32'
|
|
198
|
+
? 'the Windows service SkillshareTunnels, which starts with Windows, before anyone signs in'
|
|
199
|
+
: 'the tunnel service, which starts at every login';
|
|
200
|
+
}
|
|
201
|
+
async function runTunnelServiceCommand(deps, action, flags) {
|
|
202
|
+
const host = deps.service;
|
|
203
|
+
switch (action) {
|
|
204
|
+
case 'install': {
|
|
205
|
+
const configPath = flags.config ?? tunnelConfigPath(deps.appDir);
|
|
206
|
+
const config = await loadTunnelConfig(deps.appDir, configPath);
|
|
207
|
+
if (config.tunnels.length === 0)
|
|
208
|
+
throw new Error('No tunnel is set up yet. Run skillshare pages tunnel first.');
|
|
209
|
+
// The elevated Windows step gets the agent the user's process downloaded; it needs no login of its own.
|
|
210
|
+
const agent = flags.agent ?? await ensureAgent(deps, config.tunnels[0].server);
|
|
211
|
+
await applyTunnelService(host, configPath, agent, flags.elevated === 'true');
|
|
212
|
+
console.log(`Installed ${serviceDescription(host.platform)}. It runs now. Check it with skillshare pages tunnel service status.`);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
case 'status':
|
|
216
|
+
if (!await tunnelServiceInstalled(host))
|
|
217
|
+
console.log('The tunnel service is not installed.');
|
|
218
|
+
else
|
|
219
|
+
console.log(await tunnelServiceRunning(host) ? 'The tunnel service is running.'
|
|
220
|
+
: 'The tunnel service is installed but not running. See skillshare pages tunnel service logs.');
|
|
221
|
+
return;
|
|
222
|
+
case 'logs': {
|
|
223
|
+
const lines = Number(flags.lines ?? 50);
|
|
224
|
+
if (!Number.isInteger(lines) || lines < 1)
|
|
225
|
+
throw new Error('--lines must be a positive number.');
|
|
226
|
+
console.log(host.platform === 'win32' ? await windowsServiceLogs(host.windows().programData, lines) : await serviceLogs(deps.appDir, lines, 'tunnel'));
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
case 'uninstall': {
|
|
230
|
+
let removed;
|
|
231
|
+
if (host.platform !== 'win32')
|
|
232
|
+
removed = await unregisterService(host.user(), 'tunnel');
|
|
233
|
+
else if (flags.elevated === 'true' || await isElevated(host.windows().run))
|
|
234
|
+
removed = await uninstallWindowsService(host.windows());
|
|
235
|
+
else {
|
|
236
|
+
if (!await tunnelServiceInstalled(host)) {
|
|
237
|
+
console.log('The tunnel service was not installed.');
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
console.log('Windows asks for administrator consent to remove the Skillshare tunnel service.');
|
|
241
|
+
await runElevated(['pages', 'tunnel', 'service', 'uninstall'], host.windows().run);
|
|
242
|
+
removed = true;
|
|
243
|
+
}
|
|
244
|
+
console.log(removed ? 'The tunnel service was removed. Your tunnel Pages stay on SkillShare, offline.' : 'The tunnel service was not installed.');
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
default:
|
|
248
|
+
throw new Error('pages tunnel service requires install, status, logs or uninstall.');
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
export async function runPageTunnelCommand(positionals, flags, deps) {
|
|
252
|
+
try {
|
|
253
|
+
await runPageTunnelAction(positionals, flags, deps);
|
|
254
|
+
}
|
|
255
|
+
catch (error) {
|
|
256
|
+
if (flags.elevated === 'true') {
|
|
257
|
+
console.error(error.message);
|
|
258
|
+
await deps.pause();
|
|
259
|
+
}
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
async function runPageTunnelAction(positionals, flags, deps) {
|
|
264
|
+
const [action = 'setup', ...rest] = positionals;
|
|
265
|
+
switch (action) {
|
|
266
|
+
case 'setup': return setupTunnel(rest[0] ?? flags.slug, flags, deps);
|
|
267
|
+
case 'run': return runInTerminal(deps);
|
|
268
|
+
case 'list': {
|
|
269
|
+
const config = await loadTunnelConfig(deps.appDir);
|
|
270
|
+
if (config.tunnels.length === 0) {
|
|
271
|
+
console.log('No tunnel is set up. Run skillshare pages tunnel.');
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
for (const entry of config.tunnels)
|
|
275
|
+
console.log(`${entry.slug} localhost:${entry.port} → ${entry.server}/p/${entry.slug}/`);
|
|
276
|
+
console.log(!await tunnelServiceInstalled(deps.service)
|
|
277
|
+
? 'The tunnel service is not installed; run skillshare pages tunnel run, or install it with skillshare pages tunnel service install.'
|
|
278
|
+
: await tunnelServiceRunning(deps.service) ? 'The tunnel service is running.' : 'The tunnel service is installed but not running.');
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
case 'remove': {
|
|
282
|
+
const slug = rest[0];
|
|
283
|
+
if (!slug)
|
|
284
|
+
throw new Error('pages tunnel remove requires <slug>');
|
|
285
|
+
const config = await loadTunnelConfig(deps.appDir);
|
|
286
|
+
const remaining = config.tunnels.filter(entry => entry.slug !== slug);
|
|
287
|
+
if (remaining.length === config.tunnels.length)
|
|
288
|
+
throw new Error(`No tunnel for ${slug} is set up on this computer.`);
|
|
289
|
+
await saveTunnelConfig(deps.appDir, { ...config, tunnels: remaining });
|
|
290
|
+
if (await tunnelServiceInstalled(deps.service)) {
|
|
291
|
+
const agent = remaining.length > 0 ? await ensureAgent(deps, remaining[0].server) : undefined;
|
|
292
|
+
await applyTunnelService(deps.service, tunnelConfigPath(deps.appDir), agent, false);
|
|
293
|
+
}
|
|
294
|
+
console.log(`This computer no longer serves ${slug}. The Page stays on SkillShare, offline; delete it there or revoke its secret if you no longer need it.`);
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
case 'service': return runTunnelServiceCommand(deps, rest[0], flags);
|
|
298
|
+
default: throw new Error(`Unknown pages tunnel command '${action}'. Use setup, run, list, remove or service.`);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
async function setupTunnel(slugArgument, flags, deps) {
|
|
302
|
+
const server = await deps.signedInServer(flags.server);
|
|
303
|
+
const api = await deps.api(server);
|
|
304
|
+
const port = flags.port ? parsePort(flags.port) : deps.interactive
|
|
305
|
+
? parsePort(await deps.promptText('Which local port should SkillShare publish?', {
|
|
306
|
+
validate: value => { try {
|
|
307
|
+
parsePort(value);
|
|
308
|
+
return undefined;
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
return error.message;
|
|
312
|
+
} },
|
|
313
|
+
}))
|
|
314
|
+
: (() => { throw new Error('pages tunnel needs --port <port> without a terminal.'); })();
|
|
315
|
+
let slug = slugArgument;
|
|
316
|
+
if (!slug) {
|
|
317
|
+
if (!deps.interactive)
|
|
318
|
+
throw new Error('pages tunnel needs <slug> without a terminal.');
|
|
319
|
+
slug = await deps.promptText('Name of the application (its Page address)', { initial: suggestSlug(process.cwd()) || undefined, validate: validateSlug });
|
|
320
|
+
}
|
|
321
|
+
const problem = validateSlug(slug);
|
|
322
|
+
if (problem)
|
|
323
|
+
throw new Error(problem);
|
|
324
|
+
// Fetch the agent first: a computer without one should not get a new secret that nothing can use.
|
|
325
|
+
const agent = await downloadAgent(api, deps.appDir);
|
|
326
|
+
const config = await loadTunnelConfig(deps.appDir);
|
|
327
|
+
const registration = await registerTunnel(api, { slug, port }, config.hostId, true);
|
|
328
|
+
const entry = { server: api.baseUrl, slug: registration.slug, port, secret: registration.secret };
|
|
329
|
+
config.tunnels = [...config.tunnels.filter(other => !(other.server === entry.server && other.slug === entry.slug)), entry];
|
|
330
|
+
await saveTunnelConfig(deps.appDir, config);
|
|
331
|
+
const url = await deps.pageUrl(api, entry.slug);
|
|
332
|
+
console.log(registration.created
|
|
333
|
+
? `Created ${url} for localhost:${port}. Only you can open it; share it with others in the Page settings on SkillShare.`
|
|
334
|
+
: `${url} now serves localhost:${port}. Its access settings did not change.`);
|
|
335
|
+
console.log(`The tunnel's own secret is saved in ${tunnelConfigPath(deps.appDir)}; it replaces any previous one and works without your login.`);
|
|
336
|
+
if (!await isListening(port))
|
|
337
|
+
console.log(`Nothing answers on localhost:${port} yet; the Page shows as offline until it does.`);
|
|
338
|
+
if (await tunnelServiceInstalled(deps.service)) {
|
|
339
|
+
await applyTunnelService(deps.service, tunnelConfigPath(deps.appDir), agent.path, false);
|
|
340
|
+
console.log('Updated the tunnel service, which now serves this tunnel too.');
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
const question = deps.service.platform === 'win32'
|
|
344
|
+
? 'Install it as a Windows service, which runs from startup, before anyone signs in (needs administrator consent)?'
|
|
345
|
+
: 'Keep the tunnel running in the background, also after a restart?';
|
|
346
|
+
if (deps.interactive && await deps.promptConfirm(question, true)) {
|
|
347
|
+
await applyTunnelService(deps.service, tunnelConfigPath(deps.appDir), agent.path, false);
|
|
348
|
+
console.log(`Installed ${serviceDescription(deps.service.platform)}. Check it with skillshare pages tunnel service status.`);
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
console.log('Running the tunnel in this terminal. Stop it with Ctrl+C; install it as a service with skillshare pages tunnel service install.');
|
|
352
|
+
await runAgent(deps, agent.path);
|
|
353
|
+
}
|
|
354
|
+
async function isListening(port) {
|
|
355
|
+
return new Promise(resolve => {
|
|
356
|
+
const socket = connectTcp({ host: 'localhost', port, autoSelectFamily: true });
|
|
357
|
+
socket.setTimeout(2_000, () => { socket.destroy(); resolve(false); });
|
|
358
|
+
socket.once('connect', () => { socket.destroy(); resolve(true); });
|
|
359
|
+
socket.once('error', () => resolve(false));
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
async function runInTerminal(deps) {
|
|
363
|
+
const config = await loadTunnelConfig(deps.appDir);
|
|
364
|
+
if (config.tunnels.length === 0)
|
|
365
|
+
throw new Error(`No tunnel is set up in ${tunnelConfigPath(deps.appDir)}. Run skillshare pages tunnel.`);
|
|
366
|
+
await runAgent(deps, await ensureAgent(deps, config.tunnels[0].server));
|
|
367
|
+
}
|
|
368
|
+
/** The agent serves the tunnels in this terminal; Ctrl+C reaches it directly and ends it. */
|
|
369
|
+
async function runAgent(deps, agent) {
|
|
370
|
+
const args = ['run', '--config', tunnelConfigPath(deps.appDir)];
|
|
371
|
+
const code = await (deps.runAgent ?? spawnAgent)(agent, args);
|
|
372
|
+
if (code !== 0)
|
|
373
|
+
throw new Error(`The tunnel agent exited with code ${code}.`);
|
|
374
|
+
}
|
|
375
|
+
function spawnAgent(agent, args) {
|
|
376
|
+
return new Promise((resolve, reject) => {
|
|
377
|
+
const child = spawn(agent, args, { stdio: 'inherit' });
|
|
378
|
+
// The agent gets Ctrl+C from the terminal itself; the CLI only waits for it.
|
|
379
|
+
const ignore = () => { };
|
|
380
|
+
process.on('SIGINT', ignore);
|
|
381
|
+
child.once('error', reject);
|
|
382
|
+
child.once('exit', (code, signal) => {
|
|
383
|
+
process.off('SIGINT', ignore);
|
|
384
|
+
resolve(code ?? (signal ? 0 : 1));
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
}
|
package/dist/service-manager.js
CHANGED
|
@@ -24,8 +24,8 @@ export function servicePaths(appDir, kind = 'agents') {
|
|
|
24
24
|
}
|
|
25
25
|
const launchdLabel = (kind) => `com.quadient.skillshare.${kind}`;
|
|
26
26
|
const systemdUnitName = (kind) => `skillshare-${kind}.service`;
|
|
27
|
-
const windowsTaskName = (kind) => kind === 'agents' ? 'Skillshare Agents' : 'Skillshare Teams';
|
|
28
|
-
const description = (kind) => kind === 'agents' ? 'Skillshare agents listener' : 'Skillshare Teams session renewal';
|
|
27
|
+
const windowsTaskName = (kind) => kind === 'agents' ? 'Skillshare Agents' : kind === 'tunnel' ? 'Skillshare Tunnels' : 'Skillshare Teams';
|
|
28
|
+
const description = (kind) => kind === 'agents' ? 'Skillshare agents listener' : kind === 'tunnel' ? 'Skillshare Page tunnels' : 'Skillshare Teams session renewal';
|
|
29
29
|
/** Where the service manager keeps the service definition. */
|
|
30
30
|
export function definitionPath(environment, kind = 'agents') {
|
|
31
31
|
switch (environment.platform) {
|
|
@@ -37,8 +37,10 @@ export function definitionPath(environment, kind = 'agents') {
|
|
|
37
37
|
function xml(value) {
|
|
38
38
|
return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
39
39
|
}
|
|
40
|
+
/** The command a service runs: Node with its launcher, or a program of its own such as the tunnel agent. */
|
|
41
|
+
const serviceCommand = (node, appDir, kind, program) => program ?? [node, servicePaths(appDir, kind).launcher];
|
|
40
42
|
/** A launchd agent in the user's login session, so agents reach the keychain and the browser; started again if it fails. */
|
|
41
|
-
export function launchdPlist(node, appDir, kind = 'agents') {
|
|
43
|
+
export function launchdPlist(node, appDir, kind = 'agents', program) {
|
|
42
44
|
const paths = servicePaths(appDir, kind);
|
|
43
45
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
44
46
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
@@ -48,8 +50,7 @@ export function launchdPlist(node, appDir, kind = 'agents') {
|
|
|
48
50
|
<string>${launchdLabel(kind)}</string>
|
|
49
51
|
<key>ProgramArguments</key>
|
|
50
52
|
<array>
|
|
51
|
-
<string>${xml(
|
|
52
|
-
<string>${xml(paths.launcher)}</string>
|
|
53
|
+
${serviceCommand(node, appDir, kind, program).map(argument => ` <string>${xml(argument)}</string>`).join('\n')}
|
|
53
54
|
</array>
|
|
54
55
|
<key>WorkingDirectory</key>
|
|
55
56
|
<string>${xml(appDir)}</string>
|
|
@@ -76,7 +77,7 @@ function systemdQuote(value) {
|
|
|
76
77
|
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%')}"`;
|
|
77
78
|
}
|
|
78
79
|
/** A systemd user service, started with the user's session and again whenever it fails. */
|
|
79
|
-
export function systemdUnit(node, appDir, kind = 'agents') {
|
|
80
|
+
export function systemdUnit(node, appDir, kind = 'agents', program) {
|
|
80
81
|
const paths = servicePaths(appDir, kind);
|
|
81
82
|
// WorkingDirectory takes a literal path (including spaces), not a quoted command argument.
|
|
82
83
|
const workingDirectory = appDir.replace(/%/g, '%%');
|
|
@@ -86,7 +87,7 @@ After=network-online.target
|
|
|
86
87
|
|
|
87
88
|
[Service]
|
|
88
89
|
Type=simple
|
|
89
|
-
ExecStart=${
|
|
90
|
+
ExecStart=${serviceCommand(node, appDir, kind, program).map(systemdQuote).join(' ')}
|
|
90
91
|
WorkingDirectory=${workingDirectory}
|
|
91
92
|
Restart=on-failure
|
|
92
93
|
RestartSec=30
|
|
@@ -152,26 +153,26 @@ async function must(environment, command, args, what) {
|
|
|
152
153
|
throw new Error(`${what} failed: ${(result.stderr || result.stdout).trim() || `exit code ${result.code}`}`);
|
|
153
154
|
return result;
|
|
154
155
|
}
|
|
155
|
-
export async function registerService(environment, kind, node) {
|
|
156
|
+
export async function registerService(environment, kind, node, program) {
|
|
156
157
|
const definition = definitionPath(environment, kind);
|
|
157
158
|
await mkdir(dirname(definition), { recursive: true });
|
|
158
159
|
switch (environment.platform) {
|
|
159
160
|
case 'darwin': {
|
|
160
161
|
const domain = `gui/${environment.uid}`;
|
|
161
162
|
await environment.run('launchctl', ['bootout', `${domain}/${launchdLabel(kind)}`]);
|
|
162
|
-
await writeFile(definition, launchdPlist(node, environment.appDir, kind));
|
|
163
|
+
await writeFile(definition, launchdPlist(node, environment.appDir, kind, program));
|
|
163
164
|
await must(environment, 'launchctl', ['bootstrap', domain, definition], 'launchctl bootstrap');
|
|
164
165
|
break;
|
|
165
166
|
}
|
|
166
167
|
case 'linux':
|
|
167
|
-
await writeFile(definition, systemdUnit(node, environment.appDir, kind));
|
|
168
|
+
await writeFile(definition, systemdUnit(node, environment.appDir, kind, program));
|
|
168
169
|
await must(environment, 'systemctl', ['--user', 'daemon-reload'], 'systemctl daemon-reload');
|
|
169
170
|
await must(environment, 'systemctl', ['--user', 'enable', systemdUnitName(kind)], 'systemctl enable');
|
|
170
171
|
await must(environment, 'systemctl', ['--user', 'restart', systemdUnitName(kind)], 'systemctl restart');
|
|
171
172
|
break;
|
|
172
173
|
case 'win32':
|
|
173
174
|
// Reinstalling a watcher must stop the previous Node process as well as conhost.
|
|
174
|
-
if (kind
|
|
175
|
+
if (kind !== 'agents' && existsSync(definition))
|
|
175
176
|
await stopWindowsServiceProcesses(environment, kind);
|
|
176
177
|
// schtasks reads task definitions as UTF-16.
|
|
177
178
|
await writeFile(definition, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(windowsTaskXml(node, environment.appDir, environment.windowsUser ?? '', kind), 'utf16le')]));
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { copyFile, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { runCommand } from './agents-update.js';
|
|
4
|
+
/**
|
|
5
|
+
* The Windows service of the tunnel agent (skillshare-tunnel.exe, C# from tunnel-agent/). The agent is the service
|
|
6
|
+
* itself (run --service): it starts with Windows, before anyone signs in, under the virtual account
|
|
7
|
+
* NT SERVICE\SkillshareTunnels, which can read only its own directory, and authenticates with each tunnel's own secret.
|
|
8
|
+
* Installing, updating and removing it needs an administrator.
|
|
9
|
+
*/
|
|
10
|
+
export const WINDOWS_SERVICE_NAME = 'SkillshareTunnels';
|
|
11
|
+
export const WINDOWS_SERVICE_ACCOUNT = `NT SERVICE\\${WINDOWS_SERVICE_NAME}`;
|
|
12
|
+
const DISPLAY_NAME = 'Skillshare Page tunnels';
|
|
13
|
+
const DESCRIPTION = 'Publishes local applications of this computer as SkillShare Pages (skillshare pages tunnel).';
|
|
14
|
+
// Well-known SIDs, independent of the Windows display language.
|
|
15
|
+
const SYSTEM = '*S-1-5-18';
|
|
16
|
+
const ADMINISTRATORS = '*S-1-5-32-544';
|
|
17
|
+
const USERS = '*S-1-5-32-545';
|
|
18
|
+
export function defaultWindowsServiceEnvironment() {
|
|
19
|
+
return {
|
|
20
|
+
run: runCommand,
|
|
21
|
+
programData: process.env.ProgramData ?? 'C:\\ProgramData',
|
|
22
|
+
sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export function windowsServicePaths(programData) {
|
|
26
|
+
const home = join(programData, 'Skillshare', 'Tunnels');
|
|
27
|
+
return {
|
|
28
|
+
home,
|
|
29
|
+
agent: join(home, 'skillshare-tunnel.exe'),
|
|
30
|
+
config: join(home, 'tunnels.json'),
|
|
31
|
+
logs: join(home, 'logs'),
|
|
32
|
+
log: join(home, 'logs', 'tunnel.log'),
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/** The service's command line: the agent under the Service Control Manager, reading its own copy of the tunnels. */
|
|
36
|
+
export function windowsServiceCommand(programData) {
|
|
37
|
+
const paths = windowsServicePaths(programData);
|
|
38
|
+
return `"${paths.agent}" run --service --config "${paths.config}" --log "${paths.log}"`;
|
|
39
|
+
}
|
|
40
|
+
async function must(env, command, args, what) {
|
|
41
|
+
const result = await env.run(command, args);
|
|
42
|
+
if (result.code !== 0)
|
|
43
|
+
throw new Error(`${what} failed: ${(result.stderr || result.stdout).trim() || `exit code ${result.code}`}`);
|
|
44
|
+
return result;
|
|
45
|
+
}
|
|
46
|
+
export async function isElevated(run = runCommand) {
|
|
47
|
+
const result = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
|
|
48
|
+
'([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)']);
|
|
49
|
+
return result.code === 0 && result.stdout.trim() === 'True';
|
|
50
|
+
}
|
|
51
|
+
export async function windowsServiceState(run = runCommand) {
|
|
52
|
+
const result = await run('sc.exe', ['query', WINDOWS_SERVICE_NAME]);
|
|
53
|
+
if (result.code !== 0)
|
|
54
|
+
return 'missing';
|
|
55
|
+
const state = /STATE\s*:\s*\d+\s+(\w+)/.exec(result.stdout)?.[1];
|
|
56
|
+
switch (state) {
|
|
57
|
+
case 'RUNNING': return 'running';
|
|
58
|
+
case 'STOPPED': return 'stopped';
|
|
59
|
+
case 'START_PENDING': return 'starting';
|
|
60
|
+
case 'STOP_PENDING': return 'stopping';
|
|
61
|
+
default: return 'other';
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
async function stopService(env) {
|
|
65
|
+
if (await windowsServiceState(env.run) === 'missing')
|
|
66
|
+
return;
|
|
67
|
+
await env.run('sc.exe', ['stop', WINDOWS_SERVICE_NAME]);
|
|
68
|
+
for (let attempt = 0; attempt < 60; attempt++) {
|
|
69
|
+
const state = await windowsServiceState(env.run);
|
|
70
|
+
if (state === 'stopped' || state === 'missing')
|
|
71
|
+
return;
|
|
72
|
+
await env.sleep(500);
|
|
73
|
+
}
|
|
74
|
+
throw new Error(`The ${WINDOWS_SERVICE_NAME} service did not stop within 30 seconds.`);
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Installs or updates the service with the downloaded agent and the given tunnels (each with its own secret), then
|
|
78
|
+
* starts it. The tunnels replace those it served before. Needs an administrator.
|
|
79
|
+
*/
|
|
80
|
+
export async function installWindowsService(env, agent, config) {
|
|
81
|
+
const paths = windowsServicePaths(env.programData);
|
|
82
|
+
await stopService(env);
|
|
83
|
+
await mkdir(paths.logs, { recursive: true });
|
|
84
|
+
// The service account exists once the service does; only then can the directory be limited to it.
|
|
85
|
+
const exists = await windowsServiceState(env.run) !== 'missing';
|
|
86
|
+
const definition = ['binPath=', windowsServiceCommand(env.programData), 'start=', 'delayed-auto', 'obj=', WINDOWS_SERVICE_ACCOUNT,
|
|
87
|
+
'DisplayName=', DISPLAY_NAME];
|
|
88
|
+
if (exists)
|
|
89
|
+
await must(env, 'sc.exe', ['config', WINDOWS_SERVICE_NAME, ...definition], 'sc config');
|
|
90
|
+
else
|
|
91
|
+
await must(env, 'sc.exe', ['create', WINDOWS_SERVICE_NAME, ...definition], 'sc create');
|
|
92
|
+
await must(env, 'sc.exe', ['description', WINDOWS_SERVICE_NAME, DESCRIPTION], 'sc description');
|
|
93
|
+
await must(env, 'sc.exe', ['failure', WINDOWS_SERVICE_NAME, 'reset=', '86400', 'actions=', 'restart/60000/restart/60000/restart/60000'], 'sc failure');
|
|
94
|
+
// The tunnel secrets are readable only by the service, SYSTEM and administrators; the logs also by local users.
|
|
95
|
+
await must(env, 'icacls.exe', [paths.home, '/inheritance:r', '/grant:r', `${SYSTEM}:(OI)(CI)F`, `${ADMINISTRATORS}:(OI)(CI)F`,
|
|
96
|
+
`${WINDOWS_SERVICE_ACCOUNT}:(OI)(CI)RX`, '/T', '/C', '/Q'], 'icacls');
|
|
97
|
+
await must(env, 'icacls.exe', [paths.logs, '/grant:r', `${WINDOWS_SERVICE_ACCOUNT}:(OI)(CI)M`, `${USERS}:(OI)(CI)RX`, '/T', '/C', '/Q'], 'icacls');
|
|
98
|
+
await copyFile(agent, paths.agent);
|
|
99
|
+
await writeAtomically(paths.config, JSON.stringify(config, null, 2));
|
|
100
|
+
await must(env, 'sc.exe', ['start', WINDOWS_SERVICE_NAME], 'sc start');
|
|
101
|
+
return paths;
|
|
102
|
+
}
|
|
103
|
+
async function writeAtomically(path, content) {
|
|
104
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
105
|
+
try {
|
|
106
|
+
await writeFile(temporary, content);
|
|
107
|
+
await rename(temporary, path);
|
|
108
|
+
}
|
|
109
|
+
finally {
|
|
110
|
+
await rm(temporary, { force: true });
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** Stops and deletes the service with its directory, including the tunnel secrets. */
|
|
114
|
+
export async function uninstallWindowsService(env) {
|
|
115
|
+
const paths = windowsServicePaths(env.programData);
|
|
116
|
+
const existed = await windowsServiceState(env.run) !== 'missing';
|
|
117
|
+
await stopService(env);
|
|
118
|
+
if (existed)
|
|
119
|
+
await must(env, 'sc.exe', ['delete', WINDOWS_SERVICE_NAME], 'sc delete');
|
|
120
|
+
await rm(paths.home, { recursive: true, force: true });
|
|
121
|
+
return existed;
|
|
122
|
+
}
|
|
123
|
+
export async function windowsServiceLogs(programData, lines) {
|
|
124
|
+
try {
|
|
125
|
+
return (await readFile(windowsServicePaths(programData).log, 'utf8')).trimEnd().split('\n').slice(-lines).join('\n');
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return 'The tunnel service has not written a log yet.';
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Runs this CLI again as an administrator (Windows asks for consent) and waits for it. The elevated window keeps an
|
|
133
|
+
* error visible until Enter is pressed.
|
|
134
|
+
*/
|
|
135
|
+
export async function runElevated(args, run = runCommand) {
|
|
136
|
+
const quote = (value) => `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1')}"`;
|
|
137
|
+
const argumentList = [process.argv[1], ...args, '--elevated'].map(quote).join(' ');
|
|
138
|
+
const single = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
139
|
+
const script = `$p = Start-Process -FilePath ${single(process.execPath)} -ArgumentList ${single(argumentList)} -Verb RunAs -Wait -PassThru; exit $p.ExitCode`;
|
|
140
|
+
const result = await run('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')]);
|
|
141
|
+
if (result.code !== 0)
|
|
142
|
+
throw new Error(result.stderr.includes('canceled') || result.stderr.includes('cancelled')
|
|
143
|
+
? 'Administrator consent was declined, so the Windows service was not changed.'
|
|
144
|
+
: `The administrator step failed (exit code ${result.code}). See skillshare pages tunnel service logs.`);
|
|
145
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@quadient/skillshare",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.23.0",
|
|
4
4
|
"description": "Skillshare CLI for installing and publishing Quadient skills",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"build": "rm -rf dist && tsc -p tsconfig.build.json && node -e \"require('node:fs').copyFileSync('page-browser-client.js', 'dist/page-browser-client.js')\"",
|
|
17
17
|
"start": "node ./dist/index.js",
|
|
18
18
|
"prepublishOnly": "npm run build",
|
|
19
|
-
"test": "tsx --test session-auth.test.ts cli-args.test.ts install-files.test.ts removed-skills.test.ts output.test.ts pages.test.ts page-links.test.ts pages-secrets.test.ts pages-runtime.test.ts pages-comments.test.ts news.test.ts pages-dev.test.ts teams-auth.test.ts teams-watch.test.ts teams-service.test.ts teams-browser.test.ts salesforce.test.ts agents.test.ts agents-detection.test.ts agents-process.test.ts agents-probe.test.ts agents-lockdown.test.ts agents-approvals.test.ts agents-native-forms.test.ts agents-delivery.test.ts agents-request-upload.test.ts agents-update.test.ts login-callback.test.ts"
|
|
19
|
+
"test": "tsx --test session-auth.test.ts cli-args.test.ts install-files.test.ts removed-skills.test.ts output.test.ts pages.test.ts page-links.test.ts pages-secrets.test.ts pages-runtime.test.ts pages-backups.test.ts pages-tunnel.test.ts tunnel-windows-service.test.ts pages-comments.test.ts news.test.ts pages-dev.test.ts teams-auth.test.ts teams-watch.test.ts teams-service.test.ts teams-browser.test.ts salesforce.test.ts agents.test.ts agents-detection.test.ts agents-process.test.ts agents-probe.test.ts agents-lockdown.test.ts agents-approvals.test.ts agents-native-forms.test.ts agents-delivery.test.ts agents-request-upload.test.ts agents-update.test.ts login-callback.test.ts"
|
|
20
20
|
},
|
|
21
21
|
"publishConfig": {
|
|
22
22
|
"access": "public"
|