@insmind/cli 1.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.
Files changed (153) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -0
  3. package/contracts/operations/agent.send/input.schema.json +335 -0
  4. package/contracts/operations/agent.send/output.schema.json +248 -0
  5. package/contracts/operations/auth.status/input.schema.json +7 -0
  6. package/contracts/operations/auth.status/output.schema.json +119 -0
  7. package/contracts/operations/dam.copy/input.schema.json +42 -0
  8. package/contracts/operations/dam.copy/output.schema.json +43 -0
  9. package/contracts/operations/dam.delete/input.schema.json +24 -0
  10. package/contracts/operations/dam.delete/output.schema.json +5 -0
  11. package/contracts/operations/dam.download/input.schema.json +28 -0
  12. package/contracts/operations/dam.download/output.schema.json +51 -0
  13. package/contracts/operations/dam.folder.list/input.schema.json +36 -0
  14. package/contracts/operations/dam.folder.list/output.schema.json +104 -0
  15. package/contracts/operations/dam.get/input.schema.json +16 -0
  16. package/contracts/operations/dam.get/output.schema.json +107 -0
  17. package/contracts/operations/dam.list/input.schema.json +73 -0
  18. package/contracts/operations/dam.list/output.schema.json +145 -0
  19. package/contracts/operations/dam.move/input.schema.json +42 -0
  20. package/contracts/operations/dam.move/output.schema.json +40 -0
  21. package/contracts/operations/dam.rename/input.schema.json +42 -0
  22. package/contracts/operations/dam.rename/output.schema.json +43 -0
  23. package/contracts/operations/dam.repository.list/input.schema.json +7 -0
  24. package/contracts/operations/dam.repository.list/output.schema.json +65 -0
  25. package/contracts/operations/dam.search/input.schema.json +79 -0
  26. package/contracts/operations/dam.search/output.schema.json +145 -0
  27. package/contracts/operations/dam.tag.list/input.schema.json +21 -0
  28. package/contracts/operations/dam.tag.list/output.schema.json +52 -0
  29. package/contracts/operations/dam.upload/input.schema.json +43 -0
  30. package/contracts/operations/dam.upload/output.schema.json +107 -0
  31. package/contracts/operations/editor.apply/input.schema.json +177 -0
  32. package/contracts/operations/editor.apply/output.schema.json +15 -0
  33. package/contracts/operations/editor.connect/input.schema.json +13 -0
  34. package/contracts/operations/editor.connect/output.schema.json +17 -0
  35. package/contracts/operations/editor.disconnect/input.schema.json +7 -0
  36. package/contracts/operations/editor.disconnect/output.schema.json +14 -0
  37. package/contracts/operations/editor.save/input.schema.json +7 -0
  38. package/contracts/operations/editor.save/output.schema.json +23 -0
  39. package/contracts/operations/editor.screenshot/input.schema.json +7 -0
  40. package/contracts/operations/editor.screenshot/output.schema.json +16 -0
  41. package/contracts/operations/editor.snapshot/input.schema.json +7 -0
  42. package/contracts/operations/editor.snapshot/output.schema.json +148 -0
  43. package/contracts/operations/model.get/input.schema.json +16 -0
  44. package/contracts/operations/model.get/output.schema.json +167 -0
  45. package/contracts/operations/model.list/input.schema.json +13 -0
  46. package/contracts/operations/model.list/output.schema.json +97 -0
  47. package/contracts/operations/task.get/input.schema.json +14 -0
  48. package/contracts/operations/task.get/output.schema.json +103 -0
  49. package/contracts/operations/task.list/input.schema.json +18 -0
  50. package/contracts/operations/task.list/output.schema.json +53 -0
  51. package/contracts/operations/tool.call/input.schema.json +31 -0
  52. package/contracts/operations/tool.call/output.schema.json +115 -0
  53. package/contracts/operations/tool.list/input.schema.json +6 -0
  54. package/contracts/operations/tool.list/output.schema.json +40 -0
  55. package/dist/bin/agent-worker.js +41 -0
  56. package/dist/bin/insmind-cli.js +60 -0
  57. package/dist/bin/postinstall.js +69 -0
  58. package/dist/src/bootstrap/create-cli.js +124 -0
  59. package/dist/src/bootstrap/create-runtime.js +451 -0
  60. package/dist/src/bootstrap/run-agent-worker.js +37 -0
  61. package/dist/src/bootstrap/validators.js +169 -0
  62. package/dist/src/cli/action-binding.js +109 -0
  63. package/dist/src/cli/agent-commands.js +75 -0
  64. package/dist/src/cli/auth-commands.js +58 -0
  65. package/dist/src/cli/credits-command.js +23 -0
  66. package/dist/src/cli/dam-commands.js +470 -0
  67. package/dist/src/cli/editor-commands.js +74 -0
  68. package/dist/src/cli/errors.js +208 -0
  69. package/dist/src/cli/model-commands.js +62 -0
  70. package/dist/src/cli/org-commands.js +58 -0
  71. package/dist/src/cli/presenter.js +123 -0
  72. package/dist/src/cli/prompt.js +30 -0
  73. package/dist/src/cli/task-commands.js +48 -0
  74. package/dist/src/cli/tool-commands.js +101 -0
  75. package/dist/src/cli/update-command.js +15 -0
  76. package/dist/src/contracts/schema.js +4 -0
  77. package/dist/src/features/agent/creative-agent-adapter.js +42 -0
  78. package/dist/src/features/agent/creative-protocol.js +421 -0
  79. package/dist/src/features/agent/creative-stream.js +138 -0
  80. package/dist/src/features/agent/filems-resource-auth-key-provider.js +23 -0
  81. package/dist/src/features/agent/resource-authorizer.js +47 -0
  82. package/dist/src/features/agent/result-reader.js +30 -0
  83. package/dist/src/features/agent/use-cases.js +153 -0
  84. package/dist/src/features/auth/access-policy.js +101 -0
  85. package/dist/src/features/auth/credential-store.js +62 -0
  86. package/dist/src/features/auth/sso-service.js +196 -0
  87. package/dist/src/features/auth/state.js +129 -0
  88. package/dist/src/features/auth/use-cases.js +162 -0
  89. package/dist/src/features/credits/use-cases.js +52 -0
  90. package/dist/src/features/dam/asset-projection.js +278 -0
  91. package/dist/src/features/dam/dam-api-adapter.js +562 -0
  92. package/dist/src/features/dam/file-downloader.js +242 -0
  93. package/dist/src/features/dam/object-storage.js +193 -0
  94. package/dist/src/features/dam/operation-executor.js +72 -0
  95. package/dist/src/features/dam/registered-uploader.js +247 -0
  96. package/dist/src/features/dam/repository-catalog.js +127 -0
  97. package/dist/src/features/dam/storage-upload.js +141 -0
  98. package/dist/src/features/dam/transient-uploader.js +17 -0
  99. package/dist/src/features/dam/use-cases.js +470 -0
  100. package/dist/src/features/editor/bridge-client.js +109 -0
  101. package/dist/src/features/editor/bridge-process.js +229 -0
  102. package/dist/src/features/editor/bridge-server.js +337 -0
  103. package/dist/src/features/editor/protocol.js +1 -0
  104. package/dist/src/features/editor/public-url.js +36 -0
  105. package/dist/src/features/editor/session-state.js +78 -0
  106. package/dist/src/features/editor/session.js +213 -0
  107. package/dist/src/features/editor/use-cases.js +88 -0
  108. package/dist/src/features/org/org-service.js +76 -0
  109. package/dist/src/features/org/use-cases.js +163 -0
  110. package/dist/src/features/skill/bundled-skills.js +63 -0
  111. package/dist/src/features/skill/installer.js +271 -0
  112. package/dist/src/features/task/agent-background.js +63 -0
  113. package/dist/src/features/task/store.js +97 -0
  114. package/dist/src/features/task/types.js +1 -0
  115. package/dist/src/features/task/use-cases.js +139 -0
  116. package/dist/src/features/tool/catalog.js +83 -0
  117. package/dist/src/features/tool/dynamic-schema.js +128 -0
  118. package/dist/src/features/tool/mns-catalog-adapter.js +265 -0
  119. package/dist/src/features/tool/tool-api-adapter.js +369 -0
  120. package/dist/src/features/tool/use-cases.js +180 -0
  121. package/dist/src/features/update/latest-version.js +37 -0
  122. package/dist/src/features/update/update-notification.js +271 -0
  123. package/dist/src/features/update/update-service.js +226 -0
  124. package/dist/src/platform/installation-owner.js +81 -0
  125. package/dist/src/platform/json-input.js +67 -0
  126. package/dist/src/platform/local-json-file.js +59 -0
  127. package/dist/src/platform/open-browser.js +8 -0
  128. package/dist/src/platform/redact.js +80 -0
  129. package/dist/src/platform/remote-error-evidence.js +80 -0
  130. package/dist/src/platform/remote-protocol.js +10 -0
  131. package/dist/src/platform/resource-auth-key.js +1 -0
  132. package/dist/src/platform/safe-upload-file.js +146 -0
  133. package/dist/src/platform/signature.js +20 -0
  134. package/dist/src/platform/signed-http-transport.js +144 -0
  135. package/dist/src/platform/task-observer.js +1 -0
  136. package/dist/src/platform/url-safety.js +100 -0
  137. package/dist/src/product/billing.js +47 -0
  138. package/dist/src/product/config.js +85 -0
  139. package/dist/src/product/locale.js +38 -0
  140. package/dist/src/product/text.js +3 -0
  141. package/dist/src/telemetry/invocation.js +156 -0
  142. package/dist/src/telemetry/sls-sink.js +30 -0
  143. package/package.json +53 -0
  144. package/skills/insmind-cli/SKILL.md +15 -0
  145. package/skills/insmind-cli/references/agent.md +34 -0
  146. package/skills/insmind-cli/references/auth.md +8 -0
  147. package/skills/insmind-cli/references/creation.md +40 -0
  148. package/skills/insmind-cli/references/dam.md +51 -0
  149. package/skills/insmind-cli/references/editor.md +184 -0
  150. package/skills/insmind-cli/references/errors.md +29 -0
  151. package/skills/insmind-cli/references/generation-constraints.md +36 -0
  152. package/skills/insmind-cli/references/tool.md +31 -0
  153. package/skills/insmind-cli/references/update.md +11 -0
