@pandablessing/dsh-user-sync 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,77 @@
1
+ Copyright (c) 2026 gray-panda
2
+ dsh-user-sync is licensed under Mulan PSL v2.
3
+ You can use this software according to the terms and conditions of the Mulan PSL v2.
4
+ You may obtain a copy of Mulan PSL v2 at:
5
+ http://license.coscl.org.cn/MulanPSL2
6
+ THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
7
+ EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
8
+ MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
9
+ See the Mulan PSL v2 for more details.
10
+
11
+ 木兰宽松许可证, 第2版
12
+ Mulan Permissive Software License, Version 2
13
+
14
+ 2020年1月 http://license.coscl.org.cn/MulanPSL2
15
+
16
+ 您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第2版(“本许可证”)的如下条款的约束:
17
+
18
+ 0. 定义
19
+ “软件” 是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。
20
+ “贡献” 是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。
21
+ “贡献者” 是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。
22
+ “法人实体” 是指提交贡献的机构及其“关联实体”。
23
+ “关联实体” 是指,对“本许可证”下的行为方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。
24
+
25
+ 1. 授予版权许可
26
+ 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。
27
+
28
+ 2. 授予专利许可
29
+ 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。
30
+
31
+ 3. 无商标许可
32
+ “本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。
33
+
34
+ 4. 分发限制
35
+ 您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。
36
+
37
+ 5. 免责声明与责任限制
38
+ “软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。
39
+
40
+ 6. 语言
41
+ “本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。
42
+
43
+ 条款结束
44
+
45
+ Mulan Permissive Software License,Version 2
46
+ Mulan Permissive Software License,Version 2 (Mulan PSL v2)
47
+
48
+ January 2020 http://license.coscl.org.cn/MulanPSL2
49
+
50
+ Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions:
51
+
52
+ 0. Definition
53
+ Software means the program and related documents which are licensed under this License and comprise all Contribution(s).
54
+ Contribution means the copyrightable work licensed by a particular Contributor under this License.
55
+ Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License.
56
+ Legal Entity means the entity making a Contribution and all its Affiliates.
57
+ Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, 'control' means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity.
58
+
59
+ 1. Grant of Copyright License
60
+ Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not.
61
+
62
+ 2. Grant of Patent License
63
+ Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken.
64
+
65
+ 3. No Trademark License
66
+ No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in section 4.
67
+
68
+ 4. Distribution Restriction
69
+ You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software.
70
+
71
+ 5. Disclaimer of Warranty and Limitation of Liability
72
+ THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW IT'S CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
73
+
74
+ 6. Language
75
+ THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL.
76
+
77
+ END OF THE TERMS AND CONDITIONS
package/README.en.md ADDED
@@ -0,0 +1,36 @@
1
+ # dsh-user-sync
2
+
3
+ #### Description
4
+ dsh用户级配置同步
5
+
6
+ #### Software Architecture
7
+ Software architecture description
8
+
9
+ #### Installation
10
+
11
+ 1. xxxx
12
+ 2. xxxx
13
+ 3. xxxx
14
+
15
+ #### Instructions
16
+
17
+ 1. xxxx
18
+ 2. xxxx
19
+ 3. xxxx
20
+
21
+ #### Contribution
22
+
23
+ 1. Fork the repository
24
+ 2. Create Feat_xxx branch
25
+ 3. Commit your code
26
+ 4. Create Pull Request
27
+
28
+
29
+ #### Gitee Feature
30
+
31
+ 1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
32
+ 2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
33
+ 3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
34
+ 4. The most valuable open source project [GVP](https://gitee.com/gvp)
35
+ 5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
36
+ 6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
package/README.md CHANGED
@@ -1,3 +1,103 @@
1
- # Temporary Holding Version
1
+ # dsh-user-sync
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DeepSeek Harness(DSH)的**用户级配置同步插件**:把技能、插件清单、配置、记忆四类资产在设备间对齐。
4
+
5
+ > 当前状态:**v0.1.0 开发版**。本机打包/应用、跨机上传/恢复、缺插件装回、自动检查均已实现并实测;服务端已部署(见 [部署文档](docs/deploy.md))。
6
+ > 设计依据:[docs/design.md](docs/design.md);测试用例:[docs/test-cases.md](docs/test-cases.md)。
7
+
8
+ ## 功能
9
+
10
+ - **四类用户级资产**:技能(`~/.agents/skills`)、插件清单(profile 声明)、配置(`cordis.patch.yml` + `AGENTS.md`)、用户记忆(`memories/` 根);项目记忆与会话默认不选。
11
+ - **新覆盖旧**:包级 `createdAt` 比较,不做合并;覆盖前必须确认,先快照再写盘,失败可整批还原。
12
+ - **敏感数据硬拒绝**:文件名黑名单 + 内容模式,命中即拒绝打包并列出文件与行号。
13
+ - **官方账号自动配对**:用 `deepseekAccount` 取账号 id 派生 `accountKey`,自动向服务端换 token,**没有运营方账号登录入口**。
14
+ - **缺插件自动装回**:覆盖确认里列出缺失 bundle,一键 `installBundle`;`link:` 本地包列入手工清单。
15
+ - **自动检查**:启动检查 + 每 6 小时(可配)只读远端元数据,发现更新只提醒、不自动应用。
16
+
17
+ ## 安装
18
+
19
+ ### 从 npm(发布后)
20
+
21
+ ```powershell
22
+ cd ~/.dsh/profiles/desktop
23
+ pnpm add @pandablessing/dsh-user-sync
24
+ ```
25
+
26
+ 安装后在 DSH 设置页启用「设置同步」。
27
+
28
+ ### 开发期(junction 到本仓库)
29
+
30
+ ```powershell
31
+ # 以 junction 把仓库装进 desktop profile,改 package.json 前自动备份,失败自动回滚
32
+ powershell -NoProfile -ExecutionPolicy Bypass -File scripts\install-dev.ps1
33
+
34
+ # 回滚
35
+ scripts\uninstall-dev.cmd # 双击即可
36
+ ```
37
+
38
+ 安装后**重启 DSH**,设置页出现「设置同步」。
39
+
40
+ ## 使用
41
+
42
+ 1. 设置 → 用户同步 → 首次点「同意并启用上传」(说明上传范围与存储位置);
43
+ 2. 勾选同步范围(默认四类用户级);
44
+ 3. 「上传用户配置」→ 打包并上传;
45
+ 4. 「从远端同步」→ 检查远端,覆盖前确认。
46
+
47
+ 服务端地址在「传输与自动检查」里配置(默认内置;开发环境填 `https://dsh-user-sync-test.wenzhi.info`)。
48
+
49
+ ## 服务端
50
+
51
+ 纯 `node:http`、无第三方依赖,支持坚果云 WebDAV(凭据缺失回退本地磁盘)。部署步骤见 [docs/deploy.md](docs/deploy.md)。
52
+
53
+ ## 架构
54
+
55
+ ```text
56
+ 插件(HTTP 客户端) ──HTTPS──▶ 运营方 API ──WebDAV──▶ 坚果云
57
+ │ │
58
+ └─ 本地 state.json └─ 鉴权 / 配额 / 隔离 / 审计
59
+ ```
60
+
61
+ - 插件侧只实现 `api` 传输;`folder` 仅用于本机调试。
62
+ - 存储凭据只在服务端,插件包内不含任何存储口令。
63
+ - 身份:官方账号 id → `accountKey`(sha256 前 16 位)→ 服务端分区。
64
+
65
+ ## 构建与测试
66
+
67
+ 源码是 TypeScript,构建产物 `lib/` 与 `server/dist/` 已提交(junction 安装与部署直接可用)。
68
+
69
+ ```powershell
70
+ pnpm install # 仅开发:安装 typescript 与 @types/node
71
+ pnpm run build # 插件:src/*.ts → lib/*.js
72
+ pnpm run build:server # 服务端:server/src/*.ts → server/dist/*.js
73
+
74
+ node --test test/*.test.js # 137 条:单元 / 组件 / 时序(直接跑源码)
75
+ node scripts/audit-cases.mjs # 用例清单与结果记录一致性审计(129/129)
76
+ node scripts/e2e-clone.mjs # 替代换机演练(默认本地模式,临时起服务端,不写真实 WebDAV)
77
+ # node scripts/e2e-clone.mjs --remote https://dsh-user-sync-test.wenzhi.info # 真实服务端(会留测试目录)
78
+ powershell -File scripts/smoke.ps1 # 真实 DSH 路由冒烟
79
+ ```
80
+
81
+ ## 仓库结构
82
+
83
+ ```text
84
+ docs/design.md 完整设计(数据面 / 同步 / 安全 / UI / 契约 / 多用户)
85
+ docs/test-cases.md 测试用例清单(结果单独放 docs/test-results/)
86
+ docs/deploy.md 服务端部署与验证
87
+ lib/ 插件(宿主 + client + 传输 + 同步编排)
88
+ server/ 运营方 API(纯 node:http)
89
+ scripts/ 开发安装 / 卸载 / 冒烟 / 替代换机
90
+ test/ 单元、组件、时序测试与 fixtures
91
+ legacy/ 需求反馈稿与原型脚本
92
+ ```
93
+
94
+ ## 已知限制
95
+
96
+ - 未在 macOS/Linux 实机验证;跨平台哈希由单测(HASH-01/06)覆盖。
97
+ - 服务端单节点,未做限流与多副本;坚果云单账号有流量配额限制。
98
+ - `link:` 本地依赖需要手工放回目标机。
99
+ - 远端只保留 1 份包,上传即覆盖(回滚靠本地 `pre-restore` 快照)。
100
+
101
+ ## License
102
+
103
+ [Mulan PSL v2](LICENSE)
@@ -0,0 +1,5 @@
1
+ # dsh-user-sync 的组合包层:把插件挂进 profile。
2
+ # 用户层的 cordis.patch.yml 可覆盖此条目的 config(设置面板写入的位置)。
3
+ - insert:
4
+ - id: user-sync
5
+ name: dsh-user-sync
package/lib/apply.js ADDED
@@ -0,0 +1,111 @@
1
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { hashBytes } from './hash.js';
5
+ import { MANIFEST_PATH } from './archive.js';
6
+ import { isUnsafeRelPath, resolveInside } from './paths.js';
7
+ /**
8
+ * 应用计划:把包内文件分成「新增 / 覆盖 / 跳过」三态。
9
+ * 大小写冲突直接拒绝(§5.5)。
10
+ */
11
+ export function planApply({ manifestFiles, localFiles, }) {
12
+ const added = [];
13
+ const overwritten = [];
14
+ const skipped = [];
15
+ const seen = new Map();
16
+ for (const file of manifestFiles) {
17
+ if (isUnsafeRelPath(file.path))
18
+ throw new Error(`非法包内路径: ${file.path}`);
19
+ const lower = file.path.toLowerCase();
20
+ if (seen.has(lower) && seen.get(lower) !== file.path) {
21
+ throw new Error(`大小写冲突: ${seen.get(lower)} / ${file.path}`);
22
+ }
23
+ seen.set(lower, file.path);
24
+ const localSha = localFiles?.get(file.path);
25
+ if (localSha === undefined)
26
+ added.push(file);
27
+ else if (localSha !== file.sha256)
28
+ overwritten.push(file);
29
+ else
30
+ skipped.push(file);
31
+ }
32
+ return { added, overwritten, skipped };
33
+ }
34
+ function ensureDir(p) {
35
+ mkdirSync(p, { recursive: true });
36
+ }
37
+ function snapshotFile(abs, rel, preRestoreRoot) {
38
+ const backup = join(preRestoreRoot, rel);
39
+ ensureDir(dirname(backup));
40
+ copyFileSync(abs, backup);
41
+ return backup;
42
+ }
43
+ /**
44
+ * 应用 tar 条目到目标根。
45
+ * 先快照将被覆盖的文件,再逐文件原子写(tmp → rename);失败时整批还原。
46
+ */
47
+ export function applyEntries({ entries, targetRoot, resolveTarget, preRestoreRoot, dryRun = false, }) {
48
+ const toAbs = resolveTarget ?? ((rel) => resolveInside(targetRoot, rel));
49
+ const plan = entries.filter((entry) => entry.type !== 'dir' && entry.path !== MANIFEST_PATH);
50
+ const written = [];
51
+ const skipped = [];
52
+ const seen = new Map();
53
+ for (const entry of plan) {
54
+ if (isUnsafeRelPath(entry.path))
55
+ throw new Error(`非法包内路径: ${entry.path}`);
56
+ const lower = entry.path.toLowerCase();
57
+ if (seen.has(lower) && seen.get(lower) !== entry.path) {
58
+ throw new Error(`大小写冲突: ${seen.get(lower)} / ${entry.path}`);
59
+ }
60
+ seen.set(lower, entry.path);
61
+ }
62
+ if (dryRun)
63
+ return { written, skipped: plan.map((entry) => entry.path), snapshotPath: null };
64
+ const snapshots = [];
65
+ try {
66
+ for (const entry of plan) {
67
+ const abs = toAbs(entry.path);
68
+ ensureDir(dirname(abs));
69
+ if (entry.type === 'symlink') {
70
+ if (existsSync(abs)) {
71
+ snapshotFile(abs, entry.path, preRestoreRoot);
72
+ snapshots.push(entry.path);
73
+ rmSync(abs, { force: true });
74
+ }
75
+ symlinkSync(entry.linkTarget ?? '', abs);
76
+ written.push(entry.path);
77
+ continue;
78
+ }
79
+ const existing = existsSync(abs) ? readFileSync(abs) : null;
80
+ if (existing !== null && hashBytes(existing) === hashBytes(entry.data)) {
81
+ skipped.push(entry.path); // 内容等价:不写盘、不改 mtime
82
+ continue;
83
+ }
84
+ if (existing !== null) {
85
+ snapshotFile(abs, entry.path, preRestoreRoot);
86
+ snapshots.push(entry.path);
87
+ }
88
+ const tmp = join(dirname(abs), `.${entry.path.split('/').pop()}.tmp-${randomUUID().slice(0, 8)}`);
89
+ writeFileSync(tmp, entry.data);
90
+ renameSync(tmp, abs);
91
+ written.push(entry.path);
92
+ }
93
+ }
94
+ catch (error) {
95
+ for (const rel of snapshots) {
96
+ const backup = join(preRestoreRoot, rel);
97
+ if (existsSync(backup))
98
+ copyFileSync(backup, toAbs(rel));
99
+ }
100
+ for (const rel of written) {
101
+ if (!snapshots.includes(rel))
102
+ rmSync(toAbs(rel), { force: true });
103
+ }
104
+ throw error;
105
+ }
106
+ return {
107
+ written,
108
+ skipped,
109
+ snapshotPath: snapshots.length > 0 ? preRestoreRoot : null,
110
+ };
111
+ }
package/lib/archive.js ADDED
@@ -0,0 +1,160 @@
1
+ import { gzipSync, gunzipSync } from 'node:zlib';
2
+ const BLOCK = 512;
3
+ export const MANIFEST_PATH = '.dsh-user-sync/manifest.json';
4
+ /** 包名必须匹配;不匹配的一律在发请求前拒绝(§6.4)。 */
5
+ export const PACKAGE_ID_RE = /^dsh-user-sync-\d{8}-\d{4}-[a-z0-9]{6,16}\.tar\.gz$/;
6
+ export function isPackageId(name) {
7
+ return PACKAGE_ID_RE.test(name);
8
+ }
9
+ function writeString(buf, offset, value, length = 100) {
10
+ const bytes = Buffer.from(value, 'utf8');
11
+ if (bytes.length > length)
12
+ throw new Error(`tar 字段超长: ${value}`);
13
+ bytes.copy(buf, offset);
14
+ }
15
+ function writeOctal(buf, offset, value, length) {
16
+ const text = value.toString(8).padStart(length - 1, '0');
17
+ buf.write(`${text}\0`, offset, length, 'ascii');
18
+ }
19
+ function readString(buf, offset, length) {
20
+ const slice = buf.subarray(offset, offset + length);
21
+ const end = slice.indexOf(0);
22
+ return slice.subarray(0, end === -1 ? slice.length : end).toString('utf8');
23
+ }
24
+ function splitUstarPath(path) {
25
+ const bytes = Buffer.byteLength(path, 'utf8');
26
+ if (bytes <= 100)
27
+ return { name: path, prefix: '' };
28
+ const parts = path.split('/');
29
+ for (let i = parts.length - 1; i > 0; i--) {
30
+ const name = parts.slice(i).join('/');
31
+ const prefix = parts.slice(0, i).join('/');
32
+ if (Buffer.byteLength(name) <= 100 && Buffer.byteLength(prefix) <= 155)
33
+ return { name, prefix };
34
+ }
35
+ throw new Error(`tar 路径过长(不支持 PAX): ${path}`);
36
+ }
37
+ function headerFor({ path, mode = 0o644, size = 0, type = 'file', linkTarget = '', mtime = 0 }) {
38
+ const header = Buffer.alloc(BLOCK);
39
+ const { name, prefix } = splitUstarPath(path);
40
+ writeString(header, 0, name);
41
+ writeOctal(header, 100, mode, 8);
42
+ writeOctal(header, 108, 0, 8);
43
+ writeOctal(header, 116, 0, 8);
44
+ writeOctal(header, 124, type === 'file' ? size : 0, 12);
45
+ writeOctal(header, 136, mtime, 12);
46
+ header.write(' ', 148, 'ascii');
47
+ header.write(type === 'file' ? '0' : type === 'symlink' ? '2' : '5', 156, 'ascii');
48
+ writeString(header, 157, linkTarget, 100);
49
+ writeString(header, 257, 'ustar', 6);
50
+ writeString(header, 263, '00', 2);
51
+ if (prefix)
52
+ writeString(header, 345, prefix, 155);
53
+ let sum = 0;
54
+ for (const byte of header)
55
+ sum += byte;
56
+ header.write(`${sum.toString(8).padStart(6, '0')}\0 `, 148, 'ascii');
57
+ return header;
58
+ }
59
+ function padToBlock(buf) {
60
+ const remainder = buf.length % BLOCK;
61
+ return remainder === 0 ? buf : Buffer.concat([buf, Buffer.alloc(BLOCK - remainder)]);
62
+ }
63
+ /**
64
+ * 生成 tar 与 tar.gz。
65
+ * mode 接受 '100644' | '100755' | '120000'(与 manifest 一致)或数字。
66
+ */
67
+ export function buildTar(entries) {
68
+ const chunks = [];
69
+ for (const entry of entries) {
70
+ const type = entry.type ?? (entry.mode === '120000' ? 'symlink' : 'file');
71
+ const mode = typeof entry.mode === 'string' ? parseInt(entry.mode, 8) & 0o777 : (entry.mode ?? 0o644);
72
+ const data = type === 'file' ? (entry.data ?? Buffer.alloc(0)) : Buffer.alloc(0);
73
+ chunks.push(headerFor({ path: entry.path, mode, size: data.length, type, linkTarget: entry.linkTarget ?? '' }));
74
+ if (type === 'file')
75
+ chunks.push(padToBlock(data));
76
+ }
77
+ chunks.push(Buffer.alloc(BLOCK * 2));
78
+ return Buffer.concat(chunks);
79
+ }
80
+ export function buildTarGz(entries) {
81
+ return gzipSync(buildTar(entries));
82
+ }
83
+ /** 解析 tar(不校验内容哈希,哈希由调用方逐文件算)。 */
84
+ export function parseTar(buf) {
85
+ const entries = [];
86
+ let offset = 0;
87
+ while (offset + BLOCK <= buf.length) {
88
+ const header = buf.subarray(offset, offset + BLOCK);
89
+ if (header.every((byte) => byte === 0))
90
+ break;
91
+ const stored = parseInt(readString(header, 148, 8).trim(), 8);
92
+ let sum = 0;
93
+ for (let i = 0; i < BLOCK; i++)
94
+ sum += i >= 148 && i < 156 ? 32 : header[i];
95
+ if (stored !== sum)
96
+ throw new Error(`tar 头校验失败 @${offset}`);
97
+ const type = String.fromCharCode(header[156]);
98
+ const size = parseInt(readString(header, 124, 12).trim() || '0', 8) || 0;
99
+ const prefix = readString(header, 345, 155);
100
+ const name = readString(header, 0, 100);
101
+ const path = prefix ? `${prefix}/${name}` : name;
102
+ const rawMode = parseInt(readString(header, 100, 8).trim() || '644', 8) || 0o644;
103
+ const mode = type === '2' ? '120000' : (rawMode & 0o111) !== 0 ? '100755' : '100644';
104
+ const dataStart = offset + BLOCK;
105
+ const data = type === '0' ? buf.subarray(dataStart, dataStart + size) : Buffer.alloc(0);
106
+ entries.push({
107
+ path,
108
+ type: type === '2' ? 'symlink' : type === '5' ? 'dir' : 'file',
109
+ mode,
110
+ size,
111
+ data,
112
+ linkTarget: readString(header, 157, 100),
113
+ });
114
+ offset = dataStart + Math.ceil(size / BLOCK) * BLOCK;
115
+ }
116
+ return entries;
117
+ }
118
+ export function parseTarGz(buf) {
119
+ return parseTar(gunzipSync(buf));
120
+ }
121
+ /** 组装 manifest(首条目)。 */
122
+ export function buildManifest(files, meta) {
123
+ return {
124
+ schemaVersion: 3,
125
+ format: 'dsh-user-sync/1',
126
+ hashMode: 'lf',
127
+ packageId: meta.packageId,
128
+ createdAt: meta.createdAt,
129
+ deviceId: meta.deviceId,
130
+ platform: meta.platform,
131
+ arch: meta.arch,
132
+ dshVersion: meta.dshVersion ?? null,
133
+ profile: meta.profile,
134
+ modules: meta.modules,
135
+ bundles: meta.bundles,
136
+ dependencies: meta.dependencies,
137
+ files: files.map(({ path, sha256, size, mode }) => ({ path, sha256, size, mode })),
138
+ };
139
+ }
140
+ /** 解析 manifest;v2 的 files[].name 映射为 path,exportedAt 作为 createdAt。 */
141
+ export function normalizeManifest(raw) {
142
+ const schemaVersion = raw.schemaVersion ?? 2;
143
+ const files = (raw.files ?? []).map((file) => ({
144
+ path: file.path ?? file.name,
145
+ sha256: file.sha256,
146
+ size: file.size,
147
+ mode: file.mode ?? '100644',
148
+ }));
149
+ return {
150
+ schemaVersion,
151
+ format: raw.format ?? 'dsh-user-sync/1',
152
+ hashMode: raw.hashMode ?? 'lf',
153
+ packageId: raw.packageId ?? '',
154
+ createdAt: raw.createdAt ?? raw.exportedAt ?? null,
155
+ deviceId: raw.deviceId ?? '',
156
+ modules: raw.modules ?? ['plugins', 'config'],
157
+ ...raw,
158
+ files,
159
+ };
160
+ }
package/lib/auth.js ADDED
@@ -0,0 +1,10 @@
1
+ import { createHash } from 'node:crypto';
2
+ /**
3
+ * 官方账号 id → accountKey(sha256 前 16 个十六进制字符)。
4
+ * 与 profile 名、设备无关:同账号所有环境得到同一个值(G5)。
5
+ */
6
+ export function deriveAccountKey(accountId) {
7
+ if (!accountId)
8
+ return null;
9
+ return createHash('sha256').update(String(accountId), 'utf8').digest('hex').slice(0, 16);
10
+ }