@quadient/skillshare 1.15.1 → 1.17.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 CHANGED
@@ -278,6 +278,17 @@ npx @quadient/skillshare update "Prompt Lint" --dry-run
278
278
  npx @quadient/skillshare update 12 --target ./installed
279
279
  ```
280
280
 
281
+ When an installed skill has been removed from the registry, the interactive CLI and
282
+ `skillshare update` show each local copy with a preview of the files to remove and
283
+ the local edits or extra paths to keep. Choose **Remove installed files** to select
284
+ copies in one batch, **Keep local copies and stop checking them** to keep all files
285
+ and stop future reminders, or **Decide later** to review them on the next run.
286
+ Only unchanged files recorded at installation are removed; an edited `SKILL.md`
287
+ stays available to your agents. Older installations that cannot be verified can
288
+ also be kept without reminders. Records for directories already removed manually
289
+ are cleared without prompting. `--dry-run` previews all changes without writing;
290
+ non-interactive runs leave files untouched. Each copy is offered only once per run.
291
+
281
292
  Publish an authenticated static page. The upload replaces the page's complete
282
293
  content, and the directory must contain `index.html` at its root. By default the
283
294
  directory name is used as the page slug; build output folders such as `dist` need `--slug`:
@@ -326,7 +337,7 @@ The publish script builds `tui/`, validates the packed files with `npm pack --dr
326
337
  `skillshare pages upload <directory> --slug <slug>` accepts static sites or
327
338
  Wrangler JSON/JSONC projects. The CLI bundles Worker dependencies locally; install
328
339
  them and build frontend assets before uploading. Inspect process status and logs
329
- with `skillshare pages runtime <slug>`. Pages are served below `/p/<slug>/`, so use
340
+ with `skillshare pages runtime <slug>`. With legacy hosting, Pages are served below `/p/<slug>/`, so use
330
341
  that base path when building assets. Runtime data survives content replacement.
331
342
 
332
343
  Manage the write-only secrets an application reads through `SKILLSHARE_SECRETS`
@@ -377,15 +388,21 @@ and uses its packaged esbuild. Supported hosts are macOS Apple Silicon and Linux
377
388
  x64/ARM64; Windows users can use WSL2. `--celld <executable>` or `CELLD_EXECUTABLE`
378
389
  selects an existing installation.
379
390
 
380
- The default URL is `http://127.0.0.1:8787/p/my-app/`. The proxy removes the Page prefix
381
- and adds the same `X-Skillshare-*` request headers as SkillShare. The development
391
+ The default URL is `http://127.0.0.1:8787/`. Assets, API routes and redirects use
392
+ the root of this origin, matching isolated hosted Pages. The proxy adds the same `X-Skillshare-*` request headers as SkillShare. The development
382
393
  revision is `0`. The toolbar offers four local users covering every role combination: Alice
383
394
  (owner), Bob (neither role), Charlie (admin), and Dana (owner and admin).
384
395
  Each option shows explicit `isOwner` and `isAdmin` values, and each browser can
385
- select its own user. Customize the first
396
+ select its own user. Each dev instance uses a random identity-cookie name; cookies
397
+ from another loopback port cannot select its user. Customize the first
386
398
  user with `--user-id`, `--user-name` and `--user-email`. This is simulated local
387
399
  identity, not a real SSO login. Listeners bind only to loopback.
388
400
 
401
+ Browser mutations use the same CSRF helper as hosted Pages: fetch, asynchronous XHR
402
+ and forms receive a session-scoped token. Custom clients can GET `/__skillshare/csrf`
403
+ and send `X-Skillshare-CSRF`. Native loopback clients without browser Origin/Fetch
404
+ Metadata can still exercise mock identities without production authentication.
405
+
389
406
  The proxy filters SkillShare authentication cookies and Authorization on ordinary
390
407
  routes, scopes application cookies and redirects to the Page, and supports HTTP
391
408
  streaming and WebSockets. `/api/bypass-sso/*` preserves Authorization but forwards
@@ -430,3 +447,11 @@ contains `id`, `displayName`, `email`, `isAdmin` and `isOwner`. The hosted backe
430
447
  uses the same contract for active SkillShare users. These capabilities stay in
431
448
  the Worker and are not injected on `api/bypass-sso/*` requests. See the
