@fish-under-sea/magpie-dragonapi 0.1.2 → 0.1.3

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  把 [DragonAPI](https://newapi.dragon3api.com/) 接进 magpie:模型广场、余额、用量,外加一个能按分组建钥匙的本地界面。
4
4
 
5
- > 当前版本 **0.1.2**。只做供应商插件 + 只读看板 + 密钥管理,不做「页面里点充值」。
5
+ > 当前版本 **0.1.3**。只做供应商插件 + 只读看板 + 密钥管理,不做「页面里点充值」。
6
6
 
7
7
  ## 它是什么
8
8
 
@@ -25,7 +25,7 @@
25
25
  | **命令行** | `magpie plugin add @fish-under-sea/magpie-dragonapi` |
26
26
 
27
27
  npm 拉不到时(内网、镜像抽风):到 [Releases](https://github.com/Fish-under-sea/magpie-dragonapi/releases) 下
28
- `fish-under-sea-magpie-dragonapi-0.1.2.tgz`,解包成目录,再 `magpie plugin add <那个目录>` ——
28
+ `fish-under-sea-magpie-dragonapi-0.1.3.tgz`,解包成目录,再 `magpie plugin add <那个目录>` ——
29
29
  `plugin add` 认 `path`,和从文件夹加插件是同一条路。
30
30
 
31
31
  装好后:Settings → Plugins 里出现 **DragonAPI** 行(带一张页面),供应商列表里出现 **DragonAPI**。
package/lib/service.mjs CHANGED
@@ -30,6 +30,11 @@ import { loadState, saveState, maskKey, tailOf } from './store.mjs'
30
30
 
31
31
  const here = resolve(fileURLToPath(new URL('..', import.meta.url)))
32
32
 
33
+ /** 插件版本,从 package.json 读一次。 */
34
+ const PKG_VERSION = (() => {
35
+ try { return JSON.parse(readFileSync(join(here, 'package.json'), 'utf8')).version || '0.0.0' } catch { return '0.0.0' }
36
+ })()
37
+
33
38
  /** MIME 表只覆盖本插件真正会发的类型。 */
34
39
  const MIME = {
35
40
  '.html': 'text/html; charset=utf-8',
@@ -42,15 +47,30 @@ const MIME = {
42
47
  '.woff2': 'font/woff2',
43
48
  }
44
49
 
45
- /** 一次响应:JSON + CORS + 不缓存(页面是活的,缓存只会让人看到旧数据)。 */
50
+ /**
51
+ * 一次响应:JSON + CORS + 不缓存(页面是活的,缓存只会让人看到旧数据)。
52
+ *
53
+ * 三个 CORS 头都是必需的,少一个页面就「连不上本地服务」:
54
+ *
55
+ * Access-Control-Allow-Origin: * 页面是不透明源(Origin: null)
56
+ * Access-Control-Allow-Private-Network: true 页面在不透明源里请求 127.0.0.1,
57
+ * Chrome 会按 Private Network Access 先发预检;不放行就整个请求被拦,
58
+ * 而且报错长得像「网络不可达」,极难查。
59
+ * Access-Control-Allow-Headers / Methods 预检要过的头与方法
60
+ */
61
+ const CORS = {
62
+ 'access-control-allow-origin': '*',
63
+ 'access-control-allow-private-network': 'true',
64
+ 'access-control-allow-headers': 'content-type',
65
+ 'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
66
+ }
67
+
46
68
  function json(res, code, body) {
47
69
  const data = JSON.stringify(body)
48
70
  res.writeHead(code, {
49
71
  'content-type': 'application/json; charset=utf-8',
50
72
  'content-length': Buffer.byteLength(data),
51
- 'access-control-allow-origin': '*',
52
- 'access-control-allow-headers': 'content-type',
53
- 'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
73
+ ...CORS,
54
74
  'cache-control': 'no-store',
55
75
  })
56
76
  res.end(data)
@@ -101,7 +121,7 @@ function serveFile(res, root, rel) {
101
121
  res.writeHead(200, {
102
122
  'content-type': MIME[extname(file).toLowerCase()] || 'application/octet-stream',
103
123
  'content-length': body.length,
104
- 'access-control-allow-origin': '*',
124
+ ...CORS,
105
125
  'cache-control': 'no-cache',
106
126
  'x-content-type-options': 'nosniff',
107
127
  'referrer-policy': 'no-referrer',
@@ -151,14 +171,21 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
151
171
  async function handler(req, res) {
152
172
  const url = new URL(req.url || '/', 'http://127.0.0.1')
153
173
  const path = url.pathname
174
+ // 排查用:设 DRAGONAPI_DEBUG=1 时把每条请求打到 stderr。
175
+ // 插件页「连不上」时分不清「请求没到」还是「到了但响应不对」,这一行能分开。
176
+ if (process.env.DRAGONAPI_DEBUG) {
177
+ console.error(`[dragonapi] ${req.method} ${path} origin=${req.headers.origin || '-'} pna=${req.headers['access-control-request-private-network'] || '-'}`)
178
+ }
154
179
 
155
- // 预检:浏览器的 fetch 带自定义头时会先问一次。
180
+ // 预检:浏览器的 fetch 带自定义头、或不透明源访问 loopback 时会先问一次。
156
181
  if (req.method === 'OPTIONS') {
157
182
  res.writeHead(204, {
158
- 'access-control-allow-origin': '*',
159
- 'access-control-allow-headers': 'content-type',
160
- 'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
183
+ ...CORS,
184
+ // 允许预检结果缓存,省掉每个请求一次往返。
161
185
  'access-control-max-age': '600',
186
+ // PNA 的预检请求会带 Access-Control-Request-Private-Network,
187
+ // 响应必须有 allow-private-network(CORS 里已含),否则整个请求被拦。
188
+ 'cache-control': 'no-store',
162
189
  })
163
190
  res.end()
164
191
  return
@@ -189,7 +216,9 @@ export async function startService({ port = 3517, dir = '.', site, catalog, stat
189
216
  // ---- API ----
190
217
  try {
191
218
  if (path === '/api/ping' && req.method === 'GET') {
192
- json(res, 200, { ok: true, version: '0.1.0', port })
219
+ // 版本从 package.json 读,别硬编码:硬编码的版本号会在升级后说谎,
220
+ // 排查时容易把「旧代码还在跑」误判成「新版没修」。
221
+ json(res, 200, { ok: true, version: PKG_VERSION, port })
193
222
  return
194
223
  }
195
224
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fish-under-sea/magpie-dragonapi",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "DragonAPI for magpie: a provider plugin whose models, groups and prices come from the site's public /api/pricing, with balance and per-call usage from an sk- key, plus a local page that lists the market (read-only), shows usage and can mint new keys for a group.",
5
5
  "type": "module",
6
6
  "main": "index.mjs",
package/page/boot.js CHANGED
@@ -68,8 +68,12 @@
68
68
  }
69
69
 
70
70
  if (service) {
71
+ // 必须以 `/` 结尾再拼 query。magpie web 给的地址形如
72
+ // `http://host/_magpie/service/<token>`,少了结尾斜杠时,界面里的
73
+ // 相对/目录解析会把 token 当成文件名丢掉,接口就全打到别处。
74
+ const base = service.endsWith('/') ? service : service + '/'
71
75
  armTimeout(port)
72
- location.replace(service + '?' + q.toString())
76
+ location.replace(base + '?' + q.toString())
73
77
  return
74
78
  }
75
79
 
package/ui/app.js CHANGED
@@ -156,6 +156,38 @@ function initTheme() {
156
156
 
157
157
  // ── 请求层 ────────────────────────────────────────────────
158
158
 
159
+ /**
160
+ * API 基址:必须是绝对地址。
161
+ *
162
+ * 页面跑在 magpie 的 `sandbox="allow-scripts"` iframe 里,安全源是**不透明**
163
+ * 的(`self.origin === "null"`,localStorage / cookie 都会抛 SecurityError)。
164
+ * 在这种文档里,`fetch('/api/ping')` 这种相对路径会被 Chrome 直接判
165
+ * `TypeError: Failed to fetch`——绝对地址却正常。实测对比:
166
+ *
167
+ * 相对 path → TypeError: Failed to fetch
168
+ * 绝对 URL → 200
169
+ *
170
+ * 所以这里把「当前文档所在目录」算成基址:
171
+ * - 直接访问服务(http://127.0.0.1:3517/) → http://127.0.0.1:3517/
172
+ * - 经 magpie web 代理(…/_magpie/service/<tok>/)→ 保留那段前缀
173
+ * 不能直接用 location.origin:不透明文档里它可能报出真实源,也可能报 "null",
174
+ * 两种情况都要能工作,所以从 href 里解析并保留 pathname 的目录部分。
175
+ */
176
+ const API_BASE = (() => {
177
+ try {
178
+ const u = new URL(location.href);
179
+ const dir = u.pathname.replace(/[^/]*$/, ''); // 去掉文件名,保留目录
180
+ return u.origin + dir;
181
+ } catch {
182
+ return '/';
183
+ }
184
+ })();
185
+
186
+ /** apiUrl 把接口路径拼成绝对地址。传进来的 path 以 / 开头。 */
187
+ function apiUrl(path) {
188
+ return API_BASE.replace(/\/+$/, '') + path;
189
+ }
190
+
159
191
  class ApiError extends Error {
160
192
  constructor(message, status, payload) {
161
193
  super(message);
@@ -168,7 +200,7 @@ class ApiError extends Error {
168
200
  async function request(path, { method = 'GET', body } = {}) {
169
201
  let res;
170
202
  try {
171
- res = await fetch(path, {
203
+ res = await fetch(apiUrl(path), {
172
204
  method,
173
205
  credentials: 'omit', // opaque origin:带凭据必被拒
174
206
  cache: 'no-store', // 服务端已经自己缓存目录,浏览器别再叠一层