21 Commits
v0.3.9 ... main

Author SHA1 Message Date
deee8f378f Merge pull request 'feature-open-with-vscode' (#1) from feature-open-with-vscode into main
Some checks failed
CI/CD Pipeline for DevStar Extension / build (push) Failing after 4m31s
Reviewed-on: #1
2025-11-26 05:23:52 +00:00
559c9eba27 移除工作流安装git
All checks were successful
CI/CD Pipeline for DevStar Extension / build (pull_request) Successful in 3m41s
2025-11-26 11:51:59 +08:00
fc59ba3bd0 移除自动创建版本标签
Some checks failed
CI/CD Pipeline for DevStar Extension / build (pull_request) Has been cancelled
2025-11-26 11:45:41 +08:00
b33384ca23 删除不必要代码&&修改工作流文件
Some checks failed
CI/CD Pipeline for DevStar Extension / build (pull_request) Has been cancelled
2025-11-26 11:04:05 +08:00
325fc8f4bd 实现点击open with vscode传递端口进行端口映射
Some checks failed
CI/CD Pipeline for DevStar Extension / build (pull_request) Failing after 2m28s
2025-11-25 15:41:51 +08:00
53d875e7ca 删除掉remote-container.ts中的一些调试信息 2025-11-18 17:36:29 +08:00
bdbae6eeb1 工作流镜像修改&&添加发布插件条件限制 2025-11-18 16:28:58 +08:00
728959c6b3 修改webpack 2025-11-18 15:28:20 +08:00
8f76f80938 将构建和发布合在一个阶段,并修改了命令 2025-11-18 14:44:02 +08:00
3c87a57c26 移除上传构建产物 2025-11-18 14:19:54 +08:00
ef67c1bb2c 添加工作流文件 2025-11-18 14:04:48 +08:00
515ab4ff91 已经完成随机端口号映射 2025-11-14 15:25:14 +08:00
4c2da46260 删除了README.en.md文件并更新了README.md 2025-11-13 15:02:22 +08:00
adc822729c 登录后可以跳转到用户首页 2025-11-11 14:44:28 +08:00
754d66e1d9 将logo替换成devstar的logo 2025-11-11 05:23:43 +00:00
6e8b0c0544 可以实现跳转到devstar 2025-11-10 11:51:55 +00:00
24df60ca16 修改HOME页面 2025-11-10 08:45:19 +00:00
ab2c05711b 直接ssh进入容器并且移除自动进入HOME页面 2025-11-10 13:58:45 +08:00
7e33976d51 移除从open with vscode后自动进入home页面 2025-11-03 15:21:06 +08:00
ece4943d2a 修改ssh连接时用户为root 2025-11-03 14:04:59 +08:00
7367d3cf37 remote-container.ts调试信息更加健全 2025-11-03 13:44:18 +08:00
12 changed files with 763 additions and 402 deletions

View File

@@ -0,0 +1,34 @@
name: CI/CD Pipeline for DevStar Extension
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
container:
image: node:20-alpine
steps:
- name: 拉取代码
uses: https://devstar.cn/actions/checkout@v4
with:
fetch-depth: 0
- name: 安装依赖
run: |
npm install
- name: 构建插件
run: |
npm run package
- name: 发布插件
if: gitea.event_name == 'push' && gitea.ref == 'refs/heads/main'
run: |
npm run publish
env:
VSCE_PAT: ${{ secrets.VSCE_PAT }}

View File

@@ -1,36 +0,0 @@
# DevStar
#### Description
Super IDE Client for VS Code
#### Software Architecture
Software architecture description
#### Installation
1. xxxx
2. xxxx
3. xxxx
#### Instructions
1. xxxx
2. xxxx
3. xxxx
#### Contribution
1. Fork the repository
2. Create Feat_xxx branch
3. Commit your code
4. Create Pull Request
#### Gitee Feature
1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
4. The most valuable open source project [GVP](https://gitee.com/gvp)
5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)

View File

@@ -2,7 +2,7 @@
## User Quick Start ## User Quick Start
进入home页面home页面的功能都需要登录后才能使用 点击插件后点击open进入home页面未登录时可以通过插件跳转到devstar网站登录后可以通过插件跳转到本地devstar个人主页
登录后,登录状态会长久保存,直到主动退出登录或者卸载插件。 登录后,登录状态会长久保存,直到主动退出登录或者卸载插件。
@@ -14,26 +14,6 @@
1配置修改后重启vscode才能生效 1配置修改后重启vscode才能生效
### 创建新仓库/创建新项目
目前可供选择的字段
- name* 必填
- default_branch
- description
- gitignores
- issue_labels
- license
- object_format_name
- private
- readme
- template
- trust_model
### 打开项目
打开项目是指在vscode上打开远程容器中创建好的项目。选择项目名称右侧对应的Open project即可打开项目。
### 编译/调试 ### 编译/调试
容器环境提供了开发环境,安装好编译与调试所需要的工具链。 容器环境提供了开发环境,安装好编译与调试所需要的工具链。

BIN
assets/images/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 68 KiB

View File

@@ -2,7 +2,7 @@
"name": "devstar", "name": "devstar",
"displayName": "%displayName%", "displayName": "%displayName%",
"description": "%description%", "description": "%description%",
"version": "0.3.9", "version": "0.4.1",
"keywords": [], "keywords": [],
"publisher": "mengning", "publisher": "mengning",
"engines": { "engines": {

View File

@@ -43,31 +43,40 @@ export default class DevstarAPIHandler {
} }
}); });
// 处理非200响应状态码 // 检查响应状态码
if (!response.ok) { if (!response.ok) {
const text = await response.text(); // 读取文本防止json解析失败 const text = await response.text(); // 读取文本内容以便调试
if (response.status == 401) { console.error(`HTTP Error: ${response.status} - ${text}`);
throw new Error('Token错误') if (response.status === 401) {
throw new Error('Token错误');
} else { } else {
throw new Error(`HTTP Error: ${response.status} - ${text}`); throw new Error(`HTTP Error: ${response.status}`);
} }
} }
// 检查 Content-Type 是否为 JSON
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.includes('application/json')) {
const text = await response.text(); // 读取文本内容以便调试
console.error(`Unexpected Content-Type: ${contentType} - ${text}`);
throw new Error(`Unexpected Content-Type: ${contentType}`);
}
const responseData = await response.json(); const responseData = await response.json();
const data = responseData.data const data = responseData.data;
if (data.username == undefined || data.username == "") { if (!data || !data.username) {
throw new Error('Token对应用户不存在') throw new Error('Token对应用户不存在');
} else { }
// 验证用户名匹配 // 验证用户名匹配
if (data.username !== username) { if (data.username !== username) {
throw new Error('Token与用户名不符'); throw new Error('Token与用户名不符');
} }
}
return true; return true;
} catch (error) { } catch (error) {
console.error(error) console.error(error);
return false return false;
} }
} }

