dsh-github-studio 0.6.6 → 0.7.1

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.
@@ -0,0 +1,174 @@
1
+ import {spawn} from 'node:child_process';
2
+ import {createHash,randomUUID} from 'node:crypto';
3
+ import {mkdir,readFile,rename,stat,unlink,writeFile} from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ export function command(executable, args, {input = '', timeout = 30000} = {}) {
7
+ return new Promise((resolve, reject) => {
8
+ const child = spawn(executable, args, {windowsHide: true, stdio: ['pipe', 'pipe', 'ignore']});
9
+ let stdout = '';
10
+ child.stdout.setEncoding('utf8');
11
+ child.stdout.on('data', chunk => { stdout += chunk; });
12
+ let timedOut = false;
13
+ const timer = setTimeout(() => {
14
+ timedOut = true;
15
+ child.kill('SIGKILL');
16
+ }, timeout);
17
+ child.on('error', error => { clearTimeout(timer); reject(error); });
18
+ child.on('close', code => {
19
+ clearTimeout(timer);
20
+ if (timedOut) reject(Error('凭据操作超时。'));
21
+ else resolve({code, stdout});
22
+ });
23
+ child.stdin.on('error', () => {});
24
+ child.stdin.end(input);
25
+ });
26
+ }
27
+
28
+ export async function windowsSeal(action, value) {
29
+ if (process.platform !== 'win32') throw Error('DPAPI 仅在 Windows 上可用。');
30
+ const operation = action === 'protect' ? 'Protect' : 'Unprotect';
31
+ const script = `$ErrorActionPreference='Stop'; Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim()); $r=[Security.Cryptography.ProtectedData]::${operation}($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Write([Convert]::ToBase64String($r))`;
32
+ const result = await command('powershell.exe', ['-NoProfile','-NonInteractive','-Command',script], {
33
+ input: action === 'protect' ? Buffer.from(value, 'utf8').toString('base64') : value
34
+ });
35
+ if (result.code !== 0) throw Error('Windows 凭据保护操作失败。');
36
+ return action === 'protect' ? result.stdout.trim() : Buffer.from(result.stdout.trim(), 'base64').toString('utf8');
37
+ }
38
+
39
+ export function fileCredentialStore(root, seal = windowsSeal) {
40
+ const filename = path.join(root, 'credential.dpapi');
41
+ return {
42
+ async exists() {
43
+ try { return (await stat(filename)).isFile(); }
44
+ catch (error) { if (error.code === 'ENOENT') return false; throw error; }
45
+ },
46
+ async read() {
47
+ let encrypted;
48
+ try { encrypted = await readFile(filename, 'utf8'); }
49
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
50
+ try { return await seal('unprotect', encrypted); }
51
+ catch {
52
+ throw Object.assign(Error('本机 GitHub 凭据无法解密,请重新连接。'), {
53
+ status: 401, reason: 'decrypt_failed', hasCredential: true
54
+ });
55
+ }
56
+ },
57
+ async write(plain, beforeCommit = () => {}) {
58
+ const encrypted = await seal('protect', plain);
59
+ await mkdir(root, {recursive: true});
60
+ const temp = path.join(root, 'credential-' + randomUUID() + '.tmp');
61
+ try {
62
+ await writeFile(temp, encrypted, {mode: 0o600, flag: 'wx'});
63
+ beforeCommit();
64
+ await rename(temp, filename);
65
+ } finally { await unlink(temp).catch(() => {}); }
66
+ },
67
+ async remove() {
68
+ try { await unlink(filename); }
69
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
70
+ }
71
+ };
72
+ }
73
+
74
+ // The security tool returns the low byte of errSecItemNotFound (-25300).
75
+ const itemNotFound = 44;
76
+ const keychainError = () => Object.assign(
77
+ Error('无法访问 macOS 钥匙串。请确认登录钥匙串已解锁,并允许访问 DeepSeek GitHub Studio 的凭据。'),
78
+ {status: 503, reason: 'keychain_unavailable'}
79
+ );
80
+
81
+ export function macCredentialStore(root, {run = command, keychain} = {}) {
82
+ const service = 'DeepSeek GitHub Studio';
83
+ // Different DSH_HOME directories must not share a Keychain item.
84
+ const account = createHash('sha256').update(path.resolve(root)).digest('hex');
85
+ const identity = ['-s', service, '-a', account];
86
+ const keychains = keychain ? [keychain] : [];
87
+ async function security(args, options) {
88
+ try { return await run('/usr/bin/security', args, options); }
89
+ catch { throw keychainError(); }
90
+ }
91
+ async function find(passwordOnly) {
92
+ const flags = passwordOnly ? ['-w'] : [];
93
+ const result = await security(['find-generic-password', ...flags, ...identity, ...keychains]);
94
+ if (result.code === itemNotFound) return null;
95
+ if (result.code !== 0) throw keychainError();
96
+ return result.stdout;
97
+ }
98
+ return {
99
+ async exists() { return (await find(false)) !== null; },
100
+ async read() {
101
+ const result = await find(true);
102
+ if (result === null) return null;
103
+ const encoded = result.trim();
104
+ if (!/^v1\.[A-Za-z0-9+/]+={0,2}$/.test(encoded)) {
105
+ throw Object.assign(Error('钥匙串中的 GitHub 凭据格式无效,请重新登录。'), {
106
+ status: 401, reason: 'invalid_local', hasCredential: true
107
+ });
108
+ }
109
+ return Buffer.from(encoded.slice(3), 'base64').toString('utf8');
110
+ },
111
+ async write(plain, beforeCommit = () => {}) {
112
+ // Pass the credential through a pipe, never through the process arguments.
113
+ const encoded = 'v1.' + Buffer.from(plain, 'utf8').toString('base64');
114
+ const args = [...identity, '-U', '-w', encoded, ...keychains];
115
+ if (args.some(arg => /[\r\n\0]/.test(arg))) throw keychainError();
116
+ const quoted = args.map(arg => '"' + arg.replace(/["\\]/g, '\\$&') + '"');
117
+ const input = 'add-generic-password ' + quoted.join(' ') + '\n';
118
+ if (Buffer.byteLength(input) >= 4095) throw Error('GitHub 凭据过长,无法保存到 macOS 钥匙串。');
119
+ beforeCommit();
120
+ const result = await security(['-q', '-i'], {input});
121
+ if (result.code !== 0) throw keychainError();
122
+ },
123
+ async remove() {
124
+ const result = await security(['delete-generic-password', ...identity, ...keychains]);
125
+ if (result.code !== 0 && result.code !== itemNotFound) throw keychainError();
126
+ }
127
+ };
128
+ }
129
+
130
+ // The Android guest runs Linux and exposes Harness's managed credential provider.
131
+ // Keep its record separate from model credentials and desktop credential stores.
132
+ const harnessCredentialKey = 'github-connect/github-oauth';
133
+
134
+ export function harnessCredentialStore(getProvider) {
135
+ function provider() {
136
+ const service = getProvider();
137
+ if (!service || ['describeRecord', 'readRecord', 'modifyRecord', 'deleteRecord'].some(
138
+ method => typeof service[method] !== 'function'
139
+ )) {
140
+ throw Object.assign(Error('Harness 凭据服务不可用,请检查当前主机或重启引擎。'), {status: 503});
141
+ }
142
+ return service;
143
+ }
144
+ return {
145
+ async exists() {
146
+ return (await provider().describeRecord(harnessCredentialKey)).configured === true;
147
+ },
148
+ async read() {
149
+ const record = await provider().readRecord(harnessCredentialKey);
150
+ if (record === undefined) return null;
151
+ if (record.kind !== 'grant' || typeof record.payload?.access_token !== 'string') {
152
+ throw Object.assign(Error('GitHub 登录记录无效,请重新授权。'), {
153
+ status: 401, reason: 'invalid_local', hasCredential: true
154
+ });
155
+ }
156
+ return JSON.stringify(record.payload);
157
+ },
158
+ async write(plain, beforeCommit = () => {}) {
159
+ const payload = JSON.parse(plain);
160
+ await provider().modifyRecord(harnessCredentialKey, async () => {
161
+ beforeCommit();
162
+ return {kind: 'grant', payload};
163
+ });
164
+ },
165
+ async remove() { await provider().deleteRecord(harnessCredentialKey); }
166
+ };
167
+ }
168
+
169
+ export function credentialStore(root, seal) {
170
+ if (seal || process.platform === 'win32') return fileCredentialStore(root, seal);
171
+ if (process.platform === 'darwin') return macCredentialStore(root);
172
+ const unsupported = () => { throw Error('此主机缺少受支持的 GitHub 凭据存储。'); };
173
+ return {exists: async () => false, read: unsupported, write: unsupported, remove: unsupported};
174
+ }
@@ -1,8 +1,8 @@
1
1
  import {mkdirSync,appendFileSync,statSync,readFileSync,writeFileSync} from 'node:fs';
2
2
  import path from 'node:path';
3
- const events=new Set(['plugin_started','plugin_stopped','credential_read','credential_saved','logout','oauth_started','oauth_waiting','oauth_failed','api_response','api_failure']);
3
+ const events=new Set(['plugin_started','plugin_stopped','credential_read','credential_saved','logout','oauth_started','oauth_waiting','oauth_retry','oauth_failed','api_response','api_failure']);
4
4
  const categories=new Set(['account','search','repository','upload','authorization']);
5
- const reasons=new Set(['ok','missing','read_failed','decrypt_failed','invalid_local','invalid_credentials','forbidden','rate_limited','server_error','network_error','timeout','authorization_failed','access_denied','expired_token','device_flow_disabled','incorrect_client_credentials','incorrect_device_code','unsupported_grant_type','oauth_error','local_disconnect']);
5
+ const reasons=new Set(['ok','missing','read_failed','decrypt_failed','keychain_unavailable','invalid_local','invalid_credentials','forbidden','rate_limited','server_error','tls_error','dns_error','connection_error','network_error','timeout','authorization_failed','access_denied','expired_token','device_flow_disabled','incorrect_client_credentials','incorrect_device_code','unsupported_grant_type','oauth_error','local_disconnect']);
6
6
  /** Allowlisted metadata only. Never accept messages, URLs, queries or tokens. */
7
7
  export function createDiagnostics(root,{now=Date.now}={}){
8
8
  const file=path.join(root,'diagnostics.jsonl'),last=new Map();
@@ -1,8 +1,8 @@
1
1
  import {mkdirSync,appendFileSync,statSync,readFileSync,writeFileSync} from 'node:fs';
2
2
  import path from 'node:path';
3
- const events=new Set(['plugin_started','plugin_stopped','credential_read','credential_saved','logout','oauth_started','oauth_waiting','oauth_failed','api_response','api_failure']);
3
+ const events=new Set(['plugin_started','plugin_stopped','credential_read','credential_saved','logout','oauth_started','oauth_waiting','oauth_retry','oauth_failed','api_response','api_failure']);
4
4
  const categories=new Set(['account','search','repository','upload','authorization']);
5
- const reasons=new Set(['ok','missing','read_failed','decrypt_failed','invalid_local','invalid_credentials','forbidden','rate_limited','server_error','network_error','timeout','authorization_failed','access_denied','expired_token','device_flow_disabled','incorrect_client_credentials','incorrect_device_code','unsupported_grant_type','oauth_error','local_disconnect']);
5
+ const reasons=new Set(['ok','missing','read_failed','decrypt_failed','keychain_unavailable','invalid_local','invalid_credentials','forbidden','rate_limited','server_error','tls_error','dns_error','connection_error','network_error','timeout','authorization_failed','access_denied','expired_token','device_flow_disabled','incorrect_client_credentials','incorrect_device_code','unsupported_grant_type','oauth_error','local_disconnect']);
6
6
  /** Allowlisted metadata only. Never accept messages, URLs, queries or tokens. */
7
7
  export function createDiagnostics(root,{now=Date.now}={}){
8
8
  const file=path.join(root,'diagnostics.jsonl'),last=new Map();
package/lib/dsh-go.js ADDED
@@ -0,0 +1,148 @@
1
+ import {oauthRegistrationUrl,oauthHomepage} from './oauth-setup.mjs';
2
+
3
+ const panelId = 'github-account';
4
+ const activeLogin = login => login.state === 'preparing' || login.state === 'waiting';
5
+ const toast = text => ({type: 'toast', text});
6
+
7
+ export function githubMobileView() {
8
+ return {
9
+ v: 2, type: 'stack', title: 'GitHub',
10
+ children: [
11
+ {type: 'text', text: {$: 'data.status'}},
12
+ {type: 'collapsible', label: '首次登录?配置 GitHub OAuth App', children: [
13
+ {type: 'text', text: '已有启用了设备流的 OAuth App?直接用原来的 Client ID,同一个 ID 可用于电脑和手机。'},
14
+ {type: 'actions', items: [{label: '打开 OAuth App 注册页', action: 'register-app'}]},
15
+ {type: 'text', text: '应用名称可填 DeepSeek GitHub Studio。应用描述可留空。'},
16
+ {type: 'text', text: '主页 URL 填 ' + oauthHomepage},
17
+ {type: 'text', text: '重定向 URI 填和主页 URL 一样的仓库地址。通配符保持关闭。'},
18
+ {type: 'actions', items: [
19
+ {label: '复制主页 URL', action: 'copy-homepage'},
20
+ {label: '复制重定向 URI', action: 'copy-redirect'}
21
+ ]},
22
+ {type: 'text', text: '勾选「启用设备流」后注册。复制应用详情里的 Client ID,粘贴到下方并保存。无需 Client Secret。'},
23
+ {type: 'text', text: '点「登录 GitHub」获取设备码,再打开授权页,输入设备码并确认。'}
24
+ ]},
25
+ {type: 'form', submit: 'configure', submitLabel: '保存 Client ID', children: [
26
+ {type: 'textField', label: 'OAuth App Client ID', bind: 'data.form.clientId',
27
+ placeholder: '粘贴你的 Client ID', minLength: 5, maxLength: 120, required: true}
28
+ ]},
29
+ {type: 'actions', items: [
30
+ {label: '登录 GitHub', action: 'login'},
31
+ {label: '打开授权页', action: 'authorize'}
32
+ ]},
33
+ {type: 'actions', items: [
34
+ {label: '复制设备码', action: 'copy-code'},
35
+ {label: '取消登录', action: 'cancel'},
36
+ {label: '刷新状态', action: 'refresh'}
37
+ ]},
38
+ {type: 'confirm', id: 'disconnect', text: '断开当前 GitHub 连接?',
39
+ confirmLabel: '断开连接', cancelLabel: '取消'},
40
+ {type: 'text', tone: 'muted', text: '浏览仓库、发布版本和确认写入,请在 DSH Go 的网页版打开「设置 → GitHub」。'}
41
+ ]
42
+ };
43
+ }
44
+
45
+ export function registerMobilePanel(ctx, {auth, api, ops}) {
46
+ const listeners = new Set();
47
+ let account = '', error = '', clientId = '', version = 0, timer;
48
+ let checking;
49
+ const status = () => {
50
+ const {state, code, message} = auth.login;
51
+ if (state === 'waiting') return '设备码:' + code + (message ? '\n' + message : '');
52
+ if (state === 'preparing') return message || '正在请求 GitHub 设备码…';
53
+ if (state === 'error') return message || 'GitHub 授权失败';
54
+ return error || (account ? '已连接 @' + account : '尚未连接 GitHub');
55
+ };
56
+ const snapshot = () => ({status: status().slice(0, 400), form: {clientId}});
57
+ const publish = () => { for (const emit of listeners) emit(snapshot()); };
58
+ const refresh = () => {
59
+ if (checking) return checking;
60
+ const generation = version;
61
+ checking = (async () => {
62
+ const id = await auth.clientId();
63
+ let user = '', failure = '';
64
+ if (!activeLogin(auth.login) && await auth.hasCredential()) {
65
+ try { user = (await api.me()).login; }
66
+ catch (e) { failure = e.message; }
67
+ }
68
+ if (generation === version) {
69
+ clientId = id || '';
70
+ account = user || '';
71
+ error = failure;
72
+ publish();
73
+ }
74
+ })().finally(() => { checking = undefined; });
75
+ return checking;
76
+ };
77
+ const refreshInBackground = () => refresh().catch(() => {});
78
+ const background = action => ({
79
+ pending: {label: 'GitHub', timeoutMs: 30000},
80
+ async result() {
81
+ try { return await action(); }
82
+ catch (e) { return toast(e.message.slice(0, 40)); }
83
+ }
84
+ });
85
+ ctx.dshGo.panel(panelId, {
86
+ view: githubMobileView,
87
+ data(_scope, emit) {
88
+ listeners.add(emit);
89
+ emit(snapshot());
90
+ if (!timer) {
91
+ refreshInBackground();
92
+ let last = auth.login.state;
93
+ timer = setInterval(() => {
94
+ publish();
95
+ const state = auth.login.state;
96
+ if (state !== last && !activeLogin(auth.login)) refreshInBackground();
97
+ last = state;
98
+ }, 2000);
99
+ timer.unref?.();
100
+ }
101
+ return () => {
102
+ listeners.delete(emit);
103
+ if (!listeners.size) { clearInterval(timer); timer = undefined; }
104
+ };
105
+ },
106
+ actions: {
107
+ 'register-app': () => ({type: 'link', url: oauthRegistrationUrl}),
108
+ 'copy-homepage': () => ({type: 'copy', text: oauthHomepage}),
109
+ 'copy-redirect': () => ({type: 'copy', text: oauthHomepage}),
110
+ configure: (_scope, event) => background(async () => {
111
+ const value = event.value?.values?.['data.form.clientId'];
112
+ if (typeof value !== 'string') return toast('请输入 Client ID');
113
+ await auth.configure(value.trim());
114
+ version++;
115
+ clientId = value.trim();
116
+ publish();
117
+ return toast('Client ID 已保存');
118
+ }),
119
+ async login() {
120
+ try {
121
+ await auth.start();
122
+ publish();
123
+ auth.task?.then(refreshInBackground);
124
+ } catch (e) { publish(); return toast(e.message.slice(0, 40)); }
125
+ },
126
+ authorize: () => auth.login.state === 'waiting'
127
+ ? {type: 'link', url: 'https://github.com/login/device'} : toast('请先获取设备码'),
128
+ 'copy-code': () => auth.login.state === 'waiting' && auth.login.code
129
+ ? {type: 'copy', text: auth.login.code} : toast('暂无设备码'),
130
+ cancel() {
131
+ if (activeLogin(auth.login)) { auth.cancel(); publish(); }
132
+ },
133
+ refresh: () => background(async () => { await refresh(); return toast('状态已刷新'); }),
134
+ disconnect: (_scope, event) => {
135
+ if (event.value?.confirmed !== true) return;
136
+ return background(async () => {
137
+ await auth.logout();
138
+ ops.clearPending();
139
+ version++;
140
+ account = '';
141
+ error = '';
142
+ publish();
143
+ return toast('已断开 GitHub 连接');
144
+ });
145
+ }
146
+ }
147
+ });
148
+ }
package/lib/dsh-go.mjs ADDED
@@ -0,0 +1,148 @@
1
+ import {oauthRegistrationUrl,oauthHomepage} from './oauth-setup.mjs';
2
+
3
+ const panelId = 'github-account';
4
+ const activeLogin = login => login.state === 'preparing' || login.state === 'waiting';
5
+ const toast = text => ({type: 'toast', text});
6
+
7
+ export function githubMobileView() {
8
+ return {
9
+ v: 2, type: 'stack', title: 'GitHub',
10
+ children: [
11
+ {type: 'text', text: {$: 'data.status'}},
12
+ {type: 'collapsible', label: '首次登录?配置 GitHub OAuth App', children: [
13
+ {type: 'text', text: '已有启用了设备流的 OAuth App?直接用原来的 Client ID,同一个 ID 可用于电脑和手机。'},
14
+ {type: 'actions', items: [{label: '打开 OAuth App 注册页', action: 'register-app'}]},
15
+ {type: 'text', text: '应用名称可填 DeepSeek GitHub Studio。应用描述可留空。'},
16
+ {type: 'text', text: '主页 URL 填 ' + oauthHomepage},
17
+ {type: 'text', text: '重定向 URI 填和主页 URL 一样的仓库地址。通配符保持关闭。'},
18
+ {type: 'actions', items: [
19
+ {label: '复制主页 URL', action: 'copy-homepage'},
20
+ {label: '复制重定向 URI', action: 'copy-redirect'}
21
+ ]},
22
+ {type: 'text', text: '勾选「启用设备流」后注册。复制应用详情里的 Client ID,粘贴到下方并保存。无需 Client Secret。'},
23
+ {type: 'text', text: '点「登录 GitHub」获取设备码,再打开授权页,输入设备码并确认。'}
24
+ ]},
25
+ {type: 'form', submit: 'configure', submitLabel: '保存 Client ID', children: [
26
+ {type: 'textField', label: 'OAuth App Client ID', bind: 'data.form.clientId',
27
+ placeholder: '粘贴你的 Client ID', minLength: 5, maxLength: 120, required: true}
28
+ ]},
29
+ {type: 'actions', items: [
30
+ {label: '登录 GitHub', action: 'login'},
31
+ {label: '打开授权页', action: 'authorize'}
32
+ ]},
33
+ {type: 'actions', items: [
34
+ {label: '复制设备码', action: 'copy-code'},
35
+ {label: '取消登录', action: 'cancel'},
36
+ {label: '刷新状态', action: 'refresh'}
37
+ ]},
38
+ {type: 'confirm', id: 'disconnect', text: '断开当前 GitHub 连接?',
39
+ confirmLabel: '断开连接', cancelLabel: '取消'},
40
+ {type: 'text', tone: 'muted', text: '浏览仓库、发布版本和确认写入,请在 DSH Go 的网页版打开「设置 → GitHub」。'}
41
+ ]
42
+ };
43
+ }
44
+
45
+ export function registerMobilePanel(ctx, {auth, api, ops}) {
46
+ const listeners = new Set();
47
+ let account = '', error = '', clientId = '', version = 0, timer;
48
+ let checking;
49
+ const status = () => {
50
+ const {state, code, message} = auth.login;
51
+ if (state === 'waiting') return '设备码:' + code + (message ? '\n' + message : '');
52
+ if (state === 'preparing') return message || '正在请求 GitHub 设备码…';
53
+ if (state === 'error') return message || 'GitHub 授权失败';
54
+ return error || (account ? '已连接 @' + account : '尚未连接 GitHub');
55
+ };
56
+ const snapshot = () => ({status: status().slice(0, 400), form: {clientId}});
57
+ const publish = () => { for (const emit of listeners) emit(snapshot()); };
58
+ const refresh = () => {
59
+ if (checking) return checking;
60
+ const generation = version;
61
+ checking = (async () => {
62
+ const id = await auth.clientId();
63
+ let user = '', failure = '';
64
+ if (!activeLogin(auth.login) && await auth.hasCredential()) {
65
+ try { user = (await api.me()).login; }
66
+ catch (e) { failure = e.message; }
67
+ }
68
+ if (generation === version) {
69
+ clientId = id || '';
70
+ account = user || '';
71
+ error = failure;
72
+ publish();
73
+ }
74
+ })().finally(() => { checking = undefined; });
75
+ return checking;
76
+ };
77
+ const refreshInBackground = () => refresh().catch(() => {});
78
+ const background = action => ({
79
+ pending: {label: 'GitHub', timeoutMs: 30000},
80
+ async result() {
81
+ try { return await action(); }
82
+ catch (e) { return toast(e.message.slice(0, 40)); }
83
+ }
84
+ });
85
+ ctx.dshGo.panel(panelId, {
86
+ view: githubMobileView,
87
+ data(_scope, emit) {
88
+ listeners.add(emit);
89
+ emit(snapshot());
90
+ if (!timer) {
91
+ refreshInBackground();
92
+ let last = auth.login.state;
93
+ timer = setInterval(() => {
94
+ publish();
95
+ const state = auth.login.state;
96
+ if (state !== last && !activeLogin(auth.login)) refreshInBackground();
97
+ last = state;
98
+ }, 2000);
99
+ timer.unref?.();
100
+ }
101
+ return () => {
102
+ listeners.delete(emit);
103
+ if (!listeners.size) { clearInterval(timer); timer = undefined; }
104
+ };
105
+ },
106
+ actions: {
107
+ 'register-app': () => ({type: 'link', url: oauthRegistrationUrl}),
108
+ 'copy-homepage': () => ({type: 'copy', text: oauthHomepage}),
109
+ 'copy-redirect': () => ({type: 'copy', text: oauthHomepage}),
110
+ configure: (_scope, event) => background(async () => {
111
+ const value = event.value?.values?.['data.form.clientId'];
112
+ if (typeof value !== 'string') return toast('请输入 Client ID');
113
+ await auth.configure(value.trim());
114
+ version++;
115
+ clientId = value.trim();
116
+ publish();
117
+ return toast('Client ID 已保存');
118
+ }),
119
+ async login() {
120
+ try {
121
+ await auth.start();
122
+ publish();
123
+ auth.task?.then(refreshInBackground);
124
+ } catch (e) { publish(); return toast(e.message.slice(0, 40)); }
125
+ },
126
+ authorize: () => auth.login.state === 'waiting'
127
+ ? {type: 'link', url: 'https://github.com/login/device'} : toast('请先获取设备码'),
128
+ 'copy-code': () => auth.login.state === 'waiting' && auth.login.code
129
+ ? {type: 'copy', text: auth.login.code} : toast('暂无设备码'),
130
+ cancel() {
131
+ if (activeLogin(auth.login)) { auth.cancel(); publish(); }
132
+ },
133
+ refresh: () => background(async () => { await refresh(); return toast('状态已刷新'); }),
134
+ disconnect: (_scope, event) => {
135
+ if (event.value?.confirmed !== true) return;
136
+ return background(async () => {
137
+ await auth.logout();
138
+ ops.clearPending();
139
+ version++;
140
+ account = '';
141
+ error = '';
142
+ publish();
143
+ return toast('已断开 GitHub 连接');
144
+ });
145
+ }
146
+ }
147
+ });
148
+ }
package/lib/gh.js CHANGED
@@ -1,17 +1,109 @@
1
- import {spawn} from 'node:child_process';
2
- import {mkdir,readFile,writeFile,unlink} from 'node:fs/promises';
1
+ import {setTimeout as delay} from 'node:timers/promises';
2
+ import {networkFailure} from './network.mjs';
3
+ import {credentialStore as platformCredentialStore} from './credential-store.mjs';
4
+ import {mkdir,readFile,writeFile} from 'node:fs/promises';
3
5
  import path from 'node:path';
4
- export function command(exe,args,{input='',timeout=30000}={}){return new Promise((resolve,reject)=>{const child=spawn(exe,args,{windowsHide:true,stdio:['pipe','pipe','pipe']});let stdout='';const timer=setTimeout(()=>{child.kill();reject(Error('凭据操作超时。'));},timeout);child.on('error',e=>{clearTimeout(timer);reject(e);});child.stdout.on('data',b=>stdout+=b);child.stderr.resume();child.on('close',code=>{clearTimeout(timer);resolve({code,stdout});});child.stdin.on('error',()=>{});child.stdin.end(input);});}
5
- export async function windowsSeal(action,value){if(process.platform!=='win32')throw Error('本版凭据保护仅支持 Windows。');const operation=action==='protect'?'Protect':'Unprotect';const script=`Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim()); $r=[Security.Cryptography.ProtectedData]::${operation}($b,$null,[Security.Cryptography.DataProtectionScope]::CurrentUser); [Console]::Write([Convert]::ToBase64String($r))`;const r=await command('powershell.exe',['-NoProfile','-NonInteractive','-Command',script],{input:action==='protect'?Buffer.from(value,'utf8').toString('base64'):value});if(r.code!==0)throw Error('Windows 凭据加密失败。');return action==='protect'?r.stdout.trim():Buffer.from(r.stdout.trim(),'base64').toString('utf8');}
6
+ export {command,windowsSeal} from './credential-store.mjs';
7
+
6
8
  export class GhAuth{
7
- constructor(root,{fetchImpl=fetch,seal=windowsSeal,sleep=ms=>new Promise(r=>setTimeout(r,ms)),diagnostics=()=>{}}={}){this.root=root;this.fetch=fetchImpl;this.seal=seal;this.sleep=sleep;this.diagnostics=diagnostics;this.login={state:'idle'};}
9
+ constructor(root,{fetchImpl=fetch,seal,credentialStore=platformCredentialStore(root,seal),sleep=(ms,signal)=>delay(ms,undefined,{signal}),diagnostics=()=>{},now=Date.now}={}){
10
+ Object.assign(this,{root,fetch:fetchImpl,credentialStore,sleep,diagnostics,now});this.login={state:'idle'};this.epoch=0;
11
+ }
8
12
  async clientId(){try{return JSON.parse(await readFile(path.join(this.root,'oauth.json'),'utf8')).clientId;}catch{if(process.env.DSH_GITHUB_CLIENT_ID)return process.env.DSH_GITHUB_CLIENT_ID;try{return JSON.parse(await readFile(new URL('./publisher.json',import.meta.url),'utf8')).clientId??'';}catch{return '';}}}
9
- async configure(clientId){if(!/^[A-Za-z0-9_.-]{5,120}$/.test(clientId))throw Error('请输入有效的 OAuth App Client ID。');if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成当前登录。');await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'oauth.json'),JSON.stringify({clientId}));}
10
- async hasCredential(){try{await readFile(path.join(this.root,'credential.dpapi'));return true;}catch{return false;}}
11
- async token(){let encrypted;try{encrypted=await readFile(path.join(this.root,'credential.dpapi'),'utf8');}catch(e){this.diagnostics('credential_read',{reason:e.code==='ENOENT'?'missing':'read_failed',hasCredential:false});throw Error('请先在设置 → GitHub 中登录。');}let token;try{token=await this.seal('unprotect',encrypted);}catch{this.diagnostics('credential_read',{reason:'decrypt_failed',hasCredential:true});throw Error('本机 GitHub 凭据无法解密,请在设置 → GitHub 重新连接。');}if(typeof token!=='string'||!token.trim()){this.diagnostics('credential_read',{reason:'invalid_local',hasCredential:true});throw Error('本机 GitHub 凭据为空,请重新连接。');}this.diagnostics('credential_read',{reason:'ok',hasCredential:true});return token;}
12
- async request(url,fields){const r=await this.fetch(url,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams(fields),signal:AbortSignal.timeout(30000),redirect:'error'});if(!r.ok)throw Error(`GitHub 授权请求失败(${r.status})。`);return r.json();}
13
- async start(){if(['preparing','waiting'].includes(this.login.state))return this.login;this.login={state:'preparing'};let clientId;try{clientId=await this.clientId();if(!clientId)throw Error('请先配置插件发布者的 GitHub OAuth App Client ID,并启用 Device Flow。');}catch(e){this.login={state:'error',message:e.message};throw e;}this.diagnostics('oauth_started',{category:'authorization'});
14
- this.task=(async()=>{try{const d=await this.request('https://github.com/login/device/code',{client_id:clientId,scope:'repo'});if(d.error||!d.device_code||!d.user_code)throw Object.assign(Error(d.error_description??'设备授权未启用,请检查 OAuth App 配置。'),{reason:d.error});this.diagnostics('oauth_waiting',{category:'authorization'});this.login={state:'waiting',code:d.user_code,url:'https://github.com/login/device'};let interval=Math.max(5,Number(d.interval)||5),deadline=Date.now()+Math.min(900,Number(d.expires_in)||900)*1000;while(Date.now()<deadline){await this.sleep(interval*1000);const r=await this.request('https://github.com/login/oauth/access_token',{client_id:clientId,device_code:d.device_code,grant_type:'urn:ietf:params:oauth:grant-type:device_code'});if(r.access_token){await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'credential.dpapi'),await this.seal('protect',r.access_token),{mode:0o600});this.diagnostics('credential_saved',{reason:'ok',hasCredential:true});this.login={state:'complete'};return;}if(r.error==='authorization_pending')continue;if(r.error==='slow_down'){interval+=5;continue;}throw Object.assign(Error(r.error_description??'授权已取消或过期,请重新登录。'),{reason:r.error});}throw Object.assign(Error('授权已过期,请重新登录。'),{reason:'expired_token'});}catch(e){this.diagnostics('oauth_failed',{category:'authorization',reason:e.reason??'authorization_failed'});this.login={state:'error',message:e.message};}})();return this.login;}
15
- async logout(){if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成或取消浏览器中的登录。');await unlink(path.join(this.root,'credential.dpapi')).catch(e=>{if(e.code!=='ENOENT')throw e;});this.diagnostics('logout',{reason:'local_disconnect',hasCredential:false});this.login={state:'idle'};}
13
+ async configure(clientId){if(!/^[A-Za-z0-9_.-]{5,120}$/.test(clientId))throw Error('请输入有效的 OAuth App Client ID。');if(['preparing','waiting'].includes(this.login.state))throw Error('请先完成或取消当前登录。');await mkdir(this.root,{recursive:true});await writeFile(path.join(this.root,'oauth.json'),JSON.stringify({clientId}));}
14
+ async hasCredential(){try{return await this.credentialStore.exists();}catch{return false;}}
15
+ async credential(){
16
+ let plain;
17
+ try { plain = await this.credentialStore.read(); }
18
+ catch (error) {
19
+ this.diagnostics('credential_read',{reason:error.reason??'read_failed',hasCredential:error.hasCredential});
20
+ throw error.status ? error : Object.assign(Error('无法读取本机 GitHub 凭据。'),{status:503});
21
+ }
22
+ if(plain===null){
23
+ this.diagnostics('credential_read',{reason:'missing',hasCredential:false});
24
+ throw Object.assign(Error('请先在设置 → GitHub 中登录。'),{status:401});
25
+ }
26
+ if(typeof plain!=='string'||!plain.trim()){this.diagnostics('credential_read',{reason:'invalid_local',hasCredential:true});throw Object.assign(Error('本机 GitHub 凭据为空,请重新连接。'),{status:401});}
27
+ let data;if(plain.startsWith('{')){try{data=JSON.parse(plain);}catch{throw Object.assign(Error('本机 GitHub 凭据损坏,请重新连接。'),{status:401});}}else data={access_token:plain};
28
+ if(typeof data?.access_token!=='string'||!data.access_token.trim())throw Object.assign(Error('本机 GitHub 凭据无效,请重新连接。'),{status:401});
29
+ this.diagnostics('credential_read',{reason:'ok',hasCredential:true});return data;
30
+ }
31
+ async save(r,epoch,clientId){
32
+ if(typeof r.access_token!=='string'||!r.access_token.trim())throw Error('GitHub 未返回有效凭据,请重新授权。');
33
+ const data={access_token:r.access_token,clientId,...(typeof r.refresh_token==='string'?{refresh_token:r.refresh_token}:{}),
34
+ ...(Number(r.expires_in)>0?{expiresAt:this.now()+Number(r.expires_in)*1000}:{}),
35
+ ...(Number(r.refresh_token_expires_in)>0?{refreshExpiresAt:this.now()+Number(r.refresh_token_expires_in)*1000}:{})};
36
+ const checkCurrent = ()=>{
37
+ if(epoch!==this.epoch)throw new DOMException('登录已取消。','AbortError');
38
+ };
39
+ await this.mutate(async()=>{
40
+ checkCurrent();
41
+ await this.credentialStore.write(JSON.stringify(data),checkCurrent);
42
+ });
43
+ this.diagnostics('credential_saved',{reason:'ok',hasCredential:true});return data.access_token;
44
+ }
45
+ async token(){const d=await this.credential();if(!['preparing','waiting'].includes(this.login.state)&&d.refresh_token&&d.expiresAt&&this.now()>=d.expiresAt-60000)return this.refresh(d);return d.access_token;}
46
+ async refreshAfter401(rejected){if(['preparing','waiting'].includes(this.login.state))return null;const d=await this.credential();if(d.access_token!==rejected)return d.access_token;if(!d.refresh_token)return null;return this.refresh(d);}
47
+ async refresh(d){
48
+ if(this.refreshing)return this.refreshing;
49
+ const epoch=this.epoch,signal=this.refreshController=new AbortController();
50
+ this.refreshing=(async()=>{if(d.refreshExpiresAt&&this.now()>=d.refreshExpiresAt)throw Object.assign(Error('GitHub 续期凭据已过期,请重新登录。'),{status:401});
51
+ // Rotation can succeed before a response is lost. Never blindly replay refresh requests.
52
+ const r=await this.request('https://github.com/login/oauth/access_token',{client_id:d.clientId??await this.clientId(),grant_type:'refresh_token',refresh_token:d.refresh_token},{signal:signal.signal,attempts:1});
53
+ if(r.error||!r.refresh_token)throw Object.assign(Error('GitHub 登录已失效或续期响应不完整,请重新授权。'),{status:401});
54
+ return this.save(r,epoch,d.clientId??await this.clientId());
55
+ })();try{return await this.refreshing;}finally{this.refreshing=null;this.refreshController=null;}
56
+ }
57
+ async request(url,fields,{signal,attempts=3,deadline=Infinity,onRetry=()=>{}}={}){
58
+ for(let attempt=0;;attempt++){
59
+ signal?.throwIfAborted();const remaining=deadline-this.now();if(remaining<=0)throw Object.assign(Error('设备授权已过期,请重新登录。'),{reason:'expired_token'});
60
+ try{
61
+ const timeout=AbortSignal.timeout(Math.max(1,Math.min(30000,Math.ceil(remaining))));
62
+ const r=await this.fetch(url,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams(fields),signal:signal?AbortSignal.any([signal,timeout]):timeout,redirect:'error'});
63
+ if(!r.ok){await r.body?.cancel();throw Object.assign(Error('GitHub 授权服务暂时不可用('+r.status+')。'),{status:r.status,retryable:r.status===429||r.status>=500,retryAfter:Number(r.headers.get('retry-after'))||0,reason:'server_error'});}
64
+ try{return await r.json();}catch{throw Object.assign(Error('GitHub 返回的授权数据不完整,请检查加速线路。'),{retryable:true,reason:'network_error'});}
65
+ }catch(error){
66
+ if(signal?.aborted)throw signal.reason;
67
+ const e=error.reason||error.status?error:networkFailure(error);
68
+ if(!e.retryable||attempt+1>=attempts)throw e;
69
+ const wait=Math.max(1000*2**Math.min(attempt,4),(e.retryAfter??0)*1000);
70
+ if(this.now()+wait>=deadline)throw Object.assign(Error('设备授权已过期,请重新登录。'),{reason:'expired_token'});
71
+ onRetry(e);await this.sleep(wait,signal);
72
+ }
73
+ }
74
+ }
75
+ async start(){
76
+ if(['preparing','waiting'].includes(this.login.state))return this.login;
77
+ const epoch=++this.epoch,controller=this.controller=new AbortController(),signal=controller.signal;
78
+ this.refreshController?.abort();this.login={state:'preparing'};let clientId;
79
+ try{clientId=await this.clientId();if(!clientId)throw Error('请先配置 GitHub OAuth App Client ID,并启用 Device Flow。');}
80
+ catch(e){this.login={state:'error',message:e.message};throw e;}
81
+ if(epoch!==this.epoch)return this.login;
82
+ this.diagnostics('oauth_started',{category:'authorization'});
83
+ this.task=(async()=>{try{
84
+ const notify=e=>{if(epoch===this.epoch){this.login={...this.login,message:e.message+' 正在自动重试…'};this.diagnostics('oauth_retry',{category:'authorization',reason:e.reason});}};
85
+ const d=await this.request('https://github.com/login/device/code',{client_id:clientId,scope:'repo offline_access'},{signal,onRetry:notify});
86
+ if(d.error||!d.device_code||!d.user_code)throw Object.assign(Error('无法开始 GitHub 授权,请检查 Client ID 及 Device Flow 配置。'),{reason:d.error});
87
+ signal.throwIfAborted();this.login={state:'waiting',code:d.user_code,url:'https://github.com/login/device'};
88
+ this.diagnostics('oauth_waiting',{category:'authorization'});
89
+ let interval=Math.max(5,Number(d.interval)||5),failures=0;const deadline=this.now()+Math.min(900,Number(d.expires_in)||900)*1000;
90
+ while(this.now()<deadline){
91
+ const wait=Math.max(interval,Math.min(60,interval*2**Math.min(failures,4)))*1000;
92
+ if(this.now()+wait>=deadline)break;await this.sleep(wait,signal);signal.throwIfAborted();if(this.now()>=deadline)break;
93
+ let r;try{r=await this.request('https://github.com/login/oauth/access_token',{client_id:clientId,device_code:d.device_code,grant_type:'urn:ietf:params:oauth:grant-type:device_code'},{signal,attempts:1,deadline});}
94
+ catch(e){if(signal.aborted||!e.retryable)throw e;failures++;interval=Math.max(interval,e.retryAfter??0);notify(e);continue;}
95
+ failures=0;this.login={...this.login,message:undefined};
96
+ if(r.access_token){await this.save(r,epoch,clientId);signal.throwIfAborted();this.login={state:'complete'};return;}
97
+ if(r.error==='authorization_pending')continue;
98
+ if(r.error==='slow_down'){interval=Math.max(interval+5,Number(r.interval)||0);continue;}
99
+ throw Object.assign(Error(r.error==='access_denied'?'你已取消 GitHub 授权。':'GitHub 授权已过期或被拒绝,请重新登录。'),{reason:r.error});
100
+ }
101
+ throw Object.assign(Error('设备授权已过期,请重新登录。'),{reason:'expired_token'});
102
+ }catch(e){if(epoch!==this.epoch)return;this.diagnostics('oauth_failed',{category:'authorization',reason:e.reason??'authorization_failed'});this.login={state:'error',message:e.message};}})();return this.login;
103
+ }
104
+ cancel(){++this.epoch;this.controller?.abort();this.refreshController?.abort();this.login={state:'idle'};}
105
+ mutate(fn){const task=(this.mutation??Promise.resolve()).catch(()=>{}).then(fn);this.mutation=task;return task;}
106
+ async logout(){this.cancel();await this.mutate(()=>this.credentialStore.remove());this.diagnostics('logout',{reason:'local_disconnect',hasCredential:false});}
107
+ dispose(){this.cancel();}
16
108
  }
17
109