@teambit/api-server 0.0.0-e9df4557433da0a44e57e1a437d7602012e3009e → 0.0.0-e9fcb4212e5da6ac2dabdf37b5d89f823cd9072c
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/dist/api-for-ide.d.ts +2 -2
- package/dist/api-server.main.runtime.d.ts +48 -0
- package/dist/api-server.main.runtime.js +194 -9
- package/dist/api-server.main.runtime.js.map +1 -1
- package/dist/cli-raw.route.js +44 -10
- package/dist/cli-raw.route.js.map +1 -1
- package/package.json +45 -43
- package/types/style.d.ts +4 -0
- /package/dist/{preview-1776769578271.js → preview-1784232093942.js} +0 -0
package/dist/api-for-ide.d.ts
CHANGED
|
@@ -157,8 +157,8 @@ export declare class APIForIDE {
|
|
|
157
157
|
[relativePath: string]: string;
|
|
158
158
|
}>;
|
|
159
159
|
catObject(hash: string): Promise<string>;
|
|
160
|
-
logFile(filePath: string): Promise<import("
|
|
161
|
-
blame(filePath: string): Promise<import("
|
|
160
|
+
logFile(filePath: string): Promise<import("../teambit.component_component-log@43bccf593834145e01da972e0123346ad4fa8a3e/component-log.main.runtime").FileLog[]>;
|
|
161
|
+
blame(filePath: string): Promise<import("../teambit.component_component-log@43bccf593834145e01da972e0123346ad4fa8a3e/component-log.main.runtime").BlameLineInfo[]>;
|
|
162
162
|
changedFilesFromParent(id: string): Promise<FileHashDiffFromParent[]>;
|
|
163
163
|
getConfigForDiff(id: string): Promise<{
|
|
164
164
|
version?: string;
|
|
@@ -28,12 +28,60 @@ export declare class ApiServerMain {
|
|
|
28
28
|
private watcher;
|
|
29
29
|
private installer;
|
|
30
30
|
private importer;
|
|
31
|
+
private serverToken?;
|
|
31
32
|
constructor(workspace: Workspace, logger: Logger, express: ExpressMain, watcher: WatcherMain, installer: InstallMain, importer: ImporterMain);
|
|
32
33
|
runApiServer(options: {
|
|
33
34
|
port: number;
|
|
34
35
|
compile: boolean;
|
|
35
36
|
}): Promise<unknown>;
|
|
36
37
|
writeUsedPort(port: number): void;
|
|
38
|
+
/**
|
|
39
|
+
* Generate a fresh per-server bearer token and persist it to a 0600 file.
|
|
40
|
+
* Clients (e.g. the bit-vscode extension) read this file and send the token
|
|
41
|
+
* as `Authorization: Bearer <token>` on every request.
|
|
42
|
+
*
|
|
43
|
+
* Backwards compatibility: clients that don't yet know about this file (older
|
|
44
|
+
* extension versions) won't send the header and will receive 401 with a
|
|
45
|
+
* message pointing them at the upgrade. Old bit-server versions don't write
|
|
46
|
+
* this file, so a new client checking for it gracefully falls back to no
|
|
47
|
+
* auth header — meaning a NEW extension keeps working against an OLD
|
|
48
|
+
* bit-server.
|
|
49
|
+
*/
|
|
50
|
+
private writeServerToken;
|
|
51
|
+
private getServerTokenFilePath;
|
|
52
|
+
/**
|
|
53
|
+
* Host-header check: only accept requests targeting a loopback hostname.
|
|
54
|
+
* Defends against DNS-rebinding attacks where a malicious page on
|
|
55
|
+
* `evil.example` flips DNS to 127.0.0.1 — the browser sends `Host:
|
|
56
|
+
* evil.example`, which we reject with 403 here.
|
|
57
|
+
*
|
|
58
|
+
* The server already listens on 127.0.0.1 only, so any request reaching us
|
|
59
|
+
* arrived via loopback. The remaining concern is the *named* origin the
|
|
60
|
+
* browser thinks it's talking to.
|
|
61
|
+
*
|
|
62
|
+
* Disabled when `BIT_SERVER_HOST` resolves to a non-loopback address,
|
|
63
|
+
* since by definition the server is then reachable via a hostname we
|
|
64
|
+
* can't enumerate ahead of time (e.g. a cloud-workspace hostname). In
|
|
65
|
+
* that mode the bearer token is the primary line of defense; the
|
|
66
|
+
* unauthenticated exemptions (`OPTIONS` preflight and `/api/_health`)
|
|
67
|
+
* become reachable from the network — `/api/_health` is a tiny "ok"
|
|
68
|
+
* liveness probe and intentionally exposed.
|
|
69
|
+
*/
|
|
70
|
+
private createHostCheckMiddleware;
|
|
71
|
+
/**
|
|
72
|
+
* Authentication middleware: requires `Authorization: Bearer <serverToken>`
|
|
73
|
+
* on every request except OPTIONS preflight (handled by cors) and the
|
|
74
|
+
* unauthenticated `/api/_health` liveness probe.
|
|
75
|
+
*
|
|
76
|
+
* GET requests can also authenticate via a `?token=...` query parameter,
|
|
77
|
+
* since browser-native WebSocket and EventSource cannot set custom headers
|
|
78
|
+
* from JavaScript. The param is stripped from `req.url` before downstream
|
|
79
|
+
* handling so the proxy and logs never see it.
|
|
80
|
+
*
|
|
81
|
+
* Runs before bodyParser so unauthenticated requests can't trigger
|
|
82
|
+
* large-body parsing.
|
|
83
|
+
*/
|
|
84
|
+
private createAuthMiddleware;
|
|
37
85
|
/**
|
|
38
86
|
* Monitor the parent process (typically VSCode) and shut down if it dies.
|
|
39
87
|
*
|
|
@@ -25,13 +25,27 @@ function _fsExtra() {
|
|
|
25
25
|
};
|
|
26
26
|
return data;
|
|
27
27
|
}
|
|
28
|
+
function _crypto() {
|
|
29
|
+
const data = _interopRequireDefault(require("crypto"));
|
|
30
|
+
_crypto = function () {
|
|
31
|
+
return data;
|
|
32
|
+
};
|
|
33
|
+
return data;
|
|
34
|
+
}
|
|
28
35
|
function _express() {
|
|
29
|
-
const data = require("
|
|
36
|
+
const data = _interopRequireDefault(require("express"));
|
|
30
37
|
_express = function () {
|
|
31
38
|
return data;
|
|
32
39
|
};
|
|
33
40
|
return data;
|
|
34
41
|
}
|
|
42
|
+
function _express2() {
|
|
43
|
+
const data = require("@teambit/express");
|
|
44
|
+
_express2 = function () {
|
|
45
|
+
return data;
|
|
46
|
+
};
|
|
47
|
+
return data;
|
|
48
|
+
}
|
|
35
49
|
function _logger() {
|
|
36
50
|
const data = require("@teambit/logger");
|
|
37
51
|
_logger = function () {
|
|
@@ -289,6 +303,7 @@ class ApiServerMain {
|
|
|
289
303
|
this.watcher = watcher;
|
|
290
304
|
this.installer = installer;
|
|
291
305
|
this.importer = importer;
|
|
306
|
+
_defineProperty(this, "serverToken", void 0);
|
|
292
307
|
}
|
|
293
308
|
async runApiServer(options) {
|
|
294
309
|
if (!this.workspace) {
|
|
@@ -325,13 +340,36 @@ class ApiServerMain {
|
|
|
325
340
|
compile: options.compile
|
|
326
341
|
});
|
|
327
342
|
const port = options.port || (await this.getRandomPort());
|
|
328
|
-
const
|
|
343
|
+
const {
|
|
344
|
+
bindHost,
|
|
345
|
+
isOverride
|
|
346
|
+
} = resolveBindHost();
|
|
347
|
+
|
|
348
|
+
// Generate a per-server auth token and persist it to a 0600 file before
|
|
349
|
+
// any HTTP request can be handled. Clients (e.g. the bit-vscode extension)
|
|
350
|
+
// read it from <workspace.scope.path>/server-token.txt and send it as
|
|
351
|
+
// `Authorization: Bearer <token>`. See createAuthMiddleware below.
|
|
352
|
+
this.writeServerToken();
|
|
353
|
+
|
|
354
|
+
// Create the app *before* express.createApp registers routes, so the auth
|
|
355
|
+
// middleware runs before bodyParser — unauthenticated requests can't
|
|
356
|
+
// trigger large-body parsing. CORS is registered before auth so 401
|
|
357
|
+
// responses still carry CORS headers; otherwise browser-based clients
|
|
358
|
+
// (bit-vscode) see a misleading CORS failure instead of the JSON 401.
|
|
359
|
+
// The host-check middleware runs first to reject DNS-rebinding attacks
|
|
360
|
+
// (where a malicious page resolves attacker.example to 127.0.0.1).
|
|
361
|
+
const app = (0, _express().default)();
|
|
362
|
+
app.use(this.createHostCheckMiddleware({
|
|
363
|
+
loopbackOnly: !isOverride
|
|
364
|
+
}));
|
|
329
365
|
app.use((0, _cors().default)({
|
|
330
366
|
origin(origin, callback) {
|
|
331
367
|
callback(null, true);
|
|
332
368
|
},
|
|
333
369
|
credentials: true
|
|
334
370
|
}));
|
|
371
|
+
app.use(this.createAuthMiddleware());
|
|
372
|
+
this.express.createApp(app);
|
|
335
373
|
const proxyHeaders = {
|
|
336
374
|
Authorization: `${_scope().DEFAULT_AUTH_TYPE} ${_scope().Http.getToken()}`,
|
|
337
375
|
origin: '',
|
|
@@ -391,11 +429,12 @@ class ApiServerMain {
|
|
|
391
429
|
pathFilter: '/',
|
|
392
430
|
target: symphonyUrl,
|
|
393
431
|
ws: true,
|
|
394
|
-
secure: false,
|
|
395
|
-
// Disable SSL verification for proxy to remote server
|
|
396
432
|
changeOrigin: true
|
|
397
433
|
}));
|
|
398
|
-
|
|
434
|
+
if (isOverride) {
|
|
435
|
+
this.logger.debug(`api-server: binding to ${bindHost} (from BIT_SERVER_HOST), loopback Host-header check disabled`);
|
|
436
|
+
}
|
|
437
|
+
const server = await app.listen(port, bindHost);
|
|
399
438
|
return new Promise((resolve, reject) => {
|
|
400
439
|
server.on('error', err => {
|
|
401
440
|
reject(err);
|
|
@@ -411,7 +450,125 @@ class ApiServerMain {
|
|
|
411
450
|
}
|
|
412
451
|
writeUsedPort(port) {
|
|
413
452
|
const filePath = this.getServerPortFilePath();
|
|
414
|
-
_fsExtra().default.writeFileSync(filePath, port.toString()
|
|
453
|
+
_fsExtra().default.writeFileSync(filePath, port.toString(), {
|
|
454
|
+
mode: 0o600
|
|
455
|
+
});
|
|
456
|
+
// Node's `mode` write option is only honored when the file is created.
|
|
457
|
+
// chmod explicitly so a pre-existing file with broader permissions gets
|
|
458
|
+
// tightened to 0600.
|
|
459
|
+
_fsExtra().default.chmodSync(filePath, 0o600);
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Generate a fresh per-server bearer token and persist it to a 0600 file.
|
|
464
|
+
* Clients (e.g. the bit-vscode extension) read this file and send the token
|
|
465
|
+
* as `Authorization: Bearer <token>` on every request.
|
|
466
|
+
*
|
|
467
|
+
* Backwards compatibility: clients that don't yet know about this file (older
|
|
468
|
+
* extension versions) won't send the header and will receive 401 with a
|
|
469
|
+
* message pointing them at the upgrade. Old bit-server versions don't write
|
|
470
|
+
* this file, so a new client checking for it gracefully falls back to no
|
|
471
|
+
* auth header — meaning a NEW extension keeps working against an OLD
|
|
472
|
+
* bit-server.
|
|
473
|
+
*/
|
|
474
|
+
writeServerToken() {
|
|
475
|
+
const token = _crypto().default.randomBytes(32).toString('hex');
|
|
476
|
+
const filePath = this.getServerTokenFilePath();
|
|
477
|
+
_fsExtra().default.writeFileSync(filePath, token, {
|
|
478
|
+
mode: 0o600
|
|
479
|
+
});
|
|
480
|
+
// Node's `mode` write option is only honored when the file is created.
|
|
481
|
+
// chmod explicitly so a pre-existing file with broader permissions gets
|
|
482
|
+
// tightened to 0600.
|
|
483
|
+
_fsExtra().default.chmodSync(filePath, 0o600);
|
|
484
|
+
this.serverToken = token;
|
|
485
|
+
}
|
|
486
|
+
getServerTokenFilePath() {
|
|
487
|
+
return (0, _path().join)(this.workspace.scope.path, 'server-token.txt');
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* Host-header check: only accept requests targeting a loopback hostname.
|
|
492
|
+
* Defends against DNS-rebinding attacks where a malicious page on
|
|
493
|
+
* `evil.example` flips DNS to 127.0.0.1 — the browser sends `Host:
|
|
494
|
+
* evil.example`, which we reject with 403 here.
|
|
495
|
+
*
|
|
496
|
+
* The server already listens on 127.0.0.1 only, so any request reaching us
|
|
497
|
+
* arrived via loopback. The remaining concern is the *named* origin the
|
|
498
|
+
* browser thinks it's talking to.
|
|
499
|
+
*
|
|
500
|
+
* Disabled when `BIT_SERVER_HOST` resolves to a non-loopback address,
|
|
501
|
+
* since by definition the server is then reachable via a hostname we
|
|
502
|
+
* can't enumerate ahead of time (e.g. a cloud-workspace hostname). In
|
|
503
|
+
* that mode the bearer token is the primary line of defense; the
|
|
504
|
+
* unauthenticated exemptions (`OPTIONS` preflight and `/api/_health`)
|
|
505
|
+
* become reachable from the network — `/api/_health` is a tiny "ok"
|
|
506
|
+
* liveness probe and intentionally exposed.
|
|
507
|
+
*/
|
|
508
|
+
createHostCheckMiddleware({
|
|
509
|
+
loopbackOnly
|
|
510
|
+
}) {
|
|
511
|
+
const allowed = new Set(['localhost', '127.0.0.1', '::1']);
|
|
512
|
+
return (req, res, next) => {
|
|
513
|
+
if (!loopbackOnly) return next();
|
|
514
|
+
const hostHeader = req.headers.host || '';
|
|
515
|
+
// Parse hostname from "host:port". IPv6 may be bracketed: "[::1]:1234"
|
|
516
|
+
// → "::1"; IPv4 / hostname is plain: "127.0.0.1:1234" → "127.0.0.1".
|
|
517
|
+
// HTTP hostnames are case-insensitive, so normalize before checking.
|
|
518
|
+
const match = hostHeader.match(/^\[([^\]]+)\]|^([^:]+)/);
|
|
519
|
+
const host = match ? (match[1] || match[2]).toLowerCase() : '';
|
|
520
|
+
if (!allowed.has(host)) {
|
|
521
|
+
this.logger.debug(`api-server: rejected non-loopback Host header: ${hostHeader}`);
|
|
522
|
+
res.status(403).end();
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
return next();
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Authentication middleware: requires `Authorization: Bearer <serverToken>`
|
|
531
|
+
* on every request except OPTIONS preflight (handled by cors) and the
|
|
532
|
+
* unauthenticated `/api/_health` liveness probe.
|
|
533
|
+
*
|
|
534
|
+
* GET requests can also authenticate via a `?token=...` query parameter,
|
|
535
|
+
* since browser-native WebSocket and EventSource cannot set custom headers
|
|
536
|
+
* from JavaScript. The param is stripped from `req.url` before downstream
|
|
537
|
+
* handling so the proxy and logs never see it.
|
|
538
|
+
*
|
|
539
|
+
* Runs before bodyParser so unauthenticated requests can't trigger
|
|
540
|
+
* large-body parsing.
|
|
541
|
+
*/
|
|
542
|
+
createAuthMiddleware() {
|
|
543
|
+
return (req, res, next) => {
|
|
544
|
+
if (req.method === 'OPTIONS') return next();
|
|
545
|
+
// Use req.path (not req.url) so query strings don't bypass the
|
|
546
|
+
// health-check exemption — e.g. /api/_health?cache-buster=1.
|
|
547
|
+
if (req.path === '/api/_health') return next();
|
|
548
|
+
const provided = parseBearerToken(req.headers.authorization);
|
|
549
|
+
let authorized = !!this.serverToken && provided === this.serverToken;
|
|
550
|
+
if (!authorized && this.serverToken && req.method === 'GET') {
|
|
551
|
+
const queryIdx = req.url.indexOf('?');
|
|
552
|
+
if (queryIdx >= 0) {
|
|
553
|
+
const params = new URLSearchParams(req.url.slice(queryIdx + 1));
|
|
554
|
+
if (params.get('token') === this.serverToken) {
|
|
555
|
+
authorized = true;
|
|
556
|
+
params.delete('token');
|
|
557
|
+
const remaining = params.toString();
|
|
558
|
+
req.url = req.url.slice(0, queryIdx) + (remaining ? `?${remaining}` : '');
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
if (!authorized) {
|
|
563
|
+
this.logger.debug(`api-server: rejected unauthenticated request to ${req.path}`);
|
|
564
|
+
res.status(401).jsonp({
|
|
565
|
+
error: 'unauthorized',
|
|
566
|
+
message: 'This bit-server requires authentication. Please upgrade your bit VS Code extension to the latest version.'
|
|
567
|
+
});
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
return next();
|
|
571
|
+
};
|
|
415
572
|
}
|
|
416
573
|
|
|
417
574
|
/**
|
|
@@ -478,8 +635,7 @@ class ApiServerMain {
|
|
|
478
635
|
}
|
|
479
636
|
async getRandomPort() {
|
|
480
637
|
const startingPort = 4000; // we prefer to have the ports between 4000 and 4999.
|
|
481
|
-
|
|
482
|
-
const randomNumber = Math.floor(Math.random() * (4999 - startingPort + 1) + startingPort);
|
|
638
|
+
const randomNumber = _crypto().default.randomInt(startingPort, 5000);
|
|
483
639
|
const port = await _toolboxNetwork().Port.getPort(randomNumber, 65500);
|
|
484
640
|
return port;
|
|
485
641
|
}
|
|
@@ -515,9 +671,38 @@ class ApiServerMain {
|
|
|
515
671
|
}
|
|
516
672
|
}
|
|
517
673
|
exports.ApiServerMain = ApiServerMain;
|
|
518
|
-
_defineProperty(ApiServerMain, "dependencies", [_cli().CLIAspect, _workspace().WorkspaceAspect, _logger().LoggerAspect,
|
|
674
|
+
_defineProperty(ApiServerMain, "dependencies", [_cli().CLIAspect, _workspace().WorkspaceAspect, _logger().LoggerAspect, _express2().ExpressAspect, _watcher().WatcherAspect, _snapping().SnappingAspect, _lanes().LanesAspect, _install().InstallAspect, _export().ExportAspect, _checkout().CheckoutAspect, _componentLog().ComponentLogAspect, _importer().ImporterAspect, _componentCompare().ComponentCompareAspect, _generator().GeneratorAspect, _remove().RemoveAspect, _config().ConfigAspect, _application().ApplicationAspect, _deprecation().DeprecationAspect, _envs().EnvsAspect, _graph().GraphAspect, _scope2().ScopeAspect, _component().ComponentAspect, _schema().SchemaAspect]);
|
|
519
675
|
_defineProperty(ApiServerMain, "runtime", _cli().MainRuntime);
|
|
520
676
|
_apiServer().ApiServerAspect.addRuntime(ApiServerMain);
|
|
677
|
+
const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);
|
|
678
|
+
|
|
679
|
+
/**
|
|
680
|
+
* Resolve the api-server bind host from `BIT_SERVER_HOST`, falling back to
|
|
681
|
+
* loopback. `isOverride` is the single source of truth for "is the server
|
|
682
|
+
* reachable from outside loopback?" — used both to choose the bind address
|
|
683
|
+
* and to disable the loopback Host-header check. Derived from the *resolved*
|
|
684
|
+
* host (not env presence) so `BIT_SERVER_HOST=127.0.0.1` and whitespace-only
|
|
685
|
+
* values don't silently weaken the DNS-rebinding mitigation.
|
|
686
|
+
*/
|
|
687
|
+
function resolveBindHost() {
|
|
688
|
+
const override = process.env.BIT_SERVER_HOST?.trim();
|
|
689
|
+
const bindHost = override || '127.0.0.1';
|
|
690
|
+
return {
|
|
691
|
+
bindHost,
|
|
692
|
+
isOverride: !LOOPBACK_HOSTS.has(bindHost.toLowerCase())
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* Extract the token from an `Authorization: Bearer <token>` header.
|
|
698
|
+
* Lenient on scheme casing and surrounding whitespace so a slightly
|
|
699
|
+
* non-canonical client header doesn't get rejected.
|
|
700
|
+
*/
|
|
701
|
+
function parseBearerToken(header) {
|
|
702
|
+
if (!header) return undefined;
|
|
703
|
+
const match = header.match(/^\s*Bearer\s+(\S+)\s*$/i);
|
|
704
|
+
return match?.[1];
|
|
705
|
+
}
|
|
521
706
|
var _default = exports.default = ApiServerMain;
|
|
522
707
|
|
|
523
708
|
//# sourceMappingURL=api-server.main.runtime.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_cli","data","require","_toolboxNetwork","_fsExtra","_interopRequireDefault","_express","_logger","_lanes","_remove","_snapping","_generator","_componentCompare","_componentLog","_watcher","_config","_export","_checkout","_install","_importer","_component","_workspace","_harmonyModules","_cors","_httpProxyMiddleware","_apiServer","_cli2","_server","_ide","_apiForIde","_sseEvents","_path","_child_process","_cliRaw","_application","_deprecation","_envs","_scope","_legacy","_graph","_scope2","_schema","e","__esModule","default","_defineProperty","r","t","_toPropertyKey","Object","defineProperty","value","enumerable","configurable","writable","i","_toPrimitive","Symbol","toPrimitive","call","TypeError","String","Number","ApiServerMain","constructor","workspace","logger","express","watcher","installer","importer","runApiServer","options","Error","process","cwd","registerOnComponentChange","component","files","removedFiles","sendEventsToClients","id","toStringWithoutVersion","registerOnBitmapChange","lastModifiedTimestamp","bitMap","getLastModifiedBitmapThroughBit","secondsPassedSinceLastModified","Date","now","debug","importCurrentObjects","registerOnWorkspaceConfigChange","scope","registerOnPostExport","registerPostInstall","watch","preCompile","compile","port","getRandomPort","app","createApp","use","cors","origin","callback","credentials","proxyHeaders","Authorization","DEFAULT_AUTH_TYPE","Http","getToken","symphonyUrl","getSymphonyUrl","createProxyMiddleware","target","changeOrigin","headers","on","error","err","req","res","writeHead","end","proxyReq","fixRequestBody","proxyRes","proxyReqWs","entries","forEach","key","setHeader","pathFilter","ws","secure","server","listen","Promise","resolve","reject","consoleSuccess","writeUsedPort","startParentProcessMonitor","filePath","getServerPortFilePath","fs","writeFileSync","toString","originalPpid","ppid","parentInfo","getProcessInfo","pid","platform","checkInterval","intervalId","setInterval","currentPpid","clearInterval","exit","unref","psCommand","output","execSync","encoding","timeout","trim","startingPort","randomNumber","Math","floor","random","Port","getPort","getExistingUsedPort","fileContent","readFile","parseInt","code","undefined","join","path","provider","cli","loggerMain","snapping","lanes","exporter","checkout","componentLog","componentCompare","generator","remove","config","application","deprecation","envs","graph","schema","createLogger","ApiServerAspect","apiServer","register","ServerCmd","apiForIDE","APIForIDE","cliRoute","CLIRoute","cliRawRoute","CLIRawRoute","ideRoute","IDERoute","sseEventsRoute","SSEEventsRoute","exports","CLIAspect","WorkspaceAspect","LoggerAspect","ExpressAspect","WatcherAspect","SnappingAspect","LanesAspect","InstallAspect","ExportAspect","CheckoutAspect","ComponentLogAspect","ImporterAspect","ComponentCompareAspect","GeneratorAspect","RemoveAspect","ConfigAspect","ApplicationAspect","DeprecationAspect","EnvsAspect","GraphAspect","ScopeAspect","ComponentAspect","SchemaAspect","MainRuntime","addRuntime","_default"],"sources":["api-server.main.runtime.ts"],"sourcesContent":["import type { CLIMain } from '@teambit/cli';\nimport { CLIAspect, MainRuntime } from '@teambit/cli';\nimport { Port } from '@teambit/toolbox.network.get-port';\nimport fs from 'fs-extra';\nimport type { ExpressMain } from '@teambit/express';\nimport { ExpressAspect } from '@teambit/express';\nimport type { Logger, LoggerMain } from '@teambit/logger';\nimport { LoggerAspect } from '@teambit/logger';\nimport type { LanesMain } from '@teambit/lanes';\nimport { LanesAspect } from '@teambit/lanes';\nimport type { RemoveMain } from '@teambit/remove';\nimport { RemoveAspect } from '@teambit/remove';\nimport type { SnappingMain } from '@teambit/snapping';\nimport { SnappingAspect } from '@teambit/snapping';\nimport type { GeneratorMain } from '@teambit/generator';\nimport { GeneratorAspect } from '@teambit/generator';\nimport type { ComponentCompareMain } from '@teambit/component-compare';\nimport { ComponentCompareAspect } from '@teambit/component-compare';\nimport type { ComponentLogMain } from '@teambit/component-log';\nimport { ComponentLogAspect } from '@teambit/component-log';\nimport type { WatcherMain } from '@teambit/watcher';\nimport { WatcherAspect } from '@teambit/watcher';\nimport type { ConfigMain } from '@teambit/config';\nimport { ConfigAspect } from '@teambit/config';\nimport type { ExportMain } from '@teambit/export';\nimport { ExportAspect } from '@teambit/export';\nimport type { CheckoutMain } from '@teambit/checkout';\nimport { CheckoutAspect } from '@teambit/checkout';\nimport type { InstallMain } from '@teambit/install';\nimport { InstallAspect } from '@teambit/install';\nimport type { ImporterMain } from '@teambit/importer';\nimport { ImporterAspect } from '@teambit/importer';\nimport type { Component, ComponentMain } from '@teambit/component';\nimport { ComponentAspect } from '@teambit/component';\nimport type { Workspace } from '@teambit/workspace';\nimport { WorkspaceAspect } from '@teambit/workspace';\nimport { sendEventsToClients } from '@teambit/harmony.modules.send-server-sent-events';\nimport cors from 'cors';\nimport { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware';\nimport { ApiServerAspect } from './api-server.aspect';\nimport { CLIRoute } from './cli.route';\nimport { ServerCmd } from './server.cmd';\nimport { IDERoute } from './ide.route';\nimport { APIForIDE } from './api-for-ide';\nimport { SSEEventsRoute } from './sse-events.route';\nimport { join } from 'path';\nimport { execSync } from 'child_process';\nimport { CLIRawRoute } from './cli-raw.route';\nimport type { ApplicationMain } from '@teambit/application';\nimport { ApplicationAspect } from '@teambit/application';\nimport type { DeprecationMain } from '@teambit/deprecation';\nimport { DeprecationAspect } from '@teambit/deprecation';\nimport type { EnvsMain } from '@teambit/envs';\nimport { EnvsAspect } from '@teambit/envs';\nimport { DEFAULT_AUTH_TYPE, Http } from '@teambit/scope.network';\nimport { getSymphonyUrl } from '@teambit/legacy.constants';\nimport type { GraphMain } from '@teambit/graph';\nimport { GraphAspect } from '@teambit/graph';\nimport type { ScopeMain } from '@teambit/scope';\nimport { ScopeAspect } from '@teambit/scope';\nimport type { SchemaMain } from '@teambit/schema';\nimport { SchemaAspect } from '@teambit/schema';\n\nexport class ApiServerMain {\n constructor(\n private workspace: Workspace,\n private logger: Logger,\n private express: ExpressMain,\n private watcher: WatcherMain,\n private installer: InstallMain,\n private importer: ImporterMain\n ) {}\n\n async runApiServer(options: { port: number; compile: boolean }) {\n if (!this.workspace) {\n throw new Error(`unable to run bit-server, the current directory ${process.cwd()} is not a workspace`);\n }\n\n this.workspace.registerOnComponentChange(\n async (\n component: Component,\n files: string[], // os absolute paths\n removedFiles?: string[] // os absolute paths\n ) => {\n sendEventsToClients('onComponentChange', {\n id: component.id.toStringWithoutVersion(),\n files,\n removedFiles,\n });\n }\n );\n\n this.workspace.registerOnBitmapChange(async () => {\n const lastModifiedTimestamp = await this.workspace.bitMap.getLastModifiedBitmapThroughBit();\n const secondsPassedSinceLastModified = lastModifiedTimestamp && (Date.now() - lastModifiedTimestamp) / 1000;\n if (secondsPassedSinceLastModified && secondsPassedSinceLastModified > 1) {\n // changes by bit were done more than a second ago, so probably this .bitmap change was done by \"git pull\"\n this.logger.debug(\n `running import because we assume the .bitmap file has changed due to \"git pull\", last time it was modified by bit was ${secondsPassedSinceLastModified} seconds ago`\n );\n await this.importer.importCurrentObjects();\n }\n sendEventsToClients('onBitmapChange', {});\n });\n\n this.workspace.registerOnWorkspaceConfigChange(async () => {\n sendEventsToClients('onWorkspaceConfigChange', {});\n });\n\n this.workspace.scope.registerOnPostExport(async () => {\n sendEventsToClients('onPostExport', {});\n });\n\n this.installer.registerPostInstall(async () => {\n sendEventsToClients('onPostInstall', {});\n });\n\n await this.watcher.watch({\n preCompile: false,\n compile: options.compile,\n });\n\n const port = options.port || (await this.getRandomPort());\n\n const app = this.express.createApp();\n\n app.use(\n cors({\n origin(origin, callback) {\n callback(null, true);\n },\n credentials: true,\n })\n );\n const proxyHeaders = {\n Authorization: `${DEFAULT_AUTH_TYPE} ${Http.getToken()}`,\n origin: '',\n 'user-agent': 'bit-vscode-proxy',\n };\n const symphonyUrl = getSymphonyUrl();\n app.use(\n '/api/cloud-graphql',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n createProxyMiddleware({\n target: `${symphonyUrl}/graphql`,\n changeOrigin: true,\n headers: proxyHeaders,\n on: {\n error: (err, req, res) => {\n this.logger.error('graphql cloud proxy error', err);\n // @ts-ignore\n res.writeHead(500, {\n 'Content-Type': 'text/plain',\n });\n res.end('Something went wrong with the proxy server of bit cloud graphql');\n },\n proxyReq: fixRequestBody,\n },\n })\n );\n\n app.use(\n '/api/cloud-rest',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n createProxyMiddleware({\n target: `${symphonyUrl}`,\n changeOrigin: true,\n headers: proxyHeaders,\n on: {\n proxyRes: (proxyRes) => {\n proxyRes.headers['Access-Control-Allow-Credentials'] = 'true';\n },\n error: (err, req, res) => {\n this.logger.error('rest cloud proxy error', err);\n // @ts-ignore\n res.writeHead(500, {\n 'Content-Type': 'text/plain',\n });\n res.end('Something went wrong with the proxy server of bit cloud rest');\n },\n proxyReq: fixRequestBody,\n },\n })\n );\n\n app.use(\n '/websocket-server/subscriptions',\n createProxyMiddleware({\n on: {\n proxyReqWs: (proxyReq) => {\n Object.entries(proxyHeaders).forEach(([key, value]) => {\n proxyReq.setHeader(key, value);\n });\n },\n error: (err) => {\n this.logger.error('websocket cloud proxy error', err);\n },\n },\n pathFilter: '/',\n target: symphonyUrl,\n ws: true,\n secure: false, // Disable SSL verification for proxy to remote server\n changeOrigin: true,\n })\n );\n\n const server = await app.listen(port);\n\n return new Promise((resolve, reject) => {\n server.on('error', (err) => {\n reject(err);\n });\n server.on('listening', () => {\n // important! if you change the message here, change it also in server-forever.ts and also in the vscode extension.\n this.logger.consoleSuccess(`Bit Server is listening on port ${port}`);\n this.writeUsedPort(port);\n this.startParentProcessMonitor();\n resolve(port);\n });\n });\n }\n\n writeUsedPort(port: number) {\n const filePath = this.getServerPortFilePath();\n fs.writeFileSync(filePath, port.toString());\n }\n\n /**\n * Monitor the parent process (typically VSCode) and shut down if it dies.\n *\n * On Unix-like systems (macOS, Linux), when a parent process dies, orphaned children are\n * re-parented to PID 1 (init/launchd). By watching for `process.ppid` changing from\n * the original value to 1, we can detect that the parent exited and proactively\n * shut down the bit server to avoid leaving stale background processes running.\n *\n * Note: This orphan detection does not work on Windows, as Windows does not re-parent\n * processes to PID 1. On Windows, this method only logs the parent process info at startup.\n */\n private startParentProcessMonitor() {\n const originalPpid = process.ppid;\n\n // Log parent process info at startup\n const parentInfo = this.getProcessInfo(originalPpid);\n this.logger.debug(\n `bit server started. PID: ${process.pid}, Parent PID: ${originalPpid}, Parent command: ${parentInfo}`\n );\n\n // Skip orphan detection on Windows - PPID doesn't change to 1 when parent dies\n if (process.platform === 'win32') {\n return;\n }\n\n const checkInterval = 5000; // Check every 5 seconds\n const intervalId = setInterval(() => {\n const currentPpid = process.ppid;\n // If PPID changed to 1, our parent (e.g., VSCode) died and we were re-parented to init\n if (currentPpid === 1 && originalPpid !== 1) {\n this.logger.debug(\n `Parent process died (was PID ${originalPpid}: ${parentInfo}). Current PPID is now 1 (init/launchd). Shutting down bit server.`\n );\n clearInterval(intervalId);\n process.exit(0);\n }\n }, checkInterval);\n\n // Don't let this interval keep the process alive if everything else is done\n intervalId.unref();\n }\n\n /**\n * Get the command/path of a process by its PID.\n */\n private getProcessInfo(pid: number): string {\n try {\n if (process.platform === 'win32') {\n // Windows: use PowerShell Get-CimInstance (WMIC is deprecated/removed on modern Windows)\n const psCommand = `Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' | Select-Object -ExpandProperty CommandLine`;\n const output = execSync(`powershell.exe -NoProfile -Command \"${psCommand}\"`, {\n encoding: 'utf8',\n timeout: 2000,\n });\n return output.trim() || 'unknown';\n } else {\n // macOS/Linux: use ps\n const output = execSync(`ps -o command= -p ${pid}`, { encoding: 'utf8', timeout: 2000 });\n return output.trim() || 'unknown';\n }\n } catch {\n return 'unknown (process may have exited)';\n }\n }\n\n async getRandomPort() {\n const startingPort = 4000; // we prefer to have the ports between 4000 and 4999.\n // get random number in the range of [startingPort, 4999].\n const randomNumber = Math.floor(Math.random() * (4999 - startingPort + 1) + startingPort);\n const port = await Port.getPort(randomNumber, 65500);\n return port;\n }\n\n async getExistingUsedPort(): Promise<number | undefined> {\n const filePath = this.getServerPortFilePath();\n try {\n const fileContent = await fs.readFile(filePath, 'utf8');\n return parseInt(fileContent, 10);\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n return undefined;\n }\n throw err;\n }\n }\n\n private getServerPortFilePath() {\n return join(this.workspace.scope.path, 'server-port.txt');\n }\n\n static dependencies = [\n CLIAspect,\n WorkspaceAspect,\n LoggerAspect,\n ExpressAspect,\n WatcherAspect,\n SnappingAspect,\n LanesAspect,\n InstallAspect,\n ExportAspect,\n CheckoutAspect,\n ComponentLogAspect,\n ImporterAspect,\n ComponentCompareAspect,\n GeneratorAspect,\n RemoveAspect,\n ConfigAspect,\n ApplicationAspect,\n DeprecationAspect,\n EnvsAspect,\n GraphAspect,\n ScopeAspect,\n ComponentAspect,\n SchemaAspect,\n ];\n static runtime = MainRuntime;\n static async provider([\n cli,\n workspace,\n loggerMain,\n express,\n watcher,\n snapping,\n lanes,\n installer,\n exporter,\n checkout,\n componentLog,\n importer,\n componentCompare,\n generator,\n remove,\n config,\n application,\n deprecation,\n envs,\n graph,\n scope,\n component,\n schema,\n ]: [\n CLIMain,\n Workspace,\n LoggerMain,\n ExpressMain,\n WatcherMain,\n SnappingMain,\n LanesMain,\n InstallMain,\n ExportMain,\n CheckoutMain,\n ComponentLogMain,\n ImporterMain,\n ComponentCompareMain,\n GeneratorMain,\n RemoveMain,\n ConfigMain,\n ApplicationMain,\n DeprecationMain,\n EnvsMain,\n GraphMain,\n ScopeMain,\n ComponentMain,\n SchemaMain,\n ]) {\n const logger = loggerMain.createLogger(ApiServerAspect.id);\n const apiServer = new ApiServerMain(workspace, logger, express, watcher, installer, importer);\n cli.register(new ServerCmd(apiServer));\n\n const apiForIDE = new APIForIDE(\n workspace,\n snapping,\n lanes,\n installer,\n exporter,\n checkout,\n componentLog,\n componentCompare,\n generator,\n remove,\n config,\n application,\n deprecation,\n envs,\n graph,\n scope,\n component,\n schema,\n logger\n );\n const cliRoute = new CLIRoute(logger, cli, apiForIDE);\n const cliRawRoute = new CLIRawRoute(logger, cli, apiForIDE);\n const ideRoute = new IDERoute(logger, apiForIDE);\n const sseEventsRoute = new SSEEventsRoute(logger, cli);\n // register only when the workspace is available. don't register this on a remote-scope, for security reasons.\n if (workspace) {\n express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,kBA8PF,CACpB0J,gBAAS,EACTC,4BAAe,EACfC,sBAAY,EACZC,wBAAa,EACbC,wBAAa,EACbC,0BAAc,EACdC,oBAAW,EACXC,wBAAa,EACbC,sBAAY,EACZC,0BAAc,EACdC,kCAAkB,EAClBC,0BAAc,EACdC,0CAAsB,EACtBC,4BAAe,EACfC,sBAAY,EACZC,sBAAY,EACZC,gCAAiB,EACjBC,gCAAiB,EACjBC,kBAAU,EACVC,oBAAW,EACXC,qBAAW,EACXC,4BAAe,EACfC,sBAAY,CACb;AAAAlM,eAAA,CAtRUkB,aAAa,aAuRPiL,kBAAW;AAwF9BtC,4BAAe,CAACuC,UAAU,CAAClL,aAAa,CAAC;AAAC,IAAAmL,QAAA,GAAA1B,OAAA,CAAA5K,OAAA,GAE3BmB,aAAa","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["_cli","data","require","_toolboxNetwork","_fsExtra","_interopRequireDefault","_crypto","_express","_express2","_logger","_lanes","_remove","_snapping","_generator","_componentCompare","_componentLog","_watcher","_config","_export","_checkout","_install","_importer","_component","_workspace","_harmonyModules","_cors","_httpProxyMiddleware","_apiServer","_cli2","_server","_ide","_apiForIde","_sseEvents","_path","_child_process","_cliRaw","_application","_deprecation","_envs","_scope","_legacy","_graph","_scope2","_schema","e","__esModule","default","_defineProperty","r","t","_toPropertyKey","Object","defineProperty","value","enumerable","configurable","writable","i","_toPrimitive","Symbol","toPrimitive","call","TypeError","String","Number","ApiServerMain","constructor","workspace","logger","express","watcher","installer","importer","runApiServer","options","Error","process","cwd","registerOnComponentChange","component","files","removedFiles","sendEventsToClients","id","toStringWithoutVersion","registerOnBitmapChange","lastModifiedTimestamp","bitMap","getLastModifiedBitmapThroughBit","secondsPassedSinceLastModified","Date","now","debug","importCurrentObjects","registerOnWorkspaceConfigChange","scope","registerOnPostExport","registerPostInstall","watch","preCompile","compile","port","getRandomPort","bindHost","isOverride","resolveBindHost","writeServerToken","app","expressFactory","use","createHostCheckMiddleware","loopbackOnly","cors","origin","callback","credentials","createAuthMiddleware","createApp","proxyHeaders","Authorization","DEFAULT_AUTH_TYPE","Http","getToken","symphonyUrl","getSymphonyUrl","createProxyMiddleware","target","changeOrigin","headers","on","error","err","req","res","writeHead","end","proxyReq","fixRequestBody","proxyRes","proxyReqWs","entries","forEach","key","setHeader","pathFilter","ws","server","listen","Promise","resolve","reject","consoleSuccess","writeUsedPort","startParentProcessMonitor","filePath","getServerPortFilePath","fs","writeFileSync","toString","mode","chmodSync","token","crypto","randomBytes","getServerTokenFilePath","serverToken","join","path","allowed","Set","next","hostHeader","host","match","toLowerCase","has","status","method","provided","parseBearerToken","authorization","authorized","queryIdx","url","indexOf","params","URLSearchParams","slice","get","delete","remaining","jsonp","message","originalPpid","ppid","parentInfo","getProcessInfo","pid","platform","checkInterval","intervalId","setInterval","currentPpid","clearInterval","exit","unref","psCommand","output","execSync","encoding","timeout","trim","startingPort","randomNumber","randomInt","Port","getPort","getExistingUsedPort","fileContent","readFile","parseInt","code","undefined","provider","cli","loggerMain","snapping","lanes","exporter","checkout","componentLog","componentCompare","generator","remove","config","application","deprecation","envs","graph","schema","createLogger","ApiServerAspect","apiServer","register","ServerCmd","apiForIDE","APIForIDE","cliRoute","CLIRoute","cliRawRoute","CLIRawRoute","ideRoute","IDERoute","sseEventsRoute","SSEEventsRoute","exports","CLIAspect","WorkspaceAspect","LoggerAspect","ExpressAspect","WatcherAspect","SnappingAspect","LanesAspect","InstallAspect","ExportAspect","CheckoutAspect","ComponentLogAspect","ImporterAspect","ComponentCompareAspect","GeneratorAspect","RemoveAspect","ConfigAspect","ApplicationAspect","DeprecationAspect","EnvsAspect","GraphAspect","ScopeAspect","ComponentAspect","SchemaAspect","MainRuntime","addRuntime","LOOPBACK_HOSTS","override","env","BIT_SERVER_HOST","header","_default"],"sources":["api-server.main.runtime.ts"],"sourcesContent":["import type { CLIMain } from '@teambit/cli';\nimport { CLIAspect, MainRuntime } from '@teambit/cli';\nimport { Port } from '@teambit/toolbox.network.get-port';\nimport fs from 'fs-extra';\nimport crypto from 'crypto';\nimport expressFactory from 'express';\nimport type { ExpressMain, Middleware, Request, Response, NextFunction } from '@teambit/express';\nimport { ExpressAspect } from '@teambit/express';\nimport type { Logger, LoggerMain } from '@teambit/logger';\nimport { LoggerAspect } from '@teambit/logger';\nimport type { LanesMain } from '@teambit/lanes';\nimport { LanesAspect } from '@teambit/lanes';\nimport type { RemoveMain } from '@teambit/remove';\nimport { RemoveAspect } from '@teambit/remove';\nimport type { SnappingMain } from '@teambit/snapping';\nimport { SnappingAspect } from '@teambit/snapping';\nimport type { GeneratorMain } from '@teambit/generator';\nimport { GeneratorAspect } from '@teambit/generator';\nimport type { ComponentCompareMain } from '@teambit/component-compare';\nimport { ComponentCompareAspect } from '@teambit/component-compare';\nimport type { ComponentLogMain } from '@teambit/component-log';\nimport { ComponentLogAspect } from '@teambit/component-log';\nimport type { WatcherMain } from '@teambit/watcher';\nimport { WatcherAspect } from '@teambit/watcher';\nimport type { ConfigMain } from '@teambit/config';\nimport { ConfigAspect } from '@teambit/config';\nimport type { ExportMain } from '@teambit/export';\nimport { ExportAspect } from '@teambit/export';\nimport type { CheckoutMain } from '@teambit/checkout';\nimport { CheckoutAspect } from '@teambit/checkout';\nimport type { InstallMain } from '@teambit/install';\nimport { InstallAspect } from '@teambit/install';\nimport type { ImporterMain } from '@teambit/importer';\nimport { ImporterAspect } from '@teambit/importer';\nimport type { Component, ComponentMain } from '@teambit/component';\nimport { ComponentAspect } from '@teambit/component';\nimport type { Workspace } from '@teambit/workspace';\nimport { WorkspaceAspect } from '@teambit/workspace';\nimport { sendEventsToClients } from '@teambit/harmony.modules.send-server-sent-events';\nimport cors from 'cors';\nimport { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware';\nimport { ApiServerAspect } from './api-server.aspect';\nimport { CLIRoute } from './cli.route';\nimport { ServerCmd } from './server.cmd';\nimport { IDERoute } from './ide.route';\nimport { APIForIDE } from './api-for-ide';\nimport { SSEEventsRoute } from './sse-events.route';\nimport { join } from 'path';\nimport { execSync } from 'child_process';\nimport { CLIRawRoute } from './cli-raw.route';\nimport type { ApplicationMain } from '@teambit/application';\nimport { ApplicationAspect } from '@teambit/application';\nimport type { DeprecationMain } from '@teambit/deprecation';\nimport { DeprecationAspect } from '@teambit/deprecation';\nimport type { EnvsMain } from '@teambit/envs';\nimport { EnvsAspect } from '@teambit/envs';\nimport { DEFAULT_AUTH_TYPE, Http } from '@teambit/scope.network';\nimport { getSymphonyUrl } from '@teambit/legacy.constants';\nimport type { GraphMain } from '@teambit/graph';\nimport { GraphAspect } from '@teambit/graph';\nimport type { ScopeMain } from '@teambit/scope';\nimport { ScopeAspect } from '@teambit/scope';\nimport type { SchemaMain } from '@teambit/schema';\nimport { SchemaAspect } from '@teambit/schema';\n\nexport class ApiServerMain {\n private serverToken?: string;\n\n constructor(\n private workspace: Workspace,\n private logger: Logger,\n private express: ExpressMain,\n private watcher: WatcherMain,\n private installer: InstallMain,\n private importer: ImporterMain\n ) {}\n\n async runApiServer(options: { port: number; compile: boolean }) {\n if (!this.workspace) {\n throw new Error(`unable to run bit-server, the current directory ${process.cwd()} is not a workspace`);\n }\n\n this.workspace.registerOnComponentChange(\n async (\n component: Component,\n files: string[], // os absolute paths\n removedFiles?: string[] // os absolute paths\n ) => {\n sendEventsToClients('onComponentChange', {\n id: component.id.toStringWithoutVersion(),\n files,\n removedFiles,\n });\n }\n );\n\n this.workspace.registerOnBitmapChange(async () => {\n const lastModifiedTimestamp = await this.workspace.bitMap.getLastModifiedBitmapThroughBit();\n const secondsPassedSinceLastModified = lastModifiedTimestamp && (Date.now() - lastModifiedTimestamp) / 1000;\n if (secondsPassedSinceLastModified && secondsPassedSinceLastModified > 1) {\n // changes by bit were done more than a second ago, so probably this .bitmap change was done by \"git pull\"\n this.logger.debug(\n `running import because we assume the .bitmap file has changed due to \"git pull\", last time it was modified by bit was ${secondsPassedSinceLastModified} seconds ago`\n );\n await this.importer.importCurrentObjects();\n }\n sendEventsToClients('onBitmapChange', {});\n });\n\n this.workspace.registerOnWorkspaceConfigChange(async () => {\n sendEventsToClients('onWorkspaceConfigChange', {});\n });\n\n this.workspace.scope.registerOnPostExport(async () => {\n sendEventsToClients('onPostExport', {});\n });\n\n this.installer.registerPostInstall(async () => {\n sendEventsToClients('onPostInstall', {});\n });\n\n await this.watcher.watch({\n preCompile: false,\n compile: options.compile,\n });\n\n const port = options.port || (await this.getRandomPort());\n const { bindHost, isOverride } = resolveBindHost();\n\n // Generate a per-server auth token and persist it to a 0600 file before\n // any HTTP request can be handled. Clients (e.g. the bit-vscode extension)\n // read it from <workspace.scope.path>/server-token.txt and send it as\n // `Authorization: Bearer <token>`. See createAuthMiddleware below.\n this.writeServerToken();\n\n // Create the app *before* express.createApp registers routes, so the auth\n // middleware runs before bodyParser — unauthenticated requests can't\n // trigger large-body parsing. CORS is registered before auth so 401\n // responses still carry CORS headers; otherwise browser-based clients\n // (bit-vscode) see a misleading CORS failure instead of the JSON 401.\n // The host-check middleware runs first to reject DNS-rebinding attacks\n // (where a malicious page resolves attacker.example to 127.0.0.1).\n const app = expressFactory();\n app.use(this.createHostCheckMiddleware({ loopbackOnly: !isOverride }));\n app.use(\n cors({\n origin(origin, callback) {\n callback(null, true);\n },\n credentials: true,\n })\n );\n app.use(this.createAuthMiddleware());\n this.express.createApp(app);\n const proxyHeaders = {\n Authorization: `${DEFAULT_AUTH_TYPE} ${Http.getToken()}`,\n origin: '',\n 'user-agent': 'bit-vscode-proxy',\n };\n const symphonyUrl = getSymphonyUrl();\n app.use(\n '/api/cloud-graphql',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n createProxyMiddleware({\n target: `${symphonyUrl}/graphql`,\n changeOrigin: true,\n headers: proxyHeaders,\n on: {\n error: (err, req, res) => {\n this.logger.error('graphql cloud proxy error', err);\n // @ts-ignore\n res.writeHead(500, {\n 'Content-Type': 'text/plain',\n });\n res.end('Something went wrong with the proxy server of bit cloud graphql');\n },\n proxyReq: fixRequestBody,\n },\n })\n );\n\n app.use(\n '/api/cloud-rest',\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n createProxyMiddleware({\n target: `${symphonyUrl}`,\n changeOrigin: true,\n headers: proxyHeaders,\n on: {\n proxyRes: (proxyRes) => {\n proxyRes.headers['Access-Control-Allow-Credentials'] = 'true';\n },\n error: (err, req, res) => {\n this.logger.error('rest cloud proxy error', err);\n // @ts-ignore\n res.writeHead(500, {\n 'Content-Type': 'text/plain',\n });\n res.end('Something went wrong with the proxy server of bit cloud rest');\n },\n proxyReq: fixRequestBody,\n },\n })\n );\n\n app.use(\n '/websocket-server/subscriptions',\n createProxyMiddleware({\n on: {\n proxyReqWs: (proxyReq) => {\n Object.entries(proxyHeaders).forEach(([key, value]) => {\n proxyReq.setHeader(key, value);\n });\n },\n error: (err) => {\n this.logger.error('websocket cloud proxy error', err);\n },\n },\n pathFilter: '/',\n target: symphonyUrl,\n ws: true,\n changeOrigin: true,\n })\n );\n\n if (isOverride) {\n this.logger.debug(\n `api-server: binding to ${bindHost} (from BIT_SERVER_HOST), loopback Host-header check disabled`\n );\n }\n const server = await app.listen(port, bindHost);\n\n return new Promise((resolve, reject) => {\n server.on('error', (err) => {\n reject(err);\n });\n server.on('listening', () => {\n // important! if you change the message here, change it also in server-forever.ts and also in the vscode extension.\n this.logger.consoleSuccess(`Bit Server is listening on port ${port}`);\n this.writeUsedPort(port);\n this.startParentProcessMonitor();\n resolve(port);\n });\n });\n }\n\n writeUsedPort(port: number) {\n const filePath = this.getServerPortFilePath();\n fs.writeFileSync(filePath, port.toString(), { mode: 0o600 });\n // Node's `mode` write option is only honored when the file is created.\n // chmod explicitly so a pre-existing file with broader permissions gets\n // tightened to 0600.\n fs.chmodSync(filePath, 0o600);\n }\n\n /**\n * Generate a fresh per-server bearer token and persist it to a 0600 file.\n * Clients (e.g. the bit-vscode extension) read this file and send the token\n * as `Authorization: Bearer <token>` on every request.\n *\n * Backwards compatibility: clients that don't yet know about this file (older\n * extension versions) won't send the header and will receive 401 with a\n * message pointing them at the upgrade. Old bit-server versions don't write\n * this file, so a new client checking for it gracefully falls back to no\n * auth header — meaning a NEW extension keeps working against an OLD\n * bit-server.\n */\n private writeServerToken() {\n const token = crypto.randomBytes(32).toString('hex');\n const filePath = this.getServerTokenFilePath();\n fs.writeFileSync(filePath, token, { mode: 0o600 });\n // Node's `mode` write option is only honored when the file is created.\n // chmod explicitly so a pre-existing file with broader permissions gets\n // tightened to 0600.\n fs.chmodSync(filePath, 0o600);\n this.serverToken = token;\n }\n\n private getServerTokenFilePath() {\n return join(this.workspace.scope.path, 'server-token.txt');\n }\n\n /**\n * Host-header check: only accept requests targeting a loopback hostname.\n * Defends against DNS-rebinding attacks where a malicious page on\n * `evil.example` flips DNS to 127.0.0.1 — the browser sends `Host:\n * evil.example`, which we reject with 403 here.\n *\n * The server already listens on 127.0.0.1 only, so any request reaching us\n * arrived via loopback. The remaining concern is the *named* origin the\n * browser thinks it's talking to.\n *\n * Disabled when `BIT_SERVER_HOST` resolves to a non-loopback address,\n * since by definition the server is then reachable via a hostname we\n * can't enumerate ahead of time (e.g. a cloud-workspace hostname). In\n * that mode the bearer token is the primary line of defense; the\n * unauthenticated exemptions (`OPTIONS` preflight and `/api/_health`)\n * become reachable from the network — `/api/_health` is a tiny \"ok\"\n * liveness probe and intentionally exposed.\n */\n private createHostCheckMiddleware({ loopbackOnly }: { loopbackOnly: boolean }): Middleware {\n const allowed = new Set(['localhost', '127.0.0.1', '::1']);\n return (req: Request, res: Response, next: NextFunction) => {\n if (!loopbackOnly) return next();\n const hostHeader = req.headers.host || '';\n // Parse hostname from \"host:port\". IPv6 may be bracketed: \"[::1]:1234\"\n // → \"::1\"; IPv4 / hostname is plain: \"127.0.0.1:1234\" → \"127.0.0.1\".\n // HTTP hostnames are case-insensitive, so normalize before checking.\n const match = hostHeader.match(/^\\[([^\\]]+)\\]|^([^:]+)/);\n const host = match ? (match[1] || match[2]).toLowerCase() : '';\n if (!allowed.has(host)) {\n this.logger.debug(`api-server: rejected non-loopback Host header: ${hostHeader}`);\n res.status(403).end();\n return;\n }\n return next();\n };\n }\n\n /**\n * Authentication middleware: requires `Authorization: Bearer <serverToken>`\n * on every request except OPTIONS preflight (handled by cors) and the\n * unauthenticated `/api/_health` liveness probe.\n *\n * GET requests can also authenticate via a `?token=...` query parameter,\n * since browser-native WebSocket and EventSource cannot set custom headers\n * from JavaScript. The param is stripped from `req.url` before downstream\n * handling so the proxy and logs never see it.\n *\n * Runs before bodyParser so unauthenticated requests can't trigger\n * large-body parsing.\n */\n private createAuthMiddleware(): Middleware {\n return (req: Request, res: Response, next: NextFunction) => {\n if (req.method === 'OPTIONS') return next();\n // Use req.path (not req.url) so query strings don't bypass the\n // health-check exemption — e.g. /api/_health?cache-buster=1.\n if (req.path === '/api/_health') return next();\n\n const provided = parseBearerToken(req.headers.authorization);\n let authorized = !!this.serverToken && provided === this.serverToken;\n\n if (!authorized && this.serverToken && req.method === 'GET') {\n const queryIdx = req.url.indexOf('?');\n if (queryIdx >= 0) {\n const params = new URLSearchParams(req.url.slice(queryIdx + 1));\n if (params.get('token') === this.serverToken) {\n authorized = true;\n params.delete('token');\n const remaining = params.toString();\n req.url = req.url.slice(0, queryIdx) + (remaining ? `?${remaining}` : '');\n }\n }\n }\n\n if (!authorized) {\n this.logger.debug(`api-server: rejected unauthenticated request to ${req.path}`);\n res.status(401).jsonp({\n error: 'unauthorized',\n message:\n 'This bit-server requires authentication. Please upgrade your bit VS Code extension to the latest version.',\n });\n return;\n }\n return next();\n };\n }\n\n /**\n * Monitor the parent process (typically VSCode) and shut down if it dies.\n *\n * On Unix-like systems (macOS, Linux), when a parent process dies, orphaned children are\n * re-parented to PID 1 (init/launchd). By watching for `process.ppid` changing from\n * the original value to 1, we can detect that the parent exited and proactively\n * shut down the bit server to avoid leaving stale background processes running.\n *\n * Note: This orphan detection does not work on Windows, as Windows does not re-parent\n * processes to PID 1. On Windows, this method only logs the parent process info at startup.\n */\n private startParentProcessMonitor() {\n const originalPpid = process.ppid;\n\n // Log parent process info at startup\n const parentInfo = this.getProcessInfo(originalPpid);\n this.logger.debug(\n `bit server started. PID: ${process.pid}, Parent PID: ${originalPpid}, Parent command: ${parentInfo}`\n );\n\n // Skip orphan detection on Windows - PPID doesn't change to 1 when parent dies\n if (process.platform === 'win32') {\n return;\n }\n\n const checkInterval = 5000; // Check every 5 seconds\n const intervalId = setInterval(() => {\n const currentPpid = process.ppid;\n // If PPID changed to 1, our parent (e.g., VSCode) died and we were re-parented to init\n if (currentPpid === 1 && originalPpid !== 1) {\n this.logger.debug(\n `Parent process died (was PID ${originalPpid}: ${parentInfo}). Current PPID is now 1 (init/launchd). Shutting down bit server.`\n );\n clearInterval(intervalId);\n process.exit(0);\n }\n }, checkInterval);\n\n // Don't let this interval keep the process alive if everything else is done\n intervalId.unref();\n }\n\n /**\n * Get the command/path of a process by its PID.\n */\n private getProcessInfo(pid: number): string {\n try {\n if (process.platform === 'win32') {\n // Windows: use PowerShell Get-CimInstance (WMIC is deprecated/removed on modern Windows)\n const psCommand = `Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}' | Select-Object -ExpandProperty CommandLine`;\n const output = execSync(`powershell.exe -NoProfile -Command \"${psCommand}\"`, {\n encoding: 'utf8',\n timeout: 2000,\n });\n return output.trim() || 'unknown';\n } else {\n // macOS/Linux: use ps\n const output = execSync(`ps -o command= -p ${pid}`, { encoding: 'utf8', timeout: 2000 });\n return output.trim() || 'unknown';\n }\n } catch {\n return 'unknown (process may have exited)';\n }\n }\n\n async getRandomPort() {\n const startingPort = 4000; // we prefer to have the ports between 4000 and 4999.\n const randomNumber = crypto.randomInt(startingPort, 5000);\n const port = await Port.getPort(randomNumber, 65500);\n return port;\n }\n\n async getExistingUsedPort(): Promise<number | undefined> {\n const filePath = this.getServerPortFilePath();\n try {\n const fileContent = await fs.readFile(filePath, 'utf8');\n return parseInt(fileContent, 10);\n } catch (err: any) {\n if (err.code === 'ENOENT') {\n return undefined;\n }\n throw err;\n }\n }\n\n private getServerPortFilePath() {\n return join(this.workspace.scope.path, 'server-port.txt');\n }\n\n static dependencies = [\n CLIAspect,\n WorkspaceAspect,\n LoggerAspect,\n ExpressAspect,\n WatcherAspect,\n SnappingAspect,\n LanesAspect,\n InstallAspect,\n ExportAspect,\n CheckoutAspect,\n ComponentLogAspect,\n ImporterAspect,\n ComponentCompareAspect,\n GeneratorAspect,\n RemoveAspect,\n ConfigAspect,\n ApplicationAspect,\n DeprecationAspect,\n EnvsAspect,\n GraphAspect,\n ScopeAspect,\n ComponentAspect,\n SchemaAspect,\n ];\n static runtime = MainRuntime;\n static async provider([\n cli,\n workspace,\n loggerMain,\n express,\n watcher,\n snapping,\n lanes,\n installer,\n exporter,\n checkout,\n componentLog,\n importer,\n componentCompare,\n generator,\n remove,\n config,\n application,\n deprecation,\n envs,\n graph,\n scope,\n component,\n schema,\n ]: [\n CLIMain,\n Workspace,\n LoggerMain,\n ExpressMain,\n WatcherMain,\n SnappingMain,\n LanesMain,\n InstallMain,\n ExportMain,\n CheckoutMain,\n ComponentLogMain,\n ImporterMain,\n ComponentCompareMain,\n GeneratorMain,\n RemoveMain,\n ConfigMain,\n ApplicationMain,\n DeprecationMain,\n EnvsMain,\n GraphMain,\n ScopeMain,\n ComponentMain,\n SchemaMain,\n ]) {\n const logger = loggerMain.createLogger(ApiServerAspect.id);\n const apiServer = new ApiServerMain(workspace, logger, express, watcher, installer, importer);\n cli.register(new ServerCmd(apiServer));\n\n const apiForIDE = new APIForIDE(\n workspace,\n snapping,\n lanes,\n installer,\n exporter,\n checkout,\n componentLog,\n componentCompare,\n generator,\n remove,\n config,\n application,\n deprecation,\n envs,\n graph,\n scope,\n component,\n schema,\n logger\n );\n const cliRoute = new CLIRoute(logger, cli, apiForIDE);\n const cliRawRoute = new CLIRawRoute(logger, cli, apiForIDE);\n const ideRoute = new IDERoute(logger, apiForIDE);\n const sseEventsRoute = new SSEEventsRoute(logger, cli);\n // register only when the workspace is available. don't register this on a remote-scope, for security reasons.\n if (workspace) {\n express.register([cliRoute, cliRawRoute, ideRoute, sseEventsRoute]);\n }\n\n return apiServer;\n }\n}\n\nApiServerAspect.addRuntime(ApiServerMain);\n\nconst LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);\n\n/**\n * Resolve the api-server bind host from `BIT_SERVER_HOST`, falling back to\n * loopback. `isOverride` is the single source of truth for \"is the server\n * reachable from outside loopback?\" — used both to choose the bind address\n * and to disable the loopback Host-header check. Derived from the *resolved*\n * host (not env presence) so `BIT_SERVER_HOST=127.0.0.1` and whitespace-only\n * values don't silently weaken the DNS-rebinding mitigation.\n */\nfunction resolveBindHost(): { bindHost: string; isOverride: boolean } {\n const override = process.env.BIT_SERVER_HOST?.trim();\n const bindHost = override || '127.0.0.1';\n return { bindHost, isOverride: !LOOPBACK_HOSTS.has(bindHost.toLowerCase()) };\n}\n\n/**\n * Extract the token from an `Authorization: Bearer <token>` header.\n * Lenient on scheme casing and surrounding whitespace so a slightly\n * non-canonical client header doesn't get rejected.\n */\nfunction parseBearerToken(header: string | undefined): string | undefined {\n if (!header) return undefined;\n const match = header.match(/^\\s*Bearer\\s+(\\S+)\\s*$/i);\n return match?.[1];\n}\n\nexport default ApiServerMain;\n"],"mappings":";;;;;;AACA,SAAAA,KAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,IAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,gBAAA;EAAA,MAAAF,IAAA,GAAAC,OAAA;EAAAC,eAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAG,SAAA;EAAA,MAAAH,IAAA,GAAAI,sBAAA,CAAAH,OAAA;EAAAE,QAAA,YAAAA,CAAA;IAAA,OAAAH,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAK,QAAA;EAAA,MAAAL,IAAA,GAAAI,sBAAA,CAAAH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zC,MAAMwN,cAAc,GAAG,IAAIhH,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC;;AAEjE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAShE,eAAeA,CAAA,EAA8C;EACpE,MAAMiL,QAAQ,GAAG9M,OAAO,CAAC+M,GAAG,CAACC,eAAe,EAAEzE,IAAI,CAAC,CAAC;EACpD,MAAM5G,QAAQ,GAAGmL,QAAQ,IAAI,WAAW;EACxC,OAAO;IAAEnL,QAAQ;IAAEC,UAAU,EAAE,CAACiL,cAAc,CAAC1G,GAAG,CAACxE,QAAQ,CAACuE,WAAW,CAAC,CAAC;EAAE,CAAC;AAC9E;;AAEA;AACA;AACA;AACA;AACA;AACA,SAASK,gBAAgBA,CAAC0G,MAA0B,EAAsB;EACxE,IAAI,CAACA,MAAM,EAAE,OAAO/D,SAAS;EAC7B,MAAMjD,KAAK,GAAGgH,MAAM,CAAChH,KAAK,CAAC,yBAAyB,CAAC;EACrD,OAAOA,KAAK,GAAG,CAAC,CAAC;AACnB;AAAC,IAAAiH,QAAA,GAAA/B,OAAA,CAAAjN,OAAA,GAEcmB,aAAa","ignoreList":[]}
|
package/dist/cli-raw.route.js
CHANGED
|
@@ -25,6 +25,13 @@ function _path() {
|
|
|
25
25
|
};
|
|
26
26
|
return data;
|
|
27
27
|
}
|
|
28
|
+
function _tty() {
|
|
29
|
+
const data = require("tty");
|
|
30
|
+
_tty = function () {
|
|
31
|
+
return data;
|
|
32
|
+
};
|
|
33
|
+
return data;
|
|
34
|
+
}
|
|
28
35
|
function _chalk() {
|
|
29
36
|
const data = _interopRequireDefault(require("chalk"));
|
|
30
37
|
_chalk = function () {
|
|
@@ -57,6 +64,20 @@ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e
|
|
|
57
64
|
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
|
|
58
65
|
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
|
|
59
66
|
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
|
|
67
|
+
/**
|
|
68
|
+
* Strict allowlist of TTY device paths. Anything not matching is rejected
|
|
69
|
+
* before we attempt to open it. Combined with an `isatty` check on the
|
|
70
|
+
* opened fd, this blocks block devices, /proc files, and symlink-redirected
|
|
71
|
+
* targets.
|
|
72
|
+
*
|
|
73
|
+
* /dev/tty current process's controlling tty
|
|
74
|
+
* /dev/ttyXXXNN e.g. /dev/ttys000 (macOS), /dev/ttyS0 (Linux)
|
|
75
|
+
* /dev/pts/N pseudo-terminal slaves on Linux
|
|
76
|
+
* /dev/ptmx pseudo-terminal master
|
|
77
|
+
* /dev/console system console
|
|
78
|
+
*/
|
|
79
|
+
const TTY_PATH_RE = /^\/dev\/(tty[a-zA-Z0-9]*|pts\/\d+|ptmx|console)$/;
|
|
80
|
+
|
|
60
81
|
/**
|
|
61
82
|
* example usage:
|
|
62
83
|
* post to http://localhost:3000/api/cli
|
|
@@ -92,13 +113,12 @@ class CLIRawRoute {
|
|
|
92
113
|
}
|
|
93
114
|
}
|
|
94
115
|
|
|
95
|
-
// Validate ttyPath
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
}
|
|
116
|
+
// Validate ttyPath against a strict allowlist. The earlier check (string
|
|
117
|
+
// prefix /dev/ or /proc/) was too permissive — it allowed /dev/sda,
|
|
118
|
+
// /proc/sysrq-trigger, etc. After opening we also verify the fd is a
|
|
119
|
+
// TTY (catches symlinks pointing outside the allowlist).
|
|
120
|
+
if (ttyPath && !TTY_PATH_RE.test(ttyPath)) {
|
|
121
|
+
throw new Error(`Invalid ttyPath parameter. Must be a TTY device under /dev/.`);
|
|
102
122
|
}
|
|
103
123
|
// there are 3 methods to interact with bit-server: 1) SSE, 2) TTY, 3) PTY. See server-commander.ts for more info.
|
|
104
124
|
const isSSE = !ttyPath && !isPty;
|
|
@@ -106,16 +126,23 @@ class CLIRawRoute {
|
|
|
106
126
|
// save the original process.stdout.write method
|
|
107
127
|
const originalStdoutWrite = process.stdout.write;
|
|
108
128
|
const originalStderrWrite = process.stderr.write;
|
|
129
|
+
let fileHandle;
|
|
109
130
|
if (ttyPath) {
|
|
110
|
-
|
|
131
|
+
fileHandle = await _fsExtra().default.open(ttyPath, 'w');
|
|
132
|
+
if (!(0, _tty().isatty)(fileHandle)) {
|
|
133
|
+
await _fsExtra().default.close(fileHandle);
|
|
134
|
+
fileHandle = undefined;
|
|
135
|
+
throw new Error(`Invalid ttyPath parameter. Path is not a TTY.`);
|
|
136
|
+
}
|
|
137
|
+
const ttyFd = fileHandle;
|
|
111
138
|
// @ts-ignore monkey patch the process stdout write method
|
|
112
139
|
process.stdout.write = (chunk, encoding, callback) => {
|
|
113
|
-
_fsExtra().default.writeSync(
|
|
140
|
+
_fsExtra().default.writeSync(ttyFd, chunk.toString());
|
|
114
141
|
return originalStdoutWrite.call(process.stdout, chunk, encoding, callback);
|
|
115
142
|
};
|
|
116
143
|
// @ts-ignore monkey patch the process stderr write method
|
|
117
144
|
process.stderr.write = (chunk, encoding, callback) => {
|
|
118
|
-
_fsExtra().default.writeSync(
|
|
145
|
+
_fsExtra().default.writeSync(ttyFd, chunk.toString());
|
|
119
146
|
return originalStderrWrite.call(process.stdout, chunk, encoding, callback);
|
|
120
147
|
};
|
|
121
148
|
}
|
|
@@ -175,6 +202,13 @@ class CLIRawRoute {
|
|
|
175
202
|
if (ttyPath) {
|
|
176
203
|
process.stdout.write = originalStdoutWrite;
|
|
177
204
|
process.stderr.write = originalStderrWrite;
|
|
205
|
+
if (fileHandle !== undefined) {
|
|
206
|
+
try {
|
|
207
|
+
await _fsExtra().default.close(fileHandle);
|
|
208
|
+
} catch (err) {
|
|
209
|
+
this.logger.debug(`cli-raw: failed to close tty fd: ${err.message}`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
178
212
|
}
|
|
179
213
|
if (isSSE) {
|
|
180
214
|
delete process.env.BIT_CLI_SERVER_NO_TTY;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"names":["_cli","data","require","_fsExtra","_interopRequireDefault","_path","_chalk","_legacy","_harmonyModules","_legacy2","e","__esModule","default","_defineProperty","r","t","_toPropertyKey","Object","defineProperty","value","enumerable","configurable","writable","i","_toPrimitive","Symbol","toPrimitive","call","TypeError","String","Number","CLIRawRoute","constructor","logger","cli","apiForIDE","req","res","command","pwd","envBitFeatures","ttyPath","isPty","body","debug","resolvedPwd","path","resolve","currentDir","process","cwd","startsWith","Error","includes","isSSE","originalStdoutWrite","stdout","write","originalStderrWrite","stderr","fileHandle","fs","open","chunk","encoding","callback","writeSync","toString","env","BIT_CLI_SERVER_NO_TTY","loader","shouldSendServerEvents","currentLogger","levelFromArgv","getLevelFromArgv","legacyLogger","switchToConsoleLogger","switchToSSELogger","currentBitFeatures","BIT_FEATURES","shouldReloadFeatureToggle","reloadFeatureToggle","randomNumber","Math","floor","random","commandStr","join","cmdStrLog","logStartCmdHistory","isDaemon","enableChalk","cliParser","CLIParser","commands","groups","onCommandStartSlot","commandRunner","parse","result","runCommand","logFinishCmdHistory","clearStatusLine","json","err","YargsExitWorkaround","helpMsg","exitCode","error","status","jsonp","message","chalk","level","switchToLogger","exports"],"sources":["cli-raw.route.ts"],"sourcesContent":["import type { CLIMain } from '@teambit/cli';\nimport { CLIParser, YargsExitWorkaround } from '@teambit/cli';\nimport fs from 'fs-extra';\nimport path from 'path';\nimport chalk from 'chalk';\nimport type { Route, Request, Response } from '@teambit/express';\nimport type { Logger } from '@teambit/logger';\nimport { logger as legacyLogger, getLevelFromArgv } from '@teambit/legacy.logger';\nimport { reloadFeatureToggle } from '@teambit/harmony.modules.feature-toggle';\nimport { loader } from '@teambit/legacy.loader';\nimport type { APIForIDE } from './api-for-ide';\n\n/**\n * example usage:\n * post to http://localhost:3000/api/cli\n * with the following json as the body\n *\n{\n \"command\": [\"tag comp1 --build\"]\n}\n */\nexport class CLIRawRoute implements Route {\n constructor(\n private logger: Logger,\n private cli: CLIMain,\n private apiForIDE: APIForIDE\n ) {}\n\n method = 'post';\n route = '/cli-raw';\n\n middlewares = [\n async (req: Request, res: Response) => {\n const { command, pwd, envBitFeatures, ttyPath, isPty } = req.body;\n this.logger.debug(`cli-raw server: got request for ${command}`);\n\n // Validate pwd parameter to prevent path traversal\n if (pwd) {\n const resolvedPwd = path.resolve(pwd);\n const currentDir = process.cwd();\n if (!resolvedPwd.startsWith(currentDir)) {\n throw new Error(`Invalid pwd parameter. bit-server: ${currentDir}, pwd: ${pwd}`);\n }\n }\n\n // Validate ttyPath parameter to prevent path traversal\n if (ttyPath) {\n // ttyPath should be a legitimate terminal device path (e.g., /dev/ttys000, /dev/pts/0)\n // Validate it's a device path and doesn't contain traversal sequences\n if (ttyPath.includes('..') || !(ttyPath.startsWith('/dev/') || ttyPath.startsWith('/proc/'))) {\n throw new Error(`Invalid ttyPath parameter. Must be a legitimate terminal device path.`);\n }\n }\n // there are 3 methods to interact with bit-server: 1) SSE, 2) TTY, 3) PTY. See server-commander.ts for more info.\n const isSSE = !ttyPath && !isPty;\n\n // save the original process.stdout.write method\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n if (ttyPath) {\n const fileHandle = await fs.open(ttyPath, 'w');\n // @ts-ignore monkey patch the process stdout write method\n process.stdout.write = (chunk, encoding, callback) => {\n fs.writeSync(fileHandle, chunk.toString());\n return originalStdoutWrite.call(process.stdout, chunk, encoding, callback);\n };\n // @ts-ignore monkey patch the process stderr write method\n process.stderr.write = (chunk, encoding, callback) => {\n fs.writeSync(fileHandle, chunk.toString());\n return originalStderrWrite.call(process.stdout, chunk, encoding, callback);\n };\n }\n if (isSSE) {\n process.env.BIT_CLI_SERVER_NO_TTY = 'true';\n loader.shouldSendServerEvents = true;\n }\n\n let currentLogger;\n const levelFromArgv = getLevelFromArgv(command);\n if (levelFromArgv) {\n currentLogger = legacyLogger.logger;\n if (ttyPath || isPty) {\n legacyLogger.switchToConsoleLogger(levelFromArgv);\n }\n if (isSSE) {\n legacyLogger.switchToSSELogger(levelFromArgv);\n }\n }\n\n const currentBitFeatures = process.env.BIT_FEATURES;\n const shouldReloadFeatureToggle = currentBitFeatures !== envBitFeatures;\n if (shouldReloadFeatureToggle) {\n process.env.BIT_FEATURES = envBitFeatures;\n reloadFeatureToggle();\n }\n\n const randomNumber = Math.floor(Math.random() * 10000); // helps to distinguish between commands in the log\n const commandStr = command.join(' ');\n const cmdStrLog = `${randomNumber} ${commandStr}`;\n await this.apiForIDE.logStartCmdHistory(cmdStrLog);\n legacyLogger.isDaemon = true;\n enableChalk();\n const cliParser = new CLIParser(this.cli.commands, this.cli.groups, this.cli.onCommandStartSlot);\n try {\n const commandRunner = await cliParser.parse(command);\n const result = await commandRunner.runCommand(true);\n await this.apiForIDE.logFinishCmdHistory(cmdStrLog, 0);\n this.logger.clearStatusLine();\n res.json(result);\n } catch (err: any) {\n this.logger.clearStatusLine();\n if (err instanceof YargsExitWorkaround) {\n res.json({ data: err.helpMsg, exitCode: err.exitCode });\n } else {\n this.logger.error(`cli-raw server: got an error for ${commandStr}`, err);\n await this.apiForIDE.logFinishCmdHistory(cmdStrLog, 1);\n res.status(500);\n res.jsonp({\n message: err.message,\n error: err,\n });\n }\n } finally {\n // important! at this stage, don't write to stdout/stderr anymore, e.g. don't do \"this.logger.clearStatusLine()\"\n // because the socket (for pty) is already closed.\n if (ttyPath) {\n process.stdout.write = originalStdoutWrite;\n process.stderr.write = originalStderrWrite;\n }\n if (isSSE) {\n delete process.env.BIT_CLI_SERVER_NO_TTY;\n loader.shouldSendServerEvents = false;\n }\n // change chalk back to false, otherwise, the IDE will have colors. (this is a global setting)\n chalk.level = 0;\n if (shouldReloadFeatureToggle) {\n process.env.BIT_FEATURES = currentBitFeatures;\n reloadFeatureToggle();\n }\n if (currentLogger) {\n legacyLogger.switchToLogger(currentLogger);\n }\n }\n },\n ];\n}\n\n/**\n * because this gets called from the express server, which gets spawn from a script, chalk defaults to false.\n * only when calling this route from the terminal, we want colors. on the IDE, we don't want colors.\n */\nfunction enableChalk() {\n chalk.level = 3;\n}\n"],"mappings":";;;;;;AACA,SAAAA,KAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,IAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,SAAA;EAAA,MAAAF,IAAA,GAAAG,sBAAA,CAAAF,OAAA;EAAAC,QAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,MAAA;EAAA,MAAAJ,IAAA,GAAAG,sBAAA,CAAAF,OAAA;EAAAG,KAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAK,OAAA;EAAA,MAAAL,IAAA,GAAAG,sBAAA,CAAAF,OAAA;EAAAI,MAAA,YAAAA,CAAA;IAAA,OAAAL,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAGA,SAAAM,QAAA;EAAA,MAAAN,IAAA,GAAAC,OAAA;EAAAK,OAAA,YAAAA,CAAA;IAAA,OAAAN,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAO,gBAAA;EAAA,MAAAP,IAAA,GAAAC,OAAA;EAAAM,eAAA,YAAAA,CAAA;IAAA,OAAAP,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAQ,SAAA;EAAA,MAAAR,IAAA,GAAAC,OAAA;EAAAO,QAAA,YAAAA,CAAA;IAAA,OAAAR,IAAA;EAAA;EAAA,OAAAA,IAAA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;UACT,CAAC,CAAC;QACJ;MACF,CAAC,SAAS;QACR;QACA;QACA,IAAI/D,OAAO,EAAE;UACXQ,OAAO,CAACO,MAAM,CAACC,KAAK,GAAGF,mBAAmB;UAC1CN,OAAO,CAACU,MAAM,CAACF,KAAK,GAAGC,mBAAmB;QAC5C;QACA,IAAIJ,KAAK,EAAE;UACT,OAAOL,OAAO,CAACmB,GAAG,CAACC,qBAAqB;UACxCC,iBAAM,CAACC,sBAAsB,GAAG,KAAK;QACvC;QACA;QACAyC,gBAAK,CAACC,KAAK,GAAG,CAAC;QACf,IAAIjC,yBAAyB,EAAE;UAC7B/B,OAAO,CAACmB,GAAG,CAACW,YAAY,GAAGD,kBAAkB;UAC7C,IAAAG,qCAAmB,EAAC,CAAC;QACvB;QACA,IAAIT,aAAa,EAAE;UACjBG,gBAAY,CAACuC,cAAc,CAAC1C,aAAa,CAAC;QAC5C;MACF;IACF,CAAC,CACF;EAvHE;AAwHL;;AAEA;AACA;AACA;AACA;AAHA2C,OAAA,CAAApF,WAAA,GAAAA,WAAA;AAIA,SAAS4D,WAAWA,CAAA,EAAG;EACrBqB,gBAAK,CAACC,KAAK,GAAG,CAAC;AACjB","ignoreList":[]}
|
|
1
|
+
{"version":3,"names":["_cli","data","require","_fsExtra","_interopRequireDefault","_path","_tty","_chalk","_legacy","_harmonyModules","_legacy2","e","__esModule","default","_defineProperty","r","t","_toPropertyKey","Object","defineProperty","value","enumerable","configurable","writable","i","_toPrimitive","Symbol","toPrimitive","call","TypeError","String","Number","TTY_PATH_RE","CLIRawRoute","constructor","logger","cli","apiForIDE","req","res","command","pwd","envBitFeatures","ttyPath","isPty","body","debug","resolvedPwd","path","resolve","currentDir","process","cwd","startsWith","Error","test","isSSE","originalStdoutWrite","stdout","write","originalStderrWrite","stderr","fileHandle","fs","open","isatty","close","undefined","ttyFd","chunk","encoding","callback","writeSync","toString","env","BIT_CLI_SERVER_NO_TTY","loader","shouldSendServerEvents","currentLogger","levelFromArgv","getLevelFromArgv","legacyLogger","switchToConsoleLogger","switchToSSELogger","currentBitFeatures","BIT_FEATURES","shouldReloadFeatureToggle","reloadFeatureToggle","randomNumber","Math","floor","random","commandStr","join","cmdStrLog","logStartCmdHistory","isDaemon","enableChalk","cliParser","CLIParser","commands","groups","onCommandStartSlot","commandRunner","parse","result","runCommand","logFinishCmdHistory","clearStatusLine","json","err","YargsExitWorkaround","helpMsg","exitCode","error","status","jsonp","message","chalk","level","switchToLogger","exports"],"sources":["cli-raw.route.ts"],"sourcesContent":["import type { CLIMain } from '@teambit/cli';\nimport { CLIParser, YargsExitWorkaround } from '@teambit/cli';\nimport fs from 'fs-extra';\nimport path from 'path';\nimport { isatty } from 'tty';\nimport chalk from 'chalk';\nimport type { Route, Request, Response } from '@teambit/express';\nimport type { Logger } from '@teambit/logger';\nimport { logger as legacyLogger, getLevelFromArgv } from '@teambit/legacy.logger';\nimport { reloadFeatureToggle } from '@teambit/harmony.modules.feature-toggle';\nimport { loader } from '@teambit/legacy.loader';\nimport type { APIForIDE } from './api-for-ide';\n\n/**\n * Strict allowlist of TTY device paths. Anything not matching is rejected\n * before we attempt to open it. Combined with an `isatty` check on the\n * opened fd, this blocks block devices, /proc files, and symlink-redirected\n * targets.\n *\n * /dev/tty current process's controlling tty\n * /dev/ttyXXXNN e.g. /dev/ttys000 (macOS), /dev/ttyS0 (Linux)\n * /dev/pts/N pseudo-terminal slaves on Linux\n * /dev/ptmx pseudo-terminal master\n * /dev/console system console\n */\nconst TTY_PATH_RE = /^\\/dev\\/(tty[a-zA-Z0-9]*|pts\\/\\d+|ptmx|console)$/;\n\n/**\n * example usage:\n * post to http://localhost:3000/api/cli\n * with the following json as the body\n *\n{\n \"command\": [\"tag comp1 --build\"]\n}\n */\nexport class CLIRawRoute implements Route {\n constructor(\n private logger: Logger,\n private cli: CLIMain,\n private apiForIDE: APIForIDE\n ) {}\n\n method = 'post';\n route = '/cli-raw';\n\n middlewares = [\n async (req: Request, res: Response) => {\n const { command, pwd, envBitFeatures, ttyPath, isPty } = req.body;\n this.logger.debug(`cli-raw server: got request for ${command}`);\n\n // Validate pwd parameter to prevent path traversal\n if (pwd) {\n const resolvedPwd = path.resolve(pwd);\n const currentDir = process.cwd();\n if (!resolvedPwd.startsWith(currentDir)) {\n throw new Error(`Invalid pwd parameter. bit-server: ${currentDir}, pwd: ${pwd}`);\n }\n }\n\n // Validate ttyPath against a strict allowlist. The earlier check (string\n // prefix /dev/ or /proc/) was too permissive — it allowed /dev/sda,\n // /proc/sysrq-trigger, etc. After opening we also verify the fd is a\n // TTY (catches symlinks pointing outside the allowlist).\n if (ttyPath && !TTY_PATH_RE.test(ttyPath)) {\n throw new Error(`Invalid ttyPath parameter. Must be a TTY device under /dev/.`);\n }\n // there are 3 methods to interact with bit-server: 1) SSE, 2) TTY, 3) PTY. See server-commander.ts for more info.\n const isSSE = !ttyPath && !isPty;\n\n // save the original process.stdout.write method\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n let fileHandle: number | undefined;\n if (ttyPath) {\n fileHandle = await fs.open(ttyPath, 'w');\n if (!isatty(fileHandle)) {\n await fs.close(fileHandle);\n fileHandle = undefined;\n throw new Error(`Invalid ttyPath parameter. Path is not a TTY.`);\n }\n const ttyFd = fileHandle;\n // @ts-ignore monkey patch the process stdout write method\n process.stdout.write = (chunk, encoding, callback) => {\n fs.writeSync(ttyFd, chunk.toString());\n return originalStdoutWrite.call(process.stdout, chunk, encoding, callback);\n };\n // @ts-ignore monkey patch the process stderr write method\n process.stderr.write = (chunk, encoding, callback) => {\n fs.writeSync(ttyFd, chunk.toString());\n return originalStderrWrite.call(process.stdout, chunk, encoding, callback);\n };\n }\n if (isSSE) {\n process.env.BIT_CLI_SERVER_NO_TTY = 'true';\n loader.shouldSendServerEvents = true;\n }\n\n let currentLogger;\n const levelFromArgv = getLevelFromArgv(command);\n if (levelFromArgv) {\n currentLogger = legacyLogger.logger;\n if (ttyPath || isPty) {\n legacyLogger.switchToConsoleLogger(levelFromArgv);\n }\n if (isSSE) {\n legacyLogger.switchToSSELogger(levelFromArgv);\n }\n }\n\n const currentBitFeatures = process.env.BIT_FEATURES;\n const shouldReloadFeatureToggle = currentBitFeatures !== envBitFeatures;\n if (shouldReloadFeatureToggle) {\n process.env.BIT_FEATURES = envBitFeatures;\n reloadFeatureToggle();\n }\n\n const randomNumber = Math.floor(Math.random() * 10000); // helps to distinguish between commands in the log\n const commandStr = command.join(' ');\n const cmdStrLog = `${randomNumber} ${commandStr}`;\n await this.apiForIDE.logStartCmdHistory(cmdStrLog);\n legacyLogger.isDaemon = true;\n enableChalk();\n const cliParser = new CLIParser(this.cli.commands, this.cli.groups, this.cli.onCommandStartSlot);\n try {\n const commandRunner = await cliParser.parse(command);\n const result = await commandRunner.runCommand(true);\n await this.apiForIDE.logFinishCmdHistory(cmdStrLog, 0);\n this.logger.clearStatusLine();\n res.json(result);\n } catch (err: any) {\n this.logger.clearStatusLine();\n if (err instanceof YargsExitWorkaround) {\n res.json({ data: err.helpMsg, exitCode: err.exitCode });\n } else {\n this.logger.error(`cli-raw server: got an error for ${commandStr}`, err);\n await this.apiForIDE.logFinishCmdHistory(cmdStrLog, 1);\n res.status(500);\n res.jsonp({\n message: err.message,\n error: err,\n });\n }\n } finally {\n // important! at this stage, don't write to stdout/stderr anymore, e.g. don't do \"this.logger.clearStatusLine()\"\n // because the socket (for pty) is already closed.\n if (ttyPath) {\n process.stdout.write = originalStdoutWrite;\n process.stderr.write = originalStderrWrite;\n if (fileHandle !== undefined) {\n try {\n await fs.close(fileHandle);\n } catch (err) {\n this.logger.debug(`cli-raw: failed to close tty fd: ${(err as Error).message}`);\n }\n }\n }\n if (isSSE) {\n delete process.env.BIT_CLI_SERVER_NO_TTY;\n loader.shouldSendServerEvents = false;\n }\n // change chalk back to false, otherwise, the IDE will have colors. (this is a global setting)\n chalk.level = 0;\n if (shouldReloadFeatureToggle) {\n process.env.BIT_FEATURES = currentBitFeatures;\n reloadFeatureToggle();\n }\n if (currentLogger) {\n legacyLogger.switchToLogger(currentLogger);\n }\n }\n },\n ];\n}\n\n/**\n * because this gets called from the express server, which gets spawn from a script, chalk defaults to false.\n * only when calling this route from the terminal, we want colors. on the IDE, we don't want colors.\n */\nfunction enableChalk() {\n chalk.level = 3;\n}\n"],"mappings":";;;;;;AACA,SAAAA,KAAA;EAAA,MAAAC,IAAA,GAAAC,OAAA;EAAAF,IAAA,YAAAA,CAAA;IAAA,OAAAC,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAE,SAAA;EAAA,MAAAF,IAAA,GAAAG,sBAAA,CAAAF,OAAA;EAAAC,QAAA,YAAAA,CAAA;IAAA,OAAAF,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAI,MAAA;EAAA,MAAAJ,IAAA,GAAAG,sBAAA,CAAAF,OAAA;EAAAG,KAAA,YAAAA,CAAA;IAAA,OAAAJ,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAK,KAAA;EAAA,MAAAL,IAAA,GAAAC,OAAA;EAAAI,IAAA,YAAAA,CAAA;IAAA,OAAAL,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAM,OAAA;EAAA,MAAAN,IAAA,GAAAG,sBAAA,CAAAF,OAAA;EAAAK,MAAA,YAAAA,CAAA;IAAA,OAAAN,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AAGA,SAAAO,QAAA;EAAA,MAAAP,IAAA,GAAAC,OAAA;EAAAM,OAAA,YAAAA,CAAA;IAAA,OAAAP,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAQ,gBAAA;EAAA,MAAAR,IAAA,GAAAC,OAAA;EAAAO,eAAA,YAAAA,CAAA;IAAA,OAAAR,IAAA;EAAA;EAAA,OAAAA,IAAA;AAAA;AACA,SAAAS,SAAA;EAAA,MAAAT,IAAA,GAAAC,OAAA;EAAAQ,QAAA,YAAAA,CAAA;IAAA,OAAAT,IAAA;EA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|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teambit/api-server",
|
|
3
|
-
"version": "0.0.0-
|
|
3
|
+
"version": "0.0.0-e9fcb4212e5da6ac2dabdf37b5d89f823cd9072c",
|
|
4
4
|
"homepage": "https://bit.cloud/teambit/harmony/api-server",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"componentId": {
|
|
7
7
|
"scope": "teambit.harmony",
|
|
8
8
|
"name": "api-server",
|
|
9
|
-
"version": "
|
|
9
|
+
"version": "e9fcb4212e5da6ac2dabdf37b5d89f823cd9072c"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"filenamify": "4.2.0",
|
|
@@ -15,57 +15,59 @@
|
|
|
15
15
|
"node-fetch": "2.6.7",
|
|
16
16
|
"p-map": "4.0.0",
|
|
17
17
|
"cors": "2.8.5",
|
|
18
|
+
"express": "^4.21.2",
|
|
18
19
|
"http-proxy-middleware": "^3.0.3",
|
|
19
20
|
"chalk": "4.1.2",
|
|
20
21
|
"pretty-time": "1.1.0",
|
|
21
|
-
"@teambit/component.modules.component-url": "0.0.
|
|
22
|
-
"@teambit/component.modules.merge-helper": "0.0.
|
|
23
|
-
"@teambit/config": "0.0.
|
|
22
|
+
"@teambit/component.modules.component-url": "0.0.195",
|
|
23
|
+
"@teambit/component.modules.merge-helper": "0.0.80",
|
|
24
|
+
"@teambit/config": "0.0.1527",
|
|
24
25
|
"@teambit/lane-id": "0.0.312",
|
|
25
|
-
"@teambit/lanes.modules.diff": "0.0.
|
|
26
|
-
"@teambit/legacy.consumer": "0.0.
|
|
27
|
-
"@teambit/legacy.scope": "0.0.
|
|
28
|
-
"@teambit/legacy.utils": "0.0.
|
|
29
|
-
"@teambit/logger": "0.0.
|
|
30
|
-
"@teambit/harmony": "0.4.
|
|
31
|
-
"@teambit/cli": "0.0.
|
|
32
|
-
"@teambit/express": "0.0.
|
|
33
|
-
"@teambit/harmony.modules.send-server-sent-events": "0.0.
|
|
34
|
-
"@teambit/legacy.constants": "0.0.
|
|
35
|
-
"@teambit/scope.network": "0.0.
|
|
36
|
-
"@teambit/toolbox.network.get-port": "1.0.
|
|
37
|
-
"@teambit/harmony.modules.feature-toggle": "0.0.
|
|
38
|
-
"@teambit/legacy.loader": "0.0.
|
|
39
|
-
"@teambit/legacy.logger": "0.0.
|
|
40
|
-
"@teambit/application": "0.0.0-
|
|
41
|
-
"@teambit/checkout": "0.0.0-
|
|
42
|
-
"@teambit/component-compare": "0.0.0-
|
|
43
|
-
"@teambit/component-log": "0.0.0-
|
|
44
|
-
"@teambit/component": "0.0.0-
|
|
45
|
-
"@teambit/deprecation": "0.0.0-
|
|
46
|
-
"@teambit/envs": "0.0.0-
|
|
47
|
-
"@teambit/export": "0.0.0-
|
|
48
|
-
"@teambit/generator": "0.0.0-
|
|
49
|
-
"@teambit/graph": "0.0.0-
|
|
50
|
-
"@teambit/install": "0.0.0-
|
|
51
|
-
"@teambit/lanes": "0.0.0-
|
|
52
|
-
"@teambit/objects": "0.0.0-
|
|
53
|
-
"@teambit/remove": "0.0.0-
|
|
54
|
-
"@teambit/schema": "0.0.0-
|
|
55
|
-
"@teambit/scope": "0.0.0-
|
|
56
|
-
"@teambit/snapping": "0.0.0-
|
|
57
|
-
"@teambit/workspace": "0.0.0-
|
|
58
|
-
"@teambit/importer": "0.0.0-
|
|
59
|
-
"@teambit/watcher": "0.0.0-
|
|
26
|
+
"@teambit/lanes.modules.diff": "0.0.642",
|
|
27
|
+
"@teambit/legacy.consumer": "0.0.137",
|
|
28
|
+
"@teambit/legacy.scope": "0.0.137",
|
|
29
|
+
"@teambit/legacy.utils": "0.0.42",
|
|
30
|
+
"@teambit/logger": "0.0.1445",
|
|
31
|
+
"@teambit/harmony": "0.4.12",
|
|
32
|
+
"@teambit/cli": "0.0.1352",
|
|
33
|
+
"@teambit/express": "0.0.1451",
|
|
34
|
+
"@teambit/harmony.modules.send-server-sent-events": "0.0.22",
|
|
35
|
+
"@teambit/legacy.constants": "0.0.34",
|
|
36
|
+
"@teambit/scope.network": "0.0.137",
|
|
37
|
+
"@teambit/toolbox.network.get-port": "1.0.23",
|
|
38
|
+
"@teambit/harmony.modules.feature-toggle": "0.0.46",
|
|
39
|
+
"@teambit/legacy.loader": "0.0.23",
|
|
40
|
+
"@teambit/legacy.logger": "0.0.49",
|
|
41
|
+
"@teambit/application": "0.0.0-a6aa6228ff391f7dcf772c888cedc367e2a433c6",
|
|
42
|
+
"@teambit/checkout": "0.0.0-a836ae47177591bbef6e0d7ee58dde6619654c2a",
|
|
43
|
+
"@teambit/component-compare": "0.0.0-69bd134efd8a9b5035ae972fb8dfa0080209b1f6",
|
|
44
|
+
"@teambit/component-log": "0.0.0-43bccf593834145e01da972e0123346ad4fa8a3e",
|
|
45
|
+
"@teambit/component": "0.0.0-d7567ca66ffe8a5ef80a490a2cb5231051c3eb29",
|
|
46
|
+
"@teambit/deprecation": "0.0.0-72ce3f08f50c5525c586fa778acf0e2812a0bf9e",
|
|
47
|
+
"@teambit/envs": "0.0.0-913d5038d0067bdc2b9291b6c08d0984eabd2306",
|
|
48
|
+
"@teambit/export": "0.0.0-202711d9a22a8c3dc6465ac467207cc6009e2671",
|
|
49
|
+
"@teambit/generator": "0.0.0-8e85aa9fa034cb232f27b9af80394295438dd56e",
|
|
50
|
+
"@teambit/graph": "0.0.0-14dcf301484583902f7775e46ad8d0a726b882ac",
|
|
51
|
+
"@teambit/install": "0.0.0-cf10758c1e7be8a72ec2bdebcc09c78fd83079ad",
|
|
52
|
+
"@teambit/lanes": "0.0.0-1080403b7119628789f6257ece943572b6f5c308",
|
|
53
|
+
"@teambit/objects": "0.0.0-56354df338dbd525897e5d24c2532a02ec39fdeb",
|
|
54
|
+
"@teambit/remove": "0.0.0-6de9cae7bf6d594809a48821a9635cb29d110c82",
|
|
55
|
+
"@teambit/schema": "0.0.0-e88157c3c93ecd5defce5227208b516e94cceb73",
|
|
56
|
+
"@teambit/scope": "0.0.0-788a1635af91cc1d8eb8175d57b8c775736bf601",
|
|
57
|
+
"@teambit/snapping": "0.0.0-d45b83ebd6bb93960403df716c2bff1055d758f0",
|
|
58
|
+
"@teambit/workspace": "0.0.0-fcb514e9be19280cf93171226ca0ced9483bacbf",
|
|
59
|
+
"@teambit/importer": "0.0.0-5cd8c7e7d0eb3e53989bc3d27474dfa762034a34",
|
|
60
|
+
"@teambit/watcher": "0.0.0-5b6d668aa7e798896a9e077ef748559c321573fe"
|
|
60
61
|
},
|
|
61
62
|
"devDependencies": {
|
|
62
63
|
"@types/fs-extra": "9.0.7",
|
|
63
64
|
"@types/lodash": "4.14.165",
|
|
64
65
|
"@types/node-fetch": "2.5.12",
|
|
65
66
|
"@types/cors": "2.8.10",
|
|
67
|
+
"@types/express": "^4.17.21",
|
|
66
68
|
"@types/pretty-time": "^1.1.5",
|
|
67
69
|
"@types/mocha": "9.1.0",
|
|
68
|
-
"@teambit/harmony.envs.core-aspect-env": "0.
|
|
70
|
+
"@teambit/harmony.envs.core-aspect-env": "1.0.0"
|
|
69
71
|
},
|
|
70
72
|
"peerDependencies": {},
|
|
71
73
|
"license": "Apache-2.0",
|
|
@@ -73,6 +75,7 @@
|
|
|
73
75
|
"peerDependenciesMeta": {},
|
|
74
76
|
"exports": {
|
|
75
77
|
".": {
|
|
78
|
+
"types": "./dist/index.d.ts",
|
|
76
79
|
"node": {
|
|
77
80
|
"require": "./dist/index.js",
|
|
78
81
|
"import": "./dist/esm.mjs"
|
|
@@ -80,8 +83,7 @@
|
|
|
80
83
|
"default": "./dist/index.js"
|
|
81
84
|
},
|
|
82
85
|
"./dist/*": "./dist/*",
|
|
83
|
-
"./artifacts/*": "./artifacts/*"
|
|
84
|
-
"./*": "./*.ts"
|
|
86
|
+
"./artifacts/*": "./artifacts/*"
|
|
85
87
|
},
|
|
86
88
|
"private": false,
|
|
87
89
|
"engines": {
|
package/types/style.d.ts
CHANGED
|
@@ -40,3 +40,7 @@ declare module '*.mdx' {
|
|
|
40
40
|
const component: any;
|
|
41
41
|
export default component;
|
|
42
42
|
}
|
|
43
|
+
|
|
44
|
+
// `reset-css` ships only `reset.css` (no `.d.ts`). TS6 refuses bare
|
|
45
|
+
// side-effect imports without declarations, so we declare the module here.
|
|
46
|
+
declare module 'reset-css';
|
|
File without changes
|