@tnnevol/dsh-zcode 0.0.0-stage → 6.0.6

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,29 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "engines": {
4
+ "node": "^22.19.0 || >=24.0.0"
5
+ },
6
+ "dshPluginApi": {
7
+ "version": "0.2.1-rc.3",
8
+ "packages": [
9
+ "@deepseek-ai/dsh-atomic-write",
10
+ "@deepseek-ai/dsh-attachment",
11
+ "@deepseek-ai/dsh-client-locale",
12
+ "@deepseek-ai/dsh-client-ui-plugin-manager",
13
+ "@deepseek-ai/dsh-client-ui-primitives",
14
+ "@deepseek-ai/dsh-client-ui-renderer",
15
+ "@deepseek-ai/dsh-client-ui-session",
16
+ "@deepseek-ai/dsh-client-ui-settings",
17
+ "@deepseek-ai/dsh-client-ui-settings-plugins",
18
+ "@deepseek-ai/dsh-client-ui-slots",
19
+ "@deepseek-ai/dsh-home-paths",
20
+ "@deepseek-ai/dsh-host-webserver",
21
+ "@deepseek-ai/dsh-llm",
22
+ "@deepseek-ai/dsh-llm-pi-ai"
23
+ ]
24
+ },
25
+ "piAi": {
26
+ "package": "@earendil-works/pi-ai",
27
+ "version": "1.1.0"
28
+ }
29
+ }
@@ -0,0 +1,12 @@
1
+ # @tnnevol/dsh-zcode 组合包 patch。
2
+ #
3
+ # 本插件不接管既有接缝:它自己向 `ctx.llm` 注册一个 provider 路由
4
+ # (`dsh-zcode`),模型目录由 ZCode 账号权益实时拉取,因此**不在**这里声明
5
+ # `llm-pi-ai.providers`——静态声明会把目录固定在安装时的快照上,正是本插件
6
+ # 要解决的问题。
7
+ #
8
+ # 账号登录、模型目录和 Start Plan 额度都由宿主侧注册到 DSH Web 服务,浏览器
9
+ # 半侧在插件详情页渲染配置区块;两者都随本行激活。
10
+ - insert:
11
+ - id: dsh-zcode
12
+ name: '@tnnevol/dsh-zcode'
package/icon.png ADDED
Binary file
@@ -0,0 +1,150 @@
1
+ import { D as ZCodeFamily, o as ZCodeConsoleClient } from "./console-client-54wUcPDA.js";
2
+ import { Context } from "@deepseek-ai/cordis";
3
+ //#region src/contracts/auth.d.ts
4
+ /** 授权页信息,交给浏览器打开。 */
5
+ interface ZCodeLoginChallenge {
6
+ /** 本次授权的家族。 */
7
+ readonly family: ZCodeFamily;
8
+ /** 需要在浏览器打开的授权地址。 */
9
+ readonly authorizeUrl: string;
10
+ /** 授权链接有效期(秒)。 */
11
+ readonly expiresInSeconds: number;
12
+ }
13
+ /** 账号信息;全部来自 ZCode,缺字段时保持缺省。 */
14
+ interface ZCodeAccountInfo {
15
+ readonly userId?: string;
16
+ readonly email?: string;
17
+ readonly name?: string;
18
+ /** 头像地址(若上游返回)。 */
19
+ readonly avatar?: string;
20
+ /** 本次登录使用的家族。 */
21
+ readonly family?: ZCodeFamily;
22
+ }
23
+ /** 浏览器可见的登录状态。 */
24
+ type ZCodeAuthStatus = {
25
+ status: 'signed-out';
26
+ } | {
27
+ status: 'signing-in';
28
+ challenge?: ZCodeLoginChallenge;
29
+ } | ({
30
+ status: 'signed-in';
31
+ } & ZCodeAccountInfo) | {
32
+ status: 'error';
33
+ message: string;
34
+ };
35
+ /**
36
+ * 落盘的凭据文档。
37
+ *
38
+ * 三份材料各有用途,缺一不可:
39
+ * - `zcodeJwt`:ZCode 域凭证,额度/权益/客户端配置都用它;
40
+ * - `accessToken`:家族侧的 MaaS 凭证,换取项目令牌时使用;
41
+ * - `refreshToken`:可选,上游给了就保存,便于后续刷新。
42
+ */
43
+ interface ZCodeCredentialRecord {
44
+ readonly version: 1;
45
+ /** 登录使用的家族。 */
46
+ readonly family: ZCodeFamily;
47
+ /** ZCode 域 JWT(额度与权益的鉴权材料)。 */
48
+ readonly zcodeJwt: string;
49
+ /** 家族侧 MaaS access token。 */
50
+ readonly accessToken?: string;
51
+ /** 家族侧 refresh token。 */
52
+ readonly refreshToken?: string;
53
+ /** JWT 过期时间(epoch ms);上游未给出时缺省。 */
54
+ readonly expiresAt?: number;
55
+ readonly userId?: string;
56
+ readonly email?: string;
57
+ readonly name?: string;
58
+ readonly avatar?: string;
59
+ }
60
+ //#endregion
61
+ //#region src/host/credentials.d.ts
62
+ /** 凭据文件名(位于 DSH home 下)。 */
63
+ declare const ZCODE_AUTH_FILENAME = ".dsh-zcode-auth.json";
64
+ /** 凭据文件路径。 */
65
+ declare function zcodeAuthPath(dshHome?: string): string;
66
+ /** 文件落盘的账号凭据存储。 */
67
+ declare class ZCodeCredentialStore {
68
+ readonly filename: string;
69
+ constructor(filename?: string);
70
+ /** 读取当前凭据;不存在时返回 undefined。 */
71
+ read(): Promise<ZCodeCredentialRecord | undefined>;
72
+ /** 覆盖写入凭据(原子写 + 文件锁)。 */
73
+ write(credential: ZCodeCredentialRecord): Promise<ZCodeCredentialRecord>;
74
+ /** 删除凭据;不存在时静默成功。 */
75
+ delete(): Promise<void>;
76
+ }
77
+ //#endregion
78
+ //#region src/host/auth.d.ts
79
+ /** 授权服务依赖。 */
80
+ interface ZCodeAuthServiceOptions {
81
+ readonly store: ZCodeCredentialStore;
82
+ readonly client: ZCodeConsoleClient;
83
+ /** 凭据变化回调:登录成功或退出时触发目录/额度刷新。 */
84
+ readonly onCredentialChange?: () => void;
85
+ readonly logger?: Pick<Context['logger'], 'warn' | 'info'>;
86
+ /** 便于测试注入稳定时钟。 */
87
+ readonly now?: () => number;
88
+ /**
89
+ * 桌面授权码流程的回调地址。
90
+ *
91
+ * 桌面端用 `zcode://oauth/callback` 自定义协议接收授权码;插件在浏览器里无法
92
+ * 注册该协议,因此改为由本插件自己的同源路由接收 code 并完成换取。
93
+ */
94
+ readonly callbackBaseUrl?: () => string | undefined;
95
+ }
96
+ /** 登录服务。 */
97
+ declare class ZCodeAuthService {
98
+ private readonly options;
99
+ private cached;
100
+ private loaded;
101
+ private flow;
102
+ private lastError;
103
+ private readonly listeners;
104
+ constructor(options: ZCodeAuthServiceOptions);
105
+ private get now();
106
+ /** 订阅凭据变化;返回退订函数。 */
107
+ subscribe(listener: () => void): () => void;
108
+ private emit;
109
+ /** 读取凭据(首次读磁盘,之后走内存缓存)。 */
110
+ credential(): Promise<ZCodeCredentialRecord | undefined>;
111
+ /** 当前可用于请求的 ZCode JWT;未登录或已过期时返回 undefined。 */
112
+ zcodeJwt(): Promise<string | undefined>;
113
+ /**
114
+ * 家族侧 MaaS 令牌;`ultra` 端点用这一份凭据。
115
+ *
116
+ * 与 {@link zcodeJwt} 分开取,因为两个端点接受的凭据类型不同:`start-plan`
117
+ * 认 ZCode 域 JWT,`ultra` 认家族 MaaS 令牌。登录时上游是否返回家族令牌
118
+ * 取决于授权流程,缺失时返回 undefined,由上层给出可读提示。
119
+ */
120
+ accessToken(): Promise<string | undefined>;
121
+ /** 浏览器可见的登录状态(不含任何 token)。 */
122
+ status(): Promise<ZCodeAuthStatus>;
123
+ private challengeOf;
124
+ /**
125
+ * 发起桌面授权码登录。
126
+ *
127
+ * 授权码由上游回跳到插件自己的同源路由。state 由本服务生成并在回调时比对,
128
+ * 防止别人把授权码塞进来。
129
+ */
130
+ loginDesktop(family: ZCodeFamily, origin?: string): Promise<ZCodeLoginChallenge>;
131
+ /**
132
+ * 处理桌面授权回调。
133
+ *
134
+ * `code` 只能兑换一次;兑换成功后立刻落盘并清理进行中的 flow。
135
+ */
136
+ completeDesktopLogin(input: {
137
+ readonly code: string;
138
+ readonly state: string;
139
+ readonly family: ZCodeFamily;
140
+ }): Promise<void>;
141
+ private clearFlow;
142
+ /** 取消进行中的授权;已保存的凭据不受影响。 */
143
+ cancel(): void;
144
+ /** 退出登录:停止轮询并删除凭据。 */
145
+ logout(): Promise<void>;
146
+ /** 释放定时器(插件卸载时调用)。 */
147
+ dispose(): void;
148
+ }
149
+ //#endregion
150
+ export { zcodeAuthPath as a, ZCodeCredentialRecord as c, ZCodeCredentialStore as i, ZCodeLoginChallenge as l, ZCodeAuthServiceOptions as n, ZCodeAccountInfo as o, ZCODE_AUTH_FILENAME as r, ZCodeAuthStatus as s, ZCodeAuthService as t };
@@ -0,0 +1,206 @@
1
+ import { f as ZCODE_FAMILY_LABELS } from "./identity-DE3rOYuE.js";
2
+ import { randomBytes } from "node:crypto";
3
+ //#region src/contracts/auth.ts
4
+ /**
5
+ * 判断凭据是否已过期。
6
+ *
7
+ * ZCode 的账号 JWT 目前不带 `exp`,因此只有上游明确给出时间时才判定;
8
+ * 留 30 秒提前量,避免在临界点发出必然失败的请求。
9
+ */
10
+ function isCredentialExpired(record, now = Date.now()) {
11
+ if (record.expiresAt === void 0) return false;
12
+ return record.expiresAt - 3e4 <= now;
13
+ }
14
+ //#endregion
15
+ //#region src/host/auth.ts
16
+ /**
17
+ * ZCode 账号登录与凭据生命周期。
18
+ *
19
+ * 采用授权码流程:插件生成 state → 浏览器打开上游授权页 → 上游回跳到插件自己的
20
+ * 同源回调路由 → 用 code 换取令牌。state 与 redirect_uri 都必须在换取时原样带回,
21
+ * 前者防别人把授权码塞进来,后者是上游的校验要求。
22
+ *
23
+ * 不支持 API Key 登录:Start Plan 的模型请求只认账号身份。
24
+ *
25
+ * @module dsh-zcode/auth
26
+ */
27
+ /** 单次授权流程的有效期上限(毫秒)。 */
28
+ const AUTH_FLOW_TTL_MS = 9e5;
29
+ /** 登录服务。 */
30
+ var ZCodeAuthService = class {
31
+ options;
32
+ cached;
33
+ loaded = false;
34
+ flow;
35
+ lastError;
36
+ listeners = /* @__PURE__ */ new Set();
37
+ constructor(options) {
38
+ this.options = options;
39
+ }
40
+ get now() {
41
+ return this.options.now?.() ?? Date.now();
42
+ }
43
+ /** 订阅凭据变化;返回退订函数。 */
44
+ subscribe(listener) {
45
+ this.listeners.add(listener);
46
+ return () => this.listeners.delete(listener);
47
+ }
48
+ emit() {
49
+ for (const listener of this.listeners) try {
50
+ listener();
51
+ } catch (error) {
52
+ this.options.logger?.warn("dsh-zcode: 凭据监听器失败", error);
53
+ }
54
+ }
55
+ /** 读取凭据(首次读磁盘,之后走内存缓存)。 */
56
+ async credential() {
57
+ if (this.loaded) return this.cached;
58
+ this.cached = await this.options.store.read();
59
+ this.loaded = true;
60
+ return this.cached;
61
+ }
62
+ /** 当前可用于请求的 ZCode JWT;未登录或已过期时返回 undefined。 */
63
+ async zcodeJwt() {
64
+ const record = await this.credential();
65
+ if (record === void 0) return void 0;
66
+ if (isCredentialExpired(record, this.now)) {
67
+ this.options.logger?.warn("dsh-zcode: 账号凭据已过期,请重新登录");
68
+ return;
69
+ }
70
+ return record.zcodeJwt;
71
+ }
72
+ /**
73
+ * 家族侧 MaaS 令牌;`ultra` 端点用这一份凭据。
74
+ *
75
+ * 与 {@link zcodeJwt} 分开取,因为两个端点接受的凭据类型不同:`start-plan`
76
+ * 认 ZCode 域 JWT,`ultra` 认家族 MaaS 令牌。登录时上游是否返回家族令牌
77
+ * 取决于授权流程,缺失时返回 undefined,由上层给出可读提示。
78
+ */
79
+ async accessToken() {
80
+ const record = await this.credential();
81
+ if (record === void 0) return void 0;
82
+ if (isCredentialExpired(record, this.now)) return void 0;
83
+ const token = record.accessToken;
84
+ return typeof token === "string" && token.length > 0 ? token : void 0;
85
+ }
86
+ /** 浏览器可见的登录状态(不含任何 token)。 */
87
+ async status() {
88
+ if (this.flow !== void 0) return {
89
+ status: "signing-in",
90
+ challenge: this.challengeOf(this.flow)
91
+ };
92
+ if (this.lastError !== void 0) return {
93
+ status: "error",
94
+ message: this.lastError
95
+ };
96
+ const record = await this.credential();
97
+ if (record === void 0) return { status: "signed-out" };
98
+ return {
99
+ status: "signed-in",
100
+ family: record.family,
101
+ ...record.userId === void 0 ? {} : { userId: record.userId },
102
+ ...record.email === void 0 ? {} : { email: record.email },
103
+ ...record.name === void 0 ? {} : { name: record.name },
104
+ ...record.avatar === void 0 ? {} : { avatar: record.avatar }
105
+ };
106
+ }
107
+ challengeOf(flow) {
108
+ return {
109
+ family: flow.family,
110
+ authorizeUrl: flow.authorizeUrl,
111
+ expiresInSeconds: Math.max(0, Math.round((flow.expiresAt - this.now) / 1e3))
112
+ };
113
+ }
114
+ /**
115
+ * 发起桌面授权码登录。
116
+ *
117
+ * 授权码由上游回跳到插件自己的同源路由。state 由本服务生成并在回调时比对,
118
+ * 防止别人把授权码塞进来。
119
+ */
120
+ async loginDesktop(family, origin) {
121
+ const base = (origin === void 0 ? void 0 : `${origin}/plugins/dsh-zcode/auth/callback`) ?? this.options.callbackBaseUrl?.();
122
+ if (base === void 0 || base === "") throw new Error("zcode: 未配置桌面登录回调地址,无法发起授权码登录");
123
+ if (this.flow !== void 0) this.clearFlow();
124
+ this.lastError = void 0;
125
+ const state = randomBytes(16).toString("hex");
126
+ const callbackUrl = new URL(base);
127
+ callbackUrl.searchParams.set("family", family);
128
+ const flow = {
129
+ family,
130
+ authorizeUrl: `https://bigmodel.cn/login?${new URLSearchParams({
131
+ appId: "zcode",
132
+ redirect: callbackUrl.toString(),
133
+ state
134
+ }).toString()}`,
135
+ expiresAt: this.now + AUTH_FLOW_TTL_MS,
136
+ state,
137
+ redirectUri: callbackUrl.toString()
138
+ };
139
+ this.flow = flow;
140
+ this.emit();
141
+ return this.challengeOf(flow);
142
+ }
143
+ /**
144
+ * 处理桌面授权回调。
145
+ *
146
+ * `code` 只能兑换一次;兑换成功后立刻落盘并清理进行中的 flow。
147
+ */
148
+ async completeDesktopLogin(input) {
149
+ const flow = this.flow;
150
+ if (flow === void 0) throw new Error("zcode: 没有进行中的桌面授权,请重新发起登录");
151
+ if (flow.state !== input.state) throw new Error("zcode: 授权回调 state 不匹配,请重新发起登录");
152
+ if (flow.expiresAt <= this.now) {
153
+ this.clearFlow();
154
+ throw new Error("zcode: 授权已超时,请重新发起登录");
155
+ }
156
+ const redirectUri = flow.redirectUri;
157
+ if (redirectUri === void 0) throw new Error("zcode: 缺少回调地址,请重新发起登录");
158
+ const result = await this.options.client.exchangeDesktopCode(input.family, input.code, redirectUri, input.state);
159
+ if (result.status !== "ready") throw new Error("zcode: 授权码换取未返回凭据");
160
+ if (result.zcodeJwt.trim().length === 0) throw new Error("zcode: 授权码换取返回空凭据");
161
+ const credential = {
162
+ version: 1,
163
+ family: input.family,
164
+ zcodeJwt: result.zcodeJwt,
165
+ ...result.accessToken === void 0 ? {} : { accessToken: result.accessToken },
166
+ ...result.refreshToken === void 0 ? {} : { refreshToken: result.refreshToken },
167
+ ...result.expiresAt === void 0 ? {} : { expiresAt: result.expiresAt },
168
+ ...result.user?.userId === void 0 ? {} : { userId: result.user.userId },
169
+ ...result.user?.email === void 0 ? {} : { email: result.user.email },
170
+ ...result.user?.name === void 0 ? {} : { name: result.user.name },
171
+ ...result.user?.avatar === void 0 ? {} : { avatar: result.user.avatar }
172
+ };
173
+ this.cached = await this.options.store.write(credential);
174
+ this.loaded = true;
175
+ this.clearFlow();
176
+ this.options.logger?.info(`dsh-zcode: ${ZCODE_FAMILY_LABELS[input.family]} 桌面授权登录成功`);
177
+ this.emit();
178
+ this.options.onCredentialChange?.();
179
+ }
180
+ clearFlow() {
181
+ this.flow = void 0;
182
+ }
183
+ /** 取消进行中的授权;已保存的凭据不受影响。 */
184
+ cancel() {
185
+ this.clearFlow();
186
+ this.lastError = void 0;
187
+ this.emit();
188
+ }
189
+ /** 退出登录:停止轮询并删除凭据。 */
190
+ async logout() {
191
+ this.clearFlow();
192
+ this.lastError = void 0;
193
+ this.cached = void 0;
194
+ this.loaded = true;
195
+ await this.options.store.delete();
196
+ this.emit();
197
+ this.options.onCredentialChange?.();
198
+ }
199
+ /** 释放定时器(插件卸载时调用)。 */
200
+ dispose() {
201
+ this.clearFlow();
202
+ this.listeners.clear();
203
+ }
204
+ };
205
+ //#endregion
206
+ export { ZCodeAuthService as t };
@@ -0,0 +1,2 @@
1
+ import { a as trustedRequest, i as registerZCodeRoutes, n as ZCODE_ORIGIN_NOT_TRUSTED, r as ZCodeRoutesOptions, t as ZCODE_CATALOG_UNAVAILABLE } from "./routes-DhHLL5UC.js";
2
+ export { ZCODE_CATALOG_UNAVAILABLE, ZCODE_ORIGIN_NOT_TRUSTED, ZCodeRoutesOptions, registerZCodeRoutes, trustedRequest };
@@ -0,0 +1,2 @@
1
+ import { i as trustedRequest, n as ZCODE_ORIGIN_NOT_TRUSTED, r as registerZCodeRoutes, t as ZCODE_CATALOG_UNAVAILABLE } from "./routes-vzWlp-oN.js";
2
+ export { ZCODE_CATALOG_UNAVAILABLE, ZCODE_ORIGIN_NOT_TRUSTED, registerZCodeRoutes, trustedRequest };
package/lib/auth.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { n as ZCodeAuthServiceOptions, t as ZCodeAuthService } from "./auth-B99K5y4S.js";
2
+ export { ZCodeAuthService, ZCodeAuthServiceOptions };
package/lib/auth.js ADDED
@@ -0,0 +1,2 @@
1
+ import { t as ZCodeAuthService } from "./auth-BrDmmPY2.js";
2
+ export { ZCodeAuthService };