@quadient/skillshare 1.15.0 → 1.16.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
@@ -326,7 +326,7 @@ The publish script builds `tui/`, validates the packed files with `npm pack --dr
326
326
  `skillshare pages upload <directory> --slug <slug>` accepts static sites or
327
327
  Wrangler JSON/JSONC projects. The CLI bundles Worker dependencies locally; install
328
328
  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
329
+ with `skillshare pages runtime <slug>`. With legacy hosting, Pages are served below `/p/<slug>/`, so use
330
330
  that base path when building assets. Runtime data survives content replacement.
331
331
 
332
332
  Manage the write-only secrets an application reads through `SKILLSHARE_SECRETS`
@@ -377,15 +377,21 @@ and uses its packaged esbuild. Supported hosts are macOS Apple Silicon and Linux
377
377
  x64/ARM64; Windows users can use WSL2. `--celld <executable>` or `CELLD_EXECUTABLE`
378
378
  selects an existing installation.
379
379
 
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
380
+ The default URL is `http://127.0.0.1:8787/`. Assets, API routes and redirects use
381
+ the root of this origin, matching isolated hosted Pages. The proxy adds the same `X-Skillshare-*` request headers as SkillShare. The development
382
382
  revision is `0`. The toolbar offers four local users covering every role combination: Alice
383
383
  (owner), Bob (neither role), Charlie (admin), and Dana (owner and admin).
384
384
  Each option shows explicit `isOwner` and `isAdmin` values, and each browser can
385
- select its own user. Customize the first
385
+ select its own user. Each dev instance uses a random identity-cookie name; cookies
386
+ from another loopback port cannot select its user. Customize the first
386
387
  user with `--user-id`, `--user-name` and `--user-email`. This is simulated local
387
388
  identity, not a real SSO login. Listeners bind only to loopback.
388
389
 
390
+ Browser mutations use the same CSRF helper as hosted Pages: fetch, asynchronous XHR
391
+ and forms receive a session-scoped token. Custom clients can GET `/__skillshare/csrf`
392
+ and send `X-Skillshare-CSRF`. Native loopback clients without browser Origin/Fetch
393
+ Metadata can still exercise mock identities without production authentication.
394
+
389
395
  The proxy filters SkillShare authentication cookies and Authorization on ordinary
390
396
  routes, scopes application cookies and redirects to the Page, and supports HTTP
391
397
  streaming and WebSockets. `/api/bypass-sso/*` preserves Authorization but forwards
@@ -430,3 +436,11 @@ contains `id`, `displayName`, `email`, `isAdmin` and `isOwner`. The hosted backe
430
436
  uses the same contract for active SkillShare users. These capabilities stay in
431
437
  the Worker and are not injected on `api/bypass-sso/*` requests. See the