View File

@@ -1,5 +1,6 @@
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import * as os from 'os'; import * as os from 'os';
import * as path from 'path';
import RemoteContainer from './remote-container'; import RemoteContainer from './remote-container';
import User from './user'; import User from './user';
import * as utils from './utils' import * as utils from './utils'
@@ -8,9 +9,7 @@ export default class DSHome {
private context: vscode.ExtensionContext; private context: vscode.ExtensionContext;
private remoteContainer: RemoteContainer; private remoteContainer: RemoteContainer;
private user: User; private user: User;
private devstarHomePageUrl: string; private devstarDomain: string | undefined;
private devstarDomain: string | undefined
/** /**
* 配置项提供devstarDomain * 配置项提供devstarDomain
@@ -33,38 +32,34 @@ export default class DSHome {
this.remoteContainer = new RemoteContainer(user); this.remoteContainer = new RemoteContainer(user);
if (devstarDomain != undefined && devstarDomain != "") { if (devstarDomain != undefined && devstarDomain != "") {
this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain;
this.devstarHomePageUrl = this.devstarDomain + "/devstar-home"
} else { } else {
const devstarDomainFromConfig = utils.devstarDomain() const devstarDomainFromConfig = utils.devstarDomain();
if (devstarDomainFromConfig != undefined && devstarDomainFromConfig != "") { if (devstarDomainFromConfig != undefined && devstarDomainFromConfig != "") {
this.devstarDomain = devstarDomainFromConfig.endsWith('/') ? devstarDomainFromConfig.slice(0, -1) : devstarDomainFromConfig this.devstarDomain = devstarDomainFromConfig.endsWith('/') ? devstarDomainFromConfig.slice(0, -1) : devstarDomainFromConfig;
this.devstarHomePageUrl = this.devstarDomain + "/devstar-home"
} else { } else {
this.devstarDomain = "https://devstar.cn" this.devstarDomain = "https://devstar.cn";
this.devstarHomePageUrl = "https://devstar.cn/devstar-home"
} }
} }
} }
setUser(user: User) { setUser(user: User) {
this.user = user this.user = user;
} }
setRemoteContainer(remoteContainer: RemoteContainer) { setRemoteContainer(remoteContainer: RemoteContainer) {
this.remoteContainer = remoteContainer this.remoteContainer = remoteContainer;
} }
setDevstarDomainAndHomePageURL(devstarDomain: string) { setDevstarDomainAndHomePageURL(devstarDomain: string) {
if (devstarDomain != undefined && devstarDomain != "") { if (devstarDomain != undefined && devstarDomain != "") {
this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain;
this.devstarHomePageUrl = devstarDomain.endsWith('/') ? this.devstarDomain + "devstar-home" : devstarDomain + "/devstar-home"
} else { } else {
console.error("devstarDomain is undefined or null") console.error("devstarDomain is undefined or null");
} }
} }
async toggle(devstarHomePageUrl: string = this.devstarHomePageUrl) { async toggle() {
const panel = vscode.window.createWebviewPanel( const panel = vscode.window.createWebviewPanel(
'homeWebview', 'homeWebview',
vscode.l10n.t('Home'), vscode.l10n.t('Home'),
@@ -72,108 +67,34 @@ export default class DSHome {
{ {
enableScripts: true, enableScripts: true,
retainContextWhenHidden: true, retainContextWhenHidden: true,
localResourceRoots: [
vscode.Uri.file(path.join(this.context.extensionPath, 'assets'))
]
} }
); );
panel.webview.html = await this.getWebviewContent(devstarHomePageUrl); panel.webview.html = await this.getWebviewContent(panel);
panel.webview.onDidReceiveMessage( panel.webview.onDidReceiveMessage(
async (message) => { async (message) => {
const data = message.data const data = message.data;
const need_return = message.need_return const need_return = message.need_return;
if (need_return) { if (!need_return) {
// ================= need return ====================
switch (message.command) { switch (message.command) {
// ----------------- frequent ----------------------- case 'openExternalUrl':
case 'getHomeConfig': const url = message.url || (data && data.url);
const config = { if (url) {
language: vscode.env.language try {
} await vscode.env.openExternal(vscode.Uri.parse(url));
panel.webview.postMessage({ command: 'getHomeConfig', data: { homeConfig: config } }) vscode.window.showInformationMessage(`已在浏览器中打开: ${url}`);
break; } catch (error) {
case 'getUserToken': vscode.window.showErrorMessage(`打开链接失败: ${url}`);
const userToken = this.user.getUserTokenFromLocal() console.error('打开外部链接失败:', error);
if (userToken === undefined) {
panel.webview.postMessage({ command: 'getUserToken', data: { userToken: '' } })
break;
} else {
panel.webview.postMessage({ command: 'getUserToken', data: { userToken: userToken } })
break;
}
case 'getUsername':
const username = this.user.getUsernameFromLocal()
if (username === undefined) {
panel.webview.postMessage({ command: 'getUsername', data: { username: '' } })
break;
} else {
panel.webview.postMessage({ command: 'getUsername', data: { username: username } })
break;
}
case 'firstOpenRemoteFolder':
// data.host - project name
await this.remoteContainer.firstOpenProject(data.host, data.hostname, data.port, data.username, data.path, this.context)
break;
case 'openRemoteFolder':
this.remoteContainer.openRemoteFolder(data.host, data.port, data.username, data.path);
break;
case 'getDevstarDomain':
panel.webview.postMessage({ command: 'getDevstarDomain', data: { devstarDomain: this.devstarDomain } })
break;
// ----------------- not frequent -----------------------
case 'setUserToken':
this.user.setUserTokenToLocal(data.userToken)
if (data.userToken === this.user.getUserTokenFromLocal()) {
panel.webview.postMessage({ command: 'setUserToken', data: { ok: true } })
break;
} else {
panel.webview.postMessage({ command: 'setUserToken', data: { ok: false } })
break;
}
case 'setUsername':
this.user.setUsernameToLocal(data.username);
if (data.username === this.user.getUsernameFromLocal()) {
panel.webview.postMessage({ command: 'setUsername', data: { ok: true } });
break;
} else {
panel.webview.postMessage({ command: 'setUsername', data: { ok: false } });
break;
}
case 'getUserPublicKey':
var userPublicKey = '';
if (this.user.existUserPrivateKey()) {
userPublicKey = this.user.getUserPublicKey();
panel.webview.postMessage({ command: 'getUserPublicKey', data: { userPublicKey: userPublicKey } })
break;
} else {
panel.webview.postMessage({ command: 'getUserPublicKey', data: { userPublicKey: userPublicKey } })
break;
}
case 'createUserPublicKey':
await this.user.createUserSSHKey();
if (this.user.existUserPublicKey()) {
panel.webview.postMessage({ command: 'createUserPublicKey', data: { ok: true } })
break;
} else {
panel.webview.postMessage({ command: 'createUserPublicKey', data: { ok: false } })
break;
}
case 'getMachineName':
const machineName = os.hostname();
panel.webview.postMessage({ command: 'getMachineName', data: { machineName: machineName } })
} }
} else { } else {
// ================= don't need return ============== console.error('openExternalUrl: url is undefined', message);
// frequent vscode.window.showErrorMessage('打开链接失败: 链接地址无效');
switch (message.command) { }
// ----------------- frequent -----------------------
case 'showInformationNotification':
vscode.window.showInformationMessage(data.message);
break;
case 'showWarningNotification':
vscode.window.showWarningMessage(data.message)
break;
case 'showErrorNotification':
await utils.showErrorNotification(data.message)
break; break;
} }
} }
@@ -182,105 +103,233 @@ export default class DSHome {
this.context.subscriptions this.context.subscriptions
); );
this.context.subscriptions.push(panel) this.context.subscriptions.push(panel);
} }
async getWebviewContent(panel?: vscode.WebviewPanel): Promise<string> {
// 获取图片的 Webview URI
let logoUri = '';
if (panel) {
const logoPath = vscode.Uri.file(
path.join(this.context.extensionPath, 'assets', 'images', 'logo.png')
);
logoUri = panel.webview.asWebviewUri(logoPath).toString();
}
async getWebviewContent(devstarHomePageUrl: string): Promise<string> {
return ` return `
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DevStar Home</title> <title>DevStar Home</title>
<style>
body {
margin: 0;
padding: 20px;
font-family: var(--vscode-font-family);
background-color: var(--vscode-editor-background);
color: var(--vscode-editor-foreground);
}
.header {
text-align: center;
margin-bottom: 30px;
}
.logo {
width: auto;
height: 30px;
margin-bottom: 16px;
}
.feature-list {
list-style: none;
padding: 0;
}
.feature-item {
padding: 10px;
margin: 10px 0;
background-color: var(--vscode-button-background);
border-radius: 4px;
cursor: pointer;
text-align: center;
}
.feature-item:hover {
background-color: var(--vscode-button-hoverBackground);
}
.login-status {
padding: 10px;
margin: 10px 0;
border-radius: 4px;
text-align: center;
}
.logged-in {
background-color: var(--vscode-inputValidation-infoBackground);
border: 1px solid var(--vscode-inputValidation-infoBorder);
}
.logged-out {
background-color: var(--vscode-inputValidation-warningBackground);
border: 1px solid var(--vscode-inputValidation-warningBorder);
}
.hidden {
display: none;
}
</style>
</head> </head>
<body> <body>
<iframe id="embedded-devstar" src="${devstarHomePageUrl}" sandbox="allow-popups allow-same-origin allow-scripts allow-forms allow-top-navigation-by-user-activation" width="100%" height="100%" frameborder="0" <div class="header">
style="border: 0; left: 0; right: 0; bottom: 0; top: 0; position:absolute;"> ${logoUri ? `<img src="${logoUri}" alt="DevStar Logo" class="logo">` : '🚀'}
</iframe> <p>欢迎使用 DevStar 扩展</p>
</div>
<!-- 登录状态显示 -->
<div id="loginStatus" class="login-status hidden">
<span id="statusText"></span>
<span id="usernameDisplay"></span>
</div>
<ul class="feature-list">
<li class="feature-item" onclick="handleMainAction()" id="mainActionButton">
主要功能
</li>
</ul>
<script> <script>
const vscode = acquireVsCodeApi(); const vscode = acquireVsCodeApi();
let isLoggedIn = false;
let username = '';
function firstOpenRemoteFolder() { function vscodePostMessage(command, data) {
vscode.postMessage({ command: 'firstOpenRemoteFolder', host: host, username: username, password: password, port: port, path: path }); vscode.postMessage({
command: command,
need_return: false,
data: data
});
} }
function openRemoteFolder() {
vscode.postMessage({ command: 'openRemoteFolder', host: host, path: path });
}
function firstOpenRemoteFolderWithData(host, username, password, port, path) {
vscode.postMessage({ command: 'firstOpenRemoteFolder', host: host, username: username, password: password, port: port, path: path });
}
function openRemoteFolderWithData(host, path) {
vscode.postMessage({ command: 'openRemoteFolder', host: host, path: path });
}
async function communicateVSCode(command, data) { async function communicateVSCode(command, data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
// request to vscode vscode.postMessage({ command: command, need_return: true, data: data });
vscode.postMessage({ command: command, need_return: true, data: data })
function handleResponse(event) { function handleResponse(event) {
const jsonData = event.data; const jsonData = event.data;
if (jsonData.command === command) { if (jsonData.command === command) {
// console.log("communicateVSCode", jsonData.data) window.removeEventListener('message', handleResponse);
resolve(jsonData.data);
// return vscode response
window.removeEventListener('message', handleResponse) // 清理监听器
resolve(jsonData.data)
} }
} }
window.addEventListener('message', handleResponse) window.addEventListener('message', handleResponse);
setTimeout(() => { setTimeout(() => {
window.removeEventListener('message', handleResponse) window.removeEventListener('message', handleResponse);
reject('timeout') reject('timeout');
}, 5000); // 5秒超时 }, 5000);
}) });
} }
// 监听子页面的消息 // 检查登录状态
window.addEventListener('message', async (event) => { async function checkLoginStatus() {
// 出于安全考虑,检查 event.origin 是否是你预期的源
// if (event.origin !== "http://expected-origin.com") {
// return;
// }
try { try {
const jsonData = event.data; const userTokenResult = await communicateVSCode('getUserToken', {});
const usernameResult = await communicateVSCode('getUsername', {});
if (jsonData.target === 'vscode') { const userToken = userTokenResult.userToken;
const actionFromHome = jsonData.action username = usernameResult.username;
const dataFromHome = jsonData.data
const dataFromVSCodeResponse = await communicateVSCode(actionFromHome, dataFromHome)
var iframe = document.getElementById('embedded-devstar'); isLoggedIn = !!(userToken && userToken.trim() !== '' && username && username.trim() !== '');
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage({ action: actionFromHome, data: dataFromVSCodeResponse }, '*') updateUI();
} catch (error) {
console.error('检查登录状态失败:', error);
isLoggedIn = false;
updateUI();
} }
} else if (jsonData.target === 'vscode_no_return') { }
vscode.postMessage({ command: jsonData.action, need_return: false, data: jsonData.data })
// 更新UI显示
function updateUI() {
const loginStatus = document.getElementById('loginStatus');
const statusText = document.getElementById('statusText');
const usernameDisplay = document.getElementById('usernameDisplay');
const mainActionButton = document.getElementById('mainActionButton');
loginStatus.classList.remove('hidden');
if (isLoggedIn) {
loginStatus.classList.remove('logged-out');
loginStatus.classList.add('logged-in');
statusText.textContent = '已登录';
usernameDisplay.textContent = username ? ' - 用户: ' + username : '';
mainActionButton.textContent = '跳转到个人主页';
} else {
loginStatus.classList.remove('logged-in');
loginStatus.classList.add('logged-out');
statusText.textContent = '未登录';
usernameDisplay.textContent = '';
mainActionButton.textContent = '跳转到 DevStar 官网';
}
}
// 处理主要功能点击 - 修复消息发送格式
function handleMainAction() {
if (isLoggedIn) {
// 已登录:跳转到 hostname/username
// 使用 async 函数处理异步操作
(async () => {
try {
// 获取必要的用户信息
const devstarDomainResult = await communicateVSCode('getDevstarDomain', {});
const usernameResult = await communicateVSCode('getUsername', {});
const devstarDomain = devstarDomainResult.devstarDomain;
const username = usernameResult.username;
if (devstarDomain && username) {
const targetUrl = \`\${devstarDomain}/\${username}\`;
vscodePostMessage('showInformationNotification', {
message: \`跳转到 \${targetUrl}\`
});
vscode.postMessage({
command: 'openExternalUrl',
need_return: false,
url: targetUrl
});
} else {
vscodePostMessage('showErrorNotification', {
message: '无法获取域名或用户名信息'
});
} }
} catch (error) { } catch (error) {
console.error('Error parsing message:', error); console.error('跳转失败:', error);
} vscodePostMessage('showErrorNotification', {
message: '跳转失败,请重试'
}); });
}
})();
} else {
// 未登录:跳转到 DevStar 官网
vscodePostMessage('showInformationNotification', {message: '跳转到 DevStar 官网'});
vscode.postMessage({
command: 'openExternalUrl',
need_return: false,
url: 'https://devstar.cn'
});
}
}
// 页面加载时检查登录状态
window.addEventListener('load', async () => {
await checkLoginStatus();
});
// 可选:添加重新检查登录状态的功能
function refreshLoginStatus() {
checkLoginStatus();
vscodePostMessage('showInformationNotification', {message: '登录状态已刷新'});
}
</script> </script>
</body> </body>
</html>`;
</html>`
} }
} }

View File

@@ -4,7 +4,6 @@ import QuickAccessTreeProvider from './views/quick-access-tree';
import DSHome from './home'; import DSHome from './home';
import RemoteContainer, { openProjectWithoutLogging } from './remote-container'; import RemoteContainer, { openProjectWithoutLogging } from './remote-container';
import User from './user'; import User from './user';
import DevstarAPIHandler from './devstar-api';
import * as os from 'os'; import * as os from 'os';
import * as utils from './utils'; import * as utils from './utils';
@@ -67,7 +66,40 @@ export class DevStarExtension {
const path = params.get('path'); const path = params.get('path');
const accessToken = params.get('access_token'); const accessToken = params.get('access_token');
const devstarUsername = params.get('devstar_username'); const devstarUsername = params.get('devstar_username');
const devstarDomain = params.get('devstar_domain'); const rawDevstarDomain = params.get('devstar_domain');
let devstarDomain = rawDevstarDomain;
if (rawDevstarDomain) {
try {
const url = new URL(rawDevstarDomain);
devstarDomain = `${url.protocol}//${url.hostname}`;
// 从 rawDevstarDomain 的查询参数中提取 forwardPorts
const forwardPortsParam = url.searchParams.get('forwardPorts');
if (forwardPortsParam) {
const ports = forwardPortsParam.split(',').map(port => parseInt(port, 10)).filter(port => !isNaN(port));
console.log('解析到的 forwardPorts 参数:', ports);
context.globalState.update('forwardPorts', ports);
} else {
// 如果没有 forwardPorts 参数,清除 globalState 中的旧值
console.log('未找到 forwardPorts 参数,清除旧的 forwardPorts 配置');
context.globalState.update('forwardPorts', undefined);
}
} catch (error) {
console.error('Invalid devstar_domain URL:', error);
}
}
console.log('sanitized_devstar_domain:', devstarDomain);
// 使用修正后的 devstar_domain
if (devstarDomain) {
this.user.setDevstarDomain(devstarDomain);
this.remoteContainer.setUser(this.user);
this.dsHome.setDevstarDomainAndHomePageURL(devstarDomain);
this.dsHome.setUser(this.user);
this.dsHome.setRemoteContainer(this.remoteContainer);
context.globalState.update('devstarDomain', devstarDomain);
}
if (host && hostname && port && username && path) { if (host && hostname && port && username && path) {
const containerHost = host; const containerHost = host;
@@ -83,7 +115,6 @@ export class DevStarExtension {
this.dsHome.setDevstarDomainAndHomePageURL(devstarDomain) this.dsHome.setDevstarDomainAndHomePageURL(devstarDomain)
this.dsHome.setUser(this.user) this.dsHome.setUser(this.user)
this.dsHome.setRemoteContainer(this.remoteContainer) this.dsHome.setRemoteContainer(this.remoteContainer)
vscode.commands.executeCommand('devstar.showHome');
// 将devstar domain存在global state中 // 将devstar domain存在global state中
context.globalState.update('devstarDomain', devstarDomain) context.globalState.update('devstarDomain', devstarDomain)
@@ -144,7 +175,6 @@ export class DevStarExtension {
this.dsHome.setDevstarDomainAndHomePageURL(devstarDomain) this.dsHome.setDevstarDomainAndHomePageURL(devstarDomain)
this.dsHome.setUser(this.user) this.dsHome.setUser(this.user)
this.dsHome.setRemoteContainer(this.remoteContainer) this.dsHome.setRemoteContainer(this.remoteContainer)
vscode.commands.executeCommand('devstar.showHome');
// 将devstar domain存在global state中 // 将devstar domain存在global state中
context.globalState.update('devstarDomain', devstarDomain) context.globalState.update('devstarDomain', devstarDomain)
@@ -170,19 +200,15 @@ export class DevStarExtension {
this.registerGlobalCommands(context); this.registerGlobalCommands(context);
this.startDevStarHome(); //防止进入HOME页面
} // this.startDevStarHome();
async startDevStarHome() {
vscode.commands.executeCommand('devstar.showHome');
} }
registerGlobalCommands(context: vscode.ExtensionContext) { registerGlobalCommands(context: vscode.ExtensionContext) {
context.subscriptions.push( context.subscriptions.push(
vscode.commands.registerCommand('devstar.showHome', (url: string) => vscode.commands.registerCommand('devstar.showHome', () =>
this.dsHome.toggle(url) this.dsHome.toggle()
), ),
vscode.commands.registerCommand('devstar.clean', () => { vscode.commands.registerCommand('devstar.clean', () => {
// 先清除ssh key // 先清除ssh key

View File

@@ -1,9 +1,12 @@
// remote-container.ts
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
import * as os from 'os'; import * as os from 'os';
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import * as rd from 'readline' import * as rd from 'readline';
const { NodeSSH } = require('node-ssh') const { NodeSSH } = require('node-ssh');
const { spawn } = require('child_process');
const net = require('net');
import * as utils from './utils'; import * as utils from './utils';
import User from './user'; import User from './user';
@@ -11,130 +14,142 @@ import DevstarAPIHandler from './devstar-api';
export default class RemoteContainer { export default class RemoteContainer {
private user: User; private user: User;
private sshProcesses?: Map<string, any>;
private portMappings: Map<string, Array<{ containerPort: number, localPort: number, label: string, source: string }>> = new Map();
constructor(user: User) { constructor(user: User) {
this.user = user this.user = user;
} }
public setUser(user: User) { public setUser(user: User) {
this.user = user this.user = user;
} }
/** /**
* 第一次打开远程项目 * 第一次打开远程项目
*
* 远程环境先创建local窗口在通过命令行调用url打开目前仅支持vscode协议
* @param host 项目名称
* @param hostname ip
* @param port
* @param username
* @param path
* @param context 用于支持远程项目环境
*/ */
async firstOpenProject(host: string, hostname: string, port: number, username: string, path: string, context: vscode.ExtensionContext) { async firstOpenProject(host: string, hostname: string, port: number, username: string, path: string, context: vscode.ExtensionContext) {
if (vscode.env.remoteName) { if (vscode.env.remoteName) {
// 远程环境 try {
vscode.commands.executeCommand('workbench.action.terminal.newLocal').then(() => { await vscode.commands.executeCommand('workbench.action.terminal.newLocal');
const terminal = vscode.window.terminals[vscode.window.terminals.length - 1]; const terminal = vscode.window.terminals[vscode.window.terminals.length - 1];
if (terminal) { if (terminal) {
let devstarDomain: string | undefined = context.globalState.get("devstarDomain_" + vscode.env.sessionId) let devstarDomain: string | undefined = context.globalState.get("devstarDomain_" + vscode.env.sessionId);
if (devstarDomain == undefined || devstarDomain == "") if (devstarDomain == undefined || devstarDomain == "") {
devstarDomain = undefined devstarDomain = undefined;
}
// vscode协议 const semver = require('semver');
// 根据系统+命令行版本确定命令 const powershellVersion = context.globalState.get('powershellVersion');
const semver = require('semver') const powershell_semver_compatible_version = semver.coerce(powershellVersion);
const powershellVersion = context.globalState.get('powershellVersion')
const powershell_semver_compatible_version = semver.coerce(powershellVersion)
let command = '';
if (devstarDomain === undefined) { if (devstarDomain === undefined) {
// 不传递devstarDomain if (powershellVersion === undefined) {
if (powershellVersion === undefined) command = `code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`;
terminal.sendText(`code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`) } else if (semver.satisfies(powershell_semver_compatible_version, ">=5.1.26100")) {
else if (semver.satisfies(powershell_semver_compatible_version, ">=5.1.26100")) { command = `code --new-window ; code --% --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`;
// win & powershell >= 5.1.26100.0
terminal.sendText(`code --new-window ; code --% --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`)
} else { } else {
// win & powershell < 5.1.26100.0 command = `code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`;
terminal.sendText(`code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`)
} }
} else { } else {
if (powershellVersion === undefined) if (powershellVersion === undefined) {
terminal.sendText(`code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`) command = `code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`;
else if (semver.satisfies(powershell_semver_compatible_version, ">=5.1.26100")) { } else if (semver.satisfies(powershell_semver_compatible_version, ">=5.1.26100")) {
// win & powershell >= 5.1.26100.0 command = `code --new-window ; code --% --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`;
terminal.sendText(`code --new-window ; code --% --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`)
} else { } else {
// win & powershell < 5.1.26100.0 command = `code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`;
terminal.sendText(`code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}&devstar_domain=${devstarDomain}"`)
} }
} }
}
}) terminal.sendText(command);
} else { } else {
await this.firstConnect(host, hostname, username, port) vscode.window.showErrorMessage('无法创建终端,请检查终端是否可用。');
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : '未知错误';
vscode.window.showErrorMessage(`远程环境操作失败: ${errorMessage}`);
}
} else {
try {
await this.firstConnect(host, hostname, username, port, path)
.then((res) => { .then((res) => {
if (res === 'success') { if (res === 'success') {
// only success then open folder this.openRemoteFolder(host, port, username, path, context);
this.openRemoteFolder(host, port, username, path); } else {
vscode.window.showErrorMessage('首次连接容器失败,请检查网络和容器状态。');
} }
}) })
.catch(error => {
const errorMessage = error instanceof Error ? error.message : '未知错误';
vscode.window.showErrorMessage(`首次连接容器时发生错误: ${errorMessage}`);
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : '未知错误';
vscode.window.showErrorMessage(`打开项目失败: ${errorMessage}`);
}
} }
} }
/** /**
* local environment第一次连接其他项目 * local environment第一次连接其他项目
* @param host 项目名称
* @param hostname ip
* @param username
* @param port
* @returns 成功返回success
*/ */
// connect with key async firstConnect(host: string, hostname: string, _username: string, port: number, projectPath?: string): Promise<string> {
async firstConnect(host: string, hostname: string, username: string, port: number): Promise<string> { return new Promise(async (resolve, reject) => {
return new Promise(async (resolve) => {
const ssh = new NodeSSH(); const ssh = new NodeSSH();
vscode.window.withProgress({ vscode.window.withProgress({
location: vscode.ProgressLocation.Notification, location: vscode.ProgressLocation.Notification,
title: vscode.l10n.t("Installing vscode-server and devstar extension in container"), title: vscode.l10n.t("Installing vscode-server and devstar extension in container"),
cancellable: false cancellable: false
}, async (progress) => { }, async (progress) => {
try { try {
// 检查公私钥是否存在,如果不存在,需要创建
if (!this.user.existUserPrivateKey() || !this.user.existUserPublicKey()) { if (!this.user.existUserPrivateKey() || !this.user.existUserPublicKey()) {
await this.user.createUserSSHKey() await this.user.createUserSSHKey();
// 上传公钥
const devstarAPIHandler = new DevstarAPIHandler() const devstarAPIHandler = new DevstarAPIHandler();
const uploadResult = await devstarAPIHandler.uploadUserPublicKey(this.user) const uploadResult = await devstarAPIHandler.uploadUserPublicKey(this.user);
if (uploadResult !== "ok") { if (uploadResult !== "ok") {
throw new Error('Upload public key failed.') throw new Error('Upload public key failed.');
} }
} }
} catch (error) { } catch (error) {
console.error("Failed to first connect container: ", error) reject(error);
return;
} }
// 本地环境
try { try {
// connect with key
await ssh.connect({ await ssh.connect({
host: hostname, host: hostname,
username: username, username: 'root',
port: port, port: port,
privateKeyPath: this.user.getUserPrivateKeyPath() privateKeyPath: this.user.getUserPrivateKeyPath(),
readyTimeout: 30000,
onKeyboardInteractive: (
_name: string,
_instructions: string,
_instructionsLang: string,
_prompts: any[],
finish: (responses: string[]) => void
) => {
finish([]);
}
}); });
progress.report({ message: vscode.l10n.t("Connected! Start installation") }); progress.report({ message: vscode.l10n.t("Connected! Start installation") });
// install vscode-server and devstar extension const vscodeCommitId = await utils.getVsCodeCommitId();
const vscodeCommitId = await utils.getVsCodeCommitId()
if ("" != vscodeCommitId) { if ("" !== vscodeCommitId) {
const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz` const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz`;
const installVscodeServerScript = ` const installVscodeServerScript = `
mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\ mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\
if [ "$(ls -A ~/.vscode-server/bin/${vscodeCommitId})" ]; then if [ "$(ls -A ~/.vscode-server/bin/${vscodeCommitId})" ]; then
echo "VSCode server already exists, installing extension only"
~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar ~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar
else else
echo "Downloading and installing VSCode server"
wget ${vscodeServerUrl} -O vscode-server-linux-x64.tar.gz && \\ wget ${vscodeServerUrl} -O vscode-server-linux-x64.tar.gz && \\
mv vscode-server-linux-x64.tar.gz ~/.vscode-server/bin/${vscodeCommitId} && \\ mv vscode-server-linux-x64.tar.gz ~/.vscode-server/bin/${vscodeCommitId} && \\
cd ~/.vscode-server/bin/${vscodeCommitId} && \\ cd ~/.vscode-server/bin/${vscodeCommitId} && \\
@@ -143,84 +158,318 @@ export default class RemoteContainer {
~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar ~/.vscode-server/bin/${vscodeCommitId}/bin/code-server --install-extension mengning.devstar
fi fi
`; `;
await ssh.execCommand(installVscodeServerScript);
console.log("vscode-server and extension installed"); const installResult = await ssh.execCommand(installVscodeServerScript);
if (installResult.code === 0) {
vscode.window.showInformationMessage(vscode.l10n.t('Installation completed!')); vscode.window.showInformationMessage(vscode.l10n.t('Installation completed!'));
} else {
throw new Error(`Installation failed with exit code ${installResult.code}: ${installResult.stderr}`);
}
} else {
throw new Error('Failed to get VSCode commit ID');
}
if (projectPath) {
} }
await ssh.dispose(); await ssh.dispose();
// only connect successfully then save the host info await this.storeProjectSSHInfo(host, hostname, port, 'root');
await this.storeProjectSSHInfo(host, hostname, port, username)
resolve('success') resolve('success');
} catch (error) { } catch (error) {
console.error('Failed to install vscode-server and extension: ', error); try {
await ssh.dispose(); await ssh.dispose();
} catch (disposeError) {
}
reject(error);
} }
}); });
}); });
} }
/**
* 查找可用的本地端口 - 优先使用相同端口
*/
private async findAvailableLocalPort(containerPort: number): Promise<number> {
if (await this.isPortAvailable(containerPort)) {
return containerPort;
}
for (let offset = 1; offset <= 10; offset++) {
const port1 = containerPort + offset;
if (port1 < 65536 && await this.isPortAvailable(port1)) {
return port1;
}
const port2 = containerPort - offset;
if (port2 > 0 && await this.isPortAvailable(port2)) {
return port2;
}
}
return this.findRandomAvailablePort();
}
/**
* 检查端口是否可用
*/
private async isPortAvailable(port: number): Promise<boolean> {
return new Promise((resolve) => {
const server = net.createServer();
server.unref();
server.on('error', () => {
resolve(false);
});
server.listen(port, () => {
server.close(() => {
resolve(true);
});
});
});
}
/**
* 查找随机可用端口
*/
private async findRandomAvailablePort(): Promise<number> {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on('error', reject);
server.listen(0, () => {
const port = server.address().port;
server.close(() => {
resolve(port);
});
});
});
}
/**
* 创建 SSH 端口转发
*/
private async createSSHPortForward(hostname: string, sshPort: number, containerPort: number, localPort: number): Promise<void> {
return new Promise((resolve, reject) => {
const sshArgs = [
'-N',
'-L',
`${localPort}:localhost:${containerPort}`,
'-o', 'StrictHostKeyChecking=no',
'-o', 'UserKnownHostsFile=/dev/null',
'-p', sshPort.toString(),
'-i', this.user.getUserPrivateKeyPath(),
`root@${hostname}`
];
const sshProcess = spawn('ssh', sshArgs);
sshProcess.on('error', (error: Error) => {
reject(error);
});
sshProcess.stdout.on('data', (_data: Buffer) => {
});
sshProcess.stderr.on('data', (_data: Buffer) => {
});
if (!this.sshProcesses) {
this.sshProcesses = new Map();
}
const key = `${hostname}:${sshPort}:${containerPort}`;
this.sshProcesses.set(key, sshProcess);
setTimeout(() => {
resolve();
}, 2000);
});
}
/**
* 显示端口映射汇总信息
*/
private showPortMappingsSummary(portMappings: Array<{ containerPort: number, localPort: number, label: string, source: string }>): void {
let message = `🎯 已建立 ${portMappings.length} 个端口映射:\n\n`;
portMappings.forEach(mapping => {
const samePort = mapping.containerPort === mapping.localPort ? " ✅" : " 🔄";
message += `${mapping.label}\n`;
message += ` 容器端口: ${mapping.containerPort} → 本地端口: ${mapping.localPort}${samePort}\n`;
message += ` 访问地址: http://localhost:${mapping.localPort}\n`;
message += ` 配置来源: ${mapping.source}\n\n`;
});
vscode.window.showInformationMessage(message, '复制映射信息', '在浏览器中打开', '查看详细信息')
.then(selection => {
if (selection === '复制映射信息') {
const copyText = portMappings.map(m =>
`${m.label}: http://localhost:${m.localPort} (容器端口: ${m.containerPort})`
).join('\n');
vscode.env.clipboard.writeText(copyText);
vscode.window.showInformationMessage('端口映射信息已复制到剪贴板');
} else if (selection === '在浏览器中打开' && portMappings.length > 0) {
vscode.env.openExternal(vscode.Uri.parse(`http://localhost:${portMappings[0].localPort}`));
} else if (selection === '查看详细信息') {
}
});
}
/** /**
* 本地环境保存项目的ssh连接信息 * 本地环境保存项目的ssh连接信息
* @param host
* @param hostname
* @param port
* @param username
*/ */
async storeProjectSSHInfo(host: string, hostname: string, port: number, username: string): Promise<void> { async storeProjectSSHInfo(host: string, hostname: string, port: number, username: string): Promise<void> {
const sshConfigPath = path.join(os.homedir(), '.ssh', 'config'); const sshConfigPath = path.join(os.homedir(), '.ssh', 'config');
// check if the host and related info exist in local ssh config file before saving
var canAppendSSHConfig = true let canAppendSSHConfig = true;
if (fs.existsSync(sshConfigPath)) { if (fs.existsSync(sshConfigPath)) {
var reader = rd.createInterface(fs.createReadStream(sshConfigPath)) const reader = rd.createInterface(fs.createReadStream(sshConfigPath));
for await (const line of reader) { for await (const line of reader) {
if (line.includes(`Host ${host}`)) { if (line.includes(`Host ${host}`)) {
// the container ssh info exists canAppendSSHConfig = false;
canAppendSSHConfig = false
break; break;
} }
} }
} }
if (canAppendSSHConfig) { if (canAppendSSHConfig) {
// save the host to the local ssh config file
const privateKeyPath = this.user.getUserPrivateKeyPath(); const privateKeyPath = this.user.getUserPrivateKeyPath();
const newSShConfigContent = const newSShConfigContent =
`\nHost ${host}\n HostName ${hostname}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ${privateKeyPath}\n `; `\nHost ${host}\n HostName ${hostname}\n Port ${port}\n User ${username}\n PreferredAuthentications publickey\n IdentityFile ${privateKeyPath}\n `;
fs.writeFileSync(sshConfigPath, newSShConfigContent, { encoding: 'utf8', flag: 'a' });
console.log('Host registered in local ssh config');
}
}
try {
fs.writeFileSync(sshConfigPath, newSShConfigContent, { encoding: 'utf8', flag: 'a' });
} catch (error) {
throw error;
}
}
}
/** /**
* local env * local env
* 仅支持已经成功连接并在ssh config file中存储ssh信息的项目连接。
*
* @host 表示project name
*/ */
openRemoteFolder(host: string, port: number, username: string, path: string): void { async openRemoteFolder(host: string, port: number, _username: string, path: string, context: vscode.ExtensionContext): Promise<void> {
try {
const sshConfig = await this.getSSHConfig(host);
if (sshConfig) {
try {
// 调用 setupPortForwardingFromGlobalState 方法
await this.setupPortForwardingFromGlobalState(sshConfig.hostname, port, context);
} catch (portError) {
vscode.window.showWarningMessage('端口映射设置失败,但容器连接已建立');
}
}
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`); let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
terminal.show(true); terminal.show(true);
// 在原窗口打开
terminal.sendText(`code --remote ssh-remote+${username}@${host}:${port} ${path} --reuse-window`); const command = `code --remote ssh-remote+root@${host}:${port} ${path} --reuse-window`;
terminal.sendText(command);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : '未知错误';
vscode.window.showErrorMessage(`打开远程文件夹失败: ${errorMessage}`);
} }
} }
/**
* 从 SSH config 获取主机配置
*/
private async getSSHConfig(host: string): Promise<{ hostname: string; port: number } | null> {
const sshConfigPath = path.join(os.homedir(), '.ssh', 'config');
if (!fs.existsSync(sshConfigPath)) {
return null;
}
const configContent = fs.readFileSync(sshConfigPath, 'utf8');
const lines = configContent.split('\n');
let currentHost = '';
let hostname = '';
let port = 22;
for (const line of lines) {
const trimmed = line.trim();
if (trimmed.startsWith('Host ')) {
currentHost = trimmed.substring(5).trim();
} else if (currentHost === host) {
if (trimmed.startsWith('HostName ')) {
hostname = trimmed.substring(9).trim();
} else if (trimmed.startsWith('Port ')) {
port = parseInt(trimmed.substring(5).trim());
}
}
if (hostname && currentHost === host) {
return { hostname, port };
}
}
return null;
}
/**
* 从 globalState 获取 forwardPorts 并建立端口映射
*/
public async setupPortForwardingFromGlobalState(hostname: string, port: number, context: vscode.ExtensionContext): Promise<void> {
// 从 globalState 获取 forwardPorts 参数
const forwardPorts: number[] | undefined = context.globalState.get('forwardPorts');
if (forwardPorts && forwardPorts.length > 0) {
const portMappings: Array<{ containerPort: number, localPort: number, label: string, source: string }> = [];
for (const containerPort of forwardPorts) {
const localPort = await this.findAvailableLocalPort(containerPort);
try {
await this.createSSHPortForward(hostname, port, containerPort, localPort);
portMappings.push({
containerPort,
localPort,
label: `Port ${containerPort}`,
source: 'globalState forwardPorts'
});
} catch (error) {
console.error(`映射容器端口 ${containerPort} 到本地端口 ${localPort} 失败:`, error);
}
}
const mappingKey = `${hostname}:${port}`;
this.portMappings.set(mappingKey, portMappings);
if (portMappings.length > 0) {
this.showPortMappingsSummary(portMappings);
}
// 使用完毕后立即清除 globalState 中的 forwardPorts避免影响下一个项目
console.log('端口映射完成,清除 globalState 中的 forwardPorts');
context.globalState.update('forwardPorts', undefined);
} else {
console.log('未找到 forwardPorts 参数,跳过端口映射设置。');
}
}
}
/** /**
* 打开项目(无须插件登录) * 打开项目(无须插件登录)
* @param hostname 表示ip
* @param port
* @param username
* @param path
*/ */
export async function openProjectWithoutLogging(hostname: string, port: number, username: string, path: string): Promise<void> { export async function openProjectWithoutLogging(hostname: string, port: number, username: string, path: string): Promise<void> {
const command = `code --remote ssh-remote+${username}@${hostname}:${port} ${path} --reuse-window` const command = `code --remote ssh-remote+${username}@${hostname}:${port} ${path} --reuse-window`;
try {
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`); let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
terminal.show(true); terminal.show(true);
terminal.sendText(command); terminal.sendText(command);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : '未知错误';
vscode.window.showErrorMessage(`无登录打开项目失败: ${errorMessage}`);
}
} }

