@workskills/getskill 1.1.8 → 1.1.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/EXAMPLES.md +4 -1
- package/README.md +371 -260
- package/dist/lib/config.d.ts +10 -0
- package/dist/lib/config.js +47 -0
- package/dist/lib/logger.d.ts +7 -0
- package/dist/lib/logger.js +38 -0
- package/dist/lib/network.d.ts +5 -0
- package/dist/lib/network.js +215 -0
- package/dist/lib/publish-registry.d.ts +15 -0
- package/dist/lib/publish-registry.js +334 -0
- package/dist/lib/skill-manager.d.ts +10 -0
- package/dist/lib/skill-manager.js +278 -0
- package/dist/lib/skill-validator.d.ts +4 -0
- package/dist/lib/skill-validator.js +107 -0
- package/dist/lib/state.d.ts +18 -0
- package/dist/lib/state.js +256 -0
- package/dist/lib/system.d.ts +17 -0
- package/dist/lib/system.js +307 -0
- package/dist/lib/types.d.ts +150 -0
- package/dist/lib/types.js +2 -0
- package/dist/main.d.ts +10 -0
- package/dist/main.js +381 -0
- package/package.json +82 -58
- package/index.js +0 -1057
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.MAX_COPY_FILE_SIZE_BYTES = exports.REQUEST_TIMEOUT_MS = void 0;
|
|
7
|
+
exports.setBaseUrl = setBaseUrl;
|
|
8
|
+
exports.getBaseUrl = getBaseUrl;
|
|
9
|
+
exports.getOpenClawRootDirectory = getOpenClawRootDirectory;
|
|
10
|
+
exports.getSkillsDirectory = getSkillsDirectory;
|
|
11
|
+
exports.getSkillsCacheDirectory = getSkillsCacheDirectory;
|
|
12
|
+
exports.getGetSkillConfigDirectory = getGetSkillConfigDirectory;
|
|
13
|
+
exports.getStateFilePath = getStateFilePath;
|
|
14
|
+
exports.getAuthFilePath = getAuthFilePath;
|
|
15
|
+
const os_1 = __importDefault(require("os"));
|
|
16
|
+
const path_1 = __importDefault(require("path"));
|
|
17
|
+
let baseUrl = process.env.GETSKILL_BASE_URL || 'https://getskill.work';
|
|
18
|
+
exports.REQUEST_TIMEOUT_MS = 60000;
|
|
19
|
+
exports.MAX_COPY_FILE_SIZE_BYTES = 2 * 1024 * 1024;
|
|
20
|
+
function setBaseUrl(url) {
|
|
21
|
+
if (!url || typeof url !== 'string') {
|
|
22
|
+
throw new Error('BASE_URL 必须是有效字符串');
|
|
23
|
+
}
|
|
24
|
+
baseUrl = url.replace(/\/$/, '');
|
|
25
|
+
return baseUrl;
|
|
26
|
+
}
|
|
27
|
+
function getBaseUrl() {
|
|
28
|
+
return baseUrl;
|
|
29
|
+
}
|
|
30
|
+
function getOpenClawRootDirectory() {
|
|
31
|
+
return path_1.default.join(os_1.default.homedir(), '.openclaw');
|
|
32
|
+
}
|
|
33
|
+
function getSkillsDirectory() {
|
|
34
|
+
return path_1.default.join(getOpenClawRootDirectory(), 'skills');
|
|
35
|
+
}
|
|
36
|
+
function getSkillsCacheDirectory() {
|
|
37
|
+
return path_1.default.join(getOpenClawRootDirectory(), 'skills-cache');
|
|
38
|
+
}
|
|
39
|
+
function getGetSkillConfigDirectory() {
|
|
40
|
+
return path_1.default.join(getOpenClawRootDirectory(), 'getskill');
|
|
41
|
+
}
|
|
42
|
+
function getStateFilePath() {
|
|
43
|
+
return path_1.default.join(getGetSkillConfigDirectory(), 'state.json');
|
|
44
|
+
}
|
|
45
|
+
function getAuthFilePath() {
|
|
46
|
+
return path_1.default.join(getGetSkillConfigDirectory(), 'auth.json');
|
|
47
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.logger = void 0;
|
|
4
|
+
const LEVELS = {
|
|
5
|
+
silent: 0,
|
|
6
|
+
error: 1,
|
|
7
|
+
warn: 2,
|
|
8
|
+
info: 3,
|
|
9
|
+
debug: 4
|
|
10
|
+
};
|
|
11
|
+
function getCurrentLevel() {
|
|
12
|
+
const value = (process.env.GETSKILL_LOG_LEVEL || 'info').toLowerCase();
|
|
13
|
+
return LEVELS[value] ?? LEVELS.info;
|
|
14
|
+
}
|
|
15
|
+
function shouldLog(level) {
|
|
16
|
+
return LEVELS[level] <= getCurrentLevel();
|
|
17
|
+
}
|
|
18
|
+
function write(level, ...args) {
|
|
19
|
+
if (!shouldLog(level)) {
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
if (level === 'error') {
|
|
23
|
+
console.error(...args);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (level === 'warn') {
|
|
27
|
+
console.warn(...args);
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
console.log(...args);
|
|
31
|
+
}
|
|
32
|
+
exports.logger = {
|
|
33
|
+
error: (...args) => write('error', ...args),
|
|
34
|
+
warn: (...args) => write('warn', ...args),
|
|
35
|
+
info: (...args) => write('info', ...args),
|
|
36
|
+
debug: (...args) => write('debug', ...args)
|
|
37
|
+
};
|
|
38
|
+
exports.default = exports.logger;
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { RequestOptions, RequestResponse, SearchApiPayload, SearchOptions, SearchSkill } from './types';
|
|
2
|
+
export declare function request(url: string, options?: RequestOptions, redirectCount?: number): Promise<RequestResponse>;
|
|
3
|
+
export declare function repositoryHasSkillFile(repoFullName: string): Promise<boolean>;
|
|
4
|
+
export declare function transformSearchResults(result: SearchApiPayload, hasSkillFile?: (repoFullName: string) => Promise<boolean>): Promise<SearchSkill[]>;
|
|
5
|
+
export declare function searchSkills(keyword: string, options?: SearchOptions): Promise<SearchSkill[]>;
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.request = request;
|
|
7
|
+
exports.repositoryHasSkillFile = repositoryHasSkillFile;
|
|
8
|
+
exports.transformSearchResults = transformSearchResults;
|
|
9
|
+
exports.searchSkills = searchSkills;
|
|
10
|
+
const http_1 = __importDefault(require("http"));
|
|
11
|
+
const https_1 = __importDefault(require("https"));
|
|
12
|
+
const config_1 = require("./config");
|
|
13
|
+
const logger_1 = __importDefault(require("./logger"));
|
|
14
|
+
function request(url, options = {}, redirectCount = 0) {
|
|
15
|
+
const MAX_REDIRECTS = 5;
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
if (redirectCount >= MAX_REDIRECTS) {
|
|
18
|
+
reject(new Error(`Too many redirects (${MAX_REDIRECTS})`));
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
let urlObj;
|
|
22
|
+
try {
|
|
23
|
+
urlObj = new URL(url);
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
reject(new Error(`Invalid URL: ${url}`));
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const protocol = urlObj.protocol === 'https:' ? https_1.default : http_1.default;
|
|
30
|
+
const reqOptions = {
|
|
31
|
+
hostname: urlObj.hostname,
|
|
32
|
+
port: urlObj.port,
|
|
33
|
+
path: urlObj.pathname + urlObj.search,
|
|
34
|
+
method: options.method || 'GET',
|
|
35
|
+
headers: options.headers || {},
|
|
36
|
+
timeout: options.timeout || config_1.REQUEST_TIMEOUT_MS
|
|
37
|
+
};
|
|
38
|
+
const req = protocol.request(reqOptions, (res) => {
|
|
39
|
+
const statusCode = res.statusCode ?? 0;
|
|
40
|
+
if (options.followRedirects !== false &&
|
|
41
|
+
[301, 302, 303, 307, 308].includes(statusCode)) {
|
|
42
|
+
const locationHeader = res.headers.location;
|
|
43
|
+
const redirectUrl = Array.isArray(locationHeader)
|
|
44
|
+
? locationHeader[0]
|
|
45
|
+
: locationHeader;
|
|
46
|
+
if (!redirectUrl) {
|
|
47
|
+
reject(new Error(`Redirect location header missing (${statusCode})`));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
let newUrl;
|
|
51
|
+
try {
|
|
52
|
+
newUrl = new URL(redirectUrl, url).toString();
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
reject(new Error(`Invalid redirect URL: ${redirectUrl}`));
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
request(newUrl, options, redirectCount + 1)
|
|
59
|
+
.then(resolve)
|
|
60
|
+
.catch(reject);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
let data = '';
|
|
64
|
+
res.on('data', (chunk) => {
|
|
65
|
+
data += chunk.toString();
|
|
66
|
+
});
|
|
67
|
+
res.on('end', () => {
|
|
68
|
+
if ((statusCode >= 200 && statusCode < 300) ||
|
|
69
|
+
options.allowNonSuccessStatus) {
|
|
70
|
+
resolve({
|
|
71
|
+
statusCode,
|
|
72
|
+
headers: res.headers,
|
|
73
|
+
body: data
|
|
74
|
+
});
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
reject(new Error(`Request failed with status code ${statusCode}: ${data.substring(0, 200)}`));
|
|
78
|
+
});
|
|
79
|
+
res.on('error', (error) => {
|
|
80
|
+
reject(new Error(`Response error: ${error.message}`));
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
req.on('error', (error) => {
|
|
84
|
+
if (error.code === 'ECONNREFUSED') {
|
|
85
|
+
reject(new Error(`Connection refused: ${urlObj.hostname}`));
|
|
86
|
+
}
|
|
87
|
+
else if (error.code === 'ENOTFOUND') {
|
|
88
|
+
reject(new Error(`Host not found: ${urlObj.hostname}`));
|
|
89
|
+
}
|
|
90
|
+
else if (error.code === 'ETIMEDOUT' ||
|
|
91
|
+
error.code === 'ESOCKETTIMEDOUT') {
|
|
92
|
+
reject(new Error(`Request timeout: ${url}`));
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
reject(new Error(`Network error: ${error.message}`));
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
req.on('timeout', () => {
|
|
99
|
+
req.destroy();
|
|
100
|
+
reject(new Error(`Request timeout after ${reqOptions.timeout}ms`));
|
|
101
|
+
});
|
|
102
|
+
if (options.body) {
|
|
103
|
+
req.write(options.body);
|
|
104
|
+
}
|
|
105
|
+
req.end();
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
function mapRepositoryCandidate(item) {
|
|
109
|
+
if ('repository' in item && item.repository) {
|
|
110
|
+
return item.repository;
|
|
111
|
+
}
|
|
112
|
+
return item;
|
|
113
|
+
}
|
|
114
|
+
async function repositoryHasSkillFile(repoFullName) {
|
|
115
|
+
if (!repoFullName ||
|
|
116
|
+
typeof repoFullName !== 'string' ||
|
|
117
|
+
!repoFullName.includes('/')) {
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
const segments = repoFullName.split('/');
|
|
121
|
+
const owner = segments.shift();
|
|
122
|
+
const repo = segments.join('/');
|
|
123
|
+
if (!owner || !repo) {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
const url = `${(0, config_1.getBaseUrl)()}/api/v1/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/contents/SKILL.md`;
|
|
127
|
+
try {
|
|
128
|
+
await request(url, { timeout: Math.min(config_1.REQUEST_TIMEOUT_MS, 15000) });
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
async function transformSearchResults(result, hasSkillFile = repositoryHasSkillFile) {
|
|
136
|
+
if (!result || result.ok === false || !Array.isArray(result.data)) {
|
|
137
|
+
return [];
|
|
138
|
+
}
|
|
139
|
+
const filteredCandidates = result.data
|
|
140
|
+
.map(mapRepositoryCandidate)
|
|
141
|
+
.filter((item) => Boolean(item && (item.full_name || item.name)))
|
|
142
|
+
.filter((item) => !item.private &&
|
|
143
|
+
!item.empty &&
|
|
144
|
+
!item.archived &&
|
|
145
|
+
!item.template &&
|
|
146
|
+
!item.fork);
|
|
147
|
+
const skillChecks = await Promise.all(filteredCandidates.map(async (item) => {
|
|
148
|
+
const repoFullName = item.full_name || item.name || '';
|
|
149
|
+
const hasSkill = await hasSkillFile(repoFullName);
|
|
150
|
+
if (!hasSkill) {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
name: item.full_name || item.name || '',
|
|
155
|
+
full_name: item.full_name || '',
|
|
156
|
+
description: item.description || '',
|
|
157
|
+
html_url: item.html_url || '',
|
|
158
|
+
git_url: item.clone_url ||
|
|
159
|
+
(item.html_url ? `${item.html_url}.git` : ''),
|
|
160
|
+
clone_url: item.clone_url || ''
|
|
161
|
+
};
|
|
162
|
+
}));
|
|
163
|
+
return skillChecks.filter((item) => Boolean(item));
|
|
164
|
+
}
|
|
165
|
+
async function searchSkills(keyword, options = {}) {
|
|
166
|
+
if (!keyword || typeof keyword !== 'string') {
|
|
167
|
+
logger_1.default.error('搜索失败: 关键词无效');
|
|
168
|
+
return [];
|
|
169
|
+
}
|
|
170
|
+
const { sort = 'updated', order = 'desc', page = 1, limit = 20 } = options;
|
|
171
|
+
const fixedSearchParams = [
|
|
172
|
+
'private=false',
|
|
173
|
+
'is_private=false',
|
|
174
|
+
'archived=false',
|
|
175
|
+
'template=false'
|
|
176
|
+
].join('&');
|
|
177
|
+
const url = `${(0, config_1.getBaseUrl)()}/api/v1/repos/search?q=${encodeURIComponent(keyword)}&${fixedSearchParams}&sort=${sort}&order=${order}&page=${page}&limit=${limit}`;
|
|
178
|
+
try {
|
|
179
|
+
const response = await request(url, { timeout: config_1.REQUEST_TIMEOUT_MS });
|
|
180
|
+
if (!response.body || response.body.trim() === '') {
|
|
181
|
+
logger_1.default.warn('搜索警告: 服务器返回空响应');
|
|
182
|
+
return [];
|
|
183
|
+
}
|
|
184
|
+
let parsed;
|
|
185
|
+
try {
|
|
186
|
+
parsed = JSON.parse(response.body);
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
190
|
+
logger_1.default.error('搜索失败: JSON 解析错误', message);
|
|
191
|
+
logger_1.default.debug('响应内容:', response.body.substring(0, 200));
|
|
192
|
+
return [];
|
|
193
|
+
}
|
|
194
|
+
return transformSearchResults(parsed);
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
198
|
+
if (message.includes('Host not found')) {
|
|
199
|
+
logger_1.default.error('搜索失败: 无法连接到服务器,请检查网络或 API 地址配置');
|
|
200
|
+
}
|
|
201
|
+
else if (message.includes('timeout')) {
|
|
202
|
+
logger_1.default.error('搜索失败: 请求超时,请稍后重试');
|
|
203
|
+
}
|
|
204
|
+
else if (message.includes('Connection refused')) {
|
|
205
|
+
logger_1.default.error('搜索失败: 服务器拒绝连接,请检查 API 地址是否正确');
|
|
206
|
+
}
|
|
207
|
+
else if (message.includes('status code')) {
|
|
208
|
+
logger_1.default.error('搜索失败: 服务器返回错误', message);
|
|
209
|
+
}
|
|
210
|
+
else {
|
|
211
|
+
logger_1.default.error('搜索失败:', message);
|
|
212
|
+
}
|
|
213
|
+
return [];
|
|
214
|
+
}
|
|
215
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { AuthSession, EnsureAuthResult, PublishOptions, RegistryUser, RepoCreationResult } from './types';
|
|
2
|
+
export declare function loadAuthSession(): AuthSession | null;
|
|
3
|
+
export declare function saveAuthSession(session: AuthSession): void;
|
|
4
|
+
export declare function clearAuthSession(): void;
|
|
5
|
+
export declare function isRegistryRepoUrl(repoUrl: string): boolean;
|
|
6
|
+
export declare function buildAuthenticatedGitUrl(cloneUrl: string, session: AuthSession): string;
|
|
7
|
+
export declare function buildGitHttpExtraHeader(session: AuthSession): string;
|
|
8
|
+
export declare function fetchCurrentUser(token: string): Promise<RegistryUser | null>;
|
|
9
|
+
export declare function createAccessToken(username: string, password: string): Promise<AuthSession>;
|
|
10
|
+
export declare function registerUser(username: string, email: string, password: string): Promise<void>;
|
|
11
|
+
export declare function ensureRegistryAuth(options?: PublishOptions): Promise<EnsureAuthResult>;
|
|
12
|
+
export declare function ensureRemoteRepository(session: AuthSession, repoName: string, options?: {
|
|
13
|
+
description?: string;
|
|
14
|
+
visibility?: 'public' | 'private';
|
|
15
|
+
}): Promise<RepoCreationResult>;
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.loadAuthSession = loadAuthSession;
|
|
7
|
+
exports.saveAuthSession = saveAuthSession;
|
|
8
|
+
exports.clearAuthSession = clearAuthSession;
|
|
9
|
+
exports.isRegistryRepoUrl = isRegistryRepoUrl;
|
|
10
|
+
exports.buildAuthenticatedGitUrl = buildAuthenticatedGitUrl;
|
|
11
|
+
exports.buildGitHttpExtraHeader = buildGitHttpExtraHeader;
|
|
12
|
+
exports.fetchCurrentUser = fetchCurrentUser;
|
|
13
|
+
exports.createAccessToken = createAccessToken;
|
|
14
|
+
exports.registerUser = registerUser;
|
|
15
|
+
exports.ensureRegistryAuth = ensureRegistryAuth;
|
|
16
|
+
exports.ensureRemoteRepository = ensureRemoteRepository;
|
|
17
|
+
const fs_1 = __importDefault(require("fs"));
|
|
18
|
+
const path_1 = __importDefault(require("path"));
|
|
19
|
+
const config_1 = require("./config");
|
|
20
|
+
const logger_1 = __importDefault(require("./logger"));
|
|
21
|
+
const network_1 = require("./network");
|
|
22
|
+
const system_1 = require("./system");
|
|
23
|
+
function getCookieHeader(cookieHeader) {
|
|
24
|
+
if (!cookieHeader) {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
const values = Array.isArray(cookieHeader) ? cookieHeader : [cookieHeader];
|
|
28
|
+
const cookies = values
|
|
29
|
+
.map((item) => item.split(';')[0]?.trim())
|
|
30
|
+
.filter(Boolean);
|
|
31
|
+
return cookies.length > 0 ? cookies.join('; ') : undefined;
|
|
32
|
+
}
|
|
33
|
+
function extractCsrfToken(html) {
|
|
34
|
+
const patterns = [
|
|
35
|
+
/name=["']_csrf["']\s+value=["']([^"']+)["']/i,
|
|
36
|
+
/content=["']([^"']+)["']\s+name=["']_csrf["']/i
|
|
37
|
+
];
|
|
38
|
+
for (const pattern of patterns) {
|
|
39
|
+
const match = html.match(pattern);
|
|
40
|
+
if (match?.[1]) {
|
|
41
|
+
return match[1];
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
function extractHtmlErrorMessage(html) {
|
|
47
|
+
const match = html.match(/<(div|p)[^>]*class=["'][^"']*(?:message|error|warning)[^"']*["'][^>]*>([\s\S]*?)<\/\1>/i);
|
|
48
|
+
if (!match?.[2]) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
return match[2]
|
|
52
|
+
.replace(/<[^>]+>/g, ' ')
|
|
53
|
+
.replace(/\s+/g, ' ')
|
|
54
|
+
.trim();
|
|
55
|
+
}
|
|
56
|
+
function getAuthHeader(token) {
|
|
57
|
+
return {
|
|
58
|
+
Authorization: `token ${token}`,
|
|
59
|
+
Accept: 'application/json'
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
function getBasicAuthHeader(username, password) {
|
|
63
|
+
return `Basic ${Buffer.from(`${username}:${password}`, 'utf8').toString('base64')}`;
|
|
64
|
+
}
|
|
65
|
+
function loadAuthSession() {
|
|
66
|
+
const authFilePath = (0, config_1.getAuthFilePath)();
|
|
67
|
+
if (!fs_1.default.existsSync(authFilePath)) {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const parsed = JSON.parse(fs_1.default.readFileSync(authFilePath, 'utf8'));
|
|
72
|
+
if (!parsed.username || !parsed.token) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
username: parsed.username,
|
|
77
|
+
email: parsed.email || null,
|
|
78
|
+
token: parsed.token
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function saveAuthSession(session) {
|
|
86
|
+
const authFilePath = (0, config_1.getAuthFilePath)();
|
|
87
|
+
fs_1.default.mkdirSync(path_1.default.dirname(authFilePath), {
|
|
88
|
+
recursive: true,
|
|
89
|
+
mode: 0o700
|
|
90
|
+
});
|
|
91
|
+
fs_1.default.writeFileSync(authFilePath, JSON.stringify(session, null, 2), {
|
|
92
|
+
encoding: 'utf8',
|
|
93
|
+
mode: 0o600
|
|
94
|
+
});
|
|
95
|
+
try {
|
|
96
|
+
fs_1.default.chmodSync(authFilePath, 0o600);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
// Windows may ignore POSIX chmod semantics.
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function clearAuthSession() {
|
|
103
|
+
const authFilePath = (0, config_1.getAuthFilePath)();
|
|
104
|
+
if (fs_1.default.existsSync(authFilePath)) {
|
|
105
|
+
fs_1.default.rmSync(authFilePath, { force: true });
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function isRegistryRepoUrl(repoUrl) {
|
|
109
|
+
try {
|
|
110
|
+
const target = new URL(repoUrl);
|
|
111
|
+
const base = new URL((0, config_1.getBaseUrl)());
|
|
112
|
+
return target.host === base.host;
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function buildAuthenticatedGitUrl(cloneUrl, session) {
|
|
119
|
+
try {
|
|
120
|
+
const url = new URL(cloneUrl);
|
|
121
|
+
if (!['http:', 'https:'].includes(url.protocol)) {
|
|
122
|
+
return cloneUrl;
|
|
123
|
+
}
|
|
124
|
+
if (!isRegistryRepoUrl(cloneUrl)) {
|
|
125
|
+
return cloneUrl;
|
|
126
|
+
}
|
|
127
|
+
url.username = session.username;
|
|
128
|
+
url.password = session.token;
|
|
129
|
+
return url.toString();
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return cloneUrl;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
function buildGitHttpExtraHeader(session) {
|
|
136
|
+
return `AUTHORIZATION: basic ${Buffer.from(`${session.username}:${session.token}`, 'utf8').toString('base64')}`;
|
|
137
|
+
}
|
|
138
|
+
async function fetchCurrentUser(token) {
|
|
139
|
+
try {
|
|
140
|
+
const response = await (0, network_1.request)(`${(0, config_1.getBaseUrl)()}/api/v1/user`, {
|
|
141
|
+
headers: getAuthHeader(token)
|
|
142
|
+
});
|
|
143
|
+
const parsed = JSON.parse(response.body);
|
|
144
|
+
const username = parsed.login || parsed.username;
|
|
145
|
+
if (!username) {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
username,
|
|
150
|
+
email: parsed.email || null
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
async function createAccessToken(username, password) {
|
|
158
|
+
const response = await (0, network_1.request)(`${(0, config_1.getBaseUrl)()}/api/v1/users/${encodeURIComponent(username)}/tokens`, {
|
|
159
|
+
method: 'POST',
|
|
160
|
+
headers: {
|
|
161
|
+
Authorization: getBasicAuthHeader(username, password),
|
|
162
|
+
Accept: 'application/json',
|
|
163
|
+
'Content-Type': 'application/json'
|
|
164
|
+
},
|
|
165
|
+
body: JSON.stringify({
|
|
166
|
+
name: `getskill-cli-${Date.now()}`
|
|
167
|
+
})
|
|
168
|
+
});
|
|
169
|
+
const parsed = JSON.parse(response.body);
|
|
170
|
+
const token = parsed.sha1 || parsed.token;
|
|
171
|
+
if (!token) {
|
|
172
|
+
throw new Error('登录成功但未获取到访问令牌');
|
|
173
|
+
}
|
|
174
|
+
const currentUser = await fetchCurrentUser(token);
|
|
175
|
+
return {
|
|
176
|
+
username: currentUser?.username || username,
|
|
177
|
+
email: currentUser?.email || null,
|
|
178
|
+
token
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
async function registerUser(username, email, password) {
|
|
182
|
+
const signUpUrl = `${(0, config_1.getBaseUrl)()}/user/sign_up`;
|
|
183
|
+
const signUpPage = await (0, network_1.request)(signUpUrl, {
|
|
184
|
+
followRedirects: false,
|
|
185
|
+
allowNonSuccessStatus: true
|
|
186
|
+
});
|
|
187
|
+
const csrfToken = extractCsrfToken(signUpPage.body);
|
|
188
|
+
if (!csrfToken) {
|
|
189
|
+
throw new Error('无法获取注册页面 CSRF 信息,请确认站点允许公开注册');
|
|
190
|
+
}
|
|
191
|
+
const cookieHeader = getCookieHeader(signUpPage.headers['set-cookie']);
|
|
192
|
+
const requestBody = new URLSearchParams({
|
|
193
|
+
_csrf: csrfToken,
|
|
194
|
+
user_name: username,
|
|
195
|
+
email,
|
|
196
|
+
password,
|
|
197
|
+
retype: password
|
|
198
|
+
}).toString();
|
|
199
|
+
const response = await (0, network_1.request)(signUpUrl, {
|
|
200
|
+
method: 'POST',
|
|
201
|
+
followRedirects: false,
|
|
202
|
+
allowNonSuccessStatus: true,
|
|
203
|
+
headers: {
|
|
204
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
205
|
+
Referer: signUpUrl,
|
|
206
|
+
...(cookieHeader ? { Cookie: cookieHeader } : {})
|
|
207
|
+
},
|
|
208
|
+
body: requestBody
|
|
209
|
+
});
|
|
210
|
+
if ([302, 303].includes(response.statusCode)) {
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
const normalizedBody = response.body.toLowerCase();
|
|
214
|
+
if (normalizedBody.includes('sign in now') ||
|
|
215
|
+
normalizedBody.includes('register account')) {
|
|
216
|
+
const errorMessage = extractHtmlErrorMessage(response.body);
|
|
217
|
+
if (!errorMessage) {
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
throw new Error(errorMessage);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
async function resolveRequiredValue(question, directValue, envValue, defaultValue, secret = false) {
|
|
224
|
+
const candidate = directValue?.trim() || envValue?.trim();
|
|
225
|
+
if (candidate) {
|
|
226
|
+
return candidate;
|
|
227
|
+
}
|
|
228
|
+
return (0, system_1.promptForInput)(question, {
|
|
229
|
+
required: true,
|
|
230
|
+
defaultValue,
|
|
231
|
+
secret
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
async function ensureRegistryAuth(options = {}) {
|
|
235
|
+
const storedSession = loadAuthSession();
|
|
236
|
+
if (storedSession?.token) {
|
|
237
|
+
const currentUser = await fetchCurrentUser(storedSession.token);
|
|
238
|
+
if (currentUser?.username) {
|
|
239
|
+
const freshSession = {
|
|
240
|
+
username: currentUser.username,
|
|
241
|
+
email: currentUser.email || storedSession.email || null,
|
|
242
|
+
token: storedSession.token
|
|
243
|
+
};
|
|
244
|
+
saveAuthSession(freshSession);
|
|
245
|
+
return {
|
|
246
|
+
...freshSession,
|
|
247
|
+
mode: 'stored-token'
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
clearAuthSession();
|
|
251
|
+
logger_1.default.warn('检测到本地登录态已失效,准备重新登录。');
|
|
252
|
+
}
|
|
253
|
+
const username = await resolveRequiredValue('请输入 getskill 用户名', options.username, process.env.GETSKILL_USERNAME);
|
|
254
|
+
let email = options.email?.trim() || process.env.GETSKILL_EMAIL?.trim();
|
|
255
|
+
const password = await resolveRequiredValue('请输入 getskill 密码', options.password, process.env.GETSKILL_PASSWORD, undefined, true);
|
|
256
|
+
try {
|
|
257
|
+
const session = await createAccessToken(username, password);
|
|
258
|
+
const normalizedSession = {
|
|
259
|
+
...session,
|
|
260
|
+
email: session.email || email || null
|
|
261
|
+
};
|
|
262
|
+
saveAuthSession(normalizedSession);
|
|
263
|
+
return {
|
|
264
|
+
...normalizedSession,
|
|
265
|
+
mode: 'login'
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
270
|
+
if (!email) {
|
|
271
|
+
email = await resolveRequiredValue('未检测到可用账号,请输入邮箱以自动注册', options.email, process.env.GETSKILL_EMAIL);
|
|
272
|
+
}
|
|
273
|
+
logger_1.default.info(`登录失败,正在尝试自动注册并登录: ${message}`);
|
|
274
|
+
await registerUser(username, email, password);
|
|
275
|
+
const session = await createAccessToken(username, password);
|
|
276
|
+
const normalizedSession = {
|
|
277
|
+
...session,
|
|
278
|
+
email: session.email || email || null
|
|
279
|
+
};
|
|
280
|
+
saveAuthSession(normalizedSession);
|
|
281
|
+
return {
|
|
282
|
+
...normalizedSession,
|
|
283
|
+
mode: 'register'
|
|
284
|
+
};
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
function parseRepositoryResponse(body, fallbackName) {
|
|
288
|
+
const parsed = JSON.parse(body);
|
|
289
|
+
return {
|
|
290
|
+
name: parsed.name || fallbackName,
|
|
291
|
+
cloneUrl: parsed.clone_url ||
|
|
292
|
+
`${(0, config_1.getBaseUrl)()}/${fallbackName.replace(/^\/+/, '')}.git`,
|
|
293
|
+
htmlUrl: parsed.html_url
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
async function ensureRemoteRepository(session, repoName, options = {}) {
|
|
297
|
+
const repoDetailUrl = `${(0, config_1.getBaseUrl)()}/api/v1/repos/${encodeURIComponent(session.username)}/${encodeURIComponent(repoName)}`;
|
|
298
|
+
const detailResponse = await (0, network_1.request)(repoDetailUrl, {
|
|
299
|
+
headers: getAuthHeader(session.token),
|
|
300
|
+
allowNonSuccessStatus: true
|
|
301
|
+
});
|
|
302
|
+
if (detailResponse.statusCode >= 200 && detailResponse.statusCode < 300) {
|
|
303
|
+
const repo = parseRepositoryResponse(detailResponse.body, `${session.username}/${repoName}`);
|
|
304
|
+
return {
|
|
305
|
+
...repo,
|
|
306
|
+
existed: true
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
const createResponse = await (0, network_1.request)(`${(0, config_1.getBaseUrl)()}/api/v1/user/repos`, {
|
|
310
|
+
method: 'POST',
|
|
311
|
+
headers: {
|
|
312
|
+
...getAuthHeader(session.token),
|
|
313
|
+
'Content-Type': 'application/json'
|
|
314
|
+
},
|
|
315
|
+
body: JSON.stringify({
|
|
316
|
+
name: repoName,
|
|
317
|
+
description: options.description || '',
|
|
318
|
+
private: options.visibility === 'private',
|
|
319
|
+
auto_init: false
|
|
320
|
+
}),
|
|
321
|
+
allowNonSuccessStatus: true
|
|
322
|
+
});
|
|
323
|
+
if (createResponse.statusCode >= 200 && createResponse.statusCode < 300) {
|
|
324
|
+
const repo = parseRepositoryResponse(createResponse.body, `${session.username}/${repoName}`);
|
|
325
|
+
return {
|
|
326
|
+
...repo,
|
|
327
|
+
existed: false
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
const errorMessage = extractHtmlErrorMessage(createResponse.body) ||
|
|
331
|
+
createResponse.body.substring(0, 200) ||
|
|
332
|
+
`HTTP ${createResponse.statusCode}`;
|
|
333
|
+
throw new Error(`自动创建仓库失败: ${errorMessage}`);
|
|
334
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { DownloadOptions, DownloadResult, PublishOptions, PublishResult, RemoveInstalledSkillResult, UpdateAllResult } from './types';
|
|
2
|
+
export declare function cloneOrUpdateRepo(skillName: string, options?: DownloadOptions): Promise<string>;
|
|
3
|
+
export declare function restartOpenClawGateway(): Promise<void>;
|
|
4
|
+
export declare function downloadSkill(skillName: string, options?: DownloadOptions): Promise<DownloadResult>;
|
|
5
|
+
export declare function updateSkill(skillName: string, options?: DownloadOptions): Promise<DownloadResult>;
|
|
6
|
+
export declare function updateAllSkills(): Promise<UpdateAllResult[]>;
|
|
7
|
+
export declare function uninstallSkill(skillName: string, options?: {
|
|
8
|
+
removeCache?: boolean;
|
|
9
|
+
}): Promise<RemoveInstalledSkillResult>;
|
|
10
|
+
export declare function publishSkill(skillPath: string, options?: PublishOptions): Promise<PublishResult>;
|