engine7 7.1.133 โ 7.1.136
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 +1 -0
- package/dist/auth-server.mjs +632 -0
- package/dist/bg-worker.mjs +31660 -28486
- package/dist/cc-desktop.mjs +951 -0
- package/dist/cli.mjs +41446 -30183
- package/dist/engine-startup.mjs +59137 -46007
- package/dist/main.mjs +50062 -36930
- package/dist/recall-worker.mjs +20443 -0
- package/dist/sqlite-maintenance-worker.mjs +1163 -124
- package/dist/stop-history-worker.mjs +180 -0
- package/dist/topics-worker.mjs +3350 -1078
- package/dist/travel-authority.mjs +1068 -0
- package/dist/travel-console.mjs +2205 -0
- package/dist/travel-controller.mjs +1883 -0
- package/dist/travel-data.mjs +7250 -0
- package/dist/travel-gateway.mjs +3258 -0
- package/dist/travel-key-service.mjs +483 -0
- package/dist/travel-node-data.mjs +4930 -0
- package/dist/travel-node.mjs +21233 -0
- package/dist/travel-retire.mjs +1094 -0
- package/dist/web-console.mjs +2425 -0
- package/package.json +32 -17
- package/templates/config.template.json +45 -0
- package/templates/skills/auth-connect/SKILL.md +22 -0
- package/templates/skills/email/SKILL.md +119 -115
- package/templates/skills/email/scripts/email-config-path.test.js +52 -0
- package/templates/skills/email/scripts/email-config.d.ts +4 -0
- package/templates/skills/email/scripts/email-config.js +6 -3
- package/templates/skills/pptx/SKILL.md +5 -0
- package/templates/skills/pptx/assets/engine7-aurora/field.png +0 -0
- package/templates/skills/pptx/assets/engine7-aurora/hero.png +0 -0
- package/templates/skills/pptx/assets/engine7-aurora/wordmark.png +0 -0
- package/templates/skills/pptx/examples/engine7-aurora.cjs +190 -0
- package/templates/skills/pptx/package-lock.json +171 -0
- package/templates/skills/pptx/package.json +12 -0
- package/templates/skills/pptx/scripts/engine7-aurora.cjs +132 -0
- package/templates/skills/pptx/styles/engine7-aurora.md +136 -0
- package/templates/skills/pptx/tests/engine7-aurora.test.cjs +116 -0
- package/templates/workspace/AGENTS.md +2 -9
- package/templates/workspace/RULES.md +22 -0
- package/templates/workspace/hooks/loop-detector.mjs +37 -0
- package/templates/workspace/souls/unnamed.md +10 -0
package/README.md
CHANGED
|
@@ -9,6 +9,7 @@ Self-hosted AI agent engine with multi-platform support (Discord/Feishu/WeChat),
|
|
|
9
9
|
- ๐
Calendar with task management and reminders
|
|
10
10
|
- ๐ Optional private extensions (voice/TTS and CogniFold are maintained outside this repository)
|
|
11
11
|
- ๐ Cron jobs and background tasks
|
|
12
|
+
- ๐ง [Gmail OAuth and mail management](docs/features.md#gmail-้ฎไปถ็ฎก็): drafts, sending, labels, trash and bounded background sync, with per-action permission controls
|
|
12
13
|
- ๐ Cross-platform (Windows/Linux/macOS)
|
|
13
14
|
|
|
14
15
|
## Requirements
|
|
@@ -0,0 +1,632 @@
|
|
|
1
|
+
const require=(await import('node:module')).createRequire(import.meta.url)
|
|
2
|
+
|
|
3
|
+
// src/auth/server.ts
|
|
4
|
+
import http from "node:http";
|
|
5
|
+
import path2 from "node:path";
|
|
6
|
+
|
|
7
|
+
// src/auth/protocol.ts
|
|
8
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
9
|
+
var AuthError = class extends Error {
|
|
10
|
+
constructor(code) {
|
|
11
|
+
super(code);
|
|
12
|
+
this.code = code;
|
|
13
|
+
this.name = "AuthError";
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var randomSecret = () => randomBytes(32).toString("base64url");
|
|
17
|
+
var proofChallenge = (value) => createHash("sha256").update(value).digest("base64url");
|
|
18
|
+
function equalSecret(a, b) {
|
|
19
|
+
const x = Buffer.from(a), y = Buffer.from(b);
|
|
20
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
21
|
+
}
|
|
22
|
+
function brokerBase(value) {
|
|
23
|
+
const url = new URL(value);
|
|
24
|
+
if (url.username || url.password || url.search || url.hash || url.protocol !== "https:" && !(url.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))) throw new AuthError("invalid_broker_url");
|
|
25
|
+
if (!url.pathname.endsWith("/")) url.pathname += "/";
|
|
26
|
+
return url;
|
|
27
|
+
}
|
|
28
|
+
function opaque(value) {
|
|
29
|
+
if (typeof value !== "string" || !/^[\w-]{43}$/.test(value)) throw new AuthError("invalid_request");
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
var safeError = (error) => error instanceof AuthError ? error.code : "upstream_unavailable";
|
|
33
|
+
|
|
34
|
+
// src/auth/broker.ts
|
|
35
|
+
var AuthBroker = class {
|
|
36
|
+
constructor(options) {
|
|
37
|
+
this.options = options;
|
|
38
|
+
this.base = brokerBase(options.publicUrl);
|
|
39
|
+
this.now = options.now ?? Date.now;
|
|
40
|
+
this.providers = /* @__PURE__ */ new Map();
|
|
41
|
+
for (const p of options.providers) {
|
|
42
|
+
if (!/^[a-z][a-z0-9-]{0,40}$/.test(p.id) || this.providers.has(p.id)) throw new AuthError("invalid_provider");
|
|
43
|
+
this.providers.set(p.id, p);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
providers;
|
|
47
|
+
base;
|
|
48
|
+
now;
|
|
49
|
+
refreshing = /* @__PURE__ */ new Map();
|
|
50
|
+
catalog() {
|
|
51
|
+
this.options.store.prune(this.now());
|
|
52
|
+
return [...this.providers.values()].map((p) => ({ id: p.id, name: p.name, scopes: p.scopes, available: p.ready }));
|
|
53
|
+
}
|
|
54
|
+
authorizationOrigins() {
|
|
55
|
+
return [...new Set([...this.providers.values()].flatMap((p) => p.authorizationOrigin ? [new URL(p.authorizationOrigin).origin] : []))];
|
|
56
|
+
}
|
|
57
|
+
provider(id) {
|
|
58
|
+
const p = this.providers.get(id);
|
|
59
|
+
if (!p?.ready) throw new AuthError("provider_unavailable");
|
|
60
|
+
return p;
|
|
61
|
+
}
|
|
62
|
+
flow(id) {
|
|
63
|
+
const flow = this.options.store.flow(opaque(id));
|
|
64
|
+
if (!flow) throw new AuthError("expired");
|
|
65
|
+
if (flow.expiresAt <= this.now()) throw new AuthError("expired");
|
|
66
|
+
return flow;
|
|
67
|
+
}
|
|
68
|
+
begin(provider, label, challenge) {
|
|
69
|
+
this.provider(provider);
|
|
70
|
+
opaque(challenge);
|
|
71
|
+
if (typeof label !== "string" || !label.trim() || label.length > 64) throw new AuthError("invalid_request");
|
|
72
|
+
this.options.store.prune(this.now());
|
|
73
|
+
if (this.options.store.countFlows(this.now()) >= 1e3) throw new AuthError("capacity");
|
|
74
|
+
const flow = { id: randomSecret(), provider, label, challenge, csrfToken: randomSecret(), expiresAt: this.now() + 6e5, status: "pending" };
|
|
75
|
+
this.options.store.createFlow(flow);
|
|
76
|
+
return { id: flow.id, authUrl: new URL("flow/" + flow.id, this.base).toString(), expiresAt: flow.expiresAt };
|
|
77
|
+
}
|
|
78
|
+
open(id) {
|
|
79
|
+
const f = this.flow(id), p = this.provider(f.provider);
|
|
80
|
+
return { id: f.id, label: f.label, name: p.name, scopes: p.scopes, permissions: p.permissionLabel, status: f.status, csrfToken: f.csrfToken };
|
|
81
|
+
}
|
|
82
|
+
authorize(id, csrf) {
|
|
83
|
+
const f = this.flow(id);
|
|
84
|
+
if (!equalSecret(csrf, f.csrfToken)) throw new AuthError("invalid_csrf");
|
|
85
|
+
const target = (state2, verifier2) => this.provider(f.provider).authorizationUrl({ state: state2, challenge: proofChallenge(verifier2), redirectUri: new URL("callback/" + f.provider, this.base).toString() });
|
|
86
|
+
if (f.status === "authorizing") {
|
|
87
|
+
if (!f.state || !f.verifier) throw new AuthError("invalid_state");
|
|
88
|
+
return target(f.state, f.verifier);
|
|
89
|
+
}
|
|
90
|
+
if (f.status !== "pending") throw new AuthError("invalid_state");
|
|
91
|
+
const state = randomSecret(), verifier = randomSecret();
|
|
92
|
+
const url = target(state, verifier);
|
|
93
|
+
if (!this.options.store.transition(id, "pending", "authorizing", { state, verifier })) throw new AuthError("invalid_state");
|
|
94
|
+
return url;
|
|
95
|
+
}
|
|
96
|
+
validate(tokens, p) {
|
|
97
|
+
if (!tokens.accessToken || !Number.isFinite(tokens.expiresAt) || tokens.expiresAt <= this.now()) throw new AuthError("invalid_token");
|
|
98
|
+
if (!p.scopes.every((scope) => tokens.scopes.includes(scope))) throw new AuthError("scope_not_granted");
|
|
99
|
+
}
|
|
100
|
+
async callback(provider, state, code, error) {
|
|
101
|
+
const f = this.options.store.byState(state);
|
|
102
|
+
if (!f || f.provider !== provider || f.status !== "authorizing") throw new AuthError("invalid_state");
|
|
103
|
+
this.flow(f.id);
|
|
104
|
+
if (error) {
|
|
105
|
+
this.options.store.transition(f.id, "authorizing", error === "access_denied" ? "denied" : "failed", { error: error === "access_denied" ? "access_denied" : "authorization_failed", verifier: void 0 });
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (!code || code.length > 4096 || !f.verifier) throw new AuthError("invalid_request");
|
|
109
|
+
if (!this.options.store.transition(f.id, "authorizing", "exchanging")) throw new AuthError("invalid_state");
|
|
110
|
+
const p = this.provider(provider);
|
|
111
|
+
let tokens;
|
|
112
|
+
try {
|
|
113
|
+
tokens = await p.exchange({ code, verifier: f.verifier, redirectUri: new URL("callback/" + provider, this.base).toString() });
|
|
114
|
+
this.validate(tokens, p);
|
|
115
|
+
if (!tokens.refreshToken) throw new AuthError("refresh_token_missing");
|
|
116
|
+
const account = await p.identify(tokens.accessToken);
|
|
117
|
+
if (!account.id || !account.label || account.label.length > 256) throw new AuthError("invalid_identity");
|
|
118
|
+
const connection = { id: randomSecret(), provider, account: account.label, scopes: tokens.scopes, connectedAt: this.now(), status: "connected", challenge: f.challenge, tokens, revision: 0 };
|
|
119
|
+
if (!this.options.store.finish(f.id, connection, this.now())) throw new AuthError("expired");
|
|
120
|
+
} catch (err) {
|
|
121
|
+
this.options.store.transition(f.id, "exchanging", "failed", { error: safeError(err), verifier: void 0 });
|
|
122
|
+
if (tokens) try {
|
|
123
|
+
await p.revoke(tokens.refreshToken ?? tokens.accessToken);
|
|
124
|
+
} catch {
|
|
125
|
+
}
|
|
126
|
+
throw err instanceof AuthError ? err : new AuthError("upstream_unavailable");
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
summary(c) {
|
|
130
|
+
return { id: c.id, provider: c.provider, account: c.account, scopes: c.scopes, connectedAt: c.connectedAt, status: c.status };
|
|
131
|
+
}
|
|
132
|
+
poll(id, verifier) {
|
|
133
|
+
const f = this.flow(id);
|
|
134
|
+
if (!equalSecret(proofChallenge(verifier), f.challenge)) throw new AuthError("invalid_proof");
|
|
135
|
+
if ((f.status === "connected" || f.status === "claimed") && f.connectionId) {
|
|
136
|
+
const c = this.connection(f.connectionId, verifier);
|
|
137
|
+
this.options.store.transition(id, "connected", "claimed");
|
|
138
|
+
return { status: "connected", connection: this.summary(c) };
|
|
139
|
+
}
|
|
140
|
+
if (f.status === "failed" || f.status === "denied") return { status: f.status, error: f.error };
|
|
141
|
+
return { status: "pending" };
|
|
142
|
+
}
|
|
143
|
+
connection(id, verifier, requireActive = true) {
|
|
144
|
+
const c = this.options.store.connection(opaque(id));
|
|
145
|
+
if (!c || !equalSecret(proofChallenge(verifier), c.challenge)) throw new AuthError("invalid_proof");
|
|
146
|
+
if (requireActive && (c.status !== "connected" || !c.tokens)) throw new AuthError(c.status === "expired" ? "authorization_expired" : "disconnected");
|
|
147
|
+
return c;
|
|
148
|
+
}
|
|
149
|
+
status(id, verifier) {
|
|
150
|
+
return this.summary(this.connection(id, verifier, false));
|
|
151
|
+
}
|
|
152
|
+
async cancel(id, verifier) {
|
|
153
|
+
const flow = this.flow(id);
|
|
154
|
+
if (!equalSecret(proofChallenge(verifier), flow.challenge)) throw new AuthError("invalid_proof");
|
|
155
|
+
this.options.store.transition(id, flow.status, "denied", { error: "authorization_cancelled", verifier: void 0 });
|
|
156
|
+
if (flow.connectionId) return this.disconnect(flow.connectionId, verifier);
|
|
157
|
+
return { status: "disconnected", revocationConfirmed: flow.status !== "exchanging" };
|
|
158
|
+
}
|
|
159
|
+
async accessToken(id, verifier) {
|
|
160
|
+
const c = this.connection(id, verifier), p = this.provider(c.provider);
|
|
161
|
+
if (c.tokens.expiresAt > this.now() + 6e4) return c.tokens.accessToken;
|
|
162
|
+
const pending = this.refreshing.get(id);
|
|
163
|
+
if (pending) return pending;
|
|
164
|
+
const work = (async () => {
|
|
165
|
+
try {
|
|
166
|
+
const refreshed = await p.refresh(c.tokens.refreshToken, c.scopes);
|
|
167
|
+
this.validate(refreshed, { ...p, scopes: c.scopes });
|
|
168
|
+
const tokens = { ...refreshed, refreshToken: refreshed.refreshToken ?? c.tokens.refreshToken };
|
|
169
|
+
if (!this.options.store.updateConnection(id, c.revision, { tokens, scopes: tokens.scopes })) throw new AuthError("disconnected");
|
|
170
|
+
return tokens.accessToken;
|
|
171
|
+
} catch (err) {
|
|
172
|
+
if (err instanceof AuthError && err.code === "authorization_expired") this.options.store.updateConnection(id, c.revision, { status: "expired", tokens: void 0 });
|
|
173
|
+
throw err instanceof AuthError ? err : new AuthError("upstream_unavailable");
|
|
174
|
+
} finally {
|
|
175
|
+
this.refreshing.delete(id);
|
|
176
|
+
}
|
|
177
|
+
})();
|
|
178
|
+
this.refreshing.set(id, work);
|
|
179
|
+
return work;
|
|
180
|
+
}
|
|
181
|
+
async disconnect(id, verifier) {
|
|
182
|
+
let c = this.connection(id, verifier, false);
|
|
183
|
+
if (c.status === "connected" && c.tokens) {
|
|
184
|
+
const revocationToken = c.tokens.refreshToken ?? c.tokens.accessToken;
|
|
185
|
+
if (!this.options.store.updateConnection(id, c.revision, { status: "disconnected", tokens: void 0, revocationToken, revocationConfirmed: false })) throw new AuthError("disconnected");
|
|
186
|
+
c = this.connection(id, verifier, false);
|
|
187
|
+
}
|
|
188
|
+
if (c.revocationConfirmed) return { status: "disconnected", revocationConfirmed: true };
|
|
189
|
+
if (!c.revocationToken) return { status: "disconnected", revocationConfirmed: false };
|
|
190
|
+
try {
|
|
191
|
+
await this.provider(c.provider).revoke(c.revocationToken);
|
|
192
|
+
this.options.store.finishRevocation(id, c.revision);
|
|
193
|
+
return { status: "disconnected", revocationConfirmed: true };
|
|
194
|
+
} catch {
|
|
195
|
+
return { status: "disconnected", revocationConfirmed: false };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
// src/auth/store.ts
|
|
201
|
+
import fs from "node:fs";
|
|
202
|
+
import path from "node:path";
|
|
203
|
+
import { DatabaseSync } from "node:sqlite";
|
|
204
|
+
import { createCipheriv, createDecipheriv, randomBytes as randomBytes2 } from "node:crypto";
|
|
205
|
+
var AuthStore = class {
|
|
206
|
+
constructor(file, key) {
|
|
207
|
+
this.key = key;
|
|
208
|
+
if (key.length !== 32) throw new AuthError("invalid_vault_key");
|
|
209
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 448 });
|
|
210
|
+
this.db = new DatabaseSync(file);
|
|
211
|
+
fs.chmodSync(file, 384);
|
|
212
|
+
this.db.exec(`PRAGMA busy_timeout=5000;
|
|
213
|
+
CREATE TABLE IF NOT EXISTS auth_flows(id TEXT PRIMARY KEY,status TEXT NOT NULL,state TEXT UNIQUE,expires INTEGER NOT NULL,data TEXT NOT NULL);
|
|
214
|
+
CREATE INDEX IF NOT EXISTS auth_flows_expiry ON auth_flows(expires);
|
|
215
|
+
CREATE TABLE IF NOT EXISTS auth_connections(id TEXT PRIMARY KEY,status TEXT NOT NULL,revision INTEGER NOT NULL,data TEXT NOT NULL);`);
|
|
216
|
+
}
|
|
217
|
+
db;
|
|
218
|
+
seal(value, context) {
|
|
219
|
+
const iv = randomBytes2(12), cipher = createCipheriv("aes-256-gcm", this.key, iv);
|
|
220
|
+
cipher.setAAD(Buffer.from(context));
|
|
221
|
+
const body2 = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final()]);
|
|
222
|
+
return Buffer.concat([iv, cipher.getAuthTag(), body2]).toString("base64");
|
|
223
|
+
}
|
|
224
|
+
open(value, context) {
|
|
225
|
+
try {
|
|
226
|
+
const raw = Buffer.from(value, "base64"), cipher = createDecipheriv("aes-256-gcm", this.key, raw.subarray(0, 12));
|
|
227
|
+
cipher.setAAD(Buffer.from(context));
|
|
228
|
+
cipher.setAuthTag(raw.subarray(12, 28));
|
|
229
|
+
return JSON.parse(Buffer.concat([cipher.update(raw.subarray(28)), cipher.final()]).toString());
|
|
230
|
+
} catch {
|
|
231
|
+
throw new AuthError("invalid_vault");
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
close() {
|
|
235
|
+
this.db.close();
|
|
236
|
+
}
|
|
237
|
+
flow(id) {
|
|
238
|
+
const row = this.db.prepare("SELECT id,data FROM auth_flows WHERE id=?").get(id);
|
|
239
|
+
return row ? this.open(row.data, "flow:" + row.id) : void 0;
|
|
240
|
+
}
|
|
241
|
+
byState(state) {
|
|
242
|
+
const row = this.db.prepare("SELECT id,data FROM auth_flows WHERE state=?").get(state);
|
|
243
|
+
return row ? this.open(row.data, "flow:" + row.id) : void 0;
|
|
244
|
+
}
|
|
245
|
+
connection(id) {
|
|
246
|
+
const row = this.db.prepare("SELECT id,data FROM auth_connections WHERE id=?").get(id);
|
|
247
|
+
return row ? this.open(row.data, "connection:" + row.id) : void 0;
|
|
248
|
+
}
|
|
249
|
+
createFlow(flow) {
|
|
250
|
+
this.db.prepare("INSERT INTO auth_flows VALUES(?,?,?,?,?)").run(flow.id, flow.status, flow.state ?? null, flow.expiresAt, this.seal(flow, "flow:" + flow.id));
|
|
251
|
+
}
|
|
252
|
+
transition(id, expected, next, patch = {}) {
|
|
253
|
+
const previous = this.flow(id);
|
|
254
|
+
if (!previous || previous.status !== expected) return false;
|
|
255
|
+
const current = { ...previous, ...patch, status: next };
|
|
256
|
+
return this.db.prepare("UPDATE auth_flows SET status=?,state=?,data=? WHERE id=? AND status=?").run(next, current.state ?? null, this.seal(current, "flow:" + id), id, expected).changes === 1;
|
|
257
|
+
}
|
|
258
|
+
finish(flowId, connection, now) {
|
|
259
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
260
|
+
try {
|
|
261
|
+
const flow = this.flow(flowId);
|
|
262
|
+
if (!flow || flow.status !== "exchanging" || flow.expiresAt <= now) {
|
|
263
|
+
this.db.exec("ROLLBACK");
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
this.db.prepare("INSERT INTO auth_connections VALUES(?,?,?,?)").run(connection.id, connection.status, connection.revision, this.seal(connection, "connection:" + connection.id));
|
|
267
|
+
this.transition(flowId, "exchanging", "connected", { connectionId: connection.id, verifier: void 0 });
|
|
268
|
+
this.db.exec("COMMIT");
|
|
269
|
+
return true;
|
|
270
|
+
} catch (error) {
|
|
271
|
+
this.db.exec("ROLLBACK");
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
updateConnection(id, revision, patch) {
|
|
276
|
+
const old = this.connection(id);
|
|
277
|
+
if (!old || old.status !== "connected" || old.revision !== revision) return false;
|
|
278
|
+
const current = { ...old, ...patch, revision: revision + 1 };
|
|
279
|
+
return this.db.prepare("UPDATE auth_connections SET status=?,revision=?,data=? WHERE id=? AND status=? AND revision=?").run(current.status, current.revision, this.seal(current, "connection:" + id), id, "connected", revision).changes === 1;
|
|
280
|
+
}
|
|
281
|
+
finishRevocation(id, revision) {
|
|
282
|
+
const old = this.connection(id);
|
|
283
|
+
if (!old || old.status !== "disconnected" || old.revision !== revision) return false;
|
|
284
|
+
const current = { ...old, revocationToken: void 0, revocationConfirmed: true, revision: revision + 1 };
|
|
285
|
+
return this.db.prepare("UPDATE auth_connections SET revision=?,data=? WHERE id=? AND status=? AND revision=?").run(current.revision, this.seal(current, "connection:" + id), id, "disconnected", revision).changes === 1;
|
|
286
|
+
}
|
|
287
|
+
countFlows(now) {
|
|
288
|
+
return Number(this.db.prepare("SELECT count(*) AS n FROM auth_flows WHERE expires>?").get(now).n);
|
|
289
|
+
}
|
|
290
|
+
prune(now) {
|
|
291
|
+
const rows = this.db.prepare("SELECT id,data FROM auth_flows WHERE expires<=?").all(now);
|
|
292
|
+
for (const row of rows) {
|
|
293
|
+
const flow = this.open(row.data, "flow:" + row.id);
|
|
294
|
+
if (flow.connectionId && flow.status !== "claimed") {
|
|
295
|
+
const c = this.connection(flow.connectionId);
|
|
296
|
+
if (c?.status === "connected") this.updateConnection(c.id, c.revision, { status: "disconnected", tokens: void 0 });
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
this.db.prepare("DELETE FROM auth_flows WHERE expires<=?").run(now);
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
|
|
303
|
+
// src/auth/http.ts
|
|
304
|
+
var escape = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
305
|
+
function page(title, content) {
|
|
306
|
+
return `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(title)} \xB7 Engine7</title><style>body{margin:0;background:#14101e;color:#eee;font:17px system-ui;display:grid;place-items:center;min-height:100vh}main{max-width:420px;padding:36px}small{color:#bbb}h1{font-size:28px}button{border:0;border-radius:12px;background:#b8a0ff;padding:14px 24px;font:inherit;color:#181021;cursor:pointer}a{color:#cbbaff}p{line-height:1.65}</style><main><small>Engine7</small><h1>${escape(title)}</h1>${content}</main></html>`;
|
|
307
|
+
}
|
|
308
|
+
async function body(req) {
|
|
309
|
+
let size = 0;
|
|
310
|
+
const chunks = [];
|
|
311
|
+
for await (const part of req.iterator({ destroyOnReturn: false })) {
|
|
312
|
+
const data = Buffer.from(part);
|
|
313
|
+
size += data.length;
|
|
314
|
+
if (size > 16384) throw new AuthError("body_too_large");
|
|
315
|
+
chunks.push(data);
|
|
316
|
+
}
|
|
317
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
318
|
+
}
|
|
319
|
+
function proof(req) {
|
|
320
|
+
const value = req.headers.authorization;
|
|
321
|
+
if (typeof value !== "string" || !/^Bearer [\w-]{43}$/.test(value)) throw new AuthError("invalid_proof");
|
|
322
|
+
return value.slice(7);
|
|
323
|
+
}
|
|
324
|
+
var statusCode = (error) => error === "body_too_large" ? 413 : error === "expired" ? 410 : ["invalid_csrf", "invalid_proof", "invalid_origin"].includes(error) ? 403 : error === "provider_unavailable" ? 503 : error === "upstream_unavailable" ? 502 : 400;
|
|
325
|
+
var failureMessage = (code) => ({
|
|
326
|
+
expired: ["\u8FDE\u63A5\u94FE\u63A5\u5DF2\u8FC7\u671F", "\u8BF7\u56DE\u5230\u90AE\u4EF6\u8BBE\u7F6E\u6216\u539F\u804A\u5929\uFF0C\u70B9\u51FB\u91CD\u65B0\u8FDE\u63A5\uFF0C\u751F\u6210\u65B0\u7684\u94FE\u63A5\u3002"],
|
|
327
|
+
invalid_csrf: ["\u8BF7\u91CD\u65B0\u6253\u5F00\u8FDE\u63A5\u9875", "\u9875\u9762\u9A8C\u8BC1\u5DF2\u5931\u6548\uFF0C\u8BF7\u8FD4\u56DE\u8FDE\u63A5\u9875\u540E\u518D\u7EE7\u7EED\u6388\u6743\u3002"],
|
|
328
|
+
invalid_origin: ["\u8BF7\u91CD\u65B0\u6253\u5F00\u8FDE\u63A5\u9875", "\u8FD9\u6B21\u63D0\u4EA4\u65E0\u6CD5\u786E\u8BA4\u6765\u6E90\uFF0C\u8BF7\u8FD4\u56DE\u8FDE\u63A5\u9875\u540E\u518D\u7EE7\u7EED\u6388\u6743\u3002"],
|
|
329
|
+
invalid_state: ["\u8BF7\u6838\u5BF9\u8FDE\u63A5\u72B6\u6001", "\u8FD9\u6761\u6D41\u7A0B\u5DF2\u7ED3\u675F\u6216\u6B63\u5728\u786E\u8BA4\uFF0C\u8BF7\u8FD4\u56DE\u8FDE\u63A5\u9875\u6216\u90AE\u4EF6\u8BBE\u7F6E\u6838\u5BF9\u72B6\u6001\u3002"],
|
|
330
|
+
upstream_unavailable: ["\u8FDE\u63A5\u6682\u65F6\u4E0D\u53EF\u7528", "\u6682\u65F6\u65E0\u6CD5\u8FDE\u63A5\u670D\u52A1\u5546\uFF0C\u8BF7\u56DE\u5230\u90AE\u4EF6\u8BBE\u7F6E\u6216\u539F\u804A\u5929\uFF0C\u7A0D\u540E\u91CD\u8BD5\u3002"]
|
|
331
|
+
})[code] ?? ["\u8FDE\u63A5\u672A\u5B8C\u6210", "\u8BF7\u56DE\u5230\u90AE\u4EF6\u8BBE\u7F6E\u6216\u539F\u804A\u5929\u67E5\u770B\u8FDE\u63A5\u72B6\u6001\uFF0C\u51C6\u5907\u597D\u540E\u518D\u8BD5\u3002"];
|
|
332
|
+
function createAuthHandler(broker, publicUrl) {
|
|
333
|
+
const base = brokerBase(publicUrl);
|
|
334
|
+
return async (req, res) => {
|
|
335
|
+
res.setHeader("Cache-Control", "no-store");
|
|
336
|
+
res.setHeader("Referrer-Policy", "no-referrer");
|
|
337
|
+
res.setHeader("X-Content-Type-Options", "nosniff");
|
|
338
|
+
res.setHeader("X-Frame-Options", "DENY");
|
|
339
|
+
res.setHeader("Content-Security-Policy", `default-src 'none'; style-src 'unsafe-inline'; form-action 'self' ${broker.authorizationOrigins().join(" ")}; base-uri 'none'; frame-ancestors 'none'`);
|
|
340
|
+
let route = "";
|
|
341
|
+
const json = (value, status = 200) => {
|
|
342
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
|
|
343
|
+
res.end(JSON.stringify(value));
|
|
344
|
+
};
|
|
345
|
+
const html = (title, content, status = 200) => {
|
|
346
|
+
res.writeHead(status, { "Content-Type": "text/html; charset=utf-8" });
|
|
347
|
+
res.end(page(title, content));
|
|
348
|
+
};
|
|
349
|
+
try {
|
|
350
|
+
const url = new URL(req.url ?? "/", base.origin);
|
|
351
|
+
if (!url.pathname.startsWith(base.pathname)) {
|
|
352
|
+
json({ error: "not_found" }, 404);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
route = url.pathname.slice(base.pathname.length);
|
|
356
|
+
if (req.method === "POST" && req.headers.origin && req.headers.origin !== base.origin) throw new AuthError("invalid_origin");
|
|
357
|
+
if (route === "" && req.method === "GET") {
|
|
358
|
+
html("\u670D\u52A1\u8FDE\u63A5", "<p>\u8BF7\u4ECE\u539F\u804A\u5929\u6253\u5F00\u4F19\u4F34\u63D0\u4F9B\u7684\u8FDE\u63A5\u94FE\u63A5\uFF0C\u767B\u5F55\u5E76\u786E\u8BA4\u6743\u9650\u540E\u56DE\u5230\u804A\u5929\u3002</p>" + broker.catalog().map((p) => "<p>" + escape(p.name) + "\uFF1A" + (p.available ? "\u652F\u6301\u767B\u5F55\u6388\u6743" : "\u6388\u6743\u5165\u53E3\u51C6\u5907\u4E2D") + "</p>").join(""));
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
if (route === "providers" && req.method === "GET") {
|
|
362
|
+
json({ providers: broker.catalog() });
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
if (route === "flows" && req.method === "POST") {
|
|
366
|
+
if (!req.headers["content-type"]?.startsWith("application/json")) throw new AuthError("invalid_request");
|
|
367
|
+
let data;
|
|
368
|
+
try {
|
|
369
|
+
data = JSON.parse(await body(req));
|
|
370
|
+
} catch (error) {
|
|
371
|
+
throw error instanceof AuthError ? error : new AuthError("invalid_request");
|
|
372
|
+
}
|
|
373
|
+
json(broker.begin(data.provider, data.label, data.challenge), 201);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const landing = route.match(/^flow\/([\w-]{43})$/);
|
|
377
|
+
if (landing && req.method === "GET") {
|
|
378
|
+
const state = broker.open(landing[1]);
|
|
379
|
+
if (state.status === "connected" || state.status === "claimed") {
|
|
380
|
+
html("\u6388\u6743\u5DF2\u5B8C\u6210", "<p>\u73B0\u5728\u53EF\u4EE5\u56DE\u5230\u90AE\u4EF6\u8BBE\u7F6E\u6216\u539F\u804A\u5929\uFF0C\u4F19\u4F34\u4F1A\u7EE7\u7EED\u5E2E\u4F60\u3002</p>");
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
if (state.status === "denied" || state.status === "failed") {
|
|
384
|
+
html("\u8FDE\u63A5\u672A\u5B8C\u6210", `<p>${state.status === "denied" ? "\u8FD9\u6B21\u6388\u6743\u5DF2\u53D6\u6D88\u3002" : "\u8FD9\u6B21\u6388\u6743\u672A\u5B8C\u6210\u3002"}\u8BF7\u56DE\u5230\u90AE\u4EF6\u8BBE\u7F6E\u6216\u539F\u804A\u5929\uFF0C\u70B9\u51FB\u91CD\u65B0\u8FDE\u63A5\u3002</p>`);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
if (state.status === "exchanging") {
|
|
388
|
+
html("\u6B63\u5728\u786E\u8BA4\u6388\u6743", "<p>\u6B63\u5728\u786E\u8BA4\u670D\u52A1\u5546\u7684\u6388\u6743\u7ED3\u679C\uFF0C\u8BF7\u7A0D\u540E\u56DE\u5230\u90AE\u4EF6\u8BBE\u7F6E\u6216\u539F\u804A\u5929\u6838\u5BF9\u72B6\u6001\u3002</p>");
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
res.setHeader("Referrer-Policy", "same-origin");
|
|
392
|
+
const cookie = "engine7_auth_" + state.id + "=" + state.csrfToken + "; Path=" + base.pathname + "flow/" + state.id + "; HttpOnly; SameSite=Lax" + (base.protocol === "https:" ? "; Secure" : "");
|
|
393
|
+
res.setHeader("Set-Cookie", cookie);
|
|
394
|
+
html("\u8FDE\u63A5 " + state.name, `<p>${escape(state.label)}\u5C06\u4F7F\u7528\u8FD9\u4EFD\u8FDE\u63A5\u5E2E\u52A9\u4F60\u3002</p>${state.permissions ? "<p>" + escape(state.permissions) + "</p>" : ""}<p>\u8BF7\u524D\u5F80\u670D\u52A1\u5546\u767B\u5F55\u5E76\u786E\u8BA4\u6743\u9650\uFF0C\u5B8C\u6210\u540E\u56DE\u5230\u539F\u804A\u5929\u5373\u53EF\u3002</p><form action="${escape(base.pathname + "flow/" + state.id + "/authorize")}" method="post"><input type="hidden" name="csrf" value="${escape(state.csrfToken)}"><button type="submit">${state.status === "authorizing" ? "\u7EE7\u7EED\u6388\u6743" : "\u8FDE\u63A5 " + escape(state.name)}</button></form>`);
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
const authorize = route.match(/^flow\/([\w-]{43})\/authorize$/);
|
|
398
|
+
if (authorize && req.method === "GET") {
|
|
399
|
+
res.writeHead(303, { Location: base.pathname + "flow/" + authorize[1] });
|
|
400
|
+
res.end();
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (authorize && req.method === "POST") {
|
|
404
|
+
const form = new URLSearchParams(await body(req)), csrf = form.get("csrf") ?? "";
|
|
405
|
+
const cookieName = "engine7_auth_" + authorize[1] + "=";
|
|
406
|
+
const cookie = (req.headers.cookie ?? "").split(";").map((s) => s.trim()).find((s) => s.startsWith(cookieName))?.slice(cookieName.length) ?? "";
|
|
407
|
+
if (!csrf || !equalSecret(cookie, csrf)) throw new AuthError("invalid_csrf");
|
|
408
|
+
const target = broker.authorize(authorize[1], csrf);
|
|
409
|
+
res.writeHead(303, { Location: target });
|
|
410
|
+
res.end();
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
const callback = route.match(/^callback\/([a-z][a-z0-9-]{0,40})$/);
|
|
414
|
+
if (callback && req.method === "GET") {
|
|
415
|
+
if (url.searchParams.getAll("state").length !== 1) throw new AuthError("invalid_state");
|
|
416
|
+
const error = url.searchParams.get("error") ?? void 0;
|
|
417
|
+
await broker.callback(callback[1], url.searchParams.get("state"), url.searchParams.get("code") ?? void 0, error);
|
|
418
|
+
html(error ? "\u8FDE\u63A5\u672A\u5B8C\u6210" : "\u6388\u6743\u5DF2\u5B8C\u6210", `<p>${error ? "\u4F60\u53EF\u4EE5\u56DE\u5230\u539F\u804A\u5929\uFF0C\u51C6\u5907\u597D\u540E\u518D\u8FDE\u63A5\u3002" : "\u73B0\u5728\u53EF\u4EE5\u56DE\u5230\u539F\u804A\u5929\uFF0C\u4F19\u4F34\u4F1A\u7EE7\u7EED\u5E2E\u4F60\u3002"}</p>`);
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
const poll = route.match(/^flows\/([\w-]{43})\/poll$/);
|
|
422
|
+
if (poll && req.method === "POST") {
|
|
423
|
+
json(broker.poll(poll[1], proof(req)));
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
const cancel = route.match(/^flows\/([\w-]{43})\/cancel$/);
|
|
427
|
+
if (cancel && req.method === "POST") {
|
|
428
|
+
json(await broker.cancel(cancel[1], proof(req)));
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
const connection = route.match(/^connections\/([\w-]{43})\/(status|token|disconnect)$/);
|
|
432
|
+
if (connection) {
|
|
433
|
+
const id = connection[1], action = connection[2];
|
|
434
|
+
if (action === "status" && req.method === "GET") {
|
|
435
|
+
json({ connection: broker.status(id, proof(req)) });
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
if (action === "token" && req.method === "POST") {
|
|
439
|
+
json({ accessToken: await broker.accessToken(id, proof(req)) });
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
if (action === "disconnect" && req.method === "POST") {
|
|
443
|
+
json(await broker.disconnect(id, proof(req)));
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
json({ error: "not_found" }, 404);
|
|
448
|
+
} catch (error) {
|
|
449
|
+
req.resume();
|
|
450
|
+
const code = safeError(error);
|
|
451
|
+
if (route.startsWith("flow/") || route.startsWith("callback/")) {
|
|
452
|
+
const [title, message] = failureMessage(code);
|
|
453
|
+
const flowId = route.match(/^flow\/([\w-]{43})(?:\/authorize)?$/)?.[1];
|
|
454
|
+
const recovery = flowId && ["invalid_csrf", "invalid_origin", "invalid_state"].includes(code) ? `<p><a href="${escape(base.pathname + "flow/" + flowId)}">\u8FD4\u56DE\u8FDE\u63A5\u9875</a></p>` : "";
|
|
455
|
+
html(title, "<p>" + escape(message) + "</p>" + recovery, statusCode(code));
|
|
456
|
+
} else json({ error: code }, statusCode(code));
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// src/auth/oauth.ts
|
|
462
|
+
async function upstreamJson(url, init, fetcher = fetch, maxBytes = 65536, allowEmpty = false) {
|
|
463
|
+
try {
|
|
464
|
+
const timeout = AbortSignal.timeout(15e3);
|
|
465
|
+
const response = await fetcher(url, { ...init, redirect: "error", signal: init.signal ? AbortSignal.any([init.signal, timeout]) : timeout });
|
|
466
|
+
if (allowEmpty && response.status === 204) {
|
|
467
|
+
await response.body?.cancel();
|
|
468
|
+
return null;
|
|
469
|
+
}
|
|
470
|
+
const reader = response.body?.getReader();
|
|
471
|
+
if (!reader) throw new AuthError("invalid_upstream");
|
|
472
|
+
const pieces = [];
|
|
473
|
+
let size = 0;
|
|
474
|
+
try {
|
|
475
|
+
while (true) {
|
|
476
|
+
const chunk = await reader.read();
|
|
477
|
+
if (chunk.done) break;
|
|
478
|
+
size += chunk.value.byteLength;
|
|
479
|
+
if (size > maxBytes) throw new AuthError("upstream_too_large");
|
|
480
|
+
pieces.push(chunk.value);
|
|
481
|
+
}
|
|
482
|
+
} finally {
|
|
483
|
+
await reader.cancel().catch(() => {
|
|
484
|
+
});
|
|
485
|
+
}
|
|
486
|
+
let value;
|
|
487
|
+
try {
|
|
488
|
+
value = JSON.parse(Buffer.concat(pieces).toString());
|
|
489
|
+
} catch {
|
|
490
|
+
throw new AuthError(response.ok ? "invalid_upstream" : "upstream_rejected");
|
|
491
|
+
}
|
|
492
|
+
if (!response.ok) throw new AuthError(value?.error === "invalid_grant" ? "authorization_expired" : response.status === 404 ? "resource_not_found" : "upstream_rejected");
|
|
493
|
+
return value;
|
|
494
|
+
} catch (err) {
|
|
495
|
+
throw err instanceof AuthError ? err : new AuthError("upstream_unavailable");
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
function createOAuthProvider(d, credentials, fetcher = fetch, now = Date.now) {
|
|
499
|
+
for (const endpoint of [d.authorizeEndpoint, d.tokenEndpoint, ...d.revokeEndpoint ? [d.revokeEndpoint] : []]) brokerBase(endpoint);
|
|
500
|
+
const ready = Boolean(credentials.clientId && credentials.clientSecret);
|
|
501
|
+
async function token(fields, fallbackScopes = d.scopes) {
|
|
502
|
+
if (!ready) throw new AuthError("provider_unavailable");
|
|
503
|
+
const body2 = new URLSearchParams({ ...fields, client_id: credentials.clientId, client_secret: credentials.clientSecret });
|
|
504
|
+
const json = await upstreamJson(d.tokenEndpoint, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: body2.toString() }, fetcher);
|
|
505
|
+
if (typeof json.access_token !== "string" || !json.access_token || String(json.token_type).toLowerCase() !== "bearer" || !Number.isFinite(json.expires_in) || json.expires_in <= 0 || json.expires_in > 31536e3) throw new AuthError("invalid_token");
|
|
506
|
+
return { accessToken: json.access_token, refreshToken: typeof json.refresh_token === "string" ? json.refresh_token : void 0, expiresAt: now() + json.expires_in * 1e3, scopes: typeof json.scope === "string" ? json.scope.split(/\s+/).filter(Boolean) : [...fallbackScopes] };
|
|
507
|
+
}
|
|
508
|
+
return {
|
|
509
|
+
id: d.id,
|
|
510
|
+
name: d.name,
|
|
511
|
+
scopes: [...d.scopes],
|
|
512
|
+
ready,
|
|
513
|
+
authorizationOrigin: new URL(d.authorizeEndpoint).origin,
|
|
514
|
+
permissionLabel: d.permissionLabel,
|
|
515
|
+
authorizationUrl({ state, challenge, redirectUri }) {
|
|
516
|
+
if (!ready) throw new AuthError("provider_unavailable");
|
|
517
|
+
const url = new URL(d.authorizeEndpoint);
|
|
518
|
+
for (const [name, value] of Object.entries({ ...d.authorizeParams, client_id: credentials.clientId, response_type: "code", redirect_uri: redirectUri, state, scope: d.scopes.join(" "), code_challenge: challenge, code_challenge_method: "S256" })) url.searchParams.set(name, value);
|
|
519
|
+
return url.toString();
|
|
520
|
+
},
|
|
521
|
+
exchange: ({ code, verifier, redirectUri }) => token({ grant_type: "authorization_code", code, code_verifier: verifier, redirect_uri: redirectUri }),
|
|
522
|
+
refresh: (refreshToken, currentScopes) => token({ grant_type: "refresh_token", refresh_token: refreshToken }, currentScopes ?? d.scopes),
|
|
523
|
+
identify: (accessToken) => d.identify(accessToken, fetcher),
|
|
524
|
+
async revoke(token2) {
|
|
525
|
+
if (!d.revokeEndpoint) throw new AuthError("revocation_unavailable");
|
|
526
|
+
try {
|
|
527
|
+
const response = await fetcher(d.revokeEndpoint, { method: "POST", redirect: "error", signal: AbortSignal.timeout(15e3), headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ token: token2 }).toString() });
|
|
528
|
+
await response.body?.cancel();
|
|
529
|
+
if (!response.ok) throw new AuthError("upstream_rejected");
|
|
530
|
+
} catch (err) {
|
|
531
|
+
throw err instanceof AuthError ? err : new AuthError("upstream_unavailable");
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// src/auth/providers/gmail.ts
|
|
538
|
+
var GMAIL_MODIFY_SCOPE = "https://www.googleapis.com/auth/gmail.modify";
|
|
539
|
+
function gmailProvider(credentials, fetcher = fetch) {
|
|
540
|
+
return createOAuthProvider({
|
|
541
|
+
id: "gmail",
|
|
542
|
+
name: "Gmail",
|
|
543
|
+
scopes: [GMAIL_MODIFY_SCOPE],
|
|
544
|
+
permissionLabel: "\u8BFB\u53D6\u548C\u7BA1\u7406\u90AE\u4EF6\u3001\u8349\u7A3F\u3001\u6807\u7B7E\uFF0C\u53EF\u53D1\u9001\u90AE\u4EF6\u3002\u5177\u4F53\u64CD\u4F5C\u6309\u4F19\u4F34\u7684\u5141\u8BB8\uFF0F\u63D0\u95EE\u8BBE\u7F6E\u6267\u884C\u3002",
|
|
545
|
+
authorizeEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
|
|
546
|
+
tokenEndpoint: "https://oauth2.googleapis.com/token",
|
|
547
|
+
revokeEndpoint: "https://oauth2.googleapis.com/revoke",
|
|
548
|
+
authorizeParams: { access_type: "offline", prompt: "consent", include_granted_scopes: "false" },
|
|
549
|
+
async identify(accessToken, fetcher2) {
|
|
550
|
+
const profile = await upstreamJson("https://gmail.googleapis.com/gmail/v1/users/me/profile", { headers: { Authorization: "Bearer " + accessToken } }, fetcher2);
|
|
551
|
+
if (typeof profile.emailAddress !== "string" || !profile.emailAddress.includes("@")) throw new AuthError("invalid_identity");
|
|
552
|
+
return { id: profile.emailAddress, label: profile.emailAddress };
|
|
553
|
+
}
|
|
554
|
+
}, credentials, fetcher);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// src/auth/server.ts
|
|
558
|
+
function authServerConfig(env = process.env) {
|
|
559
|
+
let key;
|
|
560
|
+
try {
|
|
561
|
+
key = Buffer.from(opaque(env.ENGINE7_AUTH_VAULT_KEY), "base64url");
|
|
562
|
+
} catch {
|
|
563
|
+
throw new AuthError("invalid_vault_key");
|
|
564
|
+
}
|
|
565
|
+
if (key.length !== 32) throw new AuthError("invalid_vault_key");
|
|
566
|
+
const publicUrl = brokerBase(env.ENGINE7_AUTH_PUBLIC_URL ?? "https://www.twinsun.top/auth/").toString();
|
|
567
|
+
const port = Number(env.ENGINE7_AUTH_PORT ?? 6090);
|
|
568
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new AuthError("invalid_port");
|
|
569
|
+
const dataDir = env.ENGINE7_AUTH_DATA_DIR ?? "/var/lib/engine7-auth";
|
|
570
|
+
if (!path2.isAbsolute(dataDir)) throw new AuthError("invalid_data_dir");
|
|
571
|
+
return { publicUrl, dataDir, vaultKey: key, port, google: { clientId: env.ENGINE7_AUTH_GOOGLE_CLIENT_ID, clientSecret: env.ENGINE7_AUTH_GOOGLE_CLIENT_SECRET } };
|
|
572
|
+
}
|
|
573
|
+
async function startAuthServer(config) {
|
|
574
|
+
const store = new AuthStore(path2.join(config.dataDir, "vault.sqlite"), config.vaultKey);
|
|
575
|
+
const broker = new AuthBroker({ store, providers: [gmailProvider(config.google)], publicUrl: config.publicUrl });
|
|
576
|
+
const handler = createAuthHandler(broker, config.publicUrl);
|
|
577
|
+
const server = http.createServer((req, res) => {
|
|
578
|
+
void handler(req, res);
|
|
579
|
+
});
|
|
580
|
+
server.requestTimeout = 2e4;
|
|
581
|
+
server.headersTimeout = 1e4;
|
|
582
|
+
server.keepAliveTimeout = 5e3;
|
|
583
|
+
server.maxHeadersCount = 50;
|
|
584
|
+
const prune = setInterval(() => {
|
|
585
|
+
try {
|
|
586
|
+
store.prune(Date.now());
|
|
587
|
+
} catch {
|
|
588
|
+
console.error("[auth] vault maintenance failed");
|
|
589
|
+
}
|
|
590
|
+
}, 6e4);
|
|
591
|
+
prune.unref();
|
|
592
|
+
try {
|
|
593
|
+
await new Promise((resolve, reject) => {
|
|
594
|
+
server.once("error", reject);
|
|
595
|
+
server.listen(config.port, "127.0.0.1", () => {
|
|
596
|
+
server.off("error", reject);
|
|
597
|
+
resolve();
|
|
598
|
+
});
|
|
599
|
+
});
|
|
600
|
+
} catch (error) {
|
|
601
|
+
clearInterval(prune);
|
|
602
|
+
store.close();
|
|
603
|
+
throw error;
|
|
604
|
+
}
|
|
605
|
+
return { port: server.address().port, async close() {
|
|
606
|
+
clearInterval(prune);
|
|
607
|
+
server.closeIdleConnections();
|
|
608
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
609
|
+
store.close();
|
|
610
|
+
} };
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// src/auth/server-main.ts
|
|
614
|
+
try {
|
|
615
|
+
const service = await startAuthServer(authServerConfig());
|
|
616
|
+
console.log(`[auth] listening on 127.0.0.1:${service.port}`);
|
|
617
|
+
let closing = false;
|
|
618
|
+
const close = async () => {
|
|
619
|
+
if (closing) return;
|
|
620
|
+
closing = true;
|
|
621
|
+
await service.close();
|
|
622
|
+
};
|
|
623
|
+
process.once("SIGTERM", () => {
|
|
624
|
+
void close();
|
|
625
|
+
});
|
|
626
|
+
process.once("SIGINT", () => {
|
|
627
|
+
void close();
|
|
628
|
+
});
|
|
629
|
+
} catch (error) {
|
|
630
|
+
console.error("[auth] startup failed: " + safeError(error));
|
|
631
|
+
process.exitCode = 1;
|
|
632
|
+
}
|