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
This commit is contained in:
2025-11-26 05:23:52 +00: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
进入home页面home页面的功能都需要登录后才能使用
点击插件后点击open进入home页面未登录时可以通过插件跳转到devstar网站登录后可以通过插件跳转到本地devstar个人主页
登录后,登录状态会长久保存,直到主动退出登录或者卸载插件。
@@ -14,26 +14,6 @@
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",
"displayName": "%displayName%",
"description": "%description%",
"version": "0.3.9",
"version": "0.4.1",
"keywords": [],
"publisher": "mengning",
"engines": {
@@ -136,4 +136,4 @@
"extensionDependencies": [
"ms-vscode.cpptools"
]
}
}

View File

@@ -43,31 +43,40 @@ export default class DevstarAPIHandler {
}
});
// 处理非200响应状态码
// 检查响应状态码
if (!response.ok) {
const text = await response.text(); // 读取文本防止json解析失败
if (response.status == 401) {
throw new Error('Token错误')
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} - ${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 data = responseData.data
if (data.username == undefined || data.username == "") {
throw new Error('Token对应用户不存在')
} else {
// 验证用户名匹配
if (data.username !== username) {
throw new Error('Token与用户名不符');
}
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
console.error(error);
return false;
}
}

View File

@@ -1,5 +1,6 @@
import * as vscode from 'vscode';
import * as os from 'os';
import * as path from 'path';
import RemoteContainer from './remote-container';
import User from './user';
import * as utils from './utils'
@@ -8,9 +9,7 @@ export default class DSHome {
private context: vscode.ExtensionContext;
private remoteContainer: RemoteContainer;
private user: User;
private devstarHomePageUrl: string;
private devstarDomain: string | undefined
private devstarDomain: string | undefined;
/**
* 配置项提供devstarDomain
@@ -33,38 +32,34 @@ export default class DSHome {
this.remoteContainer = new RemoteContainer(user);
if (devstarDomain != undefined && devstarDomain != "") {
this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain
this.devstarHomePageUrl = this.devstarDomain + "/devstar-home"
this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain;
} else {
const devstarDomainFromConfig = utils.devstarDomain()
const devstarDomainFromConfig = utils.devstarDomain();
if (devstarDomainFromConfig != undefined && devstarDomainFromConfig != "") {
this.devstarDomain = devstarDomainFromConfig.endsWith('/') ? devstarDomainFromConfig.slice(0, -1) : devstarDomainFromConfig
this.devstarHomePageUrl = this.devstarDomain + "/devstar-home"
this.devstarDomain = devstarDomainFromConfig.endsWith('/') ? devstarDomainFromConfig.slice(0, -1) : devstarDomainFromConfig;
} else {
this.devstarDomain = "https://devstar.cn"
this.devstarHomePageUrl = "https://devstar.cn/devstar-home"
this.devstarDomain = "https://devstar.cn";
}
}
}
setUser(user: User) {
this.user = user
this.user = user;
}
setRemoteContainer(remoteContainer: RemoteContainer) {
this.remoteContainer = remoteContainer
this.remoteContainer = remoteContainer;
}
setDevstarDomainAndHomePageURL(devstarDomain: string) {
if (devstarDomain != undefined && devstarDomain != "") {
this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain
this.devstarHomePageUrl = devstarDomain.endsWith('/') ? this.devstarDomain + "devstar-home" : devstarDomain + "/devstar-home"
this.devstarDomain = devstarDomain.endsWith('/') ? devstarDomain.slice(0, -1) : devstarDomain;
} 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(
'homeWebview',
vscode.l10n.t('Home'),
@@ -72,108 +67,34 @@ export default class DSHome {
{
enableScripts: 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(
async (message) => {
const data = message.data
const need_return = message.need_return
if (need_return) {
// ================= need return ====================
const data = message.data;
const need_return = message.need_return;
if (!need_return) {
switch (message.command) {
// ----------------- frequent -----------------------
case 'getHomeConfig':
const config = {
language: vscode.env.language
}
panel.webview.postMessage({ command: 'getHomeConfig', data: { homeConfig: config } })
break;
case 'getUserToken':
const userToken = this.user.getUserTokenFromLocal()
if (userToken === undefined) {
panel.webview.postMessage({ command: 'getUserToken', data: { userToken: '' } })
break;
case 'openExternalUrl':
const url = message.url || (data && data.url);
if (url) {
try {
await vscode.env.openExternal(vscode.Uri.parse(url));
vscode.window.showInformationMessage(`已在浏览器中打开: ${url}`);
} catch (error) {
vscode.window.showErrorMessage(`打开链接失败: ${url}`);
console.error('打开外部链接失败:', error);
}
} else {
panel.webview.postMessage({ command: 'getUserToken', data: { userToken: userToken } })
break;
console.error('openExternalUrl: url is undefined', message);
vscode.window.showErrorMessage('打开链接失败: 链接地址无效');
}
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 {
// ================= don't need return ==============
// frequent
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;
}
}
@@ -182,105 +103,233 @@ export default class DSHome {
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 `
<?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>
<html lang="en">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<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>
<body>
<div class="header">
${logoUri ? `<img src="${logoUri}" alt="DevStar Logo" class="logo">` : '🚀'}
<p>欢迎使用 DevStar 扩展</p>
</div>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DevStar Home</title>
</head>
<!-- 登录状态显示 -->
<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>
<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"
style="border: 0; left: 0; right: 0; bottom: 0; top: 0; position:absolute;">
</iframe>
<script>
const vscode = acquireVsCodeApi();
let isLoggedIn = false;
let username = '';
<script>
const vscode = acquireVsCodeApi();
function firstOpenRemoteFolder() {
vscode.postMessage({ command: 'firstOpenRemoteFolder', host: host, username: username, password: password, port: port, path: path });
}
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) {
return new Promise((resolve, reject) => {
// request to vscode
vscode.postMessage({ command: command, need_return: true, data: data })
function handleResponse(event) {
const jsonData = event.data;
if (jsonData.command === command) {
// console.log("communicateVSCode", jsonData.data)
// return vscode response
window.removeEventListener('message', handleResponse) // 清理监听器
resolve(jsonData.data)
}
}
window.addEventListener('message', handleResponse)
setTimeout(() => {
window.removeEventListener('message', handleResponse)
reject('timeout')
}, 5000); // 5秒超时
})
}
// 监听子页面的消息
window.addEventListener('message', async (event) => {
// 出于安全考虑,检查 event.origin 是否是你预期的源
// if (event.origin !== "http://expected-origin.com") {
// return;
// }
try {
const jsonData = event.data;
if (jsonData.target === 'vscode') {
const actionFromHome = jsonData.action
const dataFromHome = jsonData.data
const dataFromVSCodeResponse = await communicateVSCode(actionFromHome, dataFromHome)
var iframe = document.getElementById('embedded-devstar');
if (iframe && iframe.contentWindow) {
iframe.contentWindow.postMessage({ action: actionFromHome, data: dataFromVSCodeResponse }, '*')
}
} else if (jsonData.target === 'vscode_no_return') {
vscode.postMessage({ command: jsonData.action, need_return: false, data: jsonData.data })
}
} catch (error) {
console.error('Error parsing message:', error);
}
function vscodePostMessage(command, data) {
vscode.postMessage({
command: command,
need_return: false,
data: data
});
</script>
</body>
}
</html>`
async function communicateVSCode(command, data) {
return new Promise((resolve, reject) => {
vscode.postMessage({ command: command, need_return: true, data: data });
function handleResponse(event) {
const jsonData = event.data;
if (jsonData.command === command) {
window.removeEventListener('message', handleResponse);
resolve(jsonData.data);
}
}
window.addEventListener('message', handleResponse);
setTimeout(() => {
window.removeEventListener('message', handleResponse);
reject('timeout');
}, 5000);
});
}
// 检查登录状态
async function checkLoginStatus() {
try {
const userTokenResult = await communicateVSCode('getUserToken', {});
const usernameResult = await communicateVSCode('getUsername', {});
const userToken = userTokenResult.userToken;
username = usernameResult.username;
isLoggedIn = !!(userToken && userToken.trim() !== '' && username && username.trim() !== '');
updateUI();
} catch (error) {
console.error('检查登录状态失败:', error);
isLoggedIn = false;
updateUI();
}
}
// 更新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) {
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>
</body>
</html>`;
}
}
}

View File

@@ -4,7 +4,6 @@ import QuickAccessTreeProvider from './views/quick-access-tree';
import DSHome from './home';
import RemoteContainer, { openProjectWithoutLogging } from './remote-container';
import User from './user';
import DevstarAPIHandler from './devstar-api';
import * as os from 'os';
import * as utils from './utils';
@@ -67,7 +66,40 @@ export class DevStarExtension {
const path = params.get('path');
const accessToken = params.get('access_token');
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) {
const containerHost = host;
@@ -83,7 +115,6 @@ export class DevStarExtension {
this.dsHome.setDevstarDomainAndHomePageURL(devstarDomain)
this.dsHome.setUser(this.user)
this.dsHome.setRemoteContainer(this.remoteContainer)
vscode.commands.executeCommand('devstar.showHome');
// 将devstar domain存在global state中
context.globalState.update('devstarDomain', devstarDomain)
@@ -144,7 +175,6 @@ export class DevStarExtension {
this.dsHome.setDevstarDomainAndHomePageURL(devstarDomain)
this.dsHome.setUser(this.user)
this.dsHome.setRemoteContainer(this.remoteContainer)
vscode.commands.executeCommand('devstar.showHome');
// 将devstar domain存在global state中
context.globalState.update('devstarDomain', devstarDomain)
@@ -170,19 +200,15 @@ export class DevStarExtension {
this.registerGlobalCommands(context);
this.startDevStarHome();
}
async startDevStarHome() {
vscode.commands.executeCommand('devstar.showHome');
//防止进入HOME页面
// this.startDevStarHome();
}
registerGlobalCommands(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand('devstar.showHome', (url: string) =>
this.dsHome.toggle(url)
vscode.commands.registerCommand('devstar.showHome', () =>
this.dsHome.toggle()
),
vscode.commands.registerCommand('devstar.clean', () => {
// 先清除ssh key

View File

@@ -1,9 +1,12 @@
// remote-container.ts
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import * as vscode from 'vscode';
import * as rd from 'readline'
const { NodeSSH } = require('node-ssh')
import * as rd from 'readline';
const { NodeSSH } = require('node-ssh');
const { spawn } = require('child_process');
const net = require('net');
import * as utils from './utils';
import User from './user';
@@ -11,130 +14,142 @@ import DevstarAPIHandler from './devstar-api';
export default class RemoteContainer {
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) {
this.user = user
this.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) {
if (vscode.env.remoteName) {
// 远程环境
vscode.commands.executeCommand('workbench.action.terminal.newLocal').then(() => {
try {
await vscode.commands.executeCommand('workbench.action.terminal.newLocal');
const terminal = vscode.window.terminals[vscode.window.terminals.length - 1];
if (terminal) {
let devstarDomain: string | undefined = context.globalState.get("devstarDomain_" + vscode.env.sessionId)
if (devstarDomain == undefined || devstarDomain == "")
devstarDomain = undefined
let devstarDomain: string | undefined = context.globalState.get("devstarDomain_" + vscode.env.sessionId);
if (devstarDomain == undefined || devstarDomain == "") {
devstarDomain = undefined;
}
// vscode协议
// 根据系统+命令行版本确定命令
const semver = require('semver')
const powershellVersion = context.globalState.get('powershellVersion')
const powershell_semver_compatible_version = semver.coerce(powershellVersion)
const semver = require('semver');
const powershellVersion = context.globalState.get('powershellVersion');
const powershell_semver_compatible_version = semver.coerce(powershellVersion);
let command = '';
if (devstarDomain === undefined) {
// 不传递devstarDomain
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}"`)
else if (semver.satisfies(powershell_semver_compatible_version, ">=5.1.26100")) {
// 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}"`)
if (powershellVersion === undefined) {
command = `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")) {
command = `code --new-window ; code --% --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`;
} else {
// 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}"`)
command = `code --new-window && code --open-url "vscode://mengning.devstar/openProjectSkippingLoginCheck?host=${host}&hostname=${hostname}&port=${port}&username=${username}&path=${path}"`;
}
} else {
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}"`)
else if (semver.satisfies(powershell_semver_compatible_version, ">=5.1.26100")) {
// 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}&devstar_domain=${devstarDomain}"`)
if (powershellVersion === undefined) {
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")) {
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 {
// 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}&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 {
await this.firstConnect(host, hostname, username, port)
.then((res) => {
if (res === 'success') {
// only success then open folder
this.openRemoteFolder(host, port, username, path);
}
})
terminal.sendText(command);
} else {
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) => {
if (res === 'success') {
this.openRemoteFolder(host, port, username, path, context);
} 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第一次连接其他项目
* @param host 项目名称
* @param hostname ip
* @param username
* @param port
* @returns 成功返回success
*/
// connect with key
async firstConnect(host: string, hostname: string, username: string, port: number): Promise<string> {
return new Promise(async (resolve) => {
async firstConnect(host: string, hostname: string, _username: string, port: number, projectPath?: string): Promise<string> {
return new Promise(async (resolve, reject) => {
const ssh = new NodeSSH();
vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: vscode.l10n.t("Installing vscode-server and devstar extension in container"),
cancellable: false
}, async (progress) => {
try {
// 检查公私钥是否存在,如果不存在,需要创建
if (!this.user.existUserPrivateKey() || !this.user.existUserPublicKey()) {
await this.user.createUserSSHKey()
// 上传公钥
const devstarAPIHandler = new DevstarAPIHandler()
const uploadResult = await devstarAPIHandler.uploadUserPublicKey(this.user)
await this.user.createUserSSHKey();
const devstarAPIHandler = new DevstarAPIHandler();
const uploadResult = await devstarAPIHandler.uploadUserPublicKey(this.user);
if (uploadResult !== "ok") {
throw new Error('Upload public key failed.')
throw new Error('Upload public key failed.');
}
}
} catch (error) {
console.error("Failed to first connect container: ", error)
reject(error);
return;
}
// 本地环境
try {
// connect with key
await ssh.connect({
host: hostname,
username: username,
username: 'root',
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") });
// install vscode-server and devstar extension
const vscodeCommitId = await utils.getVsCodeCommitId()
if ("" != vscodeCommitId) {
const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz`
const vscodeCommitId = await utils.getVsCodeCommitId();
if ("" !== vscodeCommitId) {
const vscodeServerUrl = `https://vscode.download.prss.microsoft.com/dbazure/download/stable/${vscodeCommitId}/vscode-server-linux-x64.tar.gz`;
const installVscodeServerScript = `
mkdir -p ~/.vscode-server/bin/${vscodeCommitId} && \\
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
else
echo "Downloading and installing VSCode server"
wget ${vscodeServerUrl} -O vscode-server-linux-x64.tar.gz && \\
mv vscode-server-linux-x64.tar.gz ~/.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
fi
`;
await ssh.execCommand(installVscodeServerScript);
console.log("vscode-server and extension installed");
vscode.window.showInformationMessage(vscode.l10n.t('Installation completed!'));
const installResult = await ssh.execCommand(installVscodeServerScript);
if (installResult.code === 0) {
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();
// only connect successfully then save the host info
await this.storeProjectSSHInfo(host, hostname, port, username)
await this.storeProjectSSHInfo(host, hostname, port, 'root');
resolve('success')
resolve('success');
} catch (error) {
console.error('Failed to install vscode-server and extension: ', error);
await ssh.dispose();
try {
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连接信息
* @param host
* @param hostname
* @param port
* @param username
*/
async storeProjectSSHInfo(host: string, hostname: string, port: number, username: string): Promise<void> {
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)) {
var reader = rd.createInterface(fs.createReadStream(sshConfigPath))
const reader = rd.createInterface(fs.createReadStream(sshConfigPath));
for await (const line of reader) {
if (line.includes(`Host ${host}`)) {
// the container ssh info exists
canAppendSSHConfig = false
canAppendSSHConfig = false;
break;
}
}
}
if (canAppendSSHConfig) {
// save the host to the local ssh config file
const privateKeyPath = this.user.getUserPrivateKeyPath();
const newSShConfigContent =
`\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
*/
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`);
terminal.show(true);
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;
}
/**
* local env
* 仅支持已经成功连接并在ssh config file中存储ssh信息的项目连接。
*
* @host 表示project name
* 从 globalState 获取 forwardPorts 并建立端口映射
*/
openRemoteFolder(host: string, port: number, username: string, path: string): void {
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
terminal.show(true);
// 在原窗口打开
terminal.sendText(`code --remote ssh-remote+${username}@${host}:${port} ${path} --reuse-window`);
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> {
const command = `code --remote ssh-remote+${username}@${hostname}:${port} ${path} --reuse-window`
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
terminal.show(true);
terminal.sendText(command);
const command = `code --remote ssh-remote+${username}@${hostname}:${port} ${path} --reuse-window`;
try {
let terminal = vscode.window.activeTerminal || vscode.window.createTerminal(`Ext Terminal`);
terminal.show(true);
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';
const {
generateKeyPairSync,
createHash
} = require('node:crypto');
const sshpk = require('sshpk');
@@ -117,8 +116,8 @@ export default class User {
}
public async isLogged(): Promise<boolean> {
const username: string|undefined = this.context.globalState.get(this.usernameKey)
const userToken: string|undefined = this.context.globalState.get(this.userTokenKey)
const username: string | undefined = this.context.globalState.get(this.usernameKey)
const userToken: string | undefined = this.context.globalState.get(this.userTokenKey)
if ((username != undefined && username != '') && (userToken != undefined && userToken != '')) {
const devstarAPIHandler = new DevstarAPIHandler(this.devstarDomain)
@@ -172,7 +171,7 @@ export default class User {
if (!this.isLogged()) {
return '';
} else {
const username: string|undefined = this.context.globalState.get(this.usernameKey)
const username: string | undefined = this.context.globalState.get(this.usernameKey)
// islogged为trueusername不为空
return path.join(os.homedir(), '.ssh', `id_rsa_${username}_${this.devstarHostname}`)
}
@@ -182,7 +181,7 @@ export default class User {
if (!this.isLogged()) {
return '';
} else {
const username: string|undefined = this.context.globalState.get(this.usernameKey)
const username: string | undefined = this.context.globalState.get(this.usernameKey)
// islogged为trueusername不为空
return path.join(os.homedir(), '.ssh', `id_rsa_${username}_${this.devstarHostname}.pub`)
}
@@ -259,8 +258,55 @@ export default class User {
this.updateLocalUserPrivateKeyPath(this.getUserPrivateKeyPath())
console.log(`Update local user private key path.`)
} catch (error) {
const username: string|undefined = this.context.globalState.get(this.usernameKey)
const username: string | undefined = this.context.globalState.get(this.usernameKey)
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 os from 'os';
import { exec } from 'child_process';
import * as path from 'path';
const {
generateKeyPairSync,

View File

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