@agentgo-tw/app-sdk 0.0.0-stage → 2.6.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/README.md +552 -2
- package/dist/browser.cjs +335 -0
- package/dist/browser.d.cts +22 -0
- package/dist/browser.d.ts +22 -0
- package/dist/browser.js +66 -0
- package/dist/chunk-4KBWZDXW.js +208 -0
- package/dist/chunk-VCZOS6GJ.js +61 -0
- package/dist/client.cjs +283 -0
- package/dist/client.d.cts +76 -0
- package/dist/client.d.ts +76 -0
- package/dist/client.js +205 -0
- package/dist/index.cjs +634 -0
- package/dist/index.d.cts +145 -0
- package/dist/index.d.ts +145 -0
- package/dist/index.js +364 -0
- package/dist/od-BVdmZf1t.d.cts +2331 -0
- package/dist/od-sGQixHat.d.ts +2331 -0
- package/dist/version-ClrVQNzw.d.cts +214 -0
- package/dist/version-ClrVQNzw.d.ts +214 -0
- package/package.json +67 -4
package/dist/client.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AcademyError,
|
|
3
|
+
SDK_VERSION,
|
|
4
|
+
errorFromResponse
|
|
5
|
+
} from "./chunk-VCZOS6GJ.js";
|
|
6
|
+
|
|
7
|
+
// src/client.ts
|
|
8
|
+
var bytesToB64url = (bytes) => {
|
|
9
|
+
let bin = "";
|
|
10
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
11
|
+
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
12
|
+
};
|
|
13
|
+
var randomB64url = (n) => bytesToB64url(crypto.getRandomValues(new Uint8Array(n)));
|
|
14
|
+
async function s256(input) {
|
|
15
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(input));
|
|
16
|
+
return bytesToB64url(new Uint8Array(digest));
|
|
17
|
+
}
|
|
18
|
+
var AcademyClient = class {
|
|
19
|
+
appOrigin;
|
|
20
|
+
client;
|
|
21
|
+
env;
|
|
22
|
+
redirectUri;
|
|
23
|
+
appSlug;
|
|
24
|
+
baseUrl;
|
|
25
|
+
storage;
|
|
26
|
+
fetchImpl;
|
|
27
|
+
skewMs;
|
|
28
|
+
keyPrefix;
|
|
29
|
+
/** 同時多個請求遇到過期時只更新一次 */
|
|
30
|
+
refreshing = null;
|
|
31
|
+
constructor(opts) {
|
|
32
|
+
const app = new URL(opts.appUrl);
|
|
33
|
+
this.appOrigin = app.origin;
|
|
34
|
+
this.client = opts.client;
|
|
35
|
+
this.redirectUri = opts.redirectUri;
|
|
36
|
+
this.appSlug = opts.appSlug ?? app.hostname.split(".")[0];
|
|
37
|
+
this.baseUrl = (opts.baseUrl ?? "https://agentgo.tw").replace(/\/+$/, "");
|
|
38
|
+
this.env = opts.env ?? (app.hostname.includes(".test.") ? "test" : "production");
|
|
39
|
+
this.storage = opts.storage;
|
|
40
|
+
this.fetchImpl = opts.fetch ?? ((input, init) => fetch(input, init));
|
|
41
|
+
this.skewMs = (opts.refreshSkewSeconds ?? 60) * 1e3;
|
|
42
|
+
this.keyPrefix = `academy:${this.client}:${app.host}`;
|
|
43
|
+
}
|
|
44
|
+
// ------------------------------------------------------------------ 授權
|
|
45
|
+
/**
|
|
46
|
+
* 產生 PKCE 與 `state`,回主站的授權網址。把這個網址交給瀏覽器開啟
|
|
47
|
+
* (擴充功能用 `chrome.identity.launchWebAuthFlow`),完成後把轉回來的網址交給 `handleRedirect()`。
|
|
48
|
+
*/
|
|
49
|
+
async authorizeUrl() {
|
|
50
|
+
const pending = { state: randomB64url(16), verifier: randomB64url(32) };
|
|
51
|
+
await this.storage.set(`${this.keyPrefix}:pending`, JSON.stringify(pending));
|
|
52
|
+
const q = new URLSearchParams({
|
|
53
|
+
app: this.appSlug,
|
|
54
|
+
client: this.client,
|
|
55
|
+
redirect_uri: this.redirectUri,
|
|
56
|
+
code_challenge: await s256(pending.verifier),
|
|
57
|
+
code_challenge_method: "S256",
|
|
58
|
+
state: pending.state
|
|
59
|
+
});
|
|
60
|
+
if (this.env === "test") q.set("env", "test");
|
|
61
|
+
return `${this.baseUrl}/apps/authorize?${q.toString()}`;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* 處理授權後轉回來的網址:核對 `state`、以授權碼換取憑證並存入 storage。
|
|
65
|
+
* 會員按了取消丟 `ACCESS_DENIED`;`state` 不符或授權碼失效丟 `TOKEN_INVALID`。
|
|
66
|
+
*/
|
|
67
|
+
async handleRedirect(url) {
|
|
68
|
+
const u = new URL(url);
|
|
69
|
+
const params = u.searchParams;
|
|
70
|
+
const raw = await this.storage.get(`${this.keyPrefix}:pending`);
|
|
71
|
+
await this.storage.remove(`${this.keyPrefix}:pending`);
|
|
72
|
+
let pending = null;
|
|
73
|
+
try {
|
|
74
|
+
pending = raw ? JSON.parse(raw) : null;
|
|
75
|
+
} catch {
|
|
76
|
+
pending = null;
|
|
77
|
+
}
|
|
78
|
+
if (!pending || params.get("state") !== pending.state) throw new AcademyError("TOKEN_INVALID", "\u6388\u6B0A\u6D41\u7A0B\u5DF2\u5931\u6548\uFF0C\u8ACB\u91CD\u65B0\u6388\u6B0A\uFF08state \u4E0D\u7B26\uFF09", 0);
|
|
79
|
+
if (params.get("error")) {
|
|
80
|
+
const error = params.get("error");
|
|
81
|
+
throw new AcademyError(error === "access_denied" ? "ACCESS_DENIED" : "TOKEN_INVALID", error === "access_denied" ? "\u5DF2\u53D6\u6D88\u6388\u6B0A" : `\u6388\u6B0A\u5931\u6557\uFF1A${error}`, 0, { error });
|
|
82
|
+
}
|
|
83
|
+
const code = params.get("code");
|
|
84
|
+
if (!code) throw new AcademyError("TOKEN_INVALID", "\u8F49\u56DE\u4F86\u7684\u7DB2\u5740\u6C92\u6709\u6388\u6B0A\u78BC", 0);
|
|
85
|
+
await this.store(
|
|
86
|
+
await this.tokenRequest({ grant_type: "authorization_code", code, code_verifier: pending.verifier, client: this.client, redirect_uri: this.redirectUri })
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
// ------------------------------------------------------------------ 使用
|
|
90
|
+
/** 是否已有憑證(不保證仍有效;實際結果以呼叫 App 為準) */
|
|
91
|
+
async isSignedIn() {
|
|
92
|
+
return await this.load() !== null;
|
|
93
|
+
}
|
|
94
|
+
/** 目前可用的存取憑證;快過期時先更新。沒有憑證或更新失敗回 null */
|
|
95
|
+
async getAccessToken() {
|
|
96
|
+
const t = await this.load();
|
|
97
|
+
if (!t) return null;
|
|
98
|
+
if (t.expiresAt - Date.now() > this.skewMs) return t.accessToken;
|
|
99
|
+
return (await this.refresh())?.accessToken ?? null;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* 呼叫 App:自動帶存取憑證;快過期時先更新,同時多個請求只更新一次。
|
|
103
|
+
* 只能打 App 自己的網域(避免憑證被送到別處)。沒有憑證、或憑證已被撤銷時丟 `TOKEN_INVALID`,由用戶端重新引導授權;
|
|
104
|
+
* 403 `SUBSCRIPTION_REQUIRED`、`APP_UNAVAILABLE` 等其他回應原樣交回。
|
|
105
|
+
*/
|
|
106
|
+
async fetch(input, init = {}) {
|
|
107
|
+
const url = new URL(String(input), this.appOrigin);
|
|
108
|
+
if (url.origin !== this.appOrigin) throw new AcademyError("INVALID_REQUEST", `\u53EA\u80FD\u547C\u53EB App \u81EA\u5DF1\u7684\u7DB2\u5740\uFF08${this.appOrigin}\uFF09`, 0);
|
|
109
|
+
let token = await this.getAccessToken();
|
|
110
|
+
if (!token) throw new AcademyError("TOKEN_INVALID", "\u5C1A\u672A\u6388\u6B0A\u6216\u6388\u6B0A\u5DF2\u5931\u6548\uFF0C\u8ACB\u91CD\u65B0\u6388\u6B0A", 401, { authorize_required: true });
|
|
111
|
+
let res = await this.send(url, init, token);
|
|
112
|
+
if (res.status === 401 && await this.isTokenInvalid(res)) {
|
|
113
|
+
token = (await this.refresh())?.accessToken ?? null;
|
|
114
|
+
if (!token) throw new AcademyError("TOKEN_INVALID", "\u6388\u6B0A\u5DF2\u5931\u6548\uFF0C\u8ACB\u91CD\u65B0\u6388\u6B0A", 401, { authorize_required: true });
|
|
115
|
+
res = await this.send(url, init, token);
|
|
116
|
+
if (res.status === 401 && await this.isTokenInvalid(res)) {
|
|
117
|
+
await this.clear();
|
|
118
|
+
throw new AcademyError("TOKEN_INVALID", "\u6388\u6B0A\u5DF2\u5931\u6548\uFF0C\u8ACB\u91CD\u65B0\u6388\u6B0A", 401, { authorize_required: true });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return res;
|
|
122
|
+
}
|
|
123
|
+
/** 登出:向平台撤銷委任並清除本機的憑證 */
|
|
124
|
+
async signOut() {
|
|
125
|
+
const t = await this.load();
|
|
126
|
+
await this.clear();
|
|
127
|
+
if (!t) return;
|
|
128
|
+
await this.fetchImpl(`${this.appOrigin}/__academy/revoke`, {
|
|
129
|
+
method: "POST",
|
|
130
|
+
headers: { "content-type": "application/json", accept: "application/json", "x-academy-sdk": SDK_VERSION },
|
|
131
|
+
body: JSON.stringify({ refresh_token: t.refreshToken })
|
|
132
|
+
}).catch(() => void 0);
|
|
133
|
+
}
|
|
134
|
+
// ------------------------------------------------------------------ 內部
|
|
135
|
+
send(url, init, token) {
|
|
136
|
+
const headers = new Headers(init.headers);
|
|
137
|
+
headers.set("authorization", `Bearer ${token}`);
|
|
138
|
+
if (!headers.has("accept")) headers.set("accept", "application/json");
|
|
139
|
+
return this.fetchImpl(url.toString(), { ...init, headers });
|
|
140
|
+
}
|
|
141
|
+
async isTokenInvalid(res) {
|
|
142
|
+
try {
|
|
143
|
+
const body = await res.clone().json();
|
|
144
|
+
return body?.code === "TOKEN_INVALID";
|
|
145
|
+
} catch {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
refresh() {
|
|
150
|
+
if (!this.refreshing) {
|
|
151
|
+
this.refreshing = (async () => {
|
|
152
|
+
const t = await this.load();
|
|
153
|
+
if (!t) return null;
|
|
154
|
+
try {
|
|
155
|
+
return await this.store(await this.tokenRequest({ grant_type: "refresh_token", refresh_token: t.refreshToken, client: this.client }));
|
|
156
|
+
} catch (e) {
|
|
157
|
+
if (e instanceof AcademyError && e.code === "TOKEN_INVALID") {
|
|
158
|
+
await this.clear();
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
throw e;
|
|
162
|
+
}
|
|
163
|
+
})().finally(() => {
|
|
164
|
+
this.refreshing = null;
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
return this.refreshing;
|
|
168
|
+
}
|
|
169
|
+
async tokenRequest(body) {
|
|
170
|
+
const res = await this.fetchImpl(`${this.appOrigin}/__academy/token`, {
|
|
171
|
+
method: "POST",
|
|
172
|
+
headers: { "content-type": "application/json", accept: "application/json", "x-academy-sdk": SDK_VERSION },
|
|
173
|
+
body: JSON.stringify(body)
|
|
174
|
+
});
|
|
175
|
+
if (!res.ok) throw await errorFromResponse(res);
|
|
176
|
+
return await res.json();
|
|
177
|
+
}
|
|
178
|
+
async store(r) {
|
|
179
|
+
const t = { accessToken: r.access_token, refreshToken: r.refresh_token, expiresAt: Date.now() + r.expires_in * 1e3 };
|
|
180
|
+
await this.storage.set(`${this.keyPrefix}:tokens`, JSON.stringify(t));
|
|
181
|
+
return t;
|
|
182
|
+
}
|
|
183
|
+
async load() {
|
|
184
|
+
const raw = await this.storage.get(`${this.keyPrefix}:tokens`);
|
|
185
|
+
if (!raw) return null;
|
|
186
|
+
try {
|
|
187
|
+
const t = JSON.parse(raw);
|
|
188
|
+
return typeof t.accessToken === "string" && typeof t.refreshToken === "string" && typeof t.expiresAt === "number" ? t : null;
|
|
189
|
+
} catch {
|
|
190
|
+
return null;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async clear() {
|
|
194
|
+
await this.storage.remove(`${this.keyPrefix}:tokens`);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
function createAcademyClient(opts) {
|
|
198
|
+
return new AcademyClient(opts);
|
|
199
|
+
}
|
|
200
|
+
export {
|
|
201
|
+
AcademyClient,
|
|
202
|
+
AcademyError,
|
|
203
|
+
SDK_VERSION,
|
|
204
|
+
createAcademyClient
|
|
205
|
+
};
|