@lark-codem/codem-cli 0.1.274-test.202611170849.0.gc5a50ef → 0.1.274

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.
@@ -1,120 +1,120 @@
1
- import { createHash } from "node:crypto";
2
- import { open, stat } from "node:fs/promises";
3
- import { isAbsolute, join } from "node:path";
4
- import { readCredentialMetadata } from "./credential-metadata.js";
5
- import { CredentialStorageError } from "./credential-errors.js";
6
- import { withCodeMConfigLock } from "./profile-io.js";
7
-
8
- const string = value => typeof value === "string" && value.trim() ? value.trim() : null;
9
- const record = value => value && typeof value === "object" && !Array.isArray(value) ? value : null;
10
- const first = (...values) => values.map(string).find(Boolean) ?? null;
11
-
12
- export function resolveProfileUser(status, value) {
13
- const config = record(value);
14
- const oauth = record(record(config?.auth)?.oauth);
15
- const info = record(oauth?.userInfo ?? oauth?.user_info);
16
- const stored = record(config?.user);
17
- return {
18
- userId: first(status.userId, oauth?.userId, oauth?.user_id, stored?.id, oauth?.codemUserId, oauth?.codem_user_id),
19
- tenantId: first(status.tenantId, oauth?.tenantId, oauth?.tenant_id),
20
- displayName: first(status.displayName, oauth?.displayName, oauth?.display_name, info?.displayName, info?.display_name, info?.name, stored?.displayName, stored?.display_name),
21
- avatarUrl: avatar(first(info?.avatarUrl, info?.avatar_url, stored?.avatarUrl, stored?.avatar_url))
22
- };
23
- }
24
-
25
- function avatar(value) {
26
- if (!value) return null;
27
- try {
28
- const url = new URL(value);
29
- const allowed = ["feishucdn.com", "larksuitecdn.com", "feishu-boe.cn"].some(root => url.hostname === root || url.hostname.endsWith(`.${root}`));
30
- return url.protocol === "https:" && allowed && !url.username && !url.password ? url.href : null;
31
- } catch { return null; }
32
- }
33
-
34
- export async function readProfileSnapshot(home) {
35
- if (!isAbsolute(home)) throw new Error("CodeM profile home must be absolute");
36
- try {
37
- if (!(await stat(home)).isDirectory()) throw new Error("CodeM profile home is not a directory");
38
- } catch (error) {
39
- if (error.code !== "ENOENT") throw error;
40
- return { schemaVersion: 1, serverUrl: null,
41
- user: { userId: null, tenantId: null, displayName: null, avatarUrl: null },
42
- account: null, device: null, identityRevision: null };
43
- }
44
- return withCodeMConfigLock(join(home, "config.json"), () => readLockedProfileSnapshot(home));
45
- }
46
-
47
- async function readLockedProfileSnapshot(home) {
48
- const configPath = join(home, "config.json");
49
- const config = await readProfileObject(configPath);
50
- let metadata;
51
- try {
52
- metadata = await readCredentialMetadata(join(home, "credential-storage.json"), config?.credentialStorageRef, "oauth");
53
- } catch (error) {
54
- if (!(error instanceof CredentialStorageError)) throw error;
55
- const kind = ["oauth", "router-ak"].includes(error.kind) ? error.kind : null;
56
- throw new CredentialStorageError(error.code.replace(/^credential_storage_/, ""), kind);
57
- }
58
- if (!config && metadata && !metadata.loggedOut) throw new CredentialStorageError("config_missing", "oauth");
59
- const device = record(config?.device);
60
- const last = record(config?.lastLoginUser ?? config?.last_login_user);
61
- const user = resolveProfileUser({}, config);
62
- const userId = user.userId ?? first(last?.userId, last?.user_id);
63
- const tenantId = user.tenantId ?? first(last?.tenantId, last?.tenant_id);
64
- const historicalMatches = (!first(last?.userId, last?.user_id) || userId === first(last?.userId, last?.user_id))
65
- && (!first(last?.tenantId, last?.tenant_id) || tenantId === first(last?.tenantId, last?.tenant_id));
66
- if (!historicalMatches) throw new Error("CodeM profile identity is inconsistent");
67
- let serverUrl = null;
68
- if (config?.serverUrl) {
69
- let url;
70
- try { url = new URL(config.serverUrl); }
71
- catch { throw new Error("CodeM profile server origin is invalid"); }
72
- if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
73
- throw new Error("CodeM profile server origin is invalid");
74
- }
75
- serverUrl = url.origin;
76
- }
77
- const deviceId = first(device?.deviceId, device?.device_id);
78
- if (deviceId && deviceId.length > 128) throw new Error("CodeM profile device identity is invalid");
79
- const bound = Boolean(deviceId && first(device?.deviceSecret, device?.device_secret) && !metadata?.loggedOut);
80
- const account = bound && userId && tenantId && serverUrl ? {
81
- userId, tenantId,
82
- displayName: user.displayName ?? first(last?.displayName, last?.display_name),
83
- avatarUrl: user.avatarUrl
84
- } : null;
85
- // Full binding login replaces both fields; OAuth generation may instead be
86
- // backfilled by scope-upgrade or a delayed mirror without any new login.
87
- const generation = [string(config?.clientId), string(config?.createdAt)];
88
- return {
89
- schemaVersion: 1,
90
- serverUrl,
91
- user: metadata?.loggedOut
92
- ? { userId: null, tenantId: null, displayName: null, avatarUrl: null }
93
- : { userId, tenantId, displayName: user.displayName ?? first(last?.displayName, last?.display_name), avatarUrl: user.avatarUrl },
94
- account,
95
- device: deviceId ? { id: deviceId, name: first(device?.deviceName, device?.device_name), binding: bound ? "ready" : "missing" } : null,
96
- identityRevision: account ? createHash("sha256").update(JSON.stringify([serverUrl, userId, tenantId, deviceId, first(device?.deviceSecret, device?.device_secret), generation])).digest("hex") : null
97
- };
98
- }
99
-
100
- async function readProfileObject(path) {
101
- let file;
102
- try { file = await open(path, "r"); }
103
- catch (error) { if (error.code === "ENOENT") return null; throw new Error("Cannot read CodeM profile metadata", { cause: error }); }
104
- try {
105
- const info = await file.stat();
106
- if (!info.isFile() || info.size > 1024 * 1024) throw new Error("Invalid profile metadata size");
107
- const buffer = Buffer.alloc(info.size + 1);
108
- let count = 0;
109
- while (count < buffer.length) {
110
- const part = await file.read(buffer, count, buffer.length - count, count);
111
- if (!part.bytesRead) break;
112
- count += part.bytesRead;
113
- }
114
- if (count > info.size) throw new Error("Profile metadata changed during read");
115
- let parsed;
116
- try { parsed = record(JSON.parse(buffer.toString("utf8", 0, count))); } catch { /* Do not surface credential bytes. */ }
117
- if (!parsed) throw new Error("Invalid CodeM profile metadata");
118
- return parsed;
119
- } finally { await file.close(); }
120
- }
1
+ import { createHash } from "node:crypto";
2
+ import { open, stat } from "node:fs/promises";
3
+ import { isAbsolute, join } from "node:path";
4
+ import { readCredentialMetadata } from "./credential-metadata.js";
5
+ import { CredentialStorageError } from "./credential-errors.js";
6
+ import { withCodeMConfigLock } from "./profile-io.js";
7
+
8
+ const string = value => typeof value === "string" && value.trim() ? value.trim() : null;
9
+ const record = value => value && typeof value === "object" && !Array.isArray(value) ? value : null;
10
+ const first = (...values) => values.map(string).find(Boolean) ?? null;
11
+
12
+ export function resolveProfileUser(status, value) {
13
+ const config = record(value);
14
+ const oauth = record(record(config?.auth)?.oauth);
15
+ const info = record(oauth?.userInfo ?? oauth?.user_info);
16
+ const stored = record(config?.user);
17
+ return {
18
+ userId: first(status.userId, oauth?.userId, oauth?.user_id, stored?.id, oauth?.codemUserId, oauth?.codem_user_id),
19
+ tenantId: first(status.tenantId, oauth?.tenantId, oauth?.tenant_id),
20
+ displayName: first(status.displayName, oauth?.displayName, oauth?.display_name, info?.displayName, info?.display_name, info?.name, stored?.displayName, stored?.display_name),
21
+ avatarUrl: avatar(first(info?.avatarUrl, info?.avatar_url, stored?.avatarUrl, stored?.avatar_url))
22
+ };
23
+ }
24
+
25
+ function avatar(value) {
26
+ if (!value) return null;
27
+ try {
28
+ const url = new URL(value);
29
+ const allowed = ["feishucdn.com", "larksuitecdn.com", "feishu-boe.cn"].some(root => url.hostname === root || url.hostname.endsWith(`.${root}`));
30
+ return url.protocol === "https:" && allowed && !url.username && !url.password ? url.href : null;
31
+ } catch { return null; }
32
+ }
33
+
34
+ export async function readProfileSnapshot(home) {
35
+ if (!isAbsolute(home)) throw new Error("CodeM profile home must be absolute");
36
+ try {
37
+ if (!(await stat(home)).isDirectory()) throw new Error("CodeM profile home is not a directory");
38
+ } catch (error) {
39
+ if (error.code !== "ENOENT") throw error;
40
+ return { schemaVersion: 1, serverUrl: null,
41
+ user: { userId: null, tenantId: null, displayName: null, avatarUrl: null },
42
+ account: null, device: null, identityRevision: null };
43
+ }
44
+ return withCodeMConfigLock(join(home, "config.json"), () => readLockedProfileSnapshot(home));
45
+ }
46
+
47
+ async function readLockedProfileSnapshot(home) {
48
+ const configPath = join(home, "config.json");
49
+ const config = await readProfileObject(configPath);
50
+ let metadata;
51
+ try {
52
+ metadata = await readCredentialMetadata(join(home, "credential-storage.json"), config?.credentialStorageRef, "oauth");
53
+ } catch (error) {
54
+ if (!(error instanceof CredentialStorageError)) throw error;
55
+ const kind = ["oauth", "router-ak"].includes(error.kind) ? error.kind : null;
56
+ throw new CredentialStorageError(error.code.replace(/^credential_storage_/, ""), kind);
57
+ }
58
+ if (!config && metadata && !metadata.loggedOut) throw new CredentialStorageError("config_missing", "oauth");
59
+ const device = record(config?.device);
60
+ const last = record(config?.lastLoginUser ?? config?.last_login_user);
61
+ const user = resolveProfileUser({}, config);
62
+ const userId = user.userId ?? first(last?.userId, last?.user_id);
63
+ const tenantId = user.tenantId ?? first(last?.tenantId, last?.tenant_id);
64
+ const historicalMatches = (!first(last?.userId, last?.user_id) || userId === first(last?.userId, last?.user_id))
65
+ && (!first(last?.tenantId, last?.tenant_id) || tenantId === first(last?.tenantId, last?.tenant_id));
66
+ if (!historicalMatches) throw new Error("CodeM profile identity is inconsistent");
67
+ let serverUrl = null;
68
+ if (config?.serverUrl) {
69
+ let url;
70
+ try { url = new URL(config.serverUrl); }
71
+ catch { throw new Error("CodeM profile server origin is invalid"); }
72
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) {
73
+ throw new Error("CodeM profile server origin is invalid");
74
+ }
75
+ serverUrl = url.origin;
76
+ }
77
+ const deviceId = first(device?.deviceId, device?.device_id);
78
+ if (deviceId && deviceId.length > 128) throw new Error("CodeM profile device identity is invalid");
79
+ const bound = Boolean(deviceId && first(device?.deviceSecret, device?.device_secret) && !metadata?.loggedOut);
80
+ const account = bound && userId && tenantId && serverUrl ? {
81
+ userId, tenantId,
82
+ displayName: user.displayName ?? first(last?.displayName, last?.display_name),
83
+ avatarUrl: user.avatarUrl
84
+ } : null;
85
+ // Full binding login replaces both fields; OAuth generation may instead be
86
+ // backfilled by scope-upgrade or a delayed mirror without any new login.
87
+ const generation = [string(config?.clientId), string(config?.createdAt)];
88
+ return {
89
+ schemaVersion: 1,
90
+ serverUrl,
91
+ user: metadata?.loggedOut
92
+ ? { userId: null, tenantId: null, displayName: null, avatarUrl: null }
93
+ : { userId, tenantId, displayName: user.displayName ?? first(last?.displayName, last?.display_name), avatarUrl: user.avatarUrl },
94
+ account,
95
+ device: deviceId ? { id: deviceId, name: first(device?.deviceName, device?.device_name), binding: bound ? "ready" : "missing" } : null,
96
+ identityRevision: account ? createHash("sha256").update(JSON.stringify([serverUrl, userId, tenantId, deviceId, first(device?.deviceSecret, device?.device_secret), generation])).digest("hex") : null
97
+ };
98
+ }
99
+
100
+ async function readProfileObject(path) {
101
+ let file;
102
+ try { file = await open(path, "r"); }
103
+ catch (error) { if (error.code === "ENOENT") return null; throw new Error("Cannot read CodeM profile metadata", { cause: error }); }
104
+ try {
105
+ const info = await file.stat();
106
+ if (!info.isFile() || info.size > 1024 * 1024) throw new Error("Invalid profile metadata size");
107
+ const buffer = Buffer.alloc(info.size + 1);
108
+ let count = 0;
109
+ while (count < buffer.length) {
110
+ const part = await file.read(buffer, count, buffer.length - count, count);
111
+ if (!part.bytesRead) break;
112
+ count += part.bytesRead;
113
+ }
114
+ if (count > info.size) throw new Error("Profile metadata changed during read");
115
+ let parsed;
116
+ try { parsed = record(JSON.parse(buffer.toString("utf8", 0, count))); } catch { /* Do not surface credential bytes. */ }
117
+ if (!parsed) throw new Error("Invalid CodeM profile metadata");
118
+ return parsed;
119
+ } finally { await file.close(); }
120
+ }