arkflow-magpie-plugins 0.0.0-stage → 2.0.19
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 +21 -0
- package/NOTICE +17 -0
- package/README.en.md +29 -0
- package/README.md +28 -2
- package/bundled/meeting-actions/SKILL.md +11 -0
- package/docs/MAGPIE-LICENSE +21 -0
- package/index.mjs +9 -0
- package/package.json +79 -4
- package/page/app.css +275 -0
- package/page/app.js +784 -0
- package/page/bootstrap.js +59 -0
- package/page/connection.js +24 -0
- package/page/icon.svg +3 -0
- package/page/index.html +28 -0
- package/page/logo.png +0 -0
- package/page/magpie-components.css +131 -0
- package/page/request.js +101 -0
- package/page/service.html +3 -0
- package/page/store-model.mjs +107 -0
- package/page/theme.js +51 -0
- package/src/accounts.mjs +124 -0
- package/src/api-client.mjs +292 -0
- package/src/bundled-skills.mjs +13 -0
- package/src/config.mjs +71 -0
- package/src/credentials.mjs +90 -0
- package/src/host-adapter.mjs +707 -0
- package/src/install-defaults.mjs +92 -0
- package/src/install-identity.mjs +32 -0
- package/src/manual-initialization.mjs +225 -0
- package/src/native-auth.mjs +62 -0
- package/src/native-control.mjs +236 -0
- package/src/native-providers.mjs +422 -0
- package/src/page-service.mjs +358 -0
- package/src/provider.mjs +44 -0
- package/src/runtime.mjs +302 -0
- package/src/session.mjs +366 -0
- package/src/skill-metadata.mjs +32 -0
- package/src/skill-packages.mjs +226 -0
- package/src/skills.mjs +454 -0
- package/src/state-store.mjs +89 -0
- package/src/sync-engine.mjs +392 -0
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
const PLUGIN_PREFIX = "/api/novaflow/v1/plugin"
|
|
2
|
+
const DESKTOP = "/api/novaflow/v1/desktop/auth"
|
|
3
|
+
const SKILLS = "/api/novaflow/v1/skill-sync"
|
|
4
|
+
const allowedPath = path => [PLUGIN_PREFIX, DESKTOP, SKILLS].some(prefix => path.startsWith(prefix + "/"))
|
|
5
|
+
export class ApiError extends Error {
|
|
6
|
+
constructor(message, { status = 0, code = "", requestId = "", cause = undefined } = {}) {
|
|
7
|
+
super(message, { cause })
|
|
8
|
+
this.name = "ApiError"
|
|
9
|
+
this.status = status
|
|
10
|
+
this.code = code
|
|
11
|
+
this.requestId = requestId
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function joinPath(base, path) {
|
|
16
|
+
return String(base ?? "").replace(/\/+$/, "") + "/" + String(path ?? "").replace(/^\/+/, "")
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function requestIdOf(metadata) {
|
|
20
|
+
return typeof metadata?.request_id === "string" ? metadata.request_id : ""
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function errorMessage(payload, status) {
|
|
24
|
+
const fields = { display_name: "技能名称不能超过160字", description: "用途说明不能超过2000字", slug: "技能标识无效,请更新插件后重试", idempotency_key: "分享请求标识无效,请重新打开分享窗口", expected_version: "技能版本已变化,请刷新后重试", package: "请选择根目录包含 SKILL.md 的 ZIP 包" }
|
|
25
|
+
const reason = payload?.reason || payload?.code
|
|
26
|
+
if (reason === "SKILL_VERSION_CONFLICT") return "技能版本或分享内容已变化,请刷新后重新选择"
|
|
27
|
+
if (reason === "SKILL_PACKAGE_INVALID" && Object.hasOwn(fields, payload?.metadata?.field)) return fields[payload.metadata.field]
|
|
28
|
+
if (reason === "SKILL_CATEGORY_INVALID" || reason === "SKILL_CATEGORY_NOT_FOUND") return "公司分类已变化,请刷新技能商店后重新选择分类"
|
|
29
|
+
return typeof payload?.message === "string" && payload.message
|
|
30
|
+
? payload.message.replace(/(?<![\w./-])nova[ -]?flow(?![\w./-])/gi, "ArkFlow")
|
|
31
|
+
: `ArkFlow returned HTTP ${status}`
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function limitedBytes(response, limit) {
|
|
35
|
+
const declared = Number(response.headers.get("content-length"))
|
|
36
|
+
if (Number.isFinite(declared) && declared > limit) {
|
|
37
|
+
await response.body?.cancel().catch(() => {})
|
|
38
|
+
throw new ApiError("ArkFlow response exceeds the size limit", { status: response.status, code: "RESPONSE_TOO_LARGE" })
|
|
39
|
+
}
|
|
40
|
+
if (!response.body) return new Uint8Array()
|
|
41
|
+
const reader = response.body.getReader()
|
|
42
|
+
const chunks = []
|
|
43
|
+
let size = 0
|
|
44
|
+
try {
|
|
45
|
+
while (true) {
|
|
46
|
+
const { done, value } = await reader.read()
|
|
47
|
+
if (done) break
|
|
48
|
+
size += value.byteLength
|
|
49
|
+
if (size > limit) throw new ApiError("ArkFlow response exceeds the size limit", { status: response.status, code: "RESPONSE_TOO_LARGE" })
|
|
50
|
+
chunks.push(value)
|
|
51
|
+
}
|
|
52
|
+
} finally {
|
|
53
|
+
await reader.cancel().catch(() => {})
|
|
54
|
+
reader.releaseLock()
|
|
55
|
+
}
|
|
56
|
+
const out = new Uint8Array(size)
|
|
57
|
+
let offset = 0
|
|
58
|
+
for (const chunk of chunks) {
|
|
59
|
+
out.set(chunk, offset)
|
|
60
|
+
offset += chunk.byteLength
|
|
61
|
+
}
|
|
62
|
+
return out
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export class ApiClient {
|
|
66
|
+
constructor(config, { fetchImpl = globalThis.fetch, now = () => Date.now() } = {}) {
|
|
67
|
+
if (typeof fetchImpl !== "function") throw new Error("fetch is unavailable")
|
|
68
|
+
this.config = config
|
|
69
|
+
this.fetchImpl = fetchImpl
|
|
70
|
+
this.now = now
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Magpie can report an empty list for malformed or filtered responses too.
|
|
74
|
+
// Verify the platform's own list using the model Key, not the session token.
|
|
75
|
+
async confirmEmptyModelList(key, signal) {
|
|
76
|
+
const timeout = AbortSignal.timeout(this.config.requestTimeoutMs)
|
|
77
|
+
const response = await this.fetchImpl(this.config.origin + "/v1/models", {
|
|
78
|
+
headers: { accept: "application/json", authorization: "Bearer " + key },
|
|
79
|
+
redirect: "error", signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
|
|
80
|
+
})
|
|
81
|
+
if (response.status !== 200) {
|
|
82
|
+
await response.body?.cancel()
|
|
83
|
+
return false
|
|
84
|
+
}
|
|
85
|
+
const data = JSON.parse(new TextDecoder().decode(await limitedBytes(response, this.config.maxResponseBytes)))
|
|
86
|
+
return data?.object === "list" && data.success !== false && !data.error && !data.has_more
|
|
87
|
+
&& Array.isArray(data.data) && data.data.length === 0
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async request(path, {
|
|
91
|
+
method = "GET",
|
|
92
|
+
accessToken = "",
|
|
93
|
+
body,
|
|
94
|
+
headers = {},
|
|
95
|
+
signal,
|
|
96
|
+
timeoutMs = this.config.requestTimeoutMs,
|
|
97
|
+
expect = "json",
|
|
98
|
+
} = {}) {
|
|
99
|
+
if (!path.startsWith("/")) throw new Error("API path must be absolute under the fixed origin")
|
|
100
|
+
const allowed = allowedPath(path)
|
|
101
|
+
if (!allowed) throw new Error("API path is outside ArkFlow's plugin contract")
|
|
102
|
+
const controller = new AbortController()
|
|
103
|
+
const timer = setTimeout(() => controller.abort(new Error("ArkFlow request timed out")), timeoutMs)
|
|
104
|
+
const abort = () => controller.abort(signal.reason)
|
|
105
|
+
signal?.addEventListener("abort", abort, { once: true })
|
|
106
|
+
try {
|
|
107
|
+
const requestHeaders = new Headers({ accept: expect === "binary" ? "*/*" : "application/json" })
|
|
108
|
+
new Headers(headers).forEach((value, name) => requestHeaders.set(name, value))
|
|
109
|
+
if (accessToken) requestHeaders.set("authorization", `Bearer ${accessToken}`)
|
|
110
|
+
let requestBody = body
|
|
111
|
+
if (body !== undefined && !(body instanceof FormData) && !(body instanceof Uint8Array) && typeof body !== "string") {
|
|
112
|
+
requestHeaders.set("content-type", "application/json")
|
|
113
|
+
requestBody = JSON.stringify(body)
|
|
114
|
+
}
|
|
115
|
+
const target = new URL(path, this.config.origin)
|
|
116
|
+
if (
|
|
117
|
+
target.origin !== this.config.origin
|
|
118
|
+
|| !allowedPath(target.pathname)
|
|
119
|
+
) {
|
|
120
|
+
throw new Error("API path normalized outside ArkFlow's plugin contract")
|
|
121
|
+
}
|
|
122
|
+
const response = await this.fetchImpl(target.href, {
|
|
123
|
+
method,
|
|
124
|
+
headers: requestHeaders,
|
|
125
|
+
body: requestBody,
|
|
126
|
+
redirect: "error",
|
|
127
|
+
signal: controller.signal,
|
|
128
|
+
})
|
|
129
|
+
if (response.status === 304) return { notModified: true, response }
|
|
130
|
+
if (!response.ok) {
|
|
131
|
+
let payload
|
|
132
|
+
try {
|
|
133
|
+
payload = JSON.parse(new TextDecoder().decode(await limitedBytes(response, 128 << 10)))
|
|
134
|
+
} catch {}
|
|
135
|
+
const error = new ApiError(
|
|
136
|
+
errorMessage(payload, response.status),
|
|
137
|
+
{
|
|
138
|
+
status: response.status,
|
|
139
|
+
code: typeof payload?.reason === "string" ? payload.reason : typeof payload?.code === "string" ? payload.code : "",
|
|
140
|
+
requestId: requestIdOf(payload?.metadata),
|
|
141
|
+
},
|
|
142
|
+
)
|
|
143
|
+
throw error
|
|
144
|
+
}
|
|
145
|
+
if (expect === "binary") return { bytes: new Uint8Array(await limitedBytes(response, this.config.maxSkillBytes)), response }
|
|
146
|
+
const bytes = await limitedBytes(response, this.config.maxResponseBytes)
|
|
147
|
+
let payload
|
|
148
|
+
try {
|
|
149
|
+
payload = JSON.parse(new TextDecoder().decode(bytes))
|
|
150
|
+
} catch (cause) {
|
|
151
|
+
throw new ApiError("ArkFlow returned invalid JSON", { status: response.status, code: "INVALID_JSON", cause })
|
|
152
|
+
}
|
|
153
|
+
if (payload && typeof payload === "object" && Object.hasOwn(payload, "code") && Object.hasOwn(payload, "data")) {
|
|
154
|
+
if (payload.code !== 0) {
|
|
155
|
+
throw new ApiError(errorMessage(payload, response.status), {
|
|
156
|
+
status: response.status,
|
|
157
|
+
code: typeof payload.reason === "string" ? payload.reason : String(payload.code),
|
|
158
|
+
requestId: requestIdOf(payload.metadata),
|
|
159
|
+
})
|
|
160
|
+
}
|
|
161
|
+
return expect === "catalog" ? { catalog: payload.data, response } : payload.data
|
|
162
|
+
}
|
|
163
|
+
return payload
|
|
164
|
+
} catch (error) {
|
|
165
|
+
if (error instanceof ApiError) throw error
|
|
166
|
+
if (controller.signal.aborted) throw new ApiError("ArkFlow request failed or timed out", { code: "NETWORK_TIMEOUT", cause: error })
|
|
167
|
+
throw new ApiError("ArkFlow request failed", { code: "NETWORK", cause: error })
|
|
168
|
+
} finally {
|
|
169
|
+
clearTimeout(timer)
|
|
170
|
+
signal?.removeEventListener("abort", abort)
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
startLogin(body, signal) { return this.request(`${DESKTOP}/start`, { method: "POST", body, signal }) }
|
|
175
|
+
exchange(body, signal) { return this.request(`${DESKTOP}/exchange`, { method: "POST", body, signal }) }
|
|
176
|
+
refresh(refresh_token) { return this.request(`${DESKTOP}/refresh`, { method: "POST", body: { refresh_token } }) }
|
|
177
|
+
revoke(accessToken) { return this.request(`${PLUGIN_PREFIX}/auth/revoke`, { method: "POST", accessToken, body: {} }) }
|
|
178
|
+
catalog(accessToken, etag, signal) {
|
|
179
|
+
return this.request(`${SKILLS}/catalog`, { accessToken, signal, expect: "catalog", headers: etag ? { "If-None-Match": etag } : {} })
|
|
180
|
+
}
|
|
181
|
+
skillReceipt(accessToken, body, signal) { return this.request(`${SKILLS}/receipts`, { method: "POST", accessToken, body, signal }) }
|
|
182
|
+
|
|
183
|
+
async bootstrap(accessToken, signal) {
|
|
184
|
+
return this.request(`${PLUGIN_PREFIX}/bootstrap`, { accessToken, signal })
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async credentialsBatch(accessToken, keyIds, expectedRevision, signal) {
|
|
188
|
+
return this.request(`${PLUGIN_PREFIX}/credentials/batch`, {
|
|
189
|
+
method: "POST",
|
|
190
|
+
accessToken,
|
|
191
|
+
body: { key_ids: keyIds, expected_revision: expectedRevision },
|
|
192
|
+
signal,
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
async sync(accessToken, revision = "", signal) {
|
|
197
|
+
const path = revision
|
|
198
|
+
? `${PLUGIN_PREFIX}/sync?if_none_match=${encodeURIComponent(revision)}`
|
|
199
|
+
: `${PLUGIN_PREFIX}/sync`
|
|
200
|
+
return this.request(path, { accessToken, signal })
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async usage(accessToken, signal) {
|
|
204
|
+
return this.request(`${PLUGIN_PREFIX}/usage`, { accessToken, signal })
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async config(accessToken, revision = "", signal) {
|
|
208
|
+
const path = revision
|
|
209
|
+
? `${PLUGIN_PREFIX}/config?if_none_match=${encodeURIComponent(revision)}`
|
|
210
|
+
: `${PLUGIN_PREFIX}/config`
|
|
211
|
+
return this.request(path, { accessToken, signal })
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async saveConfig(accessToken, payload, expectedRevision, signal) {
|
|
215
|
+
return this.request(`${PLUGIN_PREFIX}/config`, {
|
|
216
|
+
method: "PUT",
|
|
217
|
+
accessToken,
|
|
218
|
+
body: { expected_revision: expectedRevision, payload },
|
|
219
|
+
signal,
|
|
220
|
+
})
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async skills(accessToken, cursor = "", signal) {
|
|
224
|
+
const query = new URLSearchParams({ limit: "50" })
|
|
225
|
+
if (cursor) query.set("cursor", cursor)
|
|
226
|
+
return this.request(`${PLUGIN_PREFIX}/skills?${query}`, { accessToken, signal })
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
async skillStore(accessToken, signal) {
|
|
230
|
+
return this.request(`${PLUGIN_PREFIX}/skills/store`, { accessToken, signal })
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async skillStoreDetail(accessToken, sourceKind, skillId, signal) {
|
|
234
|
+
return this.request(
|
|
235
|
+
`${PLUGIN_PREFIX}/skills/store/${encodeURIComponent(sourceKind)}/${encodeURIComponent(skillId)}`,
|
|
236
|
+
{ accessToken, signal },
|
|
237
|
+
)
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async downloadSkillStoreVersion(accessToken, sourceKind, skillId, version, signal) {
|
|
241
|
+
return this.request(
|
|
242
|
+
`${PLUGIN_PREFIX}/skills/store/${encodeURIComponent(sourceKind)}/${encodeURIComponent(skillId)}/versions/${encodeURIComponent(version)}/download`,
|
|
243
|
+
{
|
|
244
|
+
accessToken,
|
|
245
|
+
signal,
|
|
246
|
+
expect: "binary",
|
|
247
|
+
},
|
|
248
|
+
)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
async skill(accessToken, skillId, signal) {
|
|
252
|
+
return this.request(`${SKILLS}/skills/${encodeURIComponent(skillId)}`, { accessToken, signal })
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async downloadSkill(accessToken, skillId, version, signal) {
|
|
256
|
+
return this.request(`${SKILLS}/skills/${encodeURIComponent(skillId)}/versions/${encodeURIComponent(version)}/download`, {
|
|
257
|
+
accessToken,
|
|
258
|
+
signal,
|
|
259
|
+
expect: "binary",
|
|
260
|
+
})
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async contributeSkill(accessToken, form, signal) {
|
|
264
|
+
return this.request(`${SKILLS}/contributions`, {
|
|
265
|
+
method: "POST",
|
|
266
|
+
accessToken,
|
|
267
|
+
body: form,
|
|
268
|
+
signal,
|
|
269
|
+
timeoutMs: 60_000,
|
|
270
|
+
})
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
async updateSkill(accessToken, skillId, form, signal) {
|
|
274
|
+
return this.request(`${SKILLS}/skills/${encodeURIComponent(skillId)}/versions`, {
|
|
275
|
+
method: "POST",
|
|
276
|
+
accessToken,
|
|
277
|
+
body: form,
|
|
278
|
+
signal,
|
|
279
|
+
timeoutMs: 60_000,
|
|
280
|
+
})
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async receipt(accessToken, receipt, signal) {
|
|
284
|
+
return this.request(`${PLUGIN_PREFIX}/sync-receipts`, {
|
|
285
|
+
method: "POST",
|
|
286
|
+
accessToken,
|
|
287
|
+
body: receipt,
|
|
288
|
+
signal,
|
|
289
|
+
})
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises"
|
|
2
|
+
import { createHash } from "node:crypto"
|
|
3
|
+
import { buildShareablePackage } from "./skill-packages.mjs"
|
|
4
|
+
|
|
5
|
+
export const bundledSkills = [{ skill_id: "builtin-meeting-actions", slug: "meeting-actions", display_name: "会议行动清单", description: "从会议纪要提取负责人、截止日期和待确认事项。", source_kind: "builtin", current_version: 1, publisher: "ArkFlow", category_id: "builtin:productivity", category_name: "效率工具", file_count: 1 }]
|
|
6
|
+
|
|
7
|
+
export async function bundledPackage(id) {
|
|
8
|
+
const skill = bundledSkills.find(item => item.skill_id === id)
|
|
9
|
+
if (!skill) throw new Error("未找到内置技能")
|
|
10
|
+
const bytes = await readFile(new URL(`../bundled/${skill.slug}/SKILL.md`, import.meta.url))
|
|
11
|
+
const pkg = await buildShareablePackage([{ path: "SKILL.md", bytes }])
|
|
12
|
+
return { skill, packageBytes: pkg.bytes, manifest: pkg.manifest, version: { version: skill.current_version, package_hash: "sha256:" + createHash("sha256").update(pkg.bytes).digest("hex"), files: pkg.manifest } }
|
|
13
|
+
}
|
package/src/config.mjs
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
export const PLUGIN_ID = "novaflow"
|
|
2
|
+
export const PLUGIN_VERSION = "2.0.19"
|
|
3
|
+
export const PRODUCTION_ORIGIN = "https://www.ycnovaflow.vip"
|
|
4
|
+
export const PRODUCTION_ORIGIN_ALIASES = Object.freeze([
|
|
5
|
+
PRODUCTION_ORIGIN,
|
|
6
|
+
"https://ycnovaflow.vip",
|
|
7
|
+
])
|
|
8
|
+
export const SERVICE_HOST = "127.0.0.1"
|
|
9
|
+
export const SERVICE_PORT = 3488
|
|
10
|
+
export const HOST_MIN_VERSION = "0.1.2058"
|
|
11
|
+
export const HOST_API_EVIDENCE = Object.freeze({
|
|
12
|
+
version: HOST_MIN_VERSION,
|
|
13
|
+
tag: "v0.1.2058",
|
|
14
|
+
tagObject: "10658173d0f3266f10e78d39b66b522371b767b5",
|
|
15
|
+
commit: "2d11cde056d6307f74b2b4318430d80bb394517d",
|
|
16
|
+
pageService: "magpie.page.service",
|
|
17
|
+
webServiceBridge: "magpie.service",
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
export function servicePort(value = SERVICE_PORT) {
|
|
21
|
+
if (!Number.isSafeInteger(value) || value < 1024 || value > 65535) throw new Error("Magpie 服务端口无效,请重新打开插件")
|
|
22
|
+
return value
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function createRuntimeConfig() {
|
|
26
|
+
return Object.freeze({
|
|
27
|
+
pluginId: PLUGIN_ID,
|
|
28
|
+
pluginVersion: PLUGIN_VERSION,
|
|
29
|
+
origin: PRODUCTION_ORIGIN,
|
|
30
|
+
hostMinVersion: HOST_MIN_VERSION,
|
|
31
|
+
serviceHost: SERVICE_HOST,
|
|
32
|
+
servicePort: SERVICE_PORT,
|
|
33
|
+
apiPrefix: "/api/novaflow/v1/plugin",
|
|
34
|
+
pollingMs: 60_000,
|
|
35
|
+
pollingJitter: 0.2,
|
|
36
|
+
retryMaxMs: 5 * 60_000,
|
|
37
|
+
requestTimeoutMs: 15_000,
|
|
38
|
+
maxResponseBytes: 8 << 20,
|
|
39
|
+
maxSkillBytes: 16 << 20,
|
|
40
|
+
maxExpandedSkillBytes: 64 << 20,
|
|
41
|
+
maxSkillFiles: 2_000,
|
|
42
|
+
})
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const PRODUCTION_CONFIG = createRuntimeConfig()
|
|
46
|
+
|
|
47
|
+
export function compareVersions(a, b) {
|
|
48
|
+
const parse = (value) => String(value ?? "").split(".").map((part) => Number.parseInt(part, 10) || 0)
|
|
49
|
+
const left = parse(a)
|
|
50
|
+
const right = parse(b)
|
|
51
|
+
const length = Math.max(left.length, right.length)
|
|
52
|
+
for (let i = 0; i < length; i++) {
|
|
53
|
+
const difference = (left[i] ?? 0) - (right[i] ?? 0)
|
|
54
|
+
if (difference !== 0) return difference < 0 ? -1 : 1
|
|
55
|
+
}
|
|
56
|
+
return 0
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function assertSupportedHost(version) {
|
|
60
|
+
if (compareVersions(version, HOST_MIN_VERSION) < 0) {
|
|
61
|
+
throw new Error(`Magpie ${HOST_MIN_VERSION} or newer is required`)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function sameOrigin(value, expected) {
|
|
66
|
+
try {
|
|
67
|
+
return new URL(value).origin === new URL(expected).origin
|
|
68
|
+
} catch {
|
|
69
|
+
return false
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
export class CredentialLoader {
|
|
2
|
+
constructor({ api, session, accounts, config, report = () => {} }) {
|
|
3
|
+
this.api = api
|
|
4
|
+
this.session = session
|
|
5
|
+
this.accounts = accounts
|
|
6
|
+
this.config = config
|
|
7
|
+
this.report = report
|
|
8
|
+
this.pending = null
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
keyIdsFromSnapshot(snapshot) {
|
|
12
|
+
const sources = [
|
|
13
|
+
snapshot?.keys,
|
|
14
|
+
snapshot?.key_catalog?.items,
|
|
15
|
+
snapshot?.credentials?.items,
|
|
16
|
+
snapshot?.bootstrap?.keys,
|
|
17
|
+
]
|
|
18
|
+
for (const source of sources) {
|
|
19
|
+
if (!Array.isArray(source)) continue
|
|
20
|
+
const ids = source
|
|
21
|
+
.map((item) => typeof item === "object" ? item?.key_id : item)
|
|
22
|
+
.filter((item) => item !== undefined && item !== null)
|
|
23
|
+
if (ids.length) return [...new Map(ids.map((id) => [String(id), id])).values()]
|
|
24
|
+
}
|
|
25
|
+
if (Array.isArray(snapshot?.key_ids)) return [...snapshot.key_ids]
|
|
26
|
+
return []
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
hasKeyCatalog(snapshot) {
|
|
30
|
+
return Array.isArray(snapshot?.keys)
|
|
31
|
+
|| Array.isArray(snapshot?.key_catalog?.items)
|
|
32
|
+
|| Array.isArray(snapshot?.credentials?.items)
|
|
33
|
+
|| Array.isArray(snapshot?.bootstrap?.keys)
|
|
34
|
+
|| Array.isArray(snapshot?.key_ids)
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
revisionFromSnapshot(snapshot) {
|
|
38
|
+
return String(
|
|
39
|
+
snapshot?.keys_revision
|
|
40
|
+
?? snapshot?.revisions?.keys
|
|
41
|
+
?? snapshot?.key_catalog?.revision
|
|
42
|
+
?? snapshot?.bootstrap_revision
|
|
43
|
+
?? "",
|
|
44
|
+
)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async load({ snapshot = null, signal } = {}) {
|
|
48
|
+
const owner = this.session.ownership?.()
|
|
49
|
+
if (this.pending && this.pendingOwner === owner) return this.pending
|
|
50
|
+
this.pendingOwner = owner
|
|
51
|
+
const pending = this.loadUnshared({ snapshot, signal }).finally(() => {
|
|
52
|
+
if (this.pending === pending) this.pending = null
|
|
53
|
+
})
|
|
54
|
+
this.pending = pending
|
|
55
|
+
return this.pending
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async loadUnshared({ snapshot, signal }) {
|
|
59
|
+
return this.session.withAccess(async (access) => {
|
|
60
|
+
const owner = this.session.ownership?.()
|
|
61
|
+
const source = snapshot ?? await this.api.sync(access, "", signal)
|
|
62
|
+
if (source?.not_modified === true) throw new Error("Credential snapshot cannot be not-modified on a full read")
|
|
63
|
+
if (!this.hasKeyCatalog(source)) {
|
|
64
|
+
throw Object.assign(new Error("ArkFlow sync omitted the authorized key catalog"), { code: "PLUGIN_CONTRACT_INCOMPLETE" })
|
|
65
|
+
}
|
|
66
|
+
const ids = this.keyIdsFromSnapshot(source)
|
|
67
|
+
const expectedRevision = this.revisionFromSnapshot(source)
|
|
68
|
+
if (!ids.length) {
|
|
69
|
+
this.session.assertOwnership?.(owner)
|
|
70
|
+
const empty = this.accounts.reconcile({ revision: expectedRevision, items: [], rejected: [] })
|
|
71
|
+
this.report("credentials.empty", { keyCount: 0 })
|
|
72
|
+
return { ...empty, snapshotRevision: expectedRevision }
|
|
73
|
+
}
|
|
74
|
+
const items = []
|
|
75
|
+
const rejected = []
|
|
76
|
+
let revision = expectedRevision
|
|
77
|
+
for (let offset = 0; offset < ids.length; offset += 100) {
|
|
78
|
+
const result = await this.api.credentialsBatch(access, ids.slice(offset, offset + 100), expectedRevision, signal)
|
|
79
|
+
if (!Array.isArray(result?.items)) throw new Error("ArkFlow credentials batch has no items array")
|
|
80
|
+
items.push(...result.items)
|
|
81
|
+
rejected.push(...(Array.isArray(result?.rejected) ? result.rejected : []))
|
|
82
|
+
if (result.revision) revision = String(result.revision)
|
|
83
|
+
}
|
|
84
|
+
this.session.assertOwnership?.(owner)
|
|
85
|
+
const projection = this.accounts.reconcile({ revision, items, rejected })
|
|
86
|
+
this.report("credentials.ready", { keyCount: projection.keyCount, rejectedCount: projection.rejectedCount })
|
|
87
|
+
return { ...projection, snapshotRevision: this.revisionFromSnapshot(source) }
|
|
88
|
+
}, { signal })
|
|
89
|
+
}
|
|
90
|
+
}
|