432
438
  [Worker example](../docs/pages-backends.md#skillshare-user-directory-from-a-worker).
439
+
440
+
441
+ When domain isolation is enabled by the server, `pages show`, upload results and
442
+ comment links use the domain advertised by `/api/auth/config`: `<slug>.pages.../`,
443
+ `<slug>--<revision>.pages.../` and reserved annotation variants. Root-relative asset
444
+ and API paths then work without a `/p/<slug>` prefix. New annotation hosts remain
445
+ unavailable until the trusted editor is enabled. No CLI publication or deployment
446
+ 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';
@@ -67,7 +67,10 @@ export function npmCommand() {
67
67
  * Installs a CLI version into its own directory under versions, without touching a global install, so no administrator
68
68
  * rights are needed. It lands under a temporary name first, so a listener never starts a half-installed version.
69
69
  */
70
+ export const isReleaseVersion = (version) => /^\d{1,6}\.\d{1,6}\.\d{1,6}$/.test(version);
70
71
  export async function installVersion(appDir, version, options = {}) {
72
+ if (!isReleaseVersion(version))
73
+ throw new Error(`Refusing to install an invalid CLI version "${version}".`);
71
74
  if ((await installedVersions(appDir)).includes(version))
72
75
  return;
73
76
  const target = join(versionsDirectory(appDir), version);
@@ -79,7 +82,8 @@ export async function installVersion(appDir, version, options = {}) {
79
82
  await writeFile(join(staging, 'package.json'), JSON.stringify({ private: true }));
80
83
  const npm = npmCommand();
81
84
  const result = await (options.run ?? runCommand)(npm.command, [...npm.args, 'install', '--prefix', staging, '--no-audit', '--no-fund',
82
- '--omit=dev', '--no-package-lock', options.spec ?? `${PACKAGE_NAME}@${version}`], { cwd: staging });
85
+ // Package scripts never run during an update; the CLI and its dependencies do not need them.
86
+ '--omit=dev', '--no-package-lock', '--ignore-scripts', options.spec ?? `${PACKAGE_NAME}@${version}`], { cwd: staging });
83
87
  if (result.code !== 0)
84
88
  throw new Error(`npm could not install ${PACKAGE_NAME}@${version}: ${lastLine(result.stderr) || `exit code ${result.code}`}`);
85
89
  const installed = join(staging, 'node_modules', '@quadient', 'skillshare');
@@ -113,13 +117,17 @@ export async function removeOtherVersions(appDir, keep) {
113
117
  }
114
118
  /** Appends timestamped lines to a log file, starting a new one when it grows past a few megabytes. */
115
119
  export function fileLog(path) {
116
- mkdirSync(dirname(path), { recursive: true });
120
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
117
121
  return (text) => {
118
122
  try {
119
- if (existsSync(path) && statSync(path).size > MAX_LOG_BYTES)
120
- 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
+ }
121
129
  const stamp = new Date().toISOString();
122
- 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 });
123
131
  }
124
132
  catch {
125
133
  // Logging must never stop the listener.
package/dist/agents.js CHANGED
@@ -8,7 +8,7 @@ import { defaultServiceEnvironment, detectServiceAgents, installService, renderS
8
8
  import { createCodexDriver } from './agents-codex.js';
9
9
  import { detectAgents, expandHome, profilesPath } from './agents-detect.js';
10
10
  import { SessionRunner, errorMessage, } from './agents-session.js';
11
- import { RESTART_FOR_UPDATE, SERVICE_ENV, WORKER_ENV, acquireListenerLock, compareVersions, describeOtherListener, installVersion, releaseListenerLock, superviseListener, } from './agents-update.js';
11
+ import { RESTART_FOR_UPDATE, SERVICE_ENV, WORKER_ENV, acquireListenerLock, compareVersions, describeOtherListener, installVersion, isReleaseVersion, releaseListenerLock, superviseListener, } from './agents-update.js';
12
12
  import { readCliVersion } from './help.js';
13
13
  const root = '/api/agents';
14
14
  const PROFILE_HINT = 'Declare named profiles in ' + profilesPath() + ' to set a working directory or extra arguments.';
@@ -253,7 +253,8 @@ export async function listen(options) {
253
253
  let result = 'stopped';
254
254
  function considerUpdate(version) {
255
255
  const current = options.updater?.currentVersion ?? readCliVersion();
256
- if (!version || compareVersions(version, current) <= 0 || updateReady === version || updating === version)
256
+ // Only a plain release number; npm would read anything else as a git, URL or file package spec.
257
+ if (!version || !isReleaseVersion(version) || compareVersions(version, current) <= 0 || updateReady === version || updating === version)
257
258
  return;
258
259
  if (!options.updater) {
259
260
  if (updateMentioned !== version)
@@ -336,6 +337,9 @@ export async function listen(options) {
336
337
  deliveries.delete(runner.sessionId); });
337
338
  }
338
339
  function handle(command) {
340
+ // The id names a local directory that is later deleted, so it must not be able to point elsewhere.
341
+ if (!isSessionId(command.sessionId))
342
+ return log(`! Ignored a command for an invalid session id.`);
339
343
  const runner = sessions.get(command.sessionId);
340
344
  switch (command.type) {
341
345
  case 'start': return start(command);
@@ -408,3 +412,5 @@ function describe(detected) {
408
412
  const profiles = detected.profiles.length ? `, profiles ${detected.profiles.map(p => p.name).join(', ')}` : '';
409
413
  return (agents.length ? agents.join(', ') : 'no supported agent found') + profiles;
410
414
  }
415
+ // Session ids from the server name local directories (pasted images); only plain identifiers are accepted.
416
+ export const isSessionId = (id) => typeof id === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(id);
package/dist/help.js CHANGED
@@ -166,7 +166,7 @@ export function renderUsage(defaultUrl) {
166
166
  ...COMMANDS.map((command) => ` ${command.name.padEnd(width)} ${command.summary}`),
167
167
  '',
168
168
  'Options:',
169
- ' --token <token> Bearer token for API requests (overrides SKILLSHARE_TOKEN)',
169
+ ' --token <token> Bearer token for API requests; visible in the process list, prefer SKILLSHARE_TOKEN',
170
170
  ' --server <url> Skillshare origin for login and Teams commands',
171
171
  ' --json Print machine-readable JSON (whoami, list, show, upload, pages, teams, salesforce, agents)',
172
172
  ' -h, --help Show help for a command',
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';
@@ -10,11 +12,11 @@ import { formatByteSize, formatDateTime, pageUrl, plural, renderPageDetail, rend
10
12
  import { runPageDev } from './pages-dev.js';
11
13
  import { runPageCommentsCommand } from './pages-comments.js';
12
14
  import { runPageSecretsCommand } from './pages-secrets.js';
13
- import { createServer } from 'node:http';
15
+ import { waitForLoginCallback } from './login-callback.js';
14
16
  import { createHash, randomBytes } from 'node:crypto';
15
17
  import { spawn } from 'node:child_process';
16
18
  import { existsSync } from 'node:fs';
17
- import { mkdir, open, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
19
+ import { chmod, mkdir, open, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises';
18
20
  import { basename, join, relative, resolve } from 'node:path';
19
21
  import { homedir } from 'node:os';
20
22
  import { cancel, confirm, intro, isCancel, log, multiselect, outro, progress, select, spinner, text } from '@clack/prompts';
@@ -347,6 +349,8 @@ async function main() {
347
349
  }
348
350
  case 'page':
349
351
  case 'pages': {
352
+ const linkConfig = await client.get('/api/auth/config');
353
+ configurePageLinks(client.baseUrl, linkConfig.pageBaseDomain);
350
354
  const action = options.positionals[0] ?? 'list';
351
355
  if (action === 'list') {
352
356
  const pages = await client.get('/api/pages');
@@ -1546,7 +1550,7 @@ async function login(baseUrl) {
1546
1550
  const state = cryptoRandomHex(16);
1547
1551
  const codeVerifier = createPkceVerifier();
1548
1552
  const codeChallenge = createPkceChallenge(codeVerifier);
1549
- const callback = await waitForLoginCallback();
1553
+ const callback = await waitForLoginCallback(state);
1550
1554
  const loginUrl = `${baseUrl}/api/cli/login?redirectUri=${encodeURIComponent(callback.redirectUri)}` +
1551
1555
  `&codeChallenge=${encodeURIComponent(codeChallenge)}` +
1552
1556
  `&state=${encodeURIComponent(state)}`;
@@ -1558,7 +1562,7 @@ async function login(baseUrl) {
1558
1562
  catch {
1559
1563
  console.log('Could not open a browser automatically. Use the URL above.');
1560
1564
  }
1561
- const authCode = await callback.wait(state, LOGIN_TIMEOUT_MS);
1565
+ const authCode = await callback.wait(LOGIN_TIMEOUT_MS);
1562
1566
  const response = await fetchJson(`${baseUrl}/api/cli/token`, {
1563
1567
  method: 'POST',
1564
1568
  headers: {
@@ -1671,60 +1675,31 @@ async function createClient(baseUrl, explicitToken) {
1671
1675
  async function loadStoredSessionOrThrow() {
1672
1676
  const session = await loadSession(resolvedBaseUrl);
1673
1677
  if (!session) {
1674
- throw new Error(`No stored session for ${resolvedBaseUrl}. Run "skillshare login${resolvedBaseUrl === LOCAL_URL ? ' local' : ''}".`);
1678
+ throw new Error(`No stored session for ${resolvedBaseUrl}. Run "skillshare login --server ${resolvedBaseUrl}".`);
1675
1679
  }
1676
1680
  return session;
1677
1681
  }
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
1682
  async function getAccessToken(options) {
1709
1683
  if (explicitToken) {
1710
1684
  return explicitToken;
1711
1685
  }
1712
1686
  const session = await loadStoredSessionOrThrow();
1713
- if (!options?.forceRefresh && new Date(session.accessTokenExpiresAt).getTime() > Date.now() + 60_000) {
1687
+ if ((!options?.forceRefresh || (options.rejectedToken !== undefined && session.accessToken !== options.rejectedToken)) && new Date(session.accessTokenExpiresAt).getTime() > Date.now() + 60_000) {
1714
1688
  return session.accessToken;
1715
1689
  }
1716
- const refreshedSession = await refreshStoredSession(session);
1690
+ const refreshedSession = await refreshSession({ path: SESSION_PATH, server: resolvedBaseUrl, previous: session, load: loadStoredSessionOrThrow, fetch: fetchFromServer });
1717
1691
  return refreshedSession.accessToken;
1718
1692
  }
1719
1693
  async function sendAuthorized(path, init, retryUnauthorized = true) {
1694
+ const sentToken = await getAccessToken();
1720
1695
  const response = await fetchFromServer(`${resolvedBaseUrl}${path}`, {
1721
1696
  ...init,
1722
- headers: await buildHeaders(() => getAccessToken(), init?.headers),
1697
+ headers: await buildHeaders(() => Promise.resolve(sentToken), init?.headers),
1723
1698
  });
1724
1699
  if (response.status !== 401 || explicitToken || !retryUnauthorized) {
1725
1700
  return response;
1726
1701
  }
1727
- const refreshedToken = await getAccessToken({ forceRefresh: true });
1702
+ const refreshedToken = await getAccessToken({ forceRefresh: true, rejectedToken: sentToken });
1728
1703
  return fetchFromServer(`${resolvedBaseUrl}${path}`, {
1729
1704
  ...init,
1730
1705
  headers: await buildHeaders(() => Promise.resolve(refreshedToken), init?.headers),
@@ -1887,14 +1862,21 @@ async function loadAnySession() {
1887
1862
  }
1888
1863
  }
1889
1864
  async function storeSession(session) {
1890
- await mkdir(APP_DIR, { recursive: true });
1891
- await writeFile(SESSION_PATH, JSON.stringify(session), {
1892
- mode: process.platform === 'win32' ? undefined : 0o600,
1893
- });
1865
+ await withSessionLock(SESSION_PATH, () => writeSessionAtomically(SESSION_PATH, session));
1866
+ }
1867
+ // Tokens and state stay readable by the current user only; the mode of writeFile applies just to new files.
1868
+ async function writePrivateFile(path, content) {
1869
+ const posix = process.platform !== 'win32';
1870
+ await mkdir(APP_DIR, { recursive: true, mode: posix ? 0o700 : undefined });
1871
+ if (posix)
1872
+ await chmod(APP_DIR, 0o700);
1873
+ await writeFile(path, content, { mode: posix ? 0o600 : undefined });
1874
+ if (posix)
1875
+ await chmod(path, 0o600);
1894
1876
  }
1895
1877
  async function logoutSession() {
1896
1878
  try {
1897
- await rm(SESSION_PATH);
1879
+ await withSessionLock(SESSION_PATH, () => rm(SESSION_PATH));
1898
1880
  console.log('Logged out.');
1899
1881
  }
1900
1882
  catch (error) {
@@ -1935,64 +1917,6 @@ async function openBrowser(url) {
1935
1917
  throw new Error(result.stderr.trim() || 'Failed to open browser.');
1936
1918
  }
1937
1919
  }
1938
- async function waitForLoginCallback() {
1939
- let resolveStatePromise = () => { };
1940
- let rejectStatePromise = () => { };
1941
- const statePromise = new Promise((resolve, reject) => {
1942
- resolveStatePromise = resolve;
1943
- rejectStatePromise = reject;
1944
- });
1945
- const server = createServer((request, response) => {
1946
- const url = new URL(request.url ?? '/', 'http://127.0.0.1');
1947
- const code = url.searchParams.get('code');
1948
- const state = url.searchParams.get('state');
1949
- const error = url.searchParams.get('error');
1950
- if (error) {
1951
- response.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
1952
- response.end(`Login failed: ${error}`);
1953
- rejectStatePromise(new Error(`Login failed: ${error}`));
1954
- return;
1955
- }
1956
- if (!code || !state) {
1957
- response.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
1958
- response.end('Missing code or state.');
1959
- return;
1960
- }
1961
- response.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
1962
- response.end('Skillshare login completed. You can close this tab.');
1963
- resolveStatePromise(JSON.stringify({ code, state }));
1964
- });
1965
- await new Promise((resolve, reject) => {
1966
- server.once('error', reject);
1967
- server.listen(0, '127.0.0.1', () => resolve());
1968
- });
1969
- const address = server.address();
1970
- if (!address || typeof address === 'string') {
1971
- throw new Error('Failed to bind local callback server.');
1972
- }
1973
- return {
1974
- redirectUri: `http://127.0.0.1:${address.port}/callback`,
1975
- async wait(expectedState, timeoutMs) {
1976
- let timer;
1977
- const timeout = new Promise((_, reject) => {
1978
- timer = setTimeout(() => {
1979
- reject(new Error(`Sign-in did not complete within ${Math.round(timeoutMs / 60_000)} minutes. Run "skillshare login" again.`));
1980
- }, timeoutMs);
1981
- });
1982
- try {
1983
- const payload = JSON.parse(await Promise.race([statePromise, timeout]));
1984
- if (payload.state !== expectedState) {
1985
- throw new Error('Login state mismatch.');
1986
- }
1987
- return payload.code;
1988
- }
1989
- finally {
1990
- clearTimeout(timer);
1991
- server.close();
1992
- }
1993
- },
1994
- };
1995
- }
1996
1920
  async function readLocalSkillMetadata(directory, baseUrl) {
1997
1921
  const resolvedDirectory = resolve(directory);
1998
1922
  const normalizedBaseUrl = normalizeText(baseUrl) ? normalizeBaseUrl(baseUrl) : null;
@@ -2120,10 +2044,7 @@ async function readStateFile(path) {
2120
2044
  }
2121
2045
  }
2122
2046
  async function writeStateFile(path, value) {
2123
- await mkdir(APP_DIR, { recursive: true });
2124
- await writeFile(path, `${JSON.stringify(value, null, 2)}\n`, {
2125
- mode: process.platform === 'win32' ? undefined : 0o600,
2126
- });
2047
+ await writePrivateFile(path, `${JSON.stringify(value, null, 2)}\n`);
2127
2048
  }
2128
2049
  async function removeLegacyLocalSkillMetadata(directory) {
2129
2050
  try {
@@ -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,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.0",
3
+ "version": "1.16.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 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"