@@ -0,0 +1,30 @@
1
+ import { RemoteProtocolError } from "../../platform/remote-protocol.js";
2
+ import { creativeTurnMessages, normalizeCreativeMessages } from "./creative-protocol.js";
3
+ /** History is a snapshot, not proof that this particular invocation finished. */
4
+ export async function readAgentResult(transport, request) {
5
+ const path = `/ai-agent/v1/thread/${encodeURIComponent(request.contextId)}`;
6
+ const access = { credential: request.credential, signal: request.signal,
7
+ ...(request.organizationId === undefined ? {} : { organizationId: request.organizationId }) };
8
+ const messages = await transport.getJson({ ...access, path: `${path}/messages` });
9
+ const connection = await transport.getJson({ ...access, path: `${path}/connection` });
10
+ if (!connection || typeof connection !== "object" || !("state" in connection)
11
+ || typeof connection.state !== "string"
12
+ || !["running", "stopping", "inactive"].includes(connection.state))
13
+ throw new RemoteProtocolError();
14
+ if (!Array.isArray(messages))
15
+ throw new RemoteProtocolError();
16
+ if (!messages.some(m => m && typeof m === "object" && m.local_message_id === request.localMessageId)) {
17
+ return { connectionState: connection.state };
18
+ }
19
+ const turn = creativeTurnMessages(messages, request.localMessageId);
20
+ if (!turn.some(m => m.role !== "user" && m.content))
21
+ return { connectionState: connection.state };
22
+ try {
23
+ return { connectionState: connection.state, partialResult: normalizeCreativeMessages(turn) };
24
+ }
25
+ catch (error) {
26
+ if (error instanceof RemoteProtocolError)
27
+ return { connectionState: connection.state };
28
+ throw error;
29
+ }
30
+ }
@@ -0,0 +1,153 @@
1
+ import { findModel, ToolInputError } from "../tool/catalog.js";
2
+ import { modelControlArgumentsAreValid } from "../tool/dynamic-schema.js";
3
+ import { parseSafeRemoteAssetUrl, UrlSafetyError } from "../../platform/url-safety.js";
4
+ export class AgentInputError extends Error {
5
+ constructor() {
6
+ super("Agent 输入不可用。");
7
+ this.name = "AgentInputError";
8
+ }
9
+ }
10
+ const mediaTypes = {
11
+ avif: "image/avif",
12
+ gif: "image/gif",
13
+ heic: "image/heic",
14
+ jpeg: "image/jpeg",
15
+ jpg: "image/jpeg",
16
+ mp4: "video/mp4",
17
+ png: "image/png",
18
+ webp: "image/webp"
19
+ };
20
+ function pathnameFilename(url) {
21
+ const segment = url.pathname.split("/").filter(Boolean).at(-1);
22
+ if (segment === undefined)
23
+ return "creative-media";
24
+ try {
25
+ return decodeURIComponent(segment) || "creative-media";
26
+ }
27
+ catch {
28
+ return segment;
29
+ }
30
+ }
31
+ function inferMediaType(filename) {
32
+ const extension = filename.split(".").at(-1)?.toLowerCase();
33
+ return extension === undefined || extension === filename.toLowerCase()
34
+ ? "application/octet-stream"
35
+ : mediaTypes[extension] ?? "application/octet-stream";
36
+ }
37
+ export function createAgentUseCases(dependencies) {
38
+ async function prepare({ input, access, signal }) {
39
+ signal.throwIfAborted();
40
+ const prepared = [];
41
+ let generation;
42
+ for (const part of input.message.parts) {
43
+ if ("data" in part && !("questionMessageId" in part.data)) {
44
+ generation = part.data;
45
+ break;
46
+ }
47
+ }
48
+ if (generation?.model !== undefined) {
49
+ dependencies.telemetry.annotate({ model_id: generation.model });
50
+ const catalog = await dependencies.telemetry.stage("catalog", () => (dependencies.catalog.load({ access, signal })));
51
+ signal.throwIfAborted();
52
+ for (const warning of catalog.warnings)
53
+ dependencies.warn(warning);
54
+ await dependencies.telemetry.stage("input", async () => {
55
+ let model;
56
+ try {
57
+ model = findModel(catalog, generation.model);
58
+ }
59
+ catch (error) {
60
+ if (error instanceof ToolInputError)
61
+ throw new AgentInputError();
62
+ throw error;
63
+ }
64
+ if (!modelControlArgumentsAreValid(model, generation.arguments ?? {}))
65
+ throw new AgentInputError();
66
+ });
67
+ }
68
+ const prepare = async () => {
69
+ for (const part of input.message.parts) {
70
+ signal.throwIfAborted();
71
+ if ("text" in part) {
72
+ prepared.push({ kind: "text", text: part.text });
73
+ continue;
74
+ }
75
+ if ("url" in part) {
76
+ const role = part.metadata?.role ?? "reference";
77
+ if (part.url.startsWith("file:")) {
78
+ const uploadInput = {
79
+ url: part.url,
80
+ ...(part.mediaType === undefined ? {} : { mediaType: part.mediaType }),
81
+ ...(part.filename === undefined ? {} : { filename: part.filename })
82
+ };
83
+ const asset = await dependencies.uploader.upload(uploadInput, access, signal);
84
+ prepared.push({ kind: "asset", asset, role });
85
+ continue;
86
+ }
87
+ let url;
88
+ try {
89
+ url = parseSafeRemoteAssetUrl(part.url);
90
+ }
91
+ catch (error) {
92
+ if (error instanceof UrlSafetyError)
93
+ throw new AgentInputError();
94
+ throw error;
95
+ }
96
+ const filename = part.filename ?? pathnameFilename(url);
97
+ prepared.push({
98
+ kind: "asset",
99
+ asset: {
100
+ url: part.url,
101
+ mediaType: part.mediaType ?? inferMediaType(filename),
102
+ filename,
103
+ fromUserUpload: false
104
+ },
105
+ role
106
+ });
107
+ continue;
108
+ }
109
+ if ("questionMessageId" in part.data) {
110
+ prepared.push({
111
+ kind: "answers",
112
+ data: {
113
+ questionMessageId: part.data.questionMessageId,
114
+ answers: part.data.answers.map((answer) => ({
115
+ question: answer.question,
116
+ values: [...answer.values]
117
+ }))
118
+ }
119
+ });
120
+ continue;
121
+ }
122
+ prepared.push({
123
+ kind: "generation",
124
+ data: {
125
+ ...(part.data.model === undefined ? {} : { model: part.data.model }),
126
+ ...(part.data.arguments === undefined
127
+ ? {}
128
+ : { arguments: { ...part.data.arguments } })
129
+ }
130
+ });
131
+ }
132
+ };
133
+ if (input.message.parts.some((part) => (typeof part === "object" && part !== null
134
+ && "url" in part && typeof part.url === "string" && part.url.startsWith("file:")))) {
135
+ await dependencies.telemetry.stage("upload", prepare);
136
+ }
137
+ else {
138
+ await prepare();
139
+ }
140
+ signal.throwIfAborted();
141
+ return {
142
+ ...(input.message.contextId === undefined
143
+ ? {}
144
+ : { contextId: input.message.contextId }),
145
+ parts: prepared
146
+ };
147
+ }
148
+ return {
149
+ async send(input) {
150
+ return dependencies.completion.complete(await prepare(input), input.access, input.signal, ...(input.observe ? [input.observe] : []));
151
+ }
152
+ };
153
+ }
@@ -0,0 +1,101 @@
1
+ import { OrganizationInvalidError } from "../org/use-cases.js";
2
+ export class AuthRequiredError extends Error {
3
+ constructor() {
4
+ super("请先执行 gd-cli auth login");
5
+ this.name = "AuthRequiredError";
6
+ }
7
+ }
8
+ export class AuthExpiredError extends Error {
9
+ constructor() {
10
+ super("登录已过期,请退出后重新登录。");
11
+ this.name = "AuthExpiredError";
12
+ }
13
+ }
14
+ const REFRESH_WINDOW_MS = 5 * 60 * 1000;
15
+ const organizationRefreshes = new Map();
16
+ export function createAccessPolicies(dependencies) {
17
+ async function readValidState(signal) {
18
+ signal.throwIfAborted();
19
+ const state = await dependencies.store.read();
20
+ signal.throwIfAborted();
21
+ if (!state)
22
+ throw new AuthRequiredError();
23
+ if (Date.parse(state.credential.expiresAt) <= dependencies.now().getTime()) {
24
+ throw new AuthExpiredError();
25
+ }
26
+ return state;
27
+ }
28
+ async function refreshOrganization(state, signal) {
29
+ const key = `${state.credential.accessKey}\0${state.organization.id}`;
30
+ let refresh = organizationRefreshes.get(key);
31
+ if (!refresh) {
32
+ refresh = (async () => {
33
+ let organization;
34
+ try {
35
+ organization = await dependencies.refreshCurrentOrganization({ state, signal });
36
+ }
37
+ catch (error) {
38
+ if (error instanceof OrganizationInvalidError) {
39
+ const latest = await dependencies.store.read();
40
+ if (sameOrganization(latest, state)) {
41
+ const { organization: _organization, ...withoutOrganization } = latest;
42
+ await dependencies.store.write(withoutOrganization);
43
+ }
44
+ }
45
+ throw error;
46
+ }
47
+ const latest = await dependencies.store.read();
48
+ if (sameOrganization(latest, state)) {
49
+ await dependencies.store.write({ ...latest, organization });
50
+ }
51
+ })();
52
+ organizationRefreshes.set(key, refresh);
53
+ }
54
+ try {
55
+ await refresh;
56
+ }
57
+ finally {
58
+ if (organizationRefreshes.get(key) === refresh)
59
+ organizationRefreshes.delete(key);
60
+ }
61
+ }
62
+ return {
63
+ none: {
64
+ async authorize(signal) {
65
+ signal.throwIfAborted();
66
+ return { policy: "none" };
67
+ }
68
+ },
69
+ credential: {
70
+ async authorize(signal) {
71
+ const state = await readValidState(signal);
72
+ return { policy: "credential", state };
73
+ }
74
+ },
75
+ organization: {
76
+ async authorize(signal) {
77
+ let state = await readValidState(signal);
78
+ if (!state.organization)
79
+ throw new OrganizationInvalidError();
80
+ if (bindingNeedsRefresh(state.organization, dependencies.now())) {
81
+ await refreshOrganization(state, signal);
82
+ state = await readValidState(signal);
83
+ if (!state.organization)
84
+ throw new OrganizationInvalidError();
85
+ }
86
+ return {
87
+ policy: "organization",
88
+ state: state
89
+ };
90
+ }
91
+ }
92
+ };
93
+ }
94
+ function bindingNeedsRefresh(organization, now) {
95
+ return organization.bindExpiresAt === undefined
96
+ || Date.parse(organization.bindExpiresAt) <= now.getTime() + REFRESH_WINDOW_MS;
97
+ }
98
+ function sameOrganization(current, expected) {
99
+ return current?.credential.accessKey === expected.credential.accessKey
100
+ && current.organization?.id === expected.organization.id;
101
+ }
@@ -0,0 +1,62 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ import { createLocalJsonFile, LocalFileError } from "../../platform/local-json-file.js";
4
+ import { AuthStateInvalidError, parseStoredAuthState } from "./state.js";
5
+ export function createLocalCredentialStore(options = {}) {
6
+ const file = options.file ?? createLocalJsonFile({
7
+ directory: join(options.homeDirectory ?? homedir(), options.stateDirectory ?? ".gd"),
8
+ filename: "credentials.json"
9
+ });
10
+ return {
11
+ async read() {
12
+ try {
13
+ const text = await file.readText();
14
+ if (text === null)
15
+ return null;
16
+ let raw;
17
+ try {
18
+ raw = JSON.parse(text);
19
+ }
20
+ catch (cause) {
21
+ throw new AuthStateInvalidError({ cause });
22
+ }
23
+ const parsed = parseStoredAuthState(raw);
24
+ if (parsed.migrated)
25
+ await file.writeTextAtomically(serialize(parsed.state));
26
+ return parsed.state;
27
+ }
28
+ catch (cause) {
29
+ if (cause instanceof AuthStateInvalidError)
30
+ throw cause;
31
+ throw invalidState(cause);
32
+ }
33
+ },
34
+ async write(state) {
35
+ try {
36
+ const validated = parseStoredAuthState(state).state;
37
+ await file.writeTextAtomically(serialize(validated));
38
+ }
39
+ catch (cause) {
40
+ if (cause instanceof AuthStateInvalidError)
41
+ throw cause;
42
+ throw invalidState(cause);
43
+ }
44
+ },
45
+ async remove() {
46
+ try {
47
+ await file.remove();
48
+ }
49
+ catch (cause) {
50
+ throw invalidState(cause);
51
+ }
52
+ }
53
+ };
54
+ }
55
+ function serialize(state) {
56
+ return `${JSON.stringify(state, null, 2)}\n`;
57
+ }
58
+ function invalidState(cause) {
59
+ return new AuthStateInvalidError({
60
+ cause: cause instanceof LocalFileError ? cause.cause : cause
61
+ });
62
+ }
@@ -0,0 +1,196 @@
1
+ import { normalizeScope } from "./state.js";
2
+ import { signBindOrganization } from "../../platform/signature.js";
3
+ export class SsoRequestError extends Error {
4
+ status;
5
+ constructor(status) {
6
+ super(status === undefined ? "无法连接稿定登录服务。" : `稿定登录服务请求失败(HTTP ${status})。`);
7
+ this.name = "SsoRequestError";
8
+ this.status = status;
9
+ }
10
+ }
11
+ export function classifyBindOutcome(input) {
12
+ const code = input.code === undefined ? "" : String(input.code).trim().toUpperCase();
13
+ const details = input.message ? { message: input.message } : {};
14
+ if (!code || code === "0" || code === "200" || code === "OK" || code === "SUCCESS") {
15
+ return input.bindExpiresAt
16
+ ? { status: "success", bindExpiresAt: input.bindExpiresAt }
17
+ : { status: "success" };
18
+ }
19
+ return code === "ORG_INVALID"
20
+ ? { status: "invalid", ...details }
21
+ : { status: "failed", ...details };
22
+ }
23
+ export function createSsoService(options) {
24
+ const baseUrl = new URL(options.ssoApi);
25
+ if (!baseUrl.pathname.endsWith("/"))
26
+ baseUrl.pathname += "/";
27
+ async function request(relativeUrl, signal, method = "POST") {
28
+ signal.throwIfAborted();
29
+ try {
30
+ return await options.fetch(new URL(relativeUrl, baseUrl), {
31
+ method,
32
+ headers: { Accept: "application/json" },
33
+ signal: AbortSignal.any([
34
+ signal,
35
+ AbortSignal.timeout(options.timeoutMs ?? 30_000)
36
+ ])
37
+ });
38
+ }
39
+ catch {
40
+ if (signal.aborted)
41
+ throw signal.reason;
42
+ throw new SsoRequestError();
43
+ }
44
+ }
45
+ return {
46
+ async startDeviceAuthorization(signal) {
47
+ const response = await request(`oauth/device-authorization?${new URLSearchParams({
48
+ clientId: options.clientId ?? "gdhub-cli"
49
+ })}`, signal);
50
+ if (!response.ok)
51
+ throw new SsoRequestError(response.status);
52
+ const body = await responseRecord(response);
53
+ const authorizeCode = nonEmptyString(body.authorize_code);
54
+ const deviceCode = nonEmptyString(body.device_code);
55
+ const expiresInSeconds = positiveNumber(body.expires_in);
56
+ const intervalSeconds = positiveNumber(body.interval);
57
+ if (!authorizeCode || !deviceCode || !expiresInSeconds || !intervalSeconds) {
58
+ throw new SsoRequestError(response.status);
59
+ }
60
+ return { authorizeCode, deviceCode, expiresInSeconds, intervalSeconds };
61
+ },
62
+ async pollDeviceToken(deviceCode, signal) {
63
+ const query = new URLSearchParams({
64
+ grantType: "device_code",
65
+ deviceCode
66
+ });
67
+ const response = await request(`oauth/device/token?${query}`, signal);
68
+ const body = await responseRecord(response);
69
+ const error = nonEmptyString(body.error)?.toLowerCase();
70
+ if (error === "authorization_pending")
71
+ return { status: "pending" };
72
+ if (error === "slow_down")
73
+ return { status: "slow_down" };
74
+ if (!response.ok)
75
+ throw new SsoRequestError(response.status);
76
+ const accessKey = nonEmptyString(body.ak);
77
+ const secretKey = nonEmptyString(body.sk);
78
+ const expiresAt = dateString(body.expires_at);
79
+ if (!accessKey || !secretKey || !expiresAt)
80
+ throw new SsoRequestError(response.status);
81
+ let scope;
82
+ try {
83
+ scope = normalizeScope(body.scope);
84
+ }
85
+ catch {
86
+ throw new SsoRequestError(response.status);
87
+ }
88
+ const result = {
89
+ status: "authorized",
90
+ credential: { accessKey, secretKey, expiresAt, scope }
91
+ };
92
+ if (isRecord(body.user)) {
93
+ const id = identifier(body.user.id);
94
+ const name = nonEmptyString(body.user.name);
95
+ if (id && name)
96
+ result.account = { id, name };
97
+ }
98
+ const organizationId = identifier(body.orgId ?? body.org_id ?? body.orgID);
99
+ if (organizationId)
100
+ result.organizationId = organizationId;
101
+ return result;
102
+ },
103
+ async getIdentity(accessKey, signal) {
104
+ const query = new URLSearchParams({ ak: accessKey });
105
+ const response = await request(`oauth/device/identity?${query}`, signal, "GET");
106
+ if (!response.ok)
107
+ throw new SsoRequestError(response.status);
108
+ const body = await responseRecord(response);
109
+ const result = {};
110
+ const userId = identifier(body.userId);
111
+ if (userId)
112
+ result.account = { id: userId, name: userId };
113
+ const organizationId = identifier(body.orgId);
114
+ if (organizationId)
115
+ result.organizationId = organizationId;
116
+ return result;
117
+ },
118
+ async bindOrganization(input, signal) {
119
+ const timestamp = Math.floor(options.now().getTime() / 1000);
120
+ const query = new URLSearchParams({
121
+ ak: input.credential.accessKey,
122
+ orgId: input.organizationId,
123
+ signature: signBindOrganization({
124
+ accessKey: input.credential.accessKey,
125
+ secretKey: input.credential.secretKey,
126
+ organizationId: input.organizationId,
127
+ timestamp
128
+ }),
129
+ timestamp: String(timestamp)
130
+ });
131
+ const response = await request(`oauth/device/bind-org?${query}`, signal);
132
+ if (!response.ok)
133
+ throw new SsoRequestError(response.status);
134
+ const text = await response.text();
135
+ if (!text.trim())
136
+ return {};
137
+ let parsed;
138
+ try {
139
+ parsed = JSON.parse(text);
140
+ }
141
+ catch {
142
+ return { message: text.trim() };
143
+ }
144
+ if (!isRecord(parsed))
145
+ throw new SsoRequestError(response.status);
146
+ const result = {};
147
+ if (typeof parsed.code === "string" || typeof parsed.code === "number") {
148
+ result.code = parsed.code;
149
+ }
150
+ const message = nonEmptyString(parsed.message);
151
+ if (message)
152
+ result.message = message;
153
+ if (parsed.bind_expires_at !== undefined) {
154
+ const bindExpiresAt = dateString(parsed.bind_expires_at);
155
+ if (!bindExpiresAt)
156
+ throw new SsoRequestError(response.status);
157
+ result.bindExpiresAt = bindExpiresAt;
158
+ }
159
+ return result;
160
+ }
161
+ };
162
+ }
163
+ async function responseRecord(response) {
164
+ try {
165
+ const value = await response.json();
166
+ if (isRecord(value))
167
+ return value;
168
+ }
169
+ catch {
170
+ // Handled as one safe protocol failure below.
171
+ }
172
+ throw new SsoRequestError(response.status);
173
+ }
174
+ function positiveNumber(value) {
175
+ return typeof value === "number" && Number.isFinite(value) && value > 0
176
+ ? value
177
+ : undefined;
178
+ }
179
+ function dateString(value) {
180
+ const text = nonEmptyString(value);
181
+ return text && !Number.isNaN(Date.parse(text)) ? text : undefined;
182
+ }
183
+ function identifier(value) {
184
+ if (typeof value === "number" && Number.isFinite(value))
185
+ return String(value);
186
+ return nonEmptyString(value);
187
+ }
188
+ function nonEmptyString(value) {
189
+ if (typeof value !== "string")
190
+ return undefined;
191
+ const text = value.trim();
192
+ return text || undefined;
193
+ }
194
+ function isRecord(value) {
195
+ return typeof value === "object" && value !== null && !Array.isArray(value);
196
+ }
@@ -0,0 +1,129 @@
1
+ export class AuthStateInvalidError extends Error {
2
+ constructor(options) {
3
+ super("本地登录状态无效。", options);
4
+ this.name = "AuthStateInvalidError";
5
+ }
6
+ }
7
+ export function parseStoredAuthState(value) {
8
+ try {
9
+ if (!isRecord(value))
10
+ throw new Error("invalid root");
11
+ if (value.version === 1)
12
+ return { state: parseVersionOne(value), migrated: false };
13
+ if (value.version === 2)
14
+ return { state: migrateVersionTwo(value), migrated: true };
15
+ throw new Error("unsupported version");
16
+ }
17
+ catch (cause) {
18
+ if (cause instanceof AuthStateInvalidError)
19
+ throw cause;
20
+ throw new AuthStateInvalidError({ cause });
21
+ }
22
+ }
23
+ function parseVersionOne(value) {
24
+ if (!isRecord(value.credential))
25
+ throw new Error("missing credential");
26
+ const credential = value.credential;
27
+ const result = {
28
+ version: 1,
29
+ credential: {
30
+ accessKey: requiredString(credential.accessKey),
31
+ secretKey: requiredString(credential.secretKey),
32
+ expiresAt: requiredDate(credential.expiresAt),
33
+ scope: requiredScope(credential.scope)
34
+ }
35
+ };
36
+ if (value.account !== undefined) {
37
+ if (!isRecord(value.account))
38
+ throw new Error("invalid account");
39
+ result.account = {
40
+ id: requiredString(value.account.id),
41
+ name: requiredString(value.account.name)
42
+ };
43
+ }
44
+ if (value.organization !== undefined) {
45
+ if (!isRecord(value.organization))
46
+ throw new Error("invalid organization");
47
+ result.organization = organization(value.organization.id, value.organization.name, value.organization.bindExpiresAt);
48
+ }
49
+ return result;
50
+ }
51
+ function migrateVersionTwo(value) {
52
+ const result = {
53
+ version: 1,
54
+ credential: {
55
+ accessKey: requiredString(value.ak),
56
+ secretKey: requiredString(value.sk),
57
+ expiresAt: requiredDate(value.expires_at),
58
+ scope: normalizeScope(value.scope)
59
+ }
60
+ };
61
+ const account = completeLegacyPair(value.user);
62
+ if (account)
63
+ result.account = account;
64
+ if (isRecord(value.current_org)) {
65
+ const id = legacyString(value.current_org.id);
66
+ const name = optionalString(value.current_org.name);
67
+ if (id && name) {
68
+ result.organization = organization(id, name, value.current_org.bind_expires_at);
69
+ }
70
+ }
71
+ return result;
72
+ }
73
+ function organization(id, name, expiresAt) {
74
+ const result = {
75
+ id: requiredString(id),
76
+ name: requiredString(name)
77
+ };
78
+ if (expiresAt !== undefined)
79
+ result.bindExpiresAt = requiredDate(expiresAt);
80
+ return result;
81
+ }
82
+ function completeLegacyPair(value) {
83
+ if (!isRecord(value))
84
+ return undefined;
85
+ const id = legacyString(value.id);
86
+ const name = optionalString(value.name);
87
+ return id && name ? { id, name } : undefined;
88
+ }
89
+ function requiredScope(value) {
90
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
91
+ throw new Error("invalid scope");
92
+ }
93
+ return normalizeScope(value);
94
+ }
95
+ export function normalizeScope(value) {
96
+ if (value === undefined || value === null)
97
+ return [];
98
+ const entries = typeof value === "string" ? value.split(",") : value;
99
+ if (!Array.isArray(entries) || entries.some((item) => typeof item !== "string")) {
100
+ throw new Error("invalid scope");
101
+ }
102
+ return entries.map((item) => item.trim()).filter(Boolean);
103
+ }
104
+ function requiredDate(value) {
105
+ const text = requiredString(value);
106
+ if (Number.isNaN(Date.parse(text)))
107
+ throw new Error("invalid date");
108
+ return text;
109
+ }
110
+ function requiredString(value) {
111
+ const text = optionalString(value);
112
+ if (!text)
113
+ throw new Error("missing string");
114
+ return text;
115
+ }
116
+ function optionalString(value) {
117
+ if (typeof value !== "string")
118
+ return undefined;
119
+ const text = value.trim();
120
+ return text || undefined;
121
+ }
122
+ function legacyString(value) {
123
+ if (typeof value === "number" && Number.isFinite(value))
124
+ return String(value);
125
+ return optionalString(value);
126
+ }
127
+ function isRecord(value) {
128
+ return typeof value === "object" && value !== null && !Array.isArray(value);
129
+ }