dsh-qwenwork-connect 0.2.2 → 0.3.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.
- package/README.md +58 -19
- package/THIRD-PARTY-NOTICES.md +135 -0
- package/bin/login.mjs +26 -6
- package/lib/catalog.js +179 -0
- package/lib/chat-shim.js +51 -23
- package/lib/client.js +281 -30
- package/lib/cosy.js +203 -0
- package/lib/credentials-seam.js +1 -1
- package/lib/credentials.js +1 -1
- package/lib/endpoint.js +2 -2
- package/lib/index.js +155 -45
- package/lib/login-device-flow.js +20 -2
- package/lib/login-route.js +31 -4
- package/lib/logout-route.js +90 -0
- package/lib/models.js +8 -10
- package/lib/rest.js +2 -2
- package/lib/signer-session.js +73 -212
- package/lib/signer-shim.js +1 -1
- package/lib/sse.js +21 -19
- package/lib/upstream-errors.js +225 -0
- package/package.json +3 -4
- package/research/qoder-wasm-glue.mjs +0 -329
- package/research/wasm.bin +0 -0
package/lib/client.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* 浏览器侧插件入口:向侧栏「插件」页贡献千问办公配置卡片。
|
|
3
3
|
*
|
|
4
4
|
* 格式要求(与 DSH 0.1.2-rc.1 的 client 模块加载器一致):
|
|
5
5
|
* 本文件不是 ESM 模块,而是 `window.__ModuleLoader__.load({ id, factory })`
|
|
@@ -29,6 +29,12 @@ window.__ModuleLoader__.load({
|
|
|
29
29
|
/** 输入框工具栏的积分读数单独用更长的轮询节奏——它是常驻的,不像卡片那样
|
|
30
30
|
* 只在展开时才拉取,60s 已足够,且省掉一半对状态接口的重复请求。 */
|
|
31
31
|
const COMPOSER_POLL_INTERVAL_MS = 60000;
|
|
32
|
+
/** 设置卡片上的设备码登录(路由在 lib/login-route.js)。 */
|
|
33
|
+
const LOGIN_START_PATH = '/plugins/dsh-qwenwork-connect/login/start';
|
|
34
|
+
const LOGIN_STATUS_PATH = '/plugins/dsh-qwenwork-connect/login/status';
|
|
35
|
+
const LOGOUT_PATH = '/plugins/dsh-qwenwork-connect/logout';
|
|
36
|
+
const LOGIN_POLL_MS = 2000;
|
|
37
|
+
const LOGIN_WAIT_MS = 180000;
|
|
32
38
|
//#endregion
|
|
33
39
|
|
|
34
40
|
//#region 样式
|
|
@@ -182,6 +188,37 @@ window.__ModuleLoader__.load({
|
|
|
182
188
|
fontSize: 13,
|
|
183
189
|
cursor: 'pointer',
|
|
184
190
|
};
|
|
191
|
+
/** 账号行右侧的退出按钮:用错误色标出「这是破坏性操作」,但仍需确认。 */
|
|
192
|
+
const logoutButtonStyle = {
|
|
193
|
+
...refreshButtonStyle,
|
|
194
|
+
marginLeft: 'auto',
|
|
195
|
+
color: 'var(--dsw-alias-state-error-primary, #d92d20)',
|
|
196
|
+
fontSize: 12,
|
|
197
|
+
padding: '3px 10px',
|
|
198
|
+
};
|
|
199
|
+
const actionRowStyle = {
|
|
200
|
+
display: 'flex',
|
|
201
|
+
alignItems: 'center',
|
|
202
|
+
gap: 8,
|
|
203
|
+
flex: '0 0 auto',
|
|
204
|
+
};
|
|
205
|
+
const loginPanelStyle = {
|
|
206
|
+
display: 'flex',
|
|
207
|
+
flexDirection: 'column',
|
|
208
|
+
gap: 6,
|
|
209
|
+
marginTop: 10,
|
|
210
|
+
padding: '10px 12px',
|
|
211
|
+
border: '1px solid var(--dsw-alias-border-l2)',
|
|
212
|
+
borderRadius: 8,
|
|
213
|
+
background: 'var(--dsw-alias-bg-module-platform)',
|
|
214
|
+
fontSize: 13,
|
|
215
|
+
lineHeight: '20px',
|
|
216
|
+
color: 'var(--dsw-alias-label-secondary)',
|
|
217
|
+
};
|
|
218
|
+
const loginLinkStyle = {
|
|
219
|
+
color: 'var(--dsw-alias-label-primary)',
|
|
220
|
+
wordBreak: 'break-all',
|
|
221
|
+
};
|
|
185
222
|
/** 千分位格式化(积分 / 请求数等)。 */
|
|
186
223
|
function formatNumber(value) {
|
|
187
224
|
if (typeof value !== 'number' || !Number.isFinite(value)) return String(value ?? '');
|
|
@@ -395,6 +432,11 @@ window.__ModuleLoader__.load({
|
|
|
395
432
|
if (state === null) {
|
|
396
433
|
return react_jsx_runtime.jsx('div', { style: errorStyle, children: t('loading') });
|
|
397
434
|
}
|
|
435
|
+
// 退出登录后 getAccountContext 会抛 CREDENTIALS_MISSING——这是预期状态,
|
|
436
|
+
// 不是故障:顶部已有「尚未登录 + 登录按钮」,不该再甩一段红色报错。
|
|
437
|
+
if (state.status === 'signed-out' && state.error?.code === 'CREDENTIALS_MISSING') {
|
|
438
|
+
return null;
|
|
439
|
+
}
|
|
398
440
|
if (state.error !== undefined && state.status !== 'signed-in') {
|
|
399
441
|
const err = state.error;
|
|
400
442
|
const text = [err.message, err.recovery].filter(Boolean).join('\n');
|
|
@@ -415,6 +457,18 @@ window.__ModuleLoader__.load({
|
|
|
415
457
|
react_jsx_runtime.jsx('span', {
|
|
416
458
|
children: t('signedInAs', { name: state.nickname ?? state.account ?? '—' }),
|
|
417
459
|
}),
|
|
460
|
+
typeof props.onLogout === 'function'
|
|
461
|
+
? react_jsx_runtime.jsx('button', {
|
|
462
|
+
type: 'button',
|
|
463
|
+
disabled: props.logoutBusy === true,
|
|
464
|
+
style:
|
|
465
|
+
props.logoutBusy === true
|
|
466
|
+
? { ...logoutButtonStyle, opacity: 0.6, cursor: 'default' }
|
|
467
|
+
: logoutButtonStyle,
|
|
468
|
+
onClick: props.onLogout,
|
|
469
|
+
children: props.logoutBusy === true ? t('loggingOut') : t('logout'),
|
|
470
|
+
})
|
|
471
|
+
: null,
|
|
418
472
|
],
|
|
419
473
|
},
|
|
420
474
|
'who',
|
|
@@ -604,6 +658,11 @@ window.__ModuleLoader__.load({
|
|
|
604
658
|
const [state, setState] = react.useState(props.initialState ?? null);
|
|
605
659
|
const [busy, setBusy] = react.useState(false);
|
|
606
660
|
const [nonce, setNonce] = react.useState(0);
|
|
661
|
+
/** 设备码登录的本地阶段:null | { phase, url?, error? }。 */
|
|
662
|
+
const [login, setLogin] = react.useState(null);
|
|
663
|
+
const [loginBusy, setLoginBusy] = react.useState(false);
|
|
664
|
+
const [logoutBusy, setLogoutBusy] = react.useState(false);
|
|
665
|
+
const [logoutError, setLogoutError] = react.useState(null);
|
|
607
666
|
|
|
608
667
|
react.useEffect(() => {
|
|
609
668
|
let cancelled = false;
|
|
@@ -642,6 +701,103 @@ window.__ModuleLoader__.load({
|
|
|
642
701
|
};
|
|
643
702
|
}, [open, t, nonce]);
|
|
644
703
|
|
|
704
|
+
// 登录轮询:拿到授权 URL 后每 2s 问一次 /login/status,
|
|
705
|
+
// 直到凭据落盘(ready)或后端报失败;成功后刷新状态卡。
|
|
706
|
+
react.useEffect(() => {
|
|
707
|
+
if (login === null || login.phase !== 'pending') return undefined;
|
|
708
|
+
let cancelled = false;
|
|
709
|
+
const startedAt = Date.now();
|
|
710
|
+
const timer = setInterval(async () => {
|
|
711
|
+
if (Date.now() - startedAt > LOGIN_WAIT_MS) {
|
|
712
|
+
clearInterval(timer);
|
|
713
|
+
if (!cancelled) setLogin({ phase: 'failed', error: t('loginTimeout') });
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
try {
|
|
717
|
+
const response = await fetch(LOGIN_STATUS_PATH, {
|
|
718
|
+
headers: { accept: 'application/json' },
|
|
719
|
+
credentials: 'same-origin',
|
|
720
|
+
});
|
|
721
|
+
if (!response.ok) return;
|
|
722
|
+
const body = await response.json();
|
|
723
|
+
if (cancelled) return;
|
|
724
|
+
if (body?.phase === 'ready') {
|
|
725
|
+
clearInterval(timer);
|
|
726
|
+
setLogin(null);
|
|
727
|
+
setNonce((value) => value + 1);
|
|
728
|
+
} else if (body?.phase === 'failed') {
|
|
729
|
+
clearInterval(timer);
|
|
730
|
+
setLogin({
|
|
731
|
+
phase: 'failed',
|
|
732
|
+
error: typeof body.error === 'string' ? body.error : t('loginFailed'),
|
|
733
|
+
});
|
|
734
|
+
}
|
|
735
|
+
} catch {
|
|
736
|
+
// 网络抖动:下一轮再试
|
|
737
|
+
}
|
|
738
|
+
}, LOGIN_POLL_MS);
|
|
739
|
+
return () => {
|
|
740
|
+
cancelled = true;
|
|
741
|
+
clearInterval(timer);
|
|
742
|
+
};
|
|
743
|
+
}, [login, t]);
|
|
744
|
+
|
|
745
|
+
/** 设备码登录:拿链接 → 开新标签页 → 轮询状态。 */
|
|
746
|
+
const startLogin = async () => {
|
|
747
|
+
setLoginBusy(true);
|
|
748
|
+
try {
|
|
749
|
+
const response = await fetch(LOGIN_START_PATH, {
|
|
750
|
+
method: 'POST',
|
|
751
|
+
headers: { accept: 'application/json' },
|
|
752
|
+
credentials: 'same-origin',
|
|
753
|
+
});
|
|
754
|
+
const body = await response.json().catch(() => null);
|
|
755
|
+
if (!response.ok) {
|
|
756
|
+
throw new Error(body?.error ?? `${t('requestFailed')} (HTTP ${response.status})`);
|
|
757
|
+
}
|
|
758
|
+
if (typeof body?.url !== 'string' || body.url === '') {
|
|
759
|
+
throw new Error(t('loginFailed'));
|
|
760
|
+
}
|
|
761
|
+
setLogin({ phase: 'pending', url: body.url });
|
|
762
|
+
window.open(body.url, '_blank', 'noopener,noreferrer');
|
|
763
|
+
} catch (error) {
|
|
764
|
+
setLogin({
|
|
765
|
+
phase: 'failed',
|
|
766
|
+
error: error instanceof Error ? error.message : String(error),
|
|
767
|
+
});
|
|
768
|
+
} finally {
|
|
769
|
+
setLoginBusy(false);
|
|
770
|
+
}
|
|
771
|
+
};
|
|
772
|
+
|
|
773
|
+
/** 退出登录:确认 → 删除本机凭据 → 立即重拉状态(回到未登录)。 */
|
|
774
|
+
const logout = async () => {
|
|
775
|
+
if (typeof window !== 'undefined' && typeof window.confirm === 'function') {
|
|
776
|
+
if (!window.confirm(t('logoutConfirm'))) return;
|
|
777
|
+
}
|
|
778
|
+
setLogoutBusy(true);
|
|
779
|
+
setLogoutError(null);
|
|
780
|
+
try {
|
|
781
|
+
const response = await fetch(LOGOUT_PATH, {
|
|
782
|
+
method: 'POST',
|
|
783
|
+
headers: { accept: 'application/json' },
|
|
784
|
+
credentials: 'same-origin',
|
|
785
|
+
});
|
|
786
|
+
const body = await response.json().catch(() => null);
|
|
787
|
+
if (!response.ok) {
|
|
788
|
+
throw new Error(body?.error ?? `${t('requestFailed')} (HTTP ${response.status})`);
|
|
789
|
+
}
|
|
790
|
+
setLogin(null);
|
|
791
|
+
setNonce((value) => value + 1);
|
|
792
|
+
} catch (error) {
|
|
793
|
+
setLogoutError(
|
|
794
|
+
`${t('logoutFailed')}: ${error instanceof Error ? error.message : String(error)}`,
|
|
795
|
+
);
|
|
796
|
+
} finally {
|
|
797
|
+
setLogoutBusy(false);
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
|
|
645
801
|
const signedIn = state !== null && state.status === 'signed-in';
|
|
646
802
|
const subtitle = signedIn
|
|
647
803
|
? state.remaining === undefined
|
|
@@ -685,22 +841,83 @@ window.__ModuleLoader__.load({
|
|
|
685
841
|
children: [
|
|
686
842
|
react_jsx_runtime.jsx('div', {
|
|
687
843
|
style: { fontSize: 13, lineHeight: '20px', color: 'var(--dsw-alias-label-secondary)' },
|
|
688
|
-
children: signedIn ? t('signedIn') : t('
|
|
844
|
+
children: signedIn ? t('signedIn') : t('notSignedIn'),
|
|
689
845
|
}),
|
|
690
|
-
react_jsx_runtime.
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
846
|
+
react_jsx_runtime.jsxs('div', {
|
|
847
|
+
style: actionRowStyle,
|
|
848
|
+
children: [
|
|
849
|
+
signedIn
|
|
850
|
+
? null
|
|
851
|
+
: react_jsx_runtime.jsx('button', {
|
|
852
|
+
type: 'button',
|
|
853
|
+
style: refreshButtonStyle,
|
|
854
|
+
disabled: loginBusy || (login !== null && login.phase === 'pending'),
|
|
855
|
+
onClick: startLogin,
|
|
856
|
+
children:
|
|
857
|
+
loginBusy || (login !== null && login.phase === 'pending')
|
|
858
|
+
? t('loggingIn')
|
|
859
|
+
: t('login'),
|
|
860
|
+
}),
|
|
861
|
+
react_jsx_runtime.jsx('button', {
|
|
862
|
+
type: 'button',
|
|
863
|
+
style: refreshButtonStyle,
|
|
864
|
+
disabled: busy,
|
|
865
|
+
onClick: () => {
|
|
866
|
+
setBusy(true);
|
|
867
|
+
setNonce((v) => v + 1);
|
|
868
|
+
setTimeout(() => setBusy(false), 800);
|
|
869
|
+
},
|
|
870
|
+
children: busy ? t('refreshing') : t('refresh'),
|
|
871
|
+
}),
|
|
872
|
+
],
|
|
700
873
|
}),
|
|
701
874
|
],
|
|
702
875
|
}),
|
|
703
|
-
|
|
876
|
+
signedIn || login !== null
|
|
877
|
+
? null
|
|
878
|
+
: react_jsx_runtime.jsx('div', {
|
|
879
|
+
style: {
|
|
880
|
+
marginTop: 8,
|
|
881
|
+
fontSize: 13,
|
|
882
|
+
lineHeight: '20px',
|
|
883
|
+
color: 'var(--dsw-alias-label-secondary)',
|
|
884
|
+
},
|
|
885
|
+
children: t('loginHint'),
|
|
886
|
+
}),
|
|
887
|
+
login === null
|
|
888
|
+
? null
|
|
889
|
+
: react_jsx_runtime.jsxs('div', {
|
|
890
|
+
style: loginPanelStyle,
|
|
891
|
+
children: [
|
|
892
|
+
react_jsx_runtime.jsx('span', {
|
|
893
|
+
children:
|
|
894
|
+
login.phase === 'failed'
|
|
895
|
+
? login.error ?? t('loginFailed')
|
|
896
|
+
: t('loginWaiting'),
|
|
897
|
+
}),
|
|
898
|
+
login.phase === 'pending' && typeof login.url === 'string'
|
|
899
|
+
? react_jsx_runtime.jsx('a', {
|
|
900
|
+
href: login.url,
|
|
901
|
+
target: '_blank',
|
|
902
|
+
rel: 'noopener noreferrer',
|
|
903
|
+
style: loginLinkStyle,
|
|
904
|
+
children: login.url,
|
|
905
|
+
})
|
|
906
|
+
: null,
|
|
907
|
+
],
|
|
908
|
+
}),
|
|
909
|
+
logoutError === null
|
|
910
|
+
? null
|
|
911
|
+
: react_jsx_runtime.jsx('div', {
|
|
912
|
+
style: loginPanelStyle,
|
|
913
|
+
children: logoutError,
|
|
914
|
+
}),
|
|
915
|
+
react_jsx_runtime.jsx(StatusBody, {
|
|
916
|
+
state,
|
|
917
|
+
t,
|
|
918
|
+
onLogout: logout,
|
|
919
|
+
logoutBusy,
|
|
920
|
+
}),
|
|
704
921
|
],
|
|
705
922
|
})
|
|
706
923
|
: null,
|
|
@@ -851,12 +1068,23 @@ window.__ModuleLoader__.load({
|
|
|
851
1068
|
//#region 文案
|
|
852
1069
|
const zh = {
|
|
853
1070
|
title: '千问办公',
|
|
854
|
-
subtitle: '
|
|
1071
|
+
subtitle: '设备码登录,直连千问办公网关',
|
|
1072
|
+
notSignedIn: '未登录',
|
|
855
1073
|
signedIn: '已登录',
|
|
856
1074
|
signedInAs: '已登录:{name}',
|
|
857
1075
|
loading: '正在读取状态…',
|
|
858
1076
|
refresh: '刷新',
|
|
859
1077
|
refreshing: '刷新中…',
|
|
1078
|
+
login: '登录',
|
|
1079
|
+
loggingIn: '等待授权…',
|
|
1080
|
+
loginHint: '尚未登录。点「登录」后,在浏览器里选择账号与团队。',
|
|
1081
|
+
loginWaiting: '已打开授权页,等待你在浏览器里完成授权…',
|
|
1082
|
+
loginTimeout: '登录超时,请重试',
|
|
1083
|
+
loginFailed: '登录失败',
|
|
1084
|
+
logout: '退出登录',
|
|
1085
|
+
loggingOut: '正在退出…',
|
|
1086
|
+
logoutConfirm: '确定要退出登录吗?本机凭据会被删除,可随时重新登录。',
|
|
1087
|
+
logoutFailed: '退出登录失败',
|
|
860
1088
|
accountHeading: '账号',
|
|
861
1089
|
quotaHeading: '剩余积分',
|
|
862
1090
|
nickname: '账号',
|
|
@@ -899,16 +1127,27 @@ window.__ModuleLoader__.load({
|
|
|
899
1127
|
// 输入框工具栏积分读数
|
|
900
1128
|
creditsUnavailable: '未登录',
|
|
901
1129
|
creditsDegraded: '积分暂不可用',
|
|
902
|
-
composerTooltip: '千问办公剩余积分 ·
|
|
1130
|
+
composerTooltip: '千问办公剩余积分 · 打开左侧「插件」→ dsh-qwenwork-connect 查看详情',
|
|
903
1131
|
};
|
|
904
1132
|
const en = {
|
|
905
1133
|
title: 'QwenWork',
|
|
906
|
-
subtitle: "
|
|
1134
|
+
subtitle: "Device-code sign-in, direct to the QwenWork gateway",
|
|
1135
|
+
notSignedIn: 'Not signed in',
|
|
907
1136
|
signedIn: 'Signed in',
|
|
908
1137
|
signedInAs: 'Signed in: {name}',
|
|
909
1138
|
loading: 'Reading status…',
|
|
910
1139
|
refresh: 'Refresh',
|
|
911
1140
|
refreshing: 'Refreshing…',
|
|
1141
|
+
login: 'Sign in',
|
|
1142
|
+
loggingIn: 'Waiting for authorization…',
|
|
1143
|
+
loginHint: 'Not signed in. Click "Sign in" and choose an account and team in the browser.',
|
|
1144
|
+
loginWaiting: 'Authorization page opened; waiting for you to finish in the browser…',
|
|
1145
|
+
loginTimeout: 'Sign-in timed out. Please try again.',
|
|
1146
|
+
loginFailed: 'Sign-in failed',
|
|
1147
|
+
logout: 'Sign out',
|
|
1148
|
+
loggingOut: 'Signing out…',
|
|
1149
|
+
logoutConfirm: 'Sign out of this device? The local credentials will be removed; you can sign in again anytime.',
|
|
1150
|
+
logoutFailed: 'Sign-out failed',
|
|
912
1151
|
accountHeading: 'Account',
|
|
913
1152
|
quotaHeading: 'Remaining credits',
|
|
914
1153
|
nickname: 'Account',
|
|
@@ -945,7 +1184,7 @@ window.__ModuleLoader__.load({
|
|
|
945
1184
|
// 输入框工具栏积分读数
|
|
946
1185
|
creditsUnavailable: 'Signed out',
|
|
947
1186
|
creditsDegraded: 'Quota unavailable',
|
|
948
|
-
composerTooltip: 'QwenWork credits remaining · see
|
|
1187
|
+
composerTooltip: 'QwenWork credits remaining · see Plugins → dsh-qwenwork-connect',
|
|
949
1188
|
};
|
|
950
1189
|
//#endregion
|
|
951
1190
|
|
|
@@ -955,8 +1194,12 @@ window.__ModuleLoader__.load({
|
|
|
955
1194
|
/**
|
|
956
1195
|
* 注册卡片文案与卡片本体。
|
|
957
1196
|
*
|
|
958
|
-
* 0.1.2
|
|
959
|
-
*
|
|
1197
|
+
* DSH 0.2.1-rc.2+ 废弃了 `settings.plugin.item`,插件配置改挂在
|
|
1198
|
+
* 侧栏「插件」页:
|
|
1199
|
+
* - `plugins.bundle.config`:key = 包名,渲染在 bundle 详情页;
|
|
1200
|
+
* - `plugins.row.config`:key = `<包名>#<patch 行 id>`,给该行一个
|
|
1201
|
+
* Configure 入口。
|
|
1202
|
+
* 两个席位共用同一个卡片;`view === 'summary'` 时只回一行摘要。
|
|
960
1203
|
*/
|
|
961
1204
|
function apply(ctx) {
|
|
962
1205
|
try {
|
|
@@ -966,17 +1209,25 @@ window.__ModuleLoader__.load({
|
|
|
966
1209
|
'dsh-qwenwork-connect: settings copy',
|
|
967
1210
|
);
|
|
968
1211
|
const t = ctx.locale.bind(namespace);
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
1212
|
+
const renderConfig = (slotProps) =>
|
|
1213
|
+
slotProps && slotProps.view === 'summary'
|
|
1214
|
+
? t('subtitle')
|
|
1215
|
+
: react_jsx_runtime.jsx(QwenWorkPluginCard, { t, initialOpen: true });
|
|
1216
|
+
for (const [slot, key] of [
|
|
1217
|
+
['plugins.bundle.config', 'dsh-qwenwork-connect'],
|
|
1218
|
+
['plugins.row.config', 'dsh-qwenwork-connect#llm-qwenwork'],
|
|
1219
|
+
]) {
|
|
1220
|
+
try {
|
|
1221
|
+
ctx.slots.inject(slot, () =>
|
|
1222
|
+
ctx.slots.register({ name: slot, key }, renderConfig),
|
|
1223
|
+
);
|
|
1224
|
+
} catch (error) {
|
|
1225
|
+
console.error(
|
|
1226
|
+
`[dsh-qwen-connect] ${slot} config slot failed to register:`,
|
|
1227
|
+
error,
|
|
1228
|
+
);
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
980
1231
|
// 输入框工具栏的积分读数。注册本身无条件,渲染与否由 ComposerCredits
|
|
981
1232
|
// 内部的 provider gate 决定(见该组件注释),所以这里再包一层 try/catch
|
|
982
1233
|
// 兜住「插槽席位不存在/字段变更」——不能因为它挂了就连带卡片也不显示。
|
package/lib/cosy.js
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 手写 COSY 信封签名(替代 WASM 签名路径)。
|
|
3
|
+
*
|
|
4
|
+
* 上游每个请求都带 `Authorization: Bearer COSY.<payload>.<sig>`:
|
|
5
|
+
* 1. 账号信息打包成 JSON,用一次性 AES-128-CBC 加密(密钥即 IV)→ `info`;
|
|
6
|
+
* 该密钥再用客户端内置 RSA 公钥加密 → `key`
|
|
7
|
+
* 2. payload = base64(JSON{v1, requestId, info, cosyVersion, ideVersion:""})
|
|
8
|
+
* 3. sig = md5(`${payload}\n${key}\n${ts}\n${body}\n${path}`)
|
|
9
|
+
*
|
|
10
|
+
* 请求体还会经过一套自定义字母表 + 三段交换的编码(`Encode=1`),
|
|
11
|
+
* 签名对的是**编码后的 wire body**。
|
|
12
|
+
*
|
|
13
|
+
* 移植自 @magpie-community/opencode-qoder-auth(MIT,见 THIRD-PARTY-NOTICES.md),
|
|
14
|
+
* 字段与客户端 1.2.0 实测一致。
|
|
15
|
+
*
|
|
16
|
+
* @module dsh-qwenwork-connect/cosy
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
constants,
|
|
21
|
+
createCipheriv,
|
|
22
|
+
createHash,
|
|
23
|
+
publicEncrypt,
|
|
24
|
+
randomBytes,
|
|
25
|
+
randomUUID,
|
|
26
|
+
} from 'node:crypto';
|
|
27
|
+
|
|
28
|
+
/** 客户端内置的 RSA 公钥,只用来包裹每次请求的 AES 密钥。 */
|
|
29
|
+
export const COSY_RSA_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
|
30
|
+
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
|
|
31
|
+
4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
|
|
32
|
+
6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
|
|
33
|
+
XcW+ML9FoCI6AOvOzwIDAQAB
|
|
34
|
+
-----END PUBLIC KEY-----`;
|
|
35
|
+
|
|
36
|
+
/** 自定义编码字母表(`Encode=1`)。 */
|
|
37
|
+
const ALPHABET = '_doRTgHZBKcGVjlvpC,@aFSx#DPuNJme&i*MzLOEn)sUrthbf%Y^w.(kIQyXqWA!';
|
|
38
|
+
const PAD = '$';
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 把请求体编码成上游 wire 形态。
|
|
42
|
+
* @param {string} text
|
|
43
|
+
* @returns {string}
|
|
44
|
+
*/
|
|
45
|
+
export function encodeBody(text) {
|
|
46
|
+
return swapThirds(segmentEncode(new TextEncoder().encode(text)));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 把上游 wire 形态解回明文(响应体可能被同样编码)。
|
|
51
|
+
* @param {string} wire
|
|
52
|
+
* @returns {string}
|
|
53
|
+
*/
|
|
54
|
+
export function decodeBody(wire) {
|
|
55
|
+
const s = swapThirds(wire);
|
|
56
|
+
const out = [];
|
|
57
|
+
for (let g = 0; g + 4 <= s.length; g += 4) {
|
|
58
|
+
const vals = [...s.slice(g, g + 4)].filter((c) => c !== PAD).map((c) => ALPHABET.indexOf(c));
|
|
59
|
+
if (vals.some((v) => v < 0)) {
|
|
60
|
+
throw new Error('qwenwork: body 含未知字符,不是 COSY 编码');
|
|
61
|
+
}
|
|
62
|
+
let x = 0;
|
|
63
|
+
for (const v of vals) x = x * 64 + v;
|
|
64
|
+
const n = Math.floor((6 * vals.length) / 8);
|
|
65
|
+
for (let k = 0; k < n; k++) {
|
|
66
|
+
out.push(Math.floor(x / 2 ** (6 * vals.length - 8 * (k + 1))) & 255);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return new TextDecoder().decode(new Uint8Array(out));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** 字符串看起来像 COSY 编码(而不是明文 JSON/SSE)。 */
|
|
73
|
+
export function looksEncoded(text) {
|
|
74
|
+
const t = String(text ?? '').trim();
|
|
75
|
+
if (t === '') return false;
|
|
76
|
+
if (t.startsWith('{') || t.startsWith('[')) return false;
|
|
77
|
+
return [...t].every((c) => c === PAD || ALPHABET.includes(c));
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 生成一次请求的 COSY 头。
|
|
82
|
+
*
|
|
83
|
+
* @param {object} params
|
|
84
|
+
* @param {string} params.url 完整请求 URL(签名时去掉 `/algo` 前缀)
|
|
85
|
+
* @param {any} params.credential 归一化凭据(token / user / loginDeviceId)
|
|
86
|
+
* @param {string} params.machineId
|
|
87
|
+
* @param {string} params.cosyVersion
|
|
88
|
+
* @param {string} [params.body] wire body(GET 为空串)
|
|
89
|
+
* @param {'chat'|'json'} [params.mode]
|
|
90
|
+
* @param {string} [params.modelKey] chat 模式必填
|
|
91
|
+
* @returns {{ headers: Record<string,string>, payload: string, signature: string }}
|
|
92
|
+
*/
|
|
93
|
+
export function buildCosyHeaders(params) {
|
|
94
|
+
const credential = params.credential ?? {};
|
|
95
|
+
const user = credential.user ?? {};
|
|
96
|
+
const uid = String(user.uid ?? user.id ?? '');
|
|
97
|
+
const token = typeof credential.token === 'string' ? credential.token : '';
|
|
98
|
+
if (uid === '' || token === '') {
|
|
99
|
+
throw new Error('qwenwork: COSY 签名缺少 uid 或 token');
|
|
100
|
+
}
|
|
101
|
+
const machineId = String(params.machineId ?? '');
|
|
102
|
+
if (machineId === '') throw new Error('qwenwork: COSY 签名缺少 machineId');
|
|
103
|
+
|
|
104
|
+
const { info, key } = buildUserBlob({ uid, user, token });
|
|
105
|
+
const payload = Buffer.from(
|
|
106
|
+
JSON.stringify({
|
|
107
|
+
version: 'v1',
|
|
108
|
+
requestId: randomUUID(),
|
|
109
|
+
info,
|
|
110
|
+
cosyVersion: params.cosyVersion,
|
|
111
|
+
ideVersion: '',
|
|
112
|
+
}),
|
|
113
|
+
).toString('base64');
|
|
114
|
+
|
|
115
|
+
const path = signedPath(params.url);
|
|
116
|
+
const ts = Math.floor(Date.now() / 1000);
|
|
117
|
+
const body = params.body ?? '';
|
|
118
|
+
const signature = createHash('md5')
|
|
119
|
+
.update(`${payload}\n${key}\n${ts}\n${body}\n${path}`)
|
|
120
|
+
.digest('hex');
|
|
121
|
+
|
|
122
|
+
const headers = {
|
|
123
|
+
Accept: params.mode === 'chat' ? 'text/event-stream' : 'application/json',
|
|
124
|
+
'Content-Type': 'application/json',
|
|
125
|
+
Authorization: `Bearer COSY.${payload}.${signature}`,
|
|
126
|
+
'Cosy-Business-Product': 'qoder_work',
|
|
127
|
+
'Cosy-Business-Type': 'agent',
|
|
128
|
+
'Cosy-ClientType': '6',
|
|
129
|
+
'Cosy-Data-Policy': user.data_policy_agreed === false ? 'disagree' : 'agree',
|
|
130
|
+
'Cosy-Date': String(ts),
|
|
131
|
+
'Cosy-Key': key,
|
|
132
|
+
'Cosy-MachineId': machineId,
|
|
133
|
+
'Cosy-MachineToken': machineId,
|
|
134
|
+
'Cosy-MachineType': '5',
|
|
135
|
+
...(typeof user.organization_id === 'string' && user.organization_id !== ''
|
|
136
|
+
? { 'Cosy-Organization-Id': user.organization_id }
|
|
137
|
+
: {}),
|
|
138
|
+
'Cosy-Scene': 'assistant',
|
|
139
|
+
'Cosy-User': uid,
|
|
140
|
+
'Cosy-Version': params.cosyVersion,
|
|
141
|
+
'Login-Version': 'v2',
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
if (params.mode === 'chat') {
|
|
145
|
+
headers['Cache-Control'] = 'no-cache';
|
|
146
|
+
headers.Connection = 'keep-alive';
|
|
147
|
+
if (typeof params.modelKey === 'string' && params.modelKey !== '') {
|
|
148
|
+
headers['X-Model-Key'] = params.modelKey;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return { headers, payload, signature };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 账号信息信封:AES-128-CBC(密钥=IV)+ RSA 包裹密钥。 */
|
|
156
|
+
function buildUserBlob({ uid, user, token }) {
|
|
157
|
+
const raw = JSON.stringify({
|
|
158
|
+
uid,
|
|
159
|
+
aid: '',
|
|
160
|
+
name: typeof user.name === 'string' ? user.name : '',
|
|
161
|
+
email: typeof user.email === 'string' ? user.email : '',
|
|
162
|
+
security_oauth_token: token,
|
|
163
|
+
});
|
|
164
|
+
const key = Buffer.from(randomBytes(8).toString('hex').slice(0, 16));
|
|
165
|
+
const cipher = createCipheriv('aes-128-cbc', key, key);
|
|
166
|
+
const info = Buffer.concat([cipher.update(raw, 'utf8'), cipher.final()]).toString('base64');
|
|
167
|
+
const wrapped = publicEncrypt(
|
|
168
|
+
{ key: COSY_RSA_PUBLIC_KEY, padding: constants.RSA_PKCS1_PADDING },
|
|
169
|
+
key,
|
|
170
|
+
).toString('base64');
|
|
171
|
+
return { info, key: wrapped };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** 签名用的 path:去掉 `/algo` 前缀,不带 query。 */
|
|
175
|
+
function signedPath(url) {
|
|
176
|
+
let path = new URL(url).pathname;
|
|
177
|
+
if (path.startsWith('/algo')) path = path.slice(5);
|
|
178
|
+
return path;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 自定义 base64:6 bit 一组,用私有字母表。 */
|
|
182
|
+
function segmentEncode(bytes) {
|
|
183
|
+
let s = '';
|
|
184
|
+
let acc = 0;
|
|
185
|
+
let nb = 0;
|
|
186
|
+
for (const b of bytes) {
|
|
187
|
+
acc = ((acc << 8) | b) & 0xffffff;
|
|
188
|
+
nb += 8;
|
|
189
|
+
while (nb >= 6) {
|
|
190
|
+
nb -= 6;
|
|
191
|
+
s += ALPHABET[(acc >> nb) & 63];
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (nb > 0) s += ALPHABET[(acc << (6 - nb)) & 63];
|
|
195
|
+
while (s.length % 4) s += PAD;
|
|
196
|
+
return s;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** 三段交换。 */
|
|
200
|
+
function swapThirds(s) {
|
|
201
|
+
const t = Math.floor(s.length / 3);
|
|
202
|
+
return t ? s.slice(s.length - t) + s.slice(t, s.length - t) + s.slice(0, t) : s;
|
|
203
|
+
}
|
package/lib/credentials-seam.js
CHANGED
|
@@ -187,7 +187,7 @@ export async function getValidToken(opts) {
|
|
|
187
187
|
*
|
|
188
188
|
* 为什么需要它(而不是复用 `getValidToken()` 再单独读磁盘):
|
|
189
189
|
*
|
|
190
|
-
* 阶段 A-2 的
|
|
190
|
+
* 阶段 A-2 的 COSY 签名除 token 外还要 `user.id` 与 `loginDeviceId`。
|
|
191
191
|
* 早期实现直接 `loadCredentials()` 读磁盘,绕过了 t1 的刷新链路,存在
|
|
192
192
|
* **两个真实缺陷**:
|
|
193
193
|
* 1. token 已过期时拿到的是失效 token(签名请求会被 401/403 拒绝);
|
package/lib/credentials.js
CHANGED
|
@@ -224,7 +224,7 @@ function normalizeUser(u) {
|
|
|
224
224
|
planName: u.planName ?? null,
|
|
225
225
|
planId: u.planId ?? null,
|
|
226
226
|
isBiz: u.isBiz ?? false,
|
|
227
|
-
// 企业 VPC 必需:
|
|
227
|
+
// 企业 VPC 必需:COSY 签名载荷(签名信封与
|
|
228
228
|
// QoderContext)依赖 organization_id / data_policy_agreed——缺失时
|
|
229
229
|
// 企业租户在 VPC 网关上得到 503 Model authorization unavailable
|
|
230
230
|
// (实测:补齐后目录/推理恢复 200)。auth-v2.dat 常缺这两个字段,
|
package/lib/endpoint.js
CHANGED
|
@@ -14,8 +14,8 @@
|
|
|
14
14
|
*
|
|
15
15
|
* 实测依据(2026-10-23,企业 VPC 租户探针脚本,已清理):
|
|
16
16
|
* - VPC /api/v1/adapter/user/account-context → 200(quota/plan 齐全);
|
|
17
|
-
* - VPC /algo/api/v2/model/list?Encode=1(
|
|
18
|
-
* - VPC /algo/.../agent_chat_generation(
|
|
17
|
+
* - VPC /algo/api/v2/model/list?Encode=1(COSY 签名)→ 200 真实目录;
|
|
18
|
+
* - VPC /algo/.../agent_chat_generation(COSY 签名)→ 200 流式推理;
|
|
19
19
|
* - 同一 token 打公有云 → 401 INVALID_TOKEN。
|
|
20
20
|
*
|
|
21
21
|
* @module dsh-qwenwork-connect/endpoint
|