432
449
  [Worker example](../docs/pages-backends.md#skillshare-user-directory-from-a-worker).
450
+
451
+
452
+ When domain isolation is enabled by the server, `pages show`, upload results and
453
+ comment links use the domain advertised by `/api/auth/config`: `<slug>.pages.../`,
454
+ `<slug>--<revision>.pages.../` and reserved annotation variants. Root-relative asset
455
+ and API paths then work without a `/p/<slug>` prefix. New annotation hosts remain
456
+ unavailable until the trusted editor is enabled. No CLI publication or deployment
457
+ is implied by these source changes.
@@ -1,7 +1,7 @@
1
1
  import { detectAgents } from './agents-detect.js';
2
2
  import { refreshServicePath } from './agents-service-path.js';
3
3
  import { existsSync } from 'node:fs';
4
- import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
4
+ import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
5
5
  import { homedir } from 'node:os';
6
6
  import { dirname, join } from 'node:path';
7
7
  import { describeOtherListener, installVersion, readListenerLock, runCommand, } from './agents-update.js';
@@ -195,9 +195,19 @@ export async function installService(environment, settings, options = {}) {
195
195
  await (options.install ?? (version => installVersion(environment.appDir, version)))(settings.version);
196
196
  const config = { ...settings, path: process.env.PATH ?? '', node: process.execPath, installedAt: new Date().toISOString() };
197
197
  const paths = servicePaths(environment.appDir);
198
- await mkdir(dirname(paths.log), { recursive: true });
199
- await writeFile(paths.config, JSON.stringify(config, null, 2));
200
- await writeFile(paths.launcher, launcherSource());
198
+ await mkdir(dirname(paths.log), { recursive: true, mode: 0o700 });
199
+ await writeFile(paths.config, JSON.stringify(config, null, 2), { mode: 0o600 });
200
+ await writeFile(paths.launcher, launcherSource(), { mode: 0o600 });
201
+ if (process.platform !== 'win32') {
202
+ await chmod(environment.appDir, 0o700);
203
+ await chmod(dirname(paths.log), 0o700);
204
+ await Promise.all([paths.config, paths.launcher].map(path => chmod(path, 0o600)));
205
+ }
206
+ for (const path of [paths.log, paths.output]) {
207
+ await writeFile(path, '', { flag: 'a', mode: 0o600 });
208
+ if (process.platform !== 'win32')
209
+ await chmod(path, 0o600);
210
+ }
201
211
  const definition = definitionPath(environment);
202
212
  await mkdir(dirname(definition), { recursive: true });
203
213
  switch (environment.platform) {
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import crossSpawn from 'cross-spawn';
3
- import { appendFileSync, existsSync, mkdirSync, renameSync, statSync } from 'node:fs';
3
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, renameSync, statSync } from 'node:fs';
4
4
  import { mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
5
5
  import { dirname, join } from 'node:path';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
@@ -117,13 +117,17 @@ export async function removeOtherVersions(appDir, keep) {
117
117
  }
118
118
  /** Appends timestamped lines to a log file, starting a new one when it grows past a few megabytes. */
119
119
  export function fileLog(path) {
120
- mkdirSync(dirname(path), { recursive: true });
120
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
121
121
  return (text) => {
122
122
  try {
123
- if (existsSync(path) && statSync(path).size > MAX_LOG_BYTES)
124
- renameSync(path, `${path}.1`);
123
+ if (existsSync(path)) {
124
+ if (process.platform !== 'win32')
125
+ chmodSync(path, 0o600);
126
+ if (statSync(path).size > MAX_LOG_BYTES)
127
+ renameSync(path, `${path}.1`);
128
+ }
125
129
  const stamp = new Date().toISOString();
126
- appendFileSync(path, text.split(/\r?\n/).filter(line => line.length > 0).map(line => `${stamp} ${line}\n`).join(''));
130
+ appendFileSync(path, text.split(/\r?\n/).filter(line => line.length > 0).map(line => `${stamp} ${line}\n`).join(''), { mode: 0o600 });
127
131
  }
128
132
  catch {
129
133
  // Logging must never stop the listener.
package/dist/help.js CHANGED
@@ -56,7 +56,7 @@ export const COMMANDS = [
56
56
  name: 'update',
57
57
  summary: 'Update installed skills to their latest versions',
58
58
  usage: ['update [skillId|skillName] [--target <directory>] [--dry-run] [--force]'],
59
- description: 'Removes files that the new version no longer contains. Installs with local changes are skipped unless you pass --force.',
59
+ description: 'Removes files that the new version no longer contains. Installs with local changes are skipped unless you pass --force. For skills removed from SkillShare, preview the files, select copies to remove in one batch, keep copies without future reminders, or decide later. Local edits and extra files are kept. Missing installation records are cleared automatically; --dry-run changes nothing.',
60
60
  options: [
61
61
  ['--target <directory>', 'Only update the install in this directory'],
62
62
  ['--dry-run', 'Print planned changes without writing files'],
package/dist/index.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { refreshSession, withSessionLock, writeSessionAtomically } from './session-auth.js';
2
+ import { configurePageLinks } from './page-links.js';
1
3
  import { runSalesforceCommand } from './salesforce.js';
2
4
  import { assertCredentialDestination, resolveTeamsObjectId, runTeamsCommand, watchTeamsInBackground } from './teams.js';
3
5
  import { runAgentsCommand, runServiceCommand } from './agents.js';
@@ -5,12 +7,13 @@ import { SERVICE_ENV } from './agents-update.js';
5
7
  import { formatUnknownCommand, parseCliArgs } from './cli-args.js';
6
8
  import { findCommand, readCliVersion, renderCommandHelp, renderUsage } from './help.js';
7
9
  import { inspectInstallTarget, installFilesAtomically } from './install-files.js';
10
+ import { formatRemovedSkillCleanup, offerRemovedSkillUninstalls } from './removed-skills.js';
8
11
  import { preparePageFiles, resolvePageSlug } from './pages.js';
9
12
  import { formatByteSize, formatDateTime, pageUrl, plural, renderPageDetail, renderPageList, renderPageRuntime, renderSkillDetail, renderSkillList, renderSkillVersion, renderUser, } from './output.js';
10
13
  import { runPageDev } from './pages-dev.js';
11
14
  import { runPageCommentsCommand } from './pages-comments.js';
12
15
  import { runPageSecretsCommand } from './pages-secrets.js';
13
- import { createServer } from 'node:http';
16
+ import { waitForLoginCallback } from './login-callback.js';
14
17
  import { createHash, randomBytes } from 'node:crypto';
15
18
  import { spawn } from 'node:child_process';
16
19
  import { existsSync } from 'node:fs';
@@ -80,6 +83,7 @@ const AGENTS = [
80
83
  const LOGIN_TIMEOUT_MS = 5 * 60_000;
81
84
  // Progress goes to stderr with --json so stdout stays machine-readable.
82
85
  let statusOutput = process.stdout;
86
+ const reviewedRemovedSkills = new Set();
83
87
  async function main() {
84
88
  const args = process.argv.slice(2);
85
89
  const command = args[0];
@@ -347,6 +351,8 @@ async function main() {
347
351
  }
348
352
  case 'page':
349
353
  case 'pages': {
354
+ const linkConfig = await client.get('/api/auth/config');
355
+ configurePageLinks(client.baseUrl, linkConfig.pageBaseDomain);
350
356
  const action = options.positionals[0] ?? 'list';
351
357
  if (action === 'list') {
352
358
  const pages = await client.get('/api/pages');
@@ -411,7 +417,8 @@ async function runInteractive() {
411
417
  const user = await ensureInteractiveLogin(baseUrl);
412
418
  const client = await createClient(baseUrl);
413
419
  log.info(`Signed in as ${user.displayName}${user.email ? ` <${user.email}>` : ''} · ${new URL(client.baseUrl).host}`);
414
- const pendingInstalledUpdates = await checkInstalledSkillsForUpdates(client);
420
+ const { candidates: pendingInstalledUpdates, removedRecords } = await checkInstalledSkillsForUpdates(client);
421
+ await uninstallRemovedSkills(removedRecords);
415
422
  if (pendingInstalledUpdates.length > 0) {
416
423
  const shouldUpdateInstalled = await promptConfirm(pendingInstalledUpdates.length === 1
417
424
  ? `There is 1 installed skill with a newer version available. Update it now?`
@@ -435,7 +442,7 @@ async function runInteractive() {
435
442
  message: 'What do you want to do?',
436
443
  options: [
437
444
  { value: 'install', label: 'Install a skill', hint: 'Browse registry and install to agents' },
438
- { value: 'update', label: 'Update installed skills', hint: 'Refresh recorded installs to the latest registry versions' },
445
+ { value: 'update', label: 'Update installed skills', hint: 'Get new versions and review skills removed from SkillShare' },
439
446
  { value: 'upload', label: 'Upload a skill', hint: 'Create a new skill or publish a version' },
440
447
  { value: 'exit', label: 'Exit' },
441
448
  ],
@@ -462,33 +469,38 @@ async function runInteractive() {
462
469
  async function checkInstalledSkillsForUpdates(client) {
463
470
  const records = (await readInstalledSkillRecords()).filter((record) => record.baseUrl === client.baseUrl);
464
471
  if (records.length === 0) {
465
- return [];
472
+ return { candidates: [], removedRecords: [] };
466
473
  }
467
474
  const status = spinner({ output: statusOutput });
468
475
  status.start(`Checking ${records.length} installed skill${records.length === 1 ? '' : 's'} for updates`);
469
476
  const problems = [];
477
+ const removedRecords = [];
470
478
  try {
471
479
  const candidates = await collectInstalledSkillUpdateCandidates(client, {
472
480
  records,
473
481
  onSkipped(skip) {
474
- if (skip.reason === 'removed' || skip.reason === 'error') {
482
+ if (skip.reason === 'removed')
483
+ removedRecords.push(skip.record);
484
+ if (skip.reason === 'error') {
475
485
  problems.push(skip.message);
476
486
  }
477
487
  },
478
488
  });
479
- status.stop(candidates.length > 0
480
- ? `${candidates.length} installed skill${candidates.length === 1 ? ' has' : 's have'} a newer version`
481
- : 'Installed skills are up to date');
489
+ status.stop(problems.length > 0
490
+ ? `Check finished with ${problems.length} ${problems.length === 1 ? 'error' : 'errors'}`
491
+ : candidates.length > 0
492
+ ? `${candidates.length} installed skill${candidates.length === 1 ? ' has' : 's have'} a newer version`
493
+ : removedRecords.length > 0 ? 'Some installed skills were removed from SkillShare' : 'Installed skills are up to date');
482
494
  if (problems.length > 0) {
483
495
  log.warn(problems.join('\n'));
484
496
  }
485
- return candidates;
497
+ return { candidates, removedRecords };
486
498
  }
487
499
  catch (error) {
488
500
  // The update check is optional; never let it block the main menu.
489
501
  status.stop('Could not check installed skills for updates');
490
502
  log.warn(error instanceof Error ? error.message : String(error));
491
- return [];
503
+ return { candidates: [], removedRecords: [] };
492
504
  }
493
505
  }
494
506
  async function ensureInteractiveLogin(baseUrl) {
@@ -639,20 +651,25 @@ async function updateInstalledSkills(client, options) {
639
651
  console.log(`No installed skills recorded for ${client.baseUrl}${selectionDescription}.`);
640
652
  return;
641
653
  }
654
+ const removedRecords = [];
642
655
  const candidates = options?.candidates
643
656
  ?? await collectInstalledSkillUpdateCandidates(client, {
644
657
  records: installedRecords,
645
658
  onSkipped(skip) {
646
- console.log(skip.message);
659
+ if (skip.reason === 'removed')
660
+ removedRecords.push(skip.record);
661
+ if (skip.reason !== 'removed')
662
+ console.log(skip.message);
647
663
  },
648
664
  });
649
- let skippedCount = installedRecords.length - candidates.length;
665
+ const cleanup = await uninstallRemovedSkills(removedRecords, dryRun);
666
+ let skippedCount = installedRecords.length - candidates.length - cleanup.uninstalled - cleanup.kept - cleanup.cleared;
650
667
  if (candidates.length === 0) {
651
668
  if (dryRun) {
652
669
  console.log(`Dry run finished. Would update 0, skipped ${skippedCount}.`);
653
670
  }
654
671
  else {
655
- console.log(`Update finished. Updated 0, skipped ${skippedCount}.`);
672
+ console.log(`Update finished. Updated 0${formatRemovedSkillCleanup(cleanup)}, skipped ${skippedCount}.`);
656
673
  }
657
674
  return;
658
675
  }
@@ -702,7 +719,20 @@ async function updateInstalledSkills(client, options) {
702
719
  console.log(`Dry run finished. Would update ${plannedCount}, skipped ${skippedCount}.`);
703
720
  return;
704
721
  }
705
- console.log(`Update finished. Updated ${updatedCount}, skipped ${skippedCount}.`);
722
+ console.log(`Update finished. Updated ${updatedCount}${formatRemovedSkillCleanup(cleanup)}, skipped ${skippedCount}.`);
723
+ }
724
+ async function uninstallRemovedSkills(records, dryRun = false) {
725
+ return offerRemovedSkillUninstalls(records, {
726
+ dryRun,
727
+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),
728
+ reviewed: reviewedRemovedSkills,
729
+ formatTarget: formatInstallTargetRoot,
730
+ log: (message) => console.log(message),
731
+ async forget(record) {
732
+ const current = await readInstalledSkillRecords();
733
+ await writeStateFile(INSTALLED_STATE_PATH, current.filter((item) => !(item.baseUrl === record.baseUrl && item.targetRoot === record.targetRoot && item.skillId === record.skillId)));
734
+ },
735
+ });
706
736
  }
707
737
  async function collectInstalledSkillUpdateCandidates(client, options) {
708
738
  const records = options?.records
@@ -1546,7 +1576,7 @@ async function login(baseUrl) {
1546
1576
  const state = cryptoRandomHex(16);
1547
1577
  const codeVerifier = createPkceVerifier();
1548
1578
  const codeChallenge = createPkceChallenge(codeVerifier);
1549
- const callback = await waitForLoginCallback();
1579
+ const callback = await waitForLoginCallback(state);
1550
1580
  const loginUrl = `${baseUrl}/api/cli/login?redirectUri=${encodeURIComponent(callback.redirectUri)}` +
1551
1581
  `&codeChallenge=${encodeURIComponent(codeChallenge)}` +
1552
1582
  `&state=${encodeURIComponent(state)}`;
@@ -1558,7 +1588,7 @@ async function login(baseUrl) {
1558
1588
  catch {
1559
1589
  console.log('Could not open a browser automatically. Use the URL above.');
1560
1590
  }
1561
- const authCode = await callback.wait(state, LOGIN_TIMEOUT_MS);
1591
+ const authCode = await callback.wait(LOGIN_TIMEOUT_MS);
1562
1592
  const response = await fetchJson(`${baseUrl}/api/cli/token`, {
1563
1593
  method: 'POST',
1564
1594
  headers: {
@@ -1671,60 +1701,31 @@ async function createClient(baseUrl, explicitToken) {
1671
1701
  async function loadStoredSessionOrThrow() {
1672
1702
  const session = await loadSession(resolvedBaseUrl);
1673
1703
  if (!session) {
1674
- throw new Error(`No stored session for ${resolvedBaseUrl}. Run "skillshare login${resolvedBaseUrl === LOCAL_URL ? ' local' : ''}".`);
1704
+ throw new Error(`No stored session for ${resolvedBaseUrl}. Run "skillshare login --server ${resolvedBaseUrl}".`);
1675
1705
  }
1676
1706
  return session;
1677
1707
  }
1678
- async function refreshStoredSession(session) {
1679
- const currentSession = session ?? await loadStoredSessionOrThrow();
1680
- if (new Date(currentSession.refreshTokenExpiresAt).getTime() <= Date.now()) {
1681
- throw new Error(`Stored session for ${resolvedBaseUrl} is no longer valid. Run "skillshare login${resolvedBaseUrl === LOCAL_URL ? ' local' : ''}" again.`);
1682
- }
1683
- const response = await fetchFromServer(`${resolvedBaseUrl}/api/cli/refresh`, {
1684
- method: 'POST',
1685
- headers: {
1686
- 'Content-Type': 'application/json',
1687
- Accept: 'application/json',
1688
- },
1689
- body: JSON.stringify({
1690
- refreshToken: currentSession.refreshToken,
1691
- }),
1692
- });
1693
- if (!response.ok) {
1694
- throw new Error(`Stored session for ${resolvedBaseUrl} is no longer valid. Run "skillshare login${resolvedBaseUrl === LOCAL_URL ? ' local' : ''}" again.`);
1695
- }
1696
- const refreshed = await response.json();
1697
- const nextSession = {
1698
- ...currentSession,
1699
- accessToken: refreshed.accessToken,
1700
- accessTokenExpiresAt: refreshed.accessTokenExpiresAt,
1701
- refreshToken: refreshed.refreshToken,
1702
- refreshTokenExpiresAt: refreshed.refreshTokenExpiresAt,
1703
- user: refreshed.user,
1704
- };
1705
- await storeSession(nextSession);
1706
- return nextSession;
1707
- }
1708
1708
  async function getAccessToken(options) {
1709
1709
  if (explicitToken) {
1710
1710
  return explicitToken;
1711
1711
  }
1712
1712
  const session = await loadStoredSessionOrThrow();
1713
- if (!options?.forceRefresh && new Date(session.accessTokenExpiresAt).getTime() > Date.now() + 60_000) {
1713
+ if ((!options?.forceRefresh || (options.rejectedToken !== undefined && session.accessToken !== options.rejectedToken)) && new Date(session.accessTokenExpiresAt).getTime() > Date.now() + 60_000) {
1714
1714
  return session.accessToken;
1715
1715
  }
1716
- const refreshedSession = await refreshStoredSession(session);
1716
+ const refreshedSession = await refreshSession({ path: SESSION_PATH, server: resolvedBaseUrl, previous: session, load: loadStoredSessionOrThrow, fetch: fetchFromServer });
1717
1717
  return refreshedSession.accessToken;
1718
1718
  }
1719
1719
  async function sendAuthorized(path, init, retryUnauthorized = true) {
1720
+ const sentToken = await getAccessToken();
1720
1721
  const response = await fetchFromServer(`${resolvedBaseUrl}${path}`, {
1721
1722
  ...init,
1722
- headers: await buildHeaders(() => getAccessToken(), init?.headers),
1723
+ headers: await buildHeaders(() => Promise.resolve(sentToken), init?.headers),
1723
1724
  });
1724
1725
  if (response.status !== 401 || explicitToken || !retryUnauthorized) {
1725
1726
  return response;
1726
1727
  }
1727
- const refreshedToken = await getAccessToken({ forceRefresh: true });
1728
+ const refreshedToken = await getAccessToken({ forceRefresh: true, rejectedToken: sentToken });
1728
1729
  return fetchFromServer(`${resolvedBaseUrl}${path}`, {
1729
1730
  ...init,
1730
1731
  headers: await buildHeaders(() => Promise.resolve(refreshedToken), init?.headers),
@@ -1887,19 +1888,21 @@ async function loadAnySession() {
1887
1888
  }
1888
1889
  }
1889
1890
  async function storeSession(session) {
1890
- await writePrivateFile(SESSION_PATH, JSON.stringify(session));
1891
+ await withSessionLock(SESSION_PATH, () => writeSessionAtomically(SESSION_PATH, session));
1891
1892
  }
1892
1893
  // Tokens and state stay readable by the current user only; the mode of writeFile applies just to new files.
1893
1894
  async function writePrivateFile(path, content) {
1894
1895
  const posix = process.platform !== 'win32';
1895
1896
  await mkdir(APP_DIR, { recursive: true, mode: posix ? 0o700 : undefined });
1897
+ if (posix)
1898
+ await chmod(APP_DIR, 0o700);
1896
1899
  await writeFile(path, content, { mode: posix ? 0o600 : undefined });
1897
1900
  if (posix)
1898
1901
  await chmod(path, 0o600);
1899
1902
  }
1900
1903
  async function logoutSession() {
1901
1904
  try {
1902
- await rm(SESSION_PATH);
1905
+ await withSessionLock(SESSION_PATH, () => rm(SESSION_PATH));
1903
1906
  console.log('Logged out.');
1904
1907
  }
1905
1908
  catch (error) {
@@ -1940,64 +1943,6 @@ async function openBrowser(url) {
1940
1943
  throw new Error(result.stderr.trim() || 'Failed to open browser.');
1941
1944
  }
1942
1945
  }
1943
- async function waitForLoginCallback() {
1944
- let resolveStatePromise = () => { };
1945
- let rejectStatePromise = () => { };
1946
- const statePromise = new Promise((resolve, reject) => {
1947
- resolveStatePromise = resolve;
1948
- rejectStatePromise = reject;
1949
- });
1950
- const server = createServer((request, response) => {
1951
- const url = new URL(request.url ?? '/', 'http://127.0.0.1');
1952
- const code = url.searchParams.get('code');
1953
- const state = url.searchParams.get('state');
1954
- const error = url.searchParams.get('error');
1955
- if (error) {
1956
- response.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
1957
- response.end(`Login failed: ${error}`);
1958
- rejectStatePromise(new Error(`Login failed: ${error}`));
1959
- return;
1960
- }
1961
- if (!code || !state) {
1962
- response.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
1963
- response.end('Missing code or state.');
1964
- return;
1965
- }
1966
- response.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
1967
- response.end('Skillshare login completed. You can close this tab.');
1968
- resolveStatePromise(JSON.stringify({ code, state }));
1969
- });
1970
- await new Promise((resolve, reject) => {
1971
- server.once('error', reject);
1972
- server.listen(0, '127.0.0.1', () => resolve());
1973
- });
1974
- const address = server.address();
1975
- if (!address || typeof address === 'string') {
1976
- throw new Error('Failed to bind local callback server.');
1977
- }
1978
- return {
1979
- redirectUri: `http://127.0.0.1:${address.port}/callback`,
1980
- async wait(expectedState, timeoutMs) {
1981
- let timer;
1982
- const timeout = new Promise((_, reject) => {
1983
- timer = setTimeout(() => {
1984
- reject(new Error(`Sign-in did not complete within ${Math.round(timeoutMs / 60_000)} minutes. Run "skillshare login" again.`));
1985
- }, timeoutMs);
1986
- });
1987
- try {
1988
- const payload = JSON.parse(await Promise.race([statePromise, timeout]));
1989
- if (payload.state !== expectedState) {
1990
- throw new Error('Login state mismatch.');
1991
- }
1992
- return payload.code;
1993
- }
1994
- finally {
1995
- clearTimeout(timer);
1996
- server.close();
1997
- }
1998
- },
1999
- };
2000
- }
2001
1946
  async function readLocalSkillMetadata(directory, baseUrl) {
2002
1947
  const resolvedDirectory = resolve(directory);
2003
1948
  const normalizedBaseUrl = normalizeText(baseUrl) ? normalizeBaseUrl(baseUrl) : null;
@@ -1,6 +1,6 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
2
  import { createReadStream } from 'node:fs';
3
- import { mkdir, readdir, rename, rm, rmdir, stat } from 'node:fs/promises';
3
+ import { lstat, mkdir, readdir, rename, rm, rmdir, stat } from 'node:fs/promises';
4
4
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
5
5
  export function resolveInsideRoot(root, relativePath) {
6
6
  const resolvedRoot = resolve(root);
@@ -46,6 +46,97 @@ export async function inspectInstallTarget(targetRoot, record) {
46
46
  }
47
47
  return modified.length > 0 ? { state: 'modified', paths: modified } : { state: 'clean' };
48
48
  }
49
+ /** Preview both installed and extra files without following symbolic links. */
50
+ export async function inspectSkillUninstall(targetRoot, files) {
51
+ const root = resolve(targetRoot);
52
+ const trackedDirectories = new Set();
53
+ for (const path of Object.keys(files ?? {})) {
54
+ const normalized = relative(root, resolveInsideRoot(root, path)).replaceAll('\\', '/');
55
+ const parts = normalized.split('/');
56
+ for (let length = 1; length < parts.length; length++)
57
+ trackedDirectories.add(parts.slice(0, length).join('/'));
58
+ }
59
+ const preview = { missing: false, legacy: !files, removable: [], preserved: [] };
60
+ let info;
61
+ try {
62
+ info = await lstat(root);
63
+ }
64
+ catch (error) {
65
+ if (error?.code !== 'ENOENT')
66
+ throw error;
67
+ return { ...preview, missing: true };
68
+ }
69
+ if (!info.isDirectory() || info.isSymbolicLink()) {
70
+ preview.preserved.push('.');
71
+ return preview;
72
+ }
73
+ async function visit(directory, prefix) {
74
+ const entries = await readdir(directory, { withFileTypes: true });
75
+ if (entries.length === 0 && prefix)
76
+ preview.preserved.push(`${prefix}/`);
77
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
78
+ const relativePath = prefix ? `${prefix}/${entry.name}` : entry.name;
79
+ const path = resolveInsideRoot(root, relativePath);
80
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
81
+ if (trackedDirectories.has(relativePath))
82
+ await visit(path, relativePath);
83
+ else
84
+ preview.preserved.push(`${relativePath}/`);
85
+ }
86
+ else if (files && await isUnchangedInstalledFile(root, relativePath, files[relativePath])) {
87
+ preview.removable.push(relativePath);
88
+ }
89
+ else {
90
+ preview.preserved.push(relativePath);
91
+ }
92
+ }
93
+ }
94
+ await visit(root, '');
95
+ return preview;
96
+ }
97
+ /** Uninstall only unchanged, tracked regular files. Recheck after the user's decision. */
98
+ export async function uninstallSkillFiles(targetRoot, files) {
99
+ const root = resolve(targetRoot);
100
+ const preview = await inspectSkillUninstall(root, files);
101
+ const removed = [];
102
+ for (const relativePath of preview.removable) {
103
+ if (!await isUnchangedInstalledFile(root, relativePath, files[relativePath]))
104
+ continue;
105
+ await rm(resolveInsideRoot(root, relativePath), { force: true });
106
+ removed.push(relativePath);
107
+ await removeEmptyParents(dirname(resolveInsideRoot(root, relativePath)), root);
108
+ }
109
+ try {
110
+ await rmdir(root);
111
+ }
112
+ catch (error) {
113
+ if (!['ENOENT', 'ENOTEMPTY', 'EEXIST', 'ENOTDIR'].includes(error?.code ?? ''))
114
+ throw error;
115
+ }
116
+ return { removed, preserved: (await inspectSkillUninstall(root, files)).preserved };
117
+ }
118
+ async function isUnchangedInstalledFile(root, relativePath, expectedHash) {
119
+ if (!expectedHash)
120
+ return false;
121
+ const path = resolveInsideRoot(root, relativePath);
122
+ try {
123
+ let parent = dirname(path);
124
+ while (true) {
125
+ const info = await lstat(parent);
126
+ if (!info.isDirectory() || info.isSymbolicLink())
127
+ return false;
128
+ if (parent === root)
129
+ break;
130
+ parent = dirname(parent);
131
+ }
132
+ return (await lstat(path)).isFile() && await hashFile(path) === expectedHash;
133
+ }
134
+ catch (error) {
135
+ if (error?.code !== 'ENOENT')
136
+ throw error;
137
+ return false;
138
+ }
139
+ }
49
140
  /**
50
141
  * Downloads every file into a sibling staging directory first, so a failed transfer
51
142
  * leaves the existing install untouched. Files from the previous manifest that the
@@ -0,0 +1,52 @@
1
+ import { createServer } from 'node:http';
2
+ export async function waitForLoginCallback(expectedState) {
3
+ let complete = () => { };
4
+ const result = new Promise(resolve => { complete = resolve; });
5
+ const server = createServer((request, response) => {
6
+ const url = new URL(request.url ?? '/', 'http://127.0.0.1');
7
+ const state = url.searchParams.get('state');
8
+ if (request.method !== 'GET' || url.pathname !== '/callback' || state !== expectedState) {
9
+ response.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
10
+ response.end('Invalid login callback.');
11
+ return;
12
+ }
13
+ const code = url.searchParams.get('code');
14
+ const error = url.searchParams.get('error');
15
+ if (!code && !error) {
16
+ response.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
17
+ response.end('Missing code.');
18
+ return;
19
+ }
20
+ response.writeHead(error ? 400 : 200, { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' });
21
+ response.end(error ? `Login failed: ${error}` : 'Skillshare login completed. You can close this tab.');
22
+ complete(error ? { error } : { code: code });
23
+ });
24
+ await new Promise((resolve, reject) => {
25
+ server.once('error', reject);
26
+ server.listen(0, '127.0.0.1', resolve);
27
+ });
28
+ const address = server.address();
29
+ if (!address || typeof address === 'string') {
30
+ server.close();
31
+ throw new Error('Failed to bind local callback server.');
32
+ }
33
+ return {
34
+ redirectUri: `http://127.0.0.1:${address.port}/callback`,
35
+ async wait(timeoutMs) {
36
+ let timer;
37
+ const timeout = new Promise((_, reject) => {
38
+ timer = setTimeout(() => reject(new Error(`Sign-in did not complete within ${Math.round(timeoutMs / 60_000)} minutes. Run "skillshare login" again.`)), timeoutMs);
39
+ });
40
+ try {
41
+ const value = await Promise.race([result, timeout]);
42
+ if (value.error)
43
+ throw new Error(`Login failed: ${value.error}`);
44
+ return value.code;
45
+ }
46
+ finally {
47
+ clearTimeout(timer);
48
+ server.close();
49
+ }
50
+ },
51
+ };
52
+ }
package/dist/output.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { pageUrl } from './page-links.js';
2
+ export { pageUrl } from './page-links.js';
1
3
  // Human-readable renderers for CLI commands. Every command also supports --json for scripts.
2
4
  export function formatTable(headers, rows) {
3
5
  const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? '').length)));
@@ -122,7 +124,7 @@ export function renderPageDetail(page, baseUrl, now = new Date()) {
122
124
  `${page.slug} (${page.kind === 'celld' ? 'application' : 'static site'})`,
123
125
  ...fields([
124
126
  ['URL', pageUrl(baseUrl, page.slug)],
125
- ['Annotate', `${baseUrl.replace(/\/+$/, '')}/pa/${encodeURIComponent(page.slug)}/`],
127
+ ['Annotate', pageUrl(baseUrl, page.slug, undefined, true)],
126
128
  ['Owner', page.ownerDisplayName],
127
129
  ['Revision', `${page.contentRevision}, updated ${formatDateTime(page.updated)}`],
128
130
  ['Users this month', page.monthlyUsage.find((usage) => usage.month === month)?.uniqueUsers ?? 0],
@@ -163,6 +165,3 @@ export function renderTeamsStatus(status) {
163
165
  ]),
164
166
  ].join('\n');
165
167
  }
166
- export function pageUrl(baseUrl, slug) {
167
- return `${baseUrl.replace(/\/+$/, '')}/p/${encodeURIComponent(slug)}/`;
168
- }
@@ -0,0 +1,61 @@
1
+ (() => {
2
+ const installed = Symbol.for('skillshare.page-client');
3
+ if (window[installed]) return;
4
+ window[installed] = true;
5
+ const raw = window.fetch.bind(window), origin = location.origin;
6
+ const unsafe = m => !['GET','HEAD','OPTIONS'].includes(m.toUpperCase());
7
+ const own = u => new URL(u, location.href).origin === origin;
8
+ let pending;
9
+ const token = () => pending ??= raw('/__skillshare/csrf', {credentials:'same-origin',cache:'no-store'})
10
+ .then(r => { if(!r.ok) throw Error('Page session expired'); return r.json(); })
11
+ .then(x => x.token).catch(e => { pending = undefined; throw e; });
12
+ window.fetch = async (input, init) => {
13
+ const url = input instanceof Request ? input.url : String(input);
14
+ const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
15
+ if (!own(url) || !unsafe(method) || new URL(url,location.href).pathname.startsWith('/api/bypass-sso/')) return raw(input,init);
16
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
17
+ headers.set('X-Skillshare-CSRF',await token());
18
+ return raw(input,{...init,headers});
19
+ };
20
+ const open = XMLHttpRequest.prototype.open, send = XMLHttpRequest.prototype.send, abort = XMLHttpRequest.prototype.abort;
21
+ const requests = new WeakMap();
22
+ XMLHttpRequest.prototype.open = function(method,url,...rest) { requests.set(this,{method,url:String(url),async:rest[0]!==false,cancelled:false}); return open.call(this,method,url,...rest); };
23
+ XMLHttpRequest.prototype.abort = function() { const r=requests.get(this); if(r) r.cancelled=true; return abort.call(this); };
24
+ XMLHttpRequest.prototype.send = function(body) {
25
+ const r = requests.get(this);
26
+ if (!r || !own(r.url) || !unsafe(r.method)) return send.call(this,body);
27
+ if (!r.async) throw Error('Synchronous Page mutations are not supported');
28
+ token().then(t => { if(r.cancelled || requests.get(this)!==r) return; this.setRequestHeader('X-Skillshare-CSRF',t); send.call(this,body); }).catch(() => this.dispatchEvent(new Event('error')));
29
+ };
30
+ const nativeSubmit = HTMLFormElement.prototype.submit;
31
+ const methodFor = (form, button) => button?.hasAttribute('formmethod') ? button.formMethod : form.method;
32
+ const actionFor = (form, button) => button?.hasAttribute('formaction') ? button.formAction : form.action;
33
+ const submitForm = async (form, button) => {
34
+ const method = methodFor(form, button), action = actionFor(form, button);
35
+ if (!own(action) || !unsafe(method)) { nativeSubmit.call(form); return; }
36
+ try {
37
+ let field = form.querySelector('input[name="__skillshare_csrf"]');
38
+ if(!field) { field=document.createElement('input'); field.type='hidden'; field.name='__skillshare_csrf'; form.append(field); }
39
+ field.value=await token();
40
+ let copy;
41
+ if(button?.name) { copy=document.createElement('input'); copy.type='hidden'; copy.name=button.name; copy.value=button.value; form.append(copy); }
42
+ const original = ['method','action','enctype','target'].map(name => [name,form.getAttribute(name)]);
43
+ try {
44
+ form.method=method; form.action=action;
45
+ if(button?.hasAttribute('formenctype')) form.enctype=button.formEnctype;
46
+ if(button?.hasAttribute('formtarget')) form.target=button.formTarget;
47
+ nativeSubmit.call(form);
48
+ } finally {
49
+ for(const [name,value] of original) if(value===null) form.removeAttribute(name); else form.setAttribute(name,value);
50
+ copy?.remove();
51
+ }
52
+ } catch { console.error('Page session expired; reload before submitting.'); }
53
+ };
54
+ HTMLFormElement.prototype.submit = function() { void submitForm(this); };
55
+ document.addEventListener('submit', event => {
56
+ if (event.defaultPrevented || !(event.target instanceof HTMLFormElement)) return;
57
+ const form = event.target, button = event.submitter;
58
+ if (!own(actionFor(form, button)) || !unsafe(methodFor(form, button))) return;
59
+ event.preventDefault(); void submitForm(form, button);
60
+ });
61
+ })();
@@ -0,0 +1,14 @@
1
+ const domains = new Map();
2
+ export function configurePageLinks(baseUrl, domain) {
3
+ const key = new URL(baseUrl).origin;
4
+ if (domain)
5
+ domains.set(key, domain);
6
+ else
7
+ domains.delete(key);
8
+ }
9
+ export function pageUrl(baseUrl, slug, revision, annotations = false) {
10
+ const domain = domains.get(new URL(baseUrl).origin);
11
+ if (domain && /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/.test(slug) && !slug.includes('--'))
12
+ return `https://${slug}${revision ? `--${revision}${annotations ? 'a' : ''}` : annotations ? '--a' : ''}.${domain}/`;
13
+ return `${baseUrl.replace(/\/+$/, '')}/${annotations ? 'pa' : 'p'}/${encodeURIComponent(slug)}${revision ? `@${revision}` : ''}/`;
14
+ }
@@ -1,7 +1,8 @@
1
+ import { pageUrl } from './page-links.js';
1
2
  import { formatDateTime } from './output.js';
2
- /** Opens the Page on /pa/ with the panel focused on the thread; the browser script reads the parameter. */
3
+ /** Open the comment's document revision with the editor focused on its thread. */
3
4
  export function pageCommentLink(baseUrl, slug, comment) {
4
- return `${baseUrl.replace(/\/+$/, '')}/pa/${encodeURIComponent(slug)}/${comment.path}?skillshare-annotation=${comment.threadId}`;
5
+ return `${pageUrl(baseUrl, slug, comment.revision, true)}${comment.path.split('/').map(encodeURIComponent).join('/')}?skillshare-annotation=${comment.threadId}`;
5
6
  }
6
7
  const ACTIONS = ['list', 'add', 'reply', 'edit', 'resolve', 'reopen', 'delete', 'enable', 'disable'];
7
8
  /** Keeps threads where the author (`mine` or a user id) wrote the first comment or any reply. */
@@ -1,10 +1,9 @@
1
+ import { readFileSync } from 'node:fs';
1
2
  import { createServer, request as httpRequest, } from 'node:http';
2
3
  import { randomBytes, timingSafeEqual } from 'node:crypto';
3
- const sessionCookie = 'skillshare.dev-user';
4
+ const pageBrowserClient = readFileSync(new URL('./page-browser-client.js', import.meta.url), 'utf8');
4
5
  const internal = '/__skillshare_dev';
5
- const hostCookie = (name) => name.startsWith('skillshare.auth') ||
6
- name.startsWith('.AspNetCore.') ||
7
- name === sessionCookie;
6
+ const hostCookie = (name) => /^(?:__host-skillshare-|skillshare\.(?:auth|page|dev-user)|\.aspnetcore\.)/i.test(name);
8
7
  const hopHeaders = [
9
8
  'connection',
10
9
  'keep-alive',
@@ -78,7 +77,9 @@ export function responseCookies(cookies, prefix) {
78
77
  });
79
78
  }
80
79
  export function createDevProxy(options) {
81
- const prefix = `/p/${options.slug}`;
80
+ const prefix = '';
81
+ const sessionCookie = 'skillshare.dev-user-' + randomBytes(16).toString('hex');
82
+ const csrfToken = randomBytes(32).toString('hex');
82
83
  const usersToken = randomBytes(32).toString('hex');
83
84
  const streams = new Set();
84
85
  const upgrades = new Set();
@@ -92,18 +93,35 @@ export function createDevProxy(options) {
92
93
  options.users[0]);
93
94
  };
94
95
  function pagePath(path) {
95
- return path.startsWith(prefix + '/') ? path.slice(prefix.length) : undefined;
96
+ return path.startsWith('/') && !path.startsWith('//') && !path.includes('\\') ? path : undefined;
96
97
  }
97
98
  function allowed(request) {
98
99
  const host = request.headers.host ?? '';
99
- return /^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host);
100
+ const address = server.address();
101
+ return typeof address === 'object' && address !== null &&
102
+ (host === `127.0.0.1:${address.port}` || host === `localhost:${address.port}`);
100
103
  }
101
- const server = createServer((request, response) => {
104
+ const server = createServer(async (request, response) => {
102
105
  if (!allowed(request)) {
103
106
  response.writeHead(403).end('Local requests only');
104
107
  return;
105
108
  }
106
- const url = new URL(request.url, `http://${request.headers.host}`);
109
+ let url;
110
+ try {
111
+ url = new URL(request.url, `http://${request.headers.host}`);
112
+ }
113
+ catch {
114
+ response.writeHead(400).end();
115
+ return;
116
+ }
117
+ if (url.origin !== `http://${request.headers.host}`) {
118
+ response.writeHead(403).end();
119
+ return;
120
+ }
121
+ if (request.headers['service-worker'] === 'script' || request.headers['sec-fetch-dest'] === 'serviceworker') {
122
+ response.writeHead(403).end();
123
+ return;
124
+ }
107
125
  if (url.pathname === `/api/pages/${encodeURIComponent(options.slug)}/users-directory`) {
108
126
  response.setHeader('Cache-Control', 'no-store');
109
127
  const token = request.headers['x-skillshare-users-token'];
@@ -120,8 +138,21 @@ export function createDevProxy(options) {
120
138
  response.end(JSON.stringify(options.users.map(({ id, displayName, email, isAdmin, isOwner }) => ({ id, displayName, email, isAdmin, isOwner }))));
121
139
  return;
122
140
  }
123
- if (url.pathname === '/' || url.pathname === prefix) {
124
- response.writeHead(307, { Location: prefix + '/' + url.search }).end();
141
+ if (url.pathname === '/__skillshare/csrf') {
142
+ if (request.method !== 'GET' || (request.headers.origin && request.headers.origin !== url.origin) ||
143
+ ['cross-site', 'same-site'].includes(String(request.headers['sec-fetch-site']))) {
144
+ response.writeHead(403).end();
145
+ return;
146
+ }
147
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }).end(JSON.stringify({ token: csrfToken }));
148
+ return;
149
+ }
150
+ if (url.pathname === '/__skillshare/client.js') {
151
+ response.writeHead(200, { 'Content-Type': 'text/javascript', 'Cache-Control': 'no-store' }).end(pageBrowserClient);
152
+ return;
153
+ }
154
+ if (url.pathname.startsWith('/__skillshare/')) {
155
+ response.writeHead(404).end();
125
156
  return;
126
157
  }
127
158
  if (url.pathname.startsWith(internal + '/')) {
@@ -142,7 +173,7 @@ export function createDevProxy(options) {
142
173
  }
143
174
  if (url.pathname === internal + '/user') {
144
175
  // Only same-origin browser navigation may switch the local identity.
145
- if (request.headers['sec-fetch-site'] === 'cross-site') {
176
+ if (['cross-site', 'same-site'].includes(String(request.headers['sec-fetch-site'])) || (request.headers.origin && request.headers.origin !== url.origin)) {
146
177
  response.writeHead(403).end();
147
178
  return;
148
179
  }
@@ -200,20 +231,57 @@ label.append(select); bar.append(label); document.body.append(bar);
200
231
  return;
201
232
  }
202
233
  const bypass = path === '/api/bypass-sso' || path.startsWith('/api/bypass-sso/');
203
- if (!bypass &&
204
- !['GET', 'HEAD'].includes(request.method ?? '') &&
205
- (request.headers['sec-fetch-site'] === 'cross-site' ||
206
- (request.headers.origin && request.headers.origin !== url.origin))) {
207
- response.writeHead(403).end('Cross-origin mutation rejected');
234
+ const navigation = request.method === 'GET' && request.headers['sec-fetch-mode'] === 'navigate' && request.headers['sec-fetch-dest'] === 'document';
235
+ if (!bypass && !navigation && ((request.headers.origin && request.headers.origin !== url.origin) ||
236
+ ['same-site', 'cross-site'].includes(String(request.headers['sec-fetch-site'])))) {
237
+ response.writeHead(403).end('Cross-origin request rejected');
208
238
  return;
209
239
  }
240
+ let bufferedBody;
241
+ if (!bypass && !['GET', 'HEAD', 'OPTIONS'].includes(request.method ?? '') &&
242
+ (request.headers.origin || request.headers['sec-fetch-site'])) {
243
+ let token = request.headers['x-skillshare-csrf'];
244
+ if (!token && /^(application\/x-www-form-urlencoded|multipart\/form-data)(;|$)/i.test(request.headers['content-type'] ?? '')) {
245
+ const chunks = [];
246
+ let length = 0;
247
+ try {
248
+ for await (const chunk of request) {
249
+ length += chunk.length;
250
+ if (length > 128 * 1024 * 1024) {
251
+ response.writeHead(413).end();
252
+ return;
253
+ }
254
+ chunks.push(Buffer.from(chunk));
255
+ }
256
+ bufferedBody = Buffer.concat(chunks);
257
+ const form = await new Response(new Uint8Array(bufferedBody), { headers: { 'Content-Type': request.headers['content-type'] } }).formData();
258
+ const value = form.get('__skillshare_csrf');
259
+ if (typeof value === 'string')
260
+ token = value;
261
+ }
262
+ catch {
263
+ response.writeHead(400).end();
264
+ return;
265
+ }
266
+ }
267
+ if (token !== csrfToken) {
268
+ response.writeHead(403).end('Missing development CSRF token');
269
+ return;
270
+ }
271
+ }
210
272
  const user = bypass ? undefined : userFor(request);
211
273
  const upstream = httpRequest(new URL(path + url.search, target), {
212
274
  method: request.method,
213
275
  headers: requestHeaders(request, user, url.origin + prefix + '/', options.slug, usersToken),
214
276
  }, (incoming) => {
215
277
  const headers = cleanHeaders(incoming.headers);
216
- headers['cache-control'] = 'private, no-cache';
278
+ headers['cache-control'] = 'no-store';
279
+ headers['cross-origin-resource-policy'] = 'same-origin';
280
+ headers['x-content-type-options'] = 'nosniff';
281
+ headers['referrer-policy'] = 'no-referrer';
282
+ for (const name of ['service-worker-allowed', 'clear-site-data', 'nel', 'report-to', 'reporting-endpoints', 'alt-svc', 'strict-transport-security', 'refresh'])
283
+ delete headers[name];
284
+ headers['content-security-policy'] = [String(headers['content-security-policy'] ?? ''), "worker-src 'none'"].filter(Boolean).join(', ');
217
285
  if (headers['set-cookie'])
218
286
  headers['set-cookie'] = responseCookies(headers['set-cookie'], prefix);
219
287
  if (headers.location) {
@@ -240,7 +308,10 @@ label.append(select); bar.append(label); document.body.append(bar);
240
308
  incoming.on('end', () => {
241
309
  delete headers['content-length'];
242
310
  delete headers.etag;
243
- const html = Buffer.concat(chunks).toString('utf8');
311
+ const originalHtml = Buffer.concat(chunks).toString('utf8');
312
+ const head = originalHtml.search(/<head\b[^>]*>/i);
313
+ const offset = head >= 0 ? originalHtml.indexOf('>', head) + 1 : /^<!doctype/i.test(originalHtml) ? originalHtml.indexOf('>') + 1 : 0;
314
+ const html = originalHtml.slice(0, offset) + '<script src="/__skillshare/client.js"></script>' + originalHtml.slice(offset);
244
315
  const script = `<script src="${internal}/client.js?version=${options.generation()}&user=${encodeURIComponent(userFor(request).id)}"></script>`;
245
316
  response.writeHead(incoming.statusCode, headers);
246
317
  response.end(html.includes('</body>')
@@ -259,14 +330,26 @@ label.append(select); bar.append(label); document.body.append(bar);
259
330
  response.end('Page connection failed');
260
331
  });
261
332
  response.on('close', () => upstream.destroy());
262
- request.pipe(upstream);
333
+ if (bufferedBody)
334
+ upstream.end(bufferedBody);
335
+ else
336
+ request.pipe(upstream);
263
337
  });
264
338
  server.on('upgrade', (request, socket, head) => {
265
339
  const target = options.target();
266
- const url = new URL(request.url, `http://${request.headers.host}`);
340
+ let url;
341
+ try {
342
+ url = new URL(request.url, `http://${request.headers.host}`);
343
+ }
344
+ catch {
345
+ socket.destroy();
346
+ return;
347
+ }
267
348
  const path = pagePath(url.pathname);
268
349
  if (!allowed(request) ||
350
+ url.origin !== `http://${request.headers.host}` ||
269
351
  !path ||
352
+ path.startsWith('/__skillshare/') || path.startsWith(internal + '/') ||
270
353
  !target ||
271
354
  (request.headers.origin && request.headers.origin !== url.origin)) {
272
355
  socket.destroy();
@@ -293,6 +376,8 @@ label.append(select); bar.append(label); document.body.append(bar);
293
376
  socket.on('error', () => peer.destroy());
294
377
  peer.on('error', () => socket.destroy());
295
378
  const responseHeaders = { ...incoming.headers };
379
+ for (const name of ['service-worker-allowed', 'clear-site-data', 'nel', 'report-to', 'reporting-endpoints', 'alt-svc', 'strict-transport-security', 'refresh'])
380
+ delete responseHeaders[name];
296
381
  if (responseHeaders['set-cookie'])
297
382
  responseHeaders['set-cookie'] = responseCookies(responseHeaders['set-cookie'], prefix);
298
383
  socket.write(`HTTP/1.1 101 Switching Protocols\r\n${Object.entries(responseHeaders)
@@ -314,6 +399,7 @@ label.append(select); bar.append(label); document.body.append(bar);
314
399
  });
315
400
  return {
316
401
  server,
402
+ sessionCookie,
317
403
  reload() {
318
404
  for (const response of streams)
319
405
  response.write(`data: ${options.generation()}\n\n`);
package/dist/pages-dev.js CHANGED
@@ -108,7 +108,7 @@ export async function startPageDev(options) {
108
108
  proxy.server.listen(port, '127.0.0.1');
109
109
  await once(proxy.server, 'listening');
110
110
  const publicPort = proxy.server.address().port;
111
- const url = `http://127.0.0.1:${publicPort}/p/${slug}/`;
111
+ const url = `http://127.0.0.1:${publicPort}/`;
112
112
  async function rebuild() {
113
113
  lastError = undefined;
114
114
  try {
@@ -0,0 +1,138 @@
1
+ import { inspectSkillUninstall, uninstallSkillFiles } from './install-files.js';
2
+ import { cancel, isCancel, multiselect, select } from '@clack/prompts';
3
+ import { plural } from './output.js';
4
+ export function formatRemovedSkillCleanup(result) {
5
+ return [
6
+ result.uninstalled ? `uninstalled ${result.uninstalled}` : '',
7
+ result.kept ? `kept locally ${result.kept}` : '',
8
+ result.cleared ? `cleared ${result.cleared} missing install record${result.cleared === 1 ? '' : 's'}` : '',
9
+ ].filter(Boolean).map(part => `, ${part}`).join('');
10
+ }
11
+ export async function offerRemovedSkillUninstalls(records, options) {
12
+ const result = { uninstalled: 0, kept: 0, cleared: 0 };
13
+ const key = (record) => JSON.stringify([record.baseUrl, record.skillId, record.targetRoot]);
14
+ if (!options.dryRun)
15
+ records = records.filter(record => !options.reviewed?.has(key(record)));
16
+ if (records.length === 0)
17
+ return result;
18
+ const reviews = [];
19
+ for (const record of records) {
20
+ if (!options.dryRun)
21
+ options.reviewed?.add(key(record));
22
+ const label = `${record.skillName || `Skill ${record.skillId}`} · ${options.formatTarget?.(record.targetRoot) ?? record.targetRoot}`;
23
+ try {
24
+ const preview = await inspectSkillUninstall(record.targetRoot, record.files);
25
+ if (preview.missing) {
26
+ if (options.dryRun) {
27
+ options.log(`Would clear missing installation: ${label}. No files remain.`);
28
+ }
29
+ else {
30
+ await options.forget(record);
31
+ result.cleared++;
32
+ options.log(`Cleared missing installation: ${label}. No files were deleted.`);
33
+ }
34
+ continue;
35
+ }
36
+ reviews.push({ record, label, preview });
37
+ }
38
+ catch (error) {
39
+ options.log(`Could not inspect ${label}: ${error instanceof Error ? error.message : String(error)}`);
40
+ }
41
+ }
42
+ if (reviews.length === 0)
43
+ return result;
44
+ options.log(`${reviews.length} local ${reviews.length === 1 ? 'copy belongs' : 'copies belong'} to skills removed from SkillShare:`);
45
+ for (const { label, preview } of reviews) {
46
+ options.log(` ${label}\n ${preview.legacy ? 'Older installation: files cannot be verified for removal.'
47
+ : `${plural(preview.removable.length, 'unchanged file')} to remove; ${plural(preview.preserved.length, 'path')} to keep (local edits or extra files).`}`);
48
+ if (preview.preserved.length > 0 && !preview.legacy) {
49
+ const shown = preview.preserved.slice(0, 4).join(', ');
50
+ options.log(` Keep: ${shown}${preview.preserved.length > 4 ? ` and ${preview.preserved.length - 4} more` : ''}`);
51
+ if (preview.preserved.includes('SKILL.md'))
52
+ options.log(' Your local SKILL.md will remain available to your agents.');
53
+ }
54
+ }
55
+ if (options.dryRun) {
56
+ options.log('Dry run: no files or installation records were changed.');
57
+ return result;
58
+ }
59
+ if (!options.interactive) {
60
+ options.log('Run "skillshare update" in an interactive terminal to remove selected copies or keep them locally and stop checking them.');
61
+ return result;
62
+ }
63
+ const uninstallable = reviews.filter(({ preview, record }) => Boolean(record.files) && preview.removable.length > 0);
64
+ const action = await (options.chooseAction ?? promptRemovedSkillAction)(uninstallable.length > 0);
65
+ if (action === 'later') {
66
+ options.log('Local copies kept. You can review them again with "skillshare update".');
67
+ return result;
68
+ }
69
+ const eligible = action === 'uninstall' ? uninstallable : reviews;
70
+ if (eligible.length === 0)
71
+ return result;
72
+ const selected = eligible.length === 1 ? eligible : await (options.chooseCopies ?? promptRemovedSkillCopies)(eligible, action);
73
+ const allowed = new Set(eligible);
74
+ for (const review of new Set(selected)) {
75
+ if (!allowed.has(review))
76
+ continue;
77
+ const { record, label } = review;
78
+ try {
79
+ if (action === 'keep') {
80
+ await options.forget(record);
81
+ result.kept++;
82
+ options.log(`Kept locally: ${label}. Files unchanged; SkillShare will no longer check this copy.`);
83
+ }
84
+ else {
85
+ const removed = await uninstallSkillFiles(record.targetRoot, record.files);
86
+ await options.forget(record);
87
+ result.uninstalled++;
88
+ options.log(`Removed ${plural(removed.removed.length, 'installed file')}: ${label}.`);
89
+ if (removed.preserved.length > 0) {
90
+ options.log(`Kept ${plural(removed.preserved.length, 'local or extra path')} in ${options.formatTarget?.(record.targetRoot) ?? record.targetRoot}. This copy will no longer be checked.`);
91
+ if (removed.preserved.includes('SKILL.md'))
92
+ options.log('Your local SKILL.md is still available to your agents.');
93
+ }
94
+ }
95
+ }
96
+ catch (error) {
97
+ options.log(`Could not ${action === 'keep' ? 'stop checking' : 'uninstall'} ${label}: ${error instanceof Error ? error.message : String(error)}`);
98
+ }
99
+ }
100
+ if (selected.length === 0)
101
+ options.log('No copies selected. Local copies and installation records kept.');
102
+ else if (reviews.length > selected.length) {
103
+ const remaining = reviews.length - selected.length;
104
+ options.log(`${remaining} other ${remaining === 1 ? 'copy' : 'copies'} left unchanged. Review again with "skillshare update".`);
105
+ }
106
+ return result;
107
+ }
108
+ async function promptRemovedSkillAction(canUninstall) {
109
+ const action = await select({
110
+ message: 'What should happen to these local copies?',
111
+ initialValue: 'later',
112
+ options: [
113
+ ...(canUninstall ? [{ value: 'uninstall', label: 'Remove installed files', hint: 'Keep local edits and extra files; choose copies next if there are several' }] : []),
114
+ { value: 'keep', label: 'Keep local copies and stop checking them', hint: 'All files stay; choose copies next if there are several' },
115
+ { value: 'later', label: 'Decide later', hint: 'Keep files and review again the next time you run SkillShare' },
116
+ ],
117
+ });
118
+ if (isCancel(action)) {
119
+ cancel('Cancelled. Local copies kept.');
120
+ process.exit(0);
121
+ }
122
+ return action;
123
+ }
124
+ async function promptRemovedSkillCopies(copies, action) {
125
+ const selected = await multiselect({
126
+ message: action === 'uninstall' ? 'Select copies to remove (local edits and extra files stay)' : 'Select local copies to stop checking (all files stay)',
127
+ options: copies.map((copy, index) => ({ value: index, label: copy.label,
128
+ hint: action === 'uninstall' ? `${plural(copy.preview.removable.length, 'file')} removed · ${plural(copy.preview.preserved.length, 'path')} kept` : 'Files unchanged',
129
+ })),
130
+ initialValues: [],
131
+ required: false,
132
+ });
133
+ if (isCancel(selected)) {
134
+ cancel('Cancelled. Local copies kept.');
135
+ process.exit(0);
136
+ }
137
+ return selected.map(index => copies[index]);
138
+ }
@@ -0,0 +1,70 @@
1
+ import { chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises';
2
+ import { dirname } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ /** All session writers share this lock, including login and logout. Never steal a
5
+ * timed-out lock: the owner may still be committing a rotated, single-use token. */
6
+ export async function withSessionLock(path, action, timeoutMs = 120_000) {
7
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
8
+ if (process.platform !== 'win32')
9
+ await chmod(dirname(path), 0o700);
10
+ const lock = `${path}.lock`;
11
+ const deadline = Date.now() + timeoutMs;
12
+ for (;;) {
13
+ try {
14
+ await mkdir(lock, { mode: 0o700 });
15
+ break;
16
+ }
17
+ catch (error) {
18
+ if (error.code !== 'EEXIST')
19
+ throw error;
20
+ if (Date.now() >= deadline)
21
+ throw new Error(`Timed out waiting for another Skillshare process to update the login session. Retry once it finishes. If a process crashed, stop all Skillshare CLI processes before removing ${lock}.`);
22
+ await new Promise(resolve => setTimeout(resolve, 25));
23
+ }
24
+ }
25
+ try {
26
+ return await action();
27
+ }
28
+ finally {
29
+ await rm(lock, { recursive: true, force: true });
30
+ }
31
+ }
32
+ export async function writeSessionAtomically(path, session) {
33
+ const temporary = `${path}.${randomUUID()}.tmp`;
34
+ try {
35
+ await writeFile(temporary, JSON.stringify(session), { mode: 0o600 });
36
+ await rename(temporary, path);
37
+ }
38
+ finally {
39
+ await rm(temporary, { force: true });
40
+ }
41
+ }
42
+ export async function refreshSession(options) {
43
+ return withSessionLock(options.path, async () => {
44
+ const current = await options.load();
45
+ // Another process may have refreshed or signed in while this caller waited.
46
+ if ((current.accessToken !== options.previous.accessToken || current.refreshToken !== options.previous.refreshToken) && Date.parse(current.accessTokenExpiresAt) > Date.now() + 60_000)
47
+ return current;
48
+ const login = `skillshare login --server ${options.server}`;
49
+ if (Date.parse(current.refreshTokenExpiresAt) <= Date.now())
50
+ throw new Error(`Skillshare login for ${options.server} has expired. Run "${login}" again.`);
51
+ const response = await options.fetch(`${options.server}/api/cli/refresh`, {
52
+ method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
53
+ body: JSON.stringify({ refreshToken: current.refreshToken }),
54
+ });
55
+ if (!response.ok) {
56
+ if (response.status === 401 || response.status === 403)
57
+ throw new Error(`Skillshare rejected the login renewal for ${options.server} (HTTP ${response.status}). Run "${login}" again; if access is still denied, contact your administrator.`);
58
+ throw new Error(`Could not renew the Skillshare login for ${options.server} (HTTP ${response.status}). Retry later; this response does not mean your login has expired.`);
59
+ }
60
+ const invalidResponse = () => new Error(`Skillshare returned an invalid login renewal response. Run "${login}" again if retrying fails.`);
61
+ const refreshed = await response.json().catch(() => { throw invalidResponse(); });
62
+ if (!refreshed || typeof refreshed.accessToken !== 'string' || !refreshed.accessToken || typeof refreshed.refreshToken !== 'string' || !refreshed.refreshToken
63
+ || !Number.isFinite(Date.parse(refreshed.accessTokenExpiresAt ?? '')) || !Number.isFinite(Date.parse(refreshed.refreshTokenExpiresAt ?? ''))) {
64
+ throw invalidResponse();
65
+ }
66
+ const next = { ...current, ...refreshed };
67
+ await writeSessionAtomically(options.path, next);
68
+ return next;
69
+ });
70
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quadient/skillshare",
3
- "version": "1.15.1",
3
+ "version": "1.17.0",
4
4
  "description": "Skillshare CLI for installing and publishing Quadient skills",
5
5
  "type": "module",
6
6
  "bin": {
@@ -13,10 +13,10 @@
13
13
  ],
14
14
  "scripts": {
15
15
  "dev": "tsx index.ts",
16
- "build": "rm -rf dist && tsc -p tsconfig.build.json",
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 cli-args.test.ts install-files.test.ts output.test.ts pages.test.ts pages-secrets.test.ts pages-comments.test.ts pages-dev.test.ts teams-auth.test.ts teams-watch.test.ts teams-browser.test.ts salesforce.test.ts agents.test.ts agents-update.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-comments.test.ts pages-dev.test.ts teams-auth.test.ts teams-watch.test.ts teams-browser.test.ts salesforce.test.ts agents.test.ts agents-update.test.ts login-callback.test.ts"
20
20
  },
21
21
  "publishConfig": {
22
22
  "access": "public"