dsh-qwenwork-connect 0.2.2 → 0.3.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.
- package/README.md +46 -19
- package/THIRD-PARTY-NOTICES.md +135 -0
- package/lib/catalog.js +179 -0
- package/lib/chat-shim.js +51 -23
- package/lib/client.js +200 -26
- 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 +149 -45
- package/lib/login-route.js +6 -1
- 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,11 @@ 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 LOGIN_POLL_MS = 2000;
|
|
36
|
+
const LOGIN_WAIT_MS = 180000;
|
|
32
37
|
//#endregion
|
|
33
38
|
|
|
34
39
|
//#region 样式
|
|
@@ -182,6 +187,29 @@ window.__ModuleLoader__.load({
|
|
|
182
187
|
fontSize: 13,
|
|
183
188
|
cursor: 'pointer',
|
|
184
189
|
};
|
|
190
|
+
const actionRowStyle = {
|
|
191
|
+
display: 'flex',
|
|
192
|
+
alignItems: 'center',
|
|
193
|
+
gap: 8,
|
|
194
|
+
flex: '0 0 auto',
|
|
195
|
+
};
|
|
196
|
+
const loginPanelStyle = {
|
|
197
|
+
display: 'flex',
|
|
198
|
+
flexDirection: 'column',
|
|
199
|
+
gap: 6,
|
|
200
|
+
marginTop: 10,
|
|
201
|
+
padding: '10px 12px',
|
|
202
|
+
border: '1px solid var(--dsw-alias-border-l2)',
|
|
203
|
+
borderRadius: 8,
|
|
204
|
+
background: 'var(--dsw-alias-bg-module-platform)',
|
|
205
|
+
fontSize: 13,
|
|
206
|
+
lineHeight: '20px',
|
|
207
|
+
color: 'var(--dsw-alias-label-secondary)',
|
|
208
|
+
};
|
|
209
|
+
const loginLinkStyle = {
|
|
210
|
+
color: 'var(--dsw-alias-label-primary)',
|
|
211
|
+
wordBreak: 'break-all',
|
|
212
|
+
};
|
|
185
213
|
/** 千分位格式化(积分 / 请求数等)。 */
|
|
186
214
|
function formatNumber(value) {
|
|
187
215
|
if (typeof value !== 'number' || !Number.isFinite(value)) return String(value ?? '');
|
|
@@ -604,6 +632,9 @@ window.__ModuleLoader__.load({
|
|
|
604
632
|
const [state, setState] = react.useState(props.initialState ?? null);
|
|
605
633
|
const [busy, setBusy] = react.useState(false);
|
|
606
634
|
const [nonce, setNonce] = react.useState(0);
|
|
635
|
+
/** 设备码登录的本地阶段:null | { phase, url?, error? }。 */
|
|
636
|
+
const [login, setLogin] = react.useState(null);
|
|
637
|
+
const [loginBusy, setLoginBusy] = react.useState(false);
|
|
607
638
|
|
|
608
639
|
react.useEffect(() => {
|
|
609
640
|
let cancelled = false;
|
|
@@ -642,6 +673,75 @@ window.__ModuleLoader__.load({
|
|
|
642
673
|
};
|
|
643
674
|
}, [open, t, nonce]);
|
|
644
675
|
|
|
676
|
+
// 登录轮询:拿到授权 URL 后每 2s 问一次 /login/status,
|
|
677
|
+
// 直到凭据落盘(ready)或后端报失败;成功后刷新状态卡。
|
|
678
|
+
react.useEffect(() => {
|
|
679
|
+
if (login === null || login.phase !== 'pending') return undefined;
|
|
680
|
+
let cancelled = false;
|
|
681
|
+
const startedAt = Date.now();
|
|
682
|
+
const timer = setInterval(async () => {
|
|
683
|
+
if (Date.now() - startedAt > LOGIN_WAIT_MS) {
|
|
684
|
+
clearInterval(timer);
|
|
685
|
+
if (!cancelled) setLogin({ phase: 'failed', error: t('loginTimeout') });
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
try {
|
|
689
|
+
const response = await fetch(LOGIN_STATUS_PATH, {
|
|
690
|
+
headers: { accept: 'application/json' },
|
|
691
|
+
credentials: 'same-origin',
|
|
692
|
+
});
|
|
693
|
+
if (!response.ok) return;
|
|
694
|
+
const body = await response.json();
|
|
695
|
+
if (cancelled) return;
|
|
696
|
+
if (body?.phase === 'ready') {
|
|
697
|
+
clearInterval(timer);
|
|
698
|
+
setLogin(null);
|
|
699
|
+
setNonce((value) => value + 1);
|
|
700
|
+
} else if (body?.phase === 'failed') {
|
|
701
|
+
clearInterval(timer);
|
|
702
|
+
setLogin({
|
|
703
|
+
phase: 'failed',
|
|
704
|
+
error: typeof body.error === 'string' ? body.error : t('loginFailed'),
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
} catch {
|
|
708
|
+
// 网络抖动:下一轮再试
|
|
709
|
+
}
|
|
710
|
+
}, LOGIN_POLL_MS);
|
|
711
|
+
return () => {
|
|
712
|
+
cancelled = true;
|
|
713
|
+
clearInterval(timer);
|
|
714
|
+
};
|
|
715
|
+
}, [login, t]);
|
|
716
|
+
|
|
717
|
+
/** 设备码登录:拿链接 → 开新标签页 → 轮询状态。 */
|
|
718
|
+
const startLogin = async () => {
|
|
719
|
+
setLoginBusy(true);
|
|
720
|
+
try {
|
|
721
|
+
const response = await fetch(LOGIN_START_PATH, {
|
|
722
|
+
method: 'POST',
|
|
723
|
+
headers: { accept: 'application/json' },
|
|
724
|
+
credentials: 'same-origin',
|
|
725
|
+
});
|
|
726
|
+
const body = await response.json().catch(() => null);
|
|
727
|
+
if (!response.ok) {
|
|
728
|
+
throw new Error(body?.error ?? `${t('requestFailed')} (HTTP ${response.status})`);
|
|
729
|
+
}
|
|
730
|
+
if (typeof body?.url !== 'string' || body.url === '') {
|
|
731
|
+
throw new Error(t('loginFailed'));
|
|
732
|
+
}
|
|
733
|
+
setLogin({ phase: 'pending', url: body.url });
|
|
734
|
+
window.open(body.url, '_blank', 'noopener,noreferrer');
|
|
735
|
+
} catch (error) {
|
|
736
|
+
setLogin({
|
|
737
|
+
phase: 'failed',
|
|
738
|
+
error: error instanceof Error ? error.message : String(error),
|
|
739
|
+
});
|
|
740
|
+
} finally {
|
|
741
|
+
setLoginBusy(false);
|
|
742
|
+
}
|
|
743
|
+
};
|
|
744
|
+
|
|
645
745
|
const signedIn = state !== null && state.status === 'signed-in';
|
|
646
746
|
const subtitle = signedIn
|
|
647
747
|
? state.remaining === undefined
|
|
@@ -687,19 +787,69 @@ window.__ModuleLoader__.load({
|
|
|
687
787
|
style: { fontSize: 13, lineHeight: '20px', color: 'var(--dsw-alias-label-secondary)' },
|
|
688
788
|
children: signedIn ? t('signedIn') : t('subtitle'),
|
|
689
789
|
}),
|
|
690
|
-
react_jsx_runtime.
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
790
|
+
react_jsx_runtime.jsxs('div', {
|
|
791
|
+
style: actionRowStyle,
|
|
792
|
+
children: [
|
|
793
|
+
signedIn
|
|
794
|
+
? null
|
|
795
|
+
: react_jsx_runtime.jsx('button', {
|
|
796
|
+
type: 'button',
|
|
797
|
+
style: refreshButtonStyle,
|
|
798
|
+
disabled: loginBusy || (login !== null && login.phase === 'pending'),
|
|
799
|
+
onClick: startLogin,
|
|
800
|
+
children:
|
|
801
|
+
loginBusy || (login !== null && login.phase === 'pending')
|
|
802
|
+
? t('loggingIn')
|
|
803
|
+
: t('login'),
|
|
804
|
+
}),
|
|
805
|
+
react_jsx_runtime.jsx('button', {
|
|
806
|
+
type: 'button',
|
|
807
|
+
style: refreshButtonStyle,
|
|
808
|
+
disabled: busy,
|
|
809
|
+
onClick: () => {
|
|
810
|
+
setBusy(true);
|
|
811
|
+
setNonce((v) => v + 1);
|
|
812
|
+
setTimeout(() => setBusy(false), 800);
|
|
813
|
+
},
|
|
814
|
+
children: busy ? t('refreshing') : t('refresh'),
|
|
815
|
+
}),
|
|
816
|
+
],
|
|
700
817
|
}),
|
|
701
818
|
],
|
|
702
819
|
}),
|
|
820
|
+
signedIn || login !== null
|
|
821
|
+
? null
|
|
822
|
+
: react_jsx_runtime.jsx('div', {
|
|
823
|
+
style: {
|
|
824
|
+
marginTop: 8,
|
|
825
|
+
fontSize: 13,
|
|
826
|
+
lineHeight: '20px',
|
|
827
|
+
color: 'var(--dsw-alias-label-secondary)',
|
|
828
|
+
},
|
|
829
|
+
children: t('loginHint'),
|
|
830
|
+
}),
|
|
831
|
+
login === null
|
|
832
|
+
? null
|
|
833
|
+
: react_jsx_runtime.jsxs('div', {
|
|
834
|
+
style: loginPanelStyle,
|
|
835
|
+
children: [
|
|
836
|
+
react_jsx_runtime.jsx('span', {
|
|
837
|
+
children:
|
|
838
|
+
login.phase === 'failed'
|
|
839
|
+
? login.error ?? t('loginFailed')
|
|
840
|
+
: t('loginWaiting'),
|
|
841
|
+
}),
|
|
842
|
+
login.phase === 'pending' && typeof login.url === 'string'
|
|
843
|
+
? react_jsx_runtime.jsx('a', {
|
|
844
|
+
href: login.url,
|
|
845
|
+
target: '_blank',
|
|
846
|
+
rel: 'noopener noreferrer',
|
|
847
|
+
style: loginLinkStyle,
|
|
848
|
+
children: login.url,
|
|
849
|
+
})
|
|
850
|
+
: null,
|
|
851
|
+
],
|
|
852
|
+
}),
|
|
703
853
|
react_jsx_runtime.jsx(StatusBody, { state, t }),
|
|
704
854
|
],
|
|
705
855
|
})
|
|
@@ -857,6 +1007,12 @@ window.__ModuleLoader__.load({
|
|
|
857
1007
|
loading: '正在读取状态…',
|
|
858
1008
|
refresh: '刷新',
|
|
859
1009
|
refreshing: '刷新中…',
|
|
1010
|
+
login: '登录',
|
|
1011
|
+
loggingIn: '等待授权…',
|
|
1012
|
+
loginHint: '尚未登录。点「登录」后,在浏览器里选择账号与团队。',
|
|
1013
|
+
loginWaiting: '已打开授权页,等待你在浏览器里完成授权…',
|
|
1014
|
+
loginTimeout: '登录超时,请重试',
|
|
1015
|
+
loginFailed: '登录失败',
|
|
860
1016
|
accountHeading: '账号',
|
|
861
1017
|
quotaHeading: '剩余积分',
|
|
862
1018
|
nickname: '账号',
|
|
@@ -899,7 +1055,7 @@ window.__ModuleLoader__.load({
|
|
|
899
1055
|
// 输入框工具栏积分读数
|
|
900
1056
|
creditsUnavailable: '未登录',
|
|
901
1057
|
creditsDegraded: '积分暂不可用',
|
|
902
|
-
composerTooltip: '千问办公剩余积分 ·
|
|
1058
|
+
composerTooltip: '千问办公剩余积分 · 打开左侧「插件」→ dsh-qwenwork-connect 查看详情',
|
|
903
1059
|
};
|
|
904
1060
|
const en = {
|
|
905
1061
|
title: 'QwenWork',
|
|
@@ -909,6 +1065,12 @@ window.__ModuleLoader__.load({
|
|
|
909
1065
|
loading: 'Reading status…',
|
|
910
1066
|
refresh: 'Refresh',
|
|
911
1067
|
refreshing: 'Refreshing…',
|
|
1068
|
+
login: 'Sign in',
|
|
1069
|
+
loggingIn: 'Waiting for authorization…',
|
|
1070
|
+
loginHint: 'Not signed in. Click "Sign in" and choose an account and team in the browser.',
|
|
1071
|
+
loginWaiting: 'Authorization page opened; waiting for you to finish in the browser…',
|
|
1072
|
+
loginTimeout: 'Sign-in timed out. Please try again.',
|
|
1073
|
+
loginFailed: 'Sign-in failed',
|
|
912
1074
|
accountHeading: 'Account',
|
|
913
1075
|
quotaHeading: 'Remaining credits',
|
|
914
1076
|
nickname: 'Account',
|
|
@@ -945,7 +1107,7 @@ window.__ModuleLoader__.load({
|
|
|
945
1107
|
// 输入框工具栏积分读数
|
|
946
1108
|
creditsUnavailable: 'Signed out',
|
|
947
1109
|
creditsDegraded: 'Quota unavailable',
|
|
948
|
-
composerTooltip: 'QwenWork credits remaining · see
|
|
1110
|
+
composerTooltip: 'QwenWork credits remaining · see Plugins → dsh-qwenwork-connect',
|
|
949
1111
|
};
|
|
950
1112
|
//#endregion
|
|
951
1113
|
|
|
@@ -955,8 +1117,12 @@ window.__ModuleLoader__.load({
|
|
|
955
1117
|
/**
|
|
956
1118
|
* 注册卡片文案与卡片本体。
|
|
957
1119
|
*
|
|
958
|
-
* 0.1.2
|
|
959
|
-
*
|
|
1120
|
+
* DSH 0.2.1-rc.2+ 废弃了 `settings.plugin.item`,插件配置改挂在
|
|
1121
|
+
* 侧栏「插件」页:
|
|
1122
|
+
* - `plugins.bundle.config`:key = 包名,渲染在 bundle 详情页;
|
|
1123
|
+
* - `plugins.row.config`:key = `<包名>#<patch 行 id>`,给该行一个
|
|
1124
|
+
* Configure 入口。
|
|
1125
|
+
* 两个席位共用同一个卡片;`view === 'summary'` 时只回一行摘要。
|
|
960
1126
|
*/
|
|
961
1127
|
function apply(ctx) {
|
|
962
1128
|
try {
|
|
@@ -966,17 +1132,25 @@ window.__ModuleLoader__.load({
|
|
|
966
1132
|
'dsh-qwenwork-connect: settings copy',
|
|
967
1133
|
);
|
|
968
1134
|
const t = ctx.locale.bind(namespace);
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
1135
|
+
const renderConfig = (slotProps) =>
|
|
1136
|
+
slotProps && slotProps.view === 'summary'
|
|
1137
|
+
? t('subtitle')
|
|
1138
|
+
: react_jsx_runtime.jsx(QwenWorkPluginCard, { t, initialOpen: true });
|
|
1139
|
+
for (const [slot, key] of [
|
|
1140
|
+
['plugins.bundle.config', 'dsh-qwenwork-connect'],
|
|
1141
|
+
['plugins.row.config', 'dsh-qwenwork-connect#llm-qwenwork'],
|
|
1142
|
+
]) {
|
|
1143
|
+
try {
|
|
1144
|
+
ctx.slots.inject(slot, () =>
|
|
1145
|
+
ctx.slots.register({ name: slot, key }, renderConfig),
|
|
1146
|
+
);
|
|
1147
|
+
} catch (error) {
|
|
1148
|
+
console.error(
|
|
1149
|
+
`[dsh-qwen-connect] ${slot} config slot failed to register:`,
|
|
1150
|
+
error,
|
|
1151
|
+
);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
980
1154
|
// 输入框工具栏的积分读数。注册本身无条件,渲染与否由 ComposerCredits
|
|
981
1155
|
// 内部的 provider gate 决定(见该组件注释),所以这里再包一层 try/catch
|
|
982
1156
|
// 兜住「插槽席位不存在/字段变更」——不能因为它挂了就连带卡片也不显示。
|
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
|