View File

@@ -6,7 +6,6 @@ import DevstarAPIHandler from './devstar-api';
import * as utils from './utils'; import * as utils from './utils';
const { const {
generateKeyPairSync, generateKeyPairSync,
createHash
} = require('node:crypto'); } = require('node:crypto');
const sshpk = require('sshpk'); const sshpk = require('sshpk');
@@ -263,4 +262,51 @@ export default class User {
console.error(`Failed to write public/private key into the user(${username}) ssh public/key file: `, error); console.error(`Failed to write public/private key into the user(${username}) ssh public/key file: `, error);
} }
} }
public async verifyToken(token: string, username: string): Promise<boolean> {
try {
const response = await fetch(this.devstarDomain + `/api/devcontainer/user`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'token ' + token
}
});
// 检查响应状态码
if (!response.ok) {
const text = await response.text(); // 读取文本内容以便调试
console.error(`HTTP Error: ${response.status} - ${text}`);
if (response.status === 401) {
throw new Error('Token错误');
} else {
throw new Error(`HTTP Error: ${response.status}`);
}
}
// 检查 Content-Type 是否为 JSON
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.includes('application/json')) {
const text = await response.text(); // 读取文本内容以便调试
console.error(`Unexpected Content-Type: ${contentType} - ${text}`);
throw new Error(`Unexpected Content-Type: ${contentType}`);
}
const responseData = await response.json();
const data = responseData.data;
if (!data || !data.username) {
throw new Error('Token对应用户不存在');
}
// 验证用户名匹配
if (data.username !== username) {
throw new Error('Token与用户名不符');
}
return true;
} catch (error) {
console.error(error);
return false;
}
}
} }

View File

@@ -3,7 +3,6 @@ import * as https from 'https';
import * as vscode from 'vscode'; import * as vscode from 'vscode';
import * as os from 'os'; import * as os from 'os';
import { exec } from 'child_process'; import { exec } from 'child_process';
import * as path from 'path';
const { const {
generateKeyPairSync, generateKeyPairSync,

View File

@@ -28,5 +28,10 @@ module.exports = {
resolve: { resolve: {
modules: [path.resolve('./node_modules'), path.resolve('./src')], modules: [path.resolve('./node_modules'), path.resolve('./src')],
extensions: ['.ts', '.js'] extensions: ['.ts', '.js']
},
node: {
__dirname: false,
__filename: false,
global: false
} }
}; };