@workskills/getskill 1.1.10 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,334 +0,0 @@
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
- }