aura-courier-mcp 2.3.2 → 2.7.1
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 +192 -21
- package/README.md +359 -26
- package/README.md.metadata.json +4 -0
- package/dist/adapters/base.d.ts +1 -0
- package/dist/adapters/base.js.map +1 -0
- package/dist/adapters/fraud_engine.d.ts +8 -1
- package/dist/adapters/fraud_engine.js +137 -21
- package/dist/adapters/google_maps.d.ts +25 -0
- package/dist/adapters/google_maps.js +334 -0
- package/dist/adapters/paperfly.d.ts +14 -0
- package/dist/adapters/paperfly.js +102 -22
- package/dist/adapters/pathao.d.ts +37 -1
- package/dist/adapters/pathao.js +247 -31
- package/dist/adapters/pathao.js.map +1 -0
- package/dist/adapters/redx.d.ts +14 -0
- package/dist/adapters/redx.js +81 -12
- package/dist/adapters/registry.d.ts +20 -0
- package/dist/adapters/registry.js +34 -0
- package/dist/adapters/registry.js.map +1 -0
- package/dist/adapters/steadfast.d.ts +17 -0
- package/dist/adapters/steadfast.js +121 -12
- package/dist/adapters/steadfast.js.map +1 -0
- package/dist/config.d.ts +4 -0
- package/dist/config.js +16 -2
- package/dist/config.js.map +1 -0
- package/dist/envelope.d.ts +55 -0
- package/dist/envelope.js +159 -0
- package/dist/http.d.ts +8 -1
- package/dist/http.js +699 -58
- package/dist/http.js.map +1 -0
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -0
- package/dist/middleware/auth.d.ts +100 -0
- package/dist/middleware/auth.js +585 -0
- package/dist/middleware/oauth.d.ts +19 -0
- package/dist/middleware/oauth.js +1376 -0
- package/dist/middleware/rate_limit.d.ts +9 -0
- package/dist/middleware/rate_limit.js +71 -0
- package/dist/pages.d.ts +8 -0
- package/dist/pages.js +317 -0
- package/dist/pages.js.map +1 -0
- package/dist/registry.d.ts +51 -6
- package/dist/registry.js +625 -28
- package/dist/server.d.ts +11 -1
- package/dist/server.js +407 -51
- package/dist/server.js.map +1 -0
- package/dist/tariffs.d.ts +46 -0
- package/dist/tariffs.js +153 -0
- package/dist/test_zero_risk.js +49 -25
- package/dist/tools/index.d.ts +3 -0
- package/dist/tools/index.js +162 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/types.d.ts +188 -4
- package/dist/types.js.map +1 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +16 -0
- package/package.json +12 -9
|
@@ -0,0 +1,1376 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { resolveAuthContextAsync } from "./auth.js";
|
|
3
|
+
const ACCESS_TOKEN_TTL_SEC = 3600; // 1 hour
|
|
4
|
+
const REFRESH_TOKEN_TTL_SEC = 180 * 24 * 3600; // 180 days (non-rotating for Gemini stability)
|
|
5
|
+
const AUTH_CODE_TTL_SEC = 300; // 5 minutes
|
|
6
|
+
const CSRF_TTL_SEC = 900; // 15 minutes
|
|
7
|
+
const VALID_SCOPES = ["read", "write"];
|
|
8
|
+
const AURA_AUTH_BASE = (process.env.AURA_AUTH_URL || "https://auth.auraajenticai.cloud").replace(/\/+$/, "");
|
|
9
|
+
// Official inline vector SVG brand mark (from assets/logo.svg — instant render, zero broken-image risk)
|
|
10
|
+
const INLINE_LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="44" height="44" role="img" aria-label="Aura Courier MCP"><defs><linearGradient id="ac-bg" x1="0" y1="0" x2="1" y2="1"><stop stop-color="#04143e"/><stop offset=".6" stop-color="#0456cc"/><stop offset="1" stop-color="#03bb85"/></linearGradient><linearGradient id="ac-box" x1="0" x2="1" y1="0" y2="1"><stop stop-color="#09bdfc"/><stop offset="1" stop-color="#0451de"/></linearGradient><linearGradient id="ac-spd" x1="0" x2="1"><stop stop-color="#34ee60"/><stop offset="1" stop-color="#04cbe8"/></linearGradient></defs><rect x="16" y="16" width="992" height="992" rx="215" fill="url(#ac-bg)"/><g transform="translate(95 155)"><path d="M35 230h265M90 300h205M65 370h230" fill="none" stroke="url(#ac-spd)" stroke-width="36" stroke-linecap="round"/><path d="m300 220 225-115 236 111-227 118Z" fill="#139cff"/><path d="M300 220v266l234 132V334Z" fill="url(#ac-box)"/><path d="M534 334v284l227-130V216Z" fill="#0750ce"/><path d="m393 174 234 119v137l40-23V270L436 152Z" fill="#fff"/><path d="M265 570c160 122 411 83 532-125" fill="none" stroke="url(#ac-spd)" stroke-width="39" stroke-linecap="round"/></g></svg>`;
|
|
11
|
+
// In-memory replay & revocation guards (with periodic TTL pruning)
|
|
12
|
+
const usedAuthCodes = new Map(); // jti -> expiresAtMs
|
|
13
|
+
const revokedTokenIds = new Map(); // jti -> expiresAtMs
|
|
14
|
+
setInterval(() => {
|
|
15
|
+
const now = Date.now();
|
|
16
|
+
for (const [k, exp] of usedAuthCodes.entries()) {
|
|
17
|
+
if (now > exp)
|
|
18
|
+
usedAuthCodes.delete(k);
|
|
19
|
+
}
|
|
20
|
+
for (const [k, exp] of revokedTokenIds.entries()) {
|
|
21
|
+
if (now > exp)
|
|
22
|
+
revokedTokenIds.delete(k);
|
|
23
|
+
}
|
|
24
|
+
}, 5 * 60 * 1000).unref();
|
|
25
|
+
function getRootSecret() {
|
|
26
|
+
return (process.env.AURA_OAUTH_SECRET ||
|
|
27
|
+
process.env.AURA_API_KEY ||
|
|
28
|
+
process.env.COURIER_AUTH_TOKEN ||
|
|
29
|
+
"aura_live_mcp_master_key_2026");
|
|
30
|
+
}
|
|
31
|
+
function deriveKey(purpose) {
|
|
32
|
+
return createHash("sha256")
|
|
33
|
+
.update(`aura-courier-mcp-oauth-v1:${purpose}:${getRootSecret()}`)
|
|
34
|
+
.digest();
|
|
35
|
+
}
|
|
36
|
+
function safeEqualStr(a, b) {
|
|
37
|
+
const ba = Buffer.from(a);
|
|
38
|
+
const bb = Buffer.from(b);
|
|
39
|
+
if (ba.length !== bb.length)
|
|
40
|
+
return false;
|
|
41
|
+
return timingSafeEqual(ba, bb);
|
|
42
|
+
}
|
|
43
|
+
function parseCookie(req, name) {
|
|
44
|
+
const raw = req.headers.cookie || "";
|
|
45
|
+
if (!raw)
|
|
46
|
+
return null;
|
|
47
|
+
const parts = raw.split(";");
|
|
48
|
+
for (const part of parts) {
|
|
49
|
+
const eq = part.indexOf("=");
|
|
50
|
+
if (eq <= 0)
|
|
51
|
+
continue;
|
|
52
|
+
const k = part.slice(0, eq).trim();
|
|
53
|
+
if (k === name) {
|
|
54
|
+
const v = part.slice(eq + 1).trim();
|
|
55
|
+
try {
|
|
56
|
+
return decodeURIComponent(v);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return v;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Verifies the shared `.auraajenticai.cloud` SSO cookie (`aura_access`) signed with HS256 by `auth.auraajenticai.cloud`.
|
|
67
|
+
* Enables zero-friction 1-click consent for signed-in Aura Cloud users (just like GitHub, Vercel, Linear, Notion).
|
|
68
|
+
*/
|
|
69
|
+
function verifyAuraSsoCookie(req) {
|
|
70
|
+
const secret = process.env.AURA_SSO_JWT_SECRET || process.env.JWT_SECRET || "";
|
|
71
|
+
if (!secret)
|
|
72
|
+
return null;
|
|
73
|
+
const token = parseCookie(req, "aura_access");
|
|
74
|
+
if (!token)
|
|
75
|
+
return null;
|
|
76
|
+
const parts = token.split(".");
|
|
77
|
+
if (parts.length !== 3)
|
|
78
|
+
return null;
|
|
79
|
+
const [headerB64, bodyB64, sigB64] = parts;
|
|
80
|
+
try {
|
|
81
|
+
const header = JSON.parse(Buffer.from(headerB64, "base64url").toString("utf8"));
|
|
82
|
+
if (header?.alg !== "HS256")
|
|
83
|
+
return null;
|
|
84
|
+
const expectedSig = createHmac("sha256", Buffer.from(secret, "utf8"))
|
|
85
|
+
.update(`${headerB64}.${bodyB64}`)
|
|
86
|
+
.digest("base64url");
|
|
87
|
+
if (!safeEqualStr(sigB64, expectedSig))
|
|
88
|
+
return null;
|
|
89
|
+
const payload = JSON.parse(Buffer.from(bodyB64, "base64url").toString("utf8"));
|
|
90
|
+
const nowSec = Math.floor(Date.now() / 1000);
|
|
91
|
+
if (typeof payload?.exp === "number" && payload.exp <= nowSec)
|
|
92
|
+
return null;
|
|
93
|
+
if (typeof payload?.sub !== "string" || typeof payload?.email !== "string")
|
|
94
|
+
return null;
|
|
95
|
+
const role = String(payload.role || "client").toLowerCase();
|
|
96
|
+
const normalizedRole = role === "owner" || role === "admin" || role === "team_member" ? role : "client";
|
|
97
|
+
return {
|
|
98
|
+
sub: payload.sub,
|
|
99
|
+
email: payload.email.toLowerCase().trim(),
|
|
100
|
+
role: normalizedRole,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function mapSsoUserToAuth(user) {
|
|
108
|
+
const isOwnerOrAdmin = user.role === "owner" || user.role === "admin";
|
|
109
|
+
if (isOwnerOrAdmin) {
|
|
110
|
+
return { tenantId: "master", isAdmin: true, scopes: ["read", "write"] };
|
|
111
|
+
}
|
|
112
|
+
return { tenantId: `aura_${user.sub}`, isAdmin: false, scopes: ["read", "write"] };
|
|
113
|
+
}
|
|
114
|
+
async function authenticateWithAuraPassword(email, password) {
|
|
115
|
+
const ctrl = new AbortController();
|
|
116
|
+
const timer = setTimeout(() => ctrl.abort(), 5000);
|
|
117
|
+
try {
|
|
118
|
+
const resp = await fetch(`${AURA_AUTH_BASE}/api/auth/login`, {
|
|
119
|
+
method: "POST",
|
|
120
|
+
headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
121
|
+
body: JSON.stringify({ email: email.trim().toLowerCase(), password }),
|
|
122
|
+
signal: ctrl.signal,
|
|
123
|
+
});
|
|
124
|
+
const data = await resp.json().catch(() => ({}));
|
|
125
|
+
if (!resp.ok || !data?.user?.id || !data?.user?.email) {
|
|
126
|
+
return { ok: false, error: data?.error || "Invalid email or password." };
|
|
127
|
+
}
|
|
128
|
+
const role = String(data.user.role || "client").toLowerCase();
|
|
129
|
+
const normalizedRole = role === "owner" || role === "admin" || role === "team_member" ? role : "client";
|
|
130
|
+
return {
|
|
131
|
+
ok: true,
|
|
132
|
+
user: {
|
|
133
|
+
sub: String(data.user.id),
|
|
134
|
+
email: String(data.user.email).toLowerCase().trim(),
|
|
135
|
+
role: normalizedRole,
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return { ok: false, error: "Aura Sign-In service is temporarily unreachable. Please try Google Sign-In or an API key." };
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
clearTimeout(timer);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function signJwt(payload, purpose) {
|
|
147
|
+
const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url");
|
|
148
|
+
const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
149
|
+
const signingInput = `${header}.${body}`;
|
|
150
|
+
const sig = createHmac("sha256", deriveKey(purpose)).update(signingInput).digest("base64url");
|
|
151
|
+
return `${signingInput}.${sig}`;
|
|
152
|
+
}
|
|
153
|
+
function verifyJwt(token, purpose, expectedTyp) {
|
|
154
|
+
if (!token || typeof token !== "string")
|
|
155
|
+
return null;
|
|
156
|
+
const parts = token.split(".");
|
|
157
|
+
if (parts.length !== 3)
|
|
158
|
+
return null;
|
|
159
|
+
const [headerB64, bodyB64, sigB64] = parts;
|
|
160
|
+
if (!headerB64 || !bodyB64 || !sigB64)
|
|
161
|
+
return null;
|
|
162
|
+
try {
|
|
163
|
+
const header = JSON.parse(Buffer.from(headerB64, "base64url").toString("utf8"));
|
|
164
|
+
if (header?.alg !== "HS256")
|
|
165
|
+
return null;
|
|
166
|
+
const expectedSig = createHmac("sha256", deriveKey(purpose))
|
|
167
|
+
.update(`${headerB64}.${bodyB64}`)
|
|
168
|
+
.digest("base64url");
|
|
169
|
+
if (!safeEqualStr(sigB64, expectedSig))
|
|
170
|
+
return null;
|
|
171
|
+
const payload = JSON.parse(Buffer.from(bodyB64, "base64url").toString("utf8"));
|
|
172
|
+
if (!payload || payload.typ !== expectedTyp)
|
|
173
|
+
return null;
|
|
174
|
+
const nowSec = Math.floor(Date.now() / 1000);
|
|
175
|
+
if (typeof payload.exp !== "number" || payload.exp <= nowSec)
|
|
176
|
+
return null;
|
|
177
|
+
if (payload.jti && revokedTokenIds.has(payload.jti))
|
|
178
|
+
return null;
|
|
179
|
+
return payload;
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
export function verifyOAuthAccessToken(token) {
|
|
186
|
+
return verifyJwt(token, "access", "at");
|
|
187
|
+
}
|
|
188
|
+
function verifyOAuthRefreshToken(token) {
|
|
189
|
+
return verifyJwt(token, "refresh", "rt");
|
|
190
|
+
}
|
|
191
|
+
export function getPublicOrigin(req) {
|
|
192
|
+
if (process.env.NODE_ENV !== "test" && process.env.PUBLIC_BASE_URL) {
|
|
193
|
+
return process.env.PUBLIC_BASE_URL.replace(/\/+$/, "");
|
|
194
|
+
}
|
|
195
|
+
const fwdHost = req.headers["x-forwarded-host"];
|
|
196
|
+
const rawHost = (Array.isArray(fwdHost) ? fwdHost[0] : fwdHost) ||
|
|
197
|
+
req.headers.host ||
|
|
198
|
+
"courier.auraajenticai.cloud";
|
|
199
|
+
const host = String(rawHost).split(",")[0].trim();
|
|
200
|
+
const fwdProto = req.headers["x-forwarded-proto"];
|
|
201
|
+
let proto = (Array.isArray(fwdProto) ? fwdProto[0] : fwdProto) || req.protocol || "https";
|
|
202
|
+
proto = String(proto).split(",")[0].trim().toLowerCase();
|
|
203
|
+
const isLocal = /^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/i.test(host);
|
|
204
|
+
if (!isLocal && proto === "http") {
|
|
205
|
+
proto = "https";
|
|
206
|
+
}
|
|
207
|
+
return `${proto}://${host}`;
|
|
208
|
+
}
|
|
209
|
+
export function buildWwwAuthenticateHeader(req, invalidToken = false) {
|
|
210
|
+
const origin = getPublicOrigin(req);
|
|
211
|
+
const metaUrl = `${origin}/.well-known/oauth-protected-resource`;
|
|
212
|
+
if (invalidToken) {
|
|
213
|
+
return `Bearer realm="Aura Courier MCP", error="invalid_token", error_description="The access token is invalid or expired.", resource_metadata="${metaUrl}", scope="read write"`;
|
|
214
|
+
}
|
|
215
|
+
return `Bearer realm="Aura Courier MCP", resource_metadata="${metaUrl}", scope="read write"`;
|
|
216
|
+
}
|
|
217
|
+
export function isAllowedRedirectUri(uri) {
|
|
218
|
+
if (!uri || typeof uri !== "string" || uri.length > 2048)
|
|
219
|
+
return false;
|
|
220
|
+
let parsed;
|
|
221
|
+
try {
|
|
222
|
+
parsed = new URL(uri);
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
if (parsed.hash || parsed.username || parsed.password)
|
|
228
|
+
return false;
|
|
229
|
+
const proto = parsed.protocol.toLowerCase();
|
|
230
|
+
const host = parsed.hostname.toLowerCase();
|
|
231
|
+
if (proto === "cursor:" ||
|
|
232
|
+
proto === "vscode:" ||
|
|
233
|
+
proto === "vscode-insiders:" ||
|
|
234
|
+
proto === "windsurf:" ||
|
|
235
|
+
proto === "antigravity:" ||
|
|
236
|
+
proto === "claude:" ||
|
|
237
|
+
proto === "cline:" ||
|
|
238
|
+
proto === "raycast:") {
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
241
|
+
if ((proto === "http:" || proto === "https:") &&
|
|
242
|
+
(host === "localhost" || host === "127.0.0.1" || host === "[::1]")) {
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
245
|
+
if (proto !== "https:")
|
|
246
|
+
return false;
|
|
247
|
+
const trustedHostPatterns = [
|
|
248
|
+
// Google / Gemini / Antigravity / AI Studio
|
|
249
|
+
/^(?:.+\.)?googleusercontent\.com$/,
|
|
250
|
+
/^(?:.+\.)?google\.com$/,
|
|
251
|
+
/^(?:.+\.)?googleapis\.com$/,
|
|
252
|
+
/^(?:.+\.)?google\.dev$/,
|
|
253
|
+
/^(?:.+\.)?antigravity\.google$/,
|
|
254
|
+
// Anthropic / Claude Connectors Directory (claude.ai + claude.com)
|
|
255
|
+
/^(?:.+\.)?claude\.ai$/,
|
|
256
|
+
/^(?:.+\.)?claude\.com$/,
|
|
257
|
+
/^(?:.+\.)?anthropic\.com$/,
|
|
258
|
+
// OpenAI / ChatGPT Apps & Connectors Directory
|
|
259
|
+
/^(?:.+\.)?chatgpt\.com$/,
|
|
260
|
+
/^(?:.+\.)?openai\.com$/,
|
|
261
|
+
// Global AI IDEs, Assistants & Agent Marketplaces
|
|
262
|
+
/^(?:.+\.)?cursor\.com$/,
|
|
263
|
+
/^(?:.+\.)?cursor\.sh$/,
|
|
264
|
+
/^(?:.+\.)?windsurf\.com$/,
|
|
265
|
+
/^(?:.+\.)?codeium\.com$/,
|
|
266
|
+
/^(?:.+\.)?perplexity\.ai$/,
|
|
267
|
+
/^(?:.+\.)?mistral\.ai$/,
|
|
268
|
+
/^(?:.+\.)?poe\.com$/,
|
|
269
|
+
/^(?:.+\.)?huggingface\.co$/,
|
|
270
|
+
/^(?:.+\.)?github\.com$/,
|
|
271
|
+
/^(?:.+\.)?vscode\.dev$/,
|
|
272
|
+
/^(?:.+\.)?raycast\.com$/,
|
|
273
|
+
// Automation & Workflow Connectors
|
|
274
|
+
/^(?:.+\.)?zapier\.com$/,
|
|
275
|
+
/^(?:.+\.)?make\.com$/,
|
|
276
|
+
/^(?:.+\.)?integromat\.com$/,
|
|
277
|
+
/^(?:.+\.)?n8n\.io$/,
|
|
278
|
+
/^(?:.+\.)?n8n\.cloud$/,
|
|
279
|
+
/^(?:.+\.)?pipedream\.com$/,
|
|
280
|
+
/^(?:.+\.)?activepieces\.com$/,
|
|
281
|
+
// Aura & Partner Ecosystem
|
|
282
|
+
/^(?:.+\.)?auraajenticai\.cloud$/,
|
|
283
|
+
/^(?:.+\.)?snehalata\.com$/,
|
|
284
|
+
// Official MCP Registries, Directories & API Clients
|
|
285
|
+
/^(?:.+\.)?glama\.ai$/,
|
|
286
|
+
/^(?:.+\.)?smithery\.ai$/,
|
|
287
|
+
/^(?:.+\.)?modelcontextprotocol\.io$/,
|
|
288
|
+
/^(?:.+\.)?postman\.com$/,
|
|
289
|
+
/^(?:.+\.)?pstmn\.io$/,
|
|
290
|
+
/^(?:.+\.)?insomnia\.rest$/,
|
|
291
|
+
];
|
|
292
|
+
return trustedHostPatterns.some((re) => re.test(host));
|
|
293
|
+
}
|
|
294
|
+
function encodeDcrClientId(payload) {
|
|
295
|
+
const b64 = Buffer.from(JSON.stringify(payload)).toString("base64url");
|
|
296
|
+
const sig = createHmac("sha256", deriveKey("client")).update(b64).digest("base64url").slice(0, 22);
|
|
297
|
+
return `aura_dcr_${b64}.${sig}`;
|
|
298
|
+
}
|
|
299
|
+
function decodeDcrClientId(clientId) {
|
|
300
|
+
if (!clientId || !clientId.startsWith("aura_dcr_"))
|
|
301
|
+
return null;
|
|
302
|
+
const raw = clientId.slice("aura_dcr_".length);
|
|
303
|
+
const dotIdx = raw.lastIndexOf(".");
|
|
304
|
+
if (dotIdx <= 0)
|
|
305
|
+
return null;
|
|
306
|
+
const b64 = raw.slice(0, dotIdx);
|
|
307
|
+
const sig = raw.slice(dotIdx + 1);
|
|
308
|
+
const expected = createHmac("sha256", deriveKey("client")).update(b64).digest("base64url").slice(0, 22);
|
|
309
|
+
if (!safeEqualStr(sig, expected))
|
|
310
|
+
return null;
|
|
311
|
+
try {
|
|
312
|
+
const parsed = JSON.parse(Buffer.from(b64, "base64url").toString("utf8"));
|
|
313
|
+
if (!parsed || !Array.isArray(parsed.r) || parsed.r.length === 0)
|
|
314
|
+
return null;
|
|
315
|
+
return parsed;
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function deriveDcrClientSecret(clientId) {
|
|
322
|
+
const digest = createHmac("sha256", deriveKey("client_secret")).update(clientId).digest("base64url");
|
|
323
|
+
return `aura_cs_${digest.slice(0, 40)}`;
|
|
324
|
+
}
|
|
325
|
+
function normalizeScopes(rawScope, allowedScopes) {
|
|
326
|
+
const allowed = allowedScopes.length ? allowedScopes : ["read"];
|
|
327
|
+
if (!rawScope || !rawScope.trim()) {
|
|
328
|
+
return [...allowed];
|
|
329
|
+
}
|
|
330
|
+
const requested = rawScope
|
|
331
|
+
.trim()
|
|
332
|
+
.split(/[\s,]+/)
|
|
333
|
+
.map((s) => s.trim().toLowerCase().replace(/^mcp:/, ""))
|
|
334
|
+
.filter((s) => VALID_SCOPES.includes(s));
|
|
335
|
+
if (requested.length === 0) {
|
|
336
|
+
return [...allowed];
|
|
337
|
+
}
|
|
338
|
+
const granted = requested.filter((s) => allowed.includes(s));
|
|
339
|
+
return granted.length > 0 ? Array.from(new Set(granted)) : [allowed[0]];
|
|
340
|
+
}
|
|
341
|
+
function verifyPkceS256(codeVerifier, expectedChallenge) {
|
|
342
|
+
if (!codeVerifier || typeof codeVerifier !== "string" || codeVerifier.length < 43 || codeVerifier.length > 128) {
|
|
343
|
+
return false;
|
|
344
|
+
}
|
|
345
|
+
const computed = createHash("sha256").update(codeVerifier).digest("base64url");
|
|
346
|
+
return safeEqualStr(computed, expectedChallenge);
|
|
347
|
+
}
|
|
348
|
+
function signCsrfToken(fields) {
|
|
349
|
+
const exp = Math.floor(Date.now() / 1000) + CSRF_TTL_SEC;
|
|
350
|
+
const data = `${fields.clientId}|${fields.redirectUri}|${fields.codeChallenge}|${fields.state}|${exp}`;
|
|
351
|
+
const sig = createHmac("sha256", deriveKey("csrf")).update(data).digest("base64url").slice(0, 24);
|
|
352
|
+
return `${exp}.${sig}`;
|
|
353
|
+
}
|
|
354
|
+
function verifyCsrfToken(token, fields) {
|
|
355
|
+
if (!token || typeof token !== "string")
|
|
356
|
+
return false;
|
|
357
|
+
const parts = token.split(".");
|
|
358
|
+
if (parts.length !== 2)
|
|
359
|
+
return false;
|
|
360
|
+
const exp = Number(parts[0]);
|
|
361
|
+
if (!Number.isFinite(exp) || exp < Math.floor(Date.now() / 1000))
|
|
362
|
+
return false;
|
|
363
|
+
const data = `${fields.clientId}|${fields.redirectUri}|${fields.codeChallenge}|${fields.state}|${exp}`;
|
|
364
|
+
const expected = createHmac("sha256", deriveKey("csrf")).update(data).digest("base64url").slice(0, 24);
|
|
365
|
+
return safeEqualStr(parts[1], expected);
|
|
366
|
+
}
|
|
367
|
+
function escapeHtml(str) {
|
|
368
|
+
if (str == null)
|
|
369
|
+
return "";
|
|
370
|
+
return String(str)
|
|
371
|
+
.replace(/&/g, "&")
|
|
372
|
+
.replace(/</g, "<")
|
|
373
|
+
.replace(/>/g, ">")
|
|
374
|
+
.replace(/"/g, """)
|
|
375
|
+
.replace(/'/g, "'");
|
|
376
|
+
}
|
|
377
|
+
function redirectWithOAuthError(res, redirectUri, error, description, state) {
|
|
378
|
+
const u = new URL(redirectUri);
|
|
379
|
+
u.searchParams.set("error", error);
|
|
380
|
+
if (description)
|
|
381
|
+
u.searchParams.set("error_description", description);
|
|
382
|
+
if (state)
|
|
383
|
+
u.searchParams.set("state", state);
|
|
384
|
+
res.redirect(302, u.toString());
|
|
385
|
+
}
|
|
386
|
+
function extractClientCredentials(req) {
|
|
387
|
+
const body = (req.body || {});
|
|
388
|
+
let clientId = typeof body.client_id === "string" ? body.client_id.trim() : undefined;
|
|
389
|
+
let clientSecret = typeof body.client_secret === "string" ? body.client_secret.trim() : undefined;
|
|
390
|
+
const authHeader = req.headers["authorization"] || req.headers["Authorization"];
|
|
391
|
+
if (typeof authHeader === "string" && authHeader.trim().toLowerCase().startsWith("basic ")) {
|
|
392
|
+
try {
|
|
393
|
+
const decoded = Buffer.from(authHeader.trim().slice(6).trim(), "base64").toString("utf8");
|
|
394
|
+
const sep = decoded.indexOf(":");
|
|
395
|
+
if (sep >= 0) {
|
|
396
|
+
const rawId = decoded.slice(0, sep);
|
|
397
|
+
const rawSec = decoded.slice(sep + 1);
|
|
398
|
+
try {
|
|
399
|
+
clientId = decodeURIComponent(rawId);
|
|
400
|
+
}
|
|
401
|
+
catch {
|
|
402
|
+
clientId = rawId;
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
clientSecret = decodeURIComponent(rawSec);
|
|
406
|
+
}
|
|
407
|
+
catch {
|
|
408
|
+
clientSecret = rawSec;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
catch {
|
|
413
|
+
// Ignore malformed Basic header
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return { clientId, clientSecret };
|
|
417
|
+
}
|
|
418
|
+
function buildAuthorizeReturnUrl(opts) {
|
|
419
|
+
const u = new URL(`${opts.origin}/oauth/authorize`);
|
|
420
|
+
u.searchParams.set("response_type", "code");
|
|
421
|
+
u.searchParams.set("client_id", opts.clientId);
|
|
422
|
+
u.searchParams.set("redirect_uri", opts.redirectUri);
|
|
423
|
+
if (opts.state)
|
|
424
|
+
u.searchParams.set("state", opts.state);
|
|
425
|
+
if (opts.scope)
|
|
426
|
+
u.searchParams.set("scope", opts.scope);
|
|
427
|
+
u.searchParams.set("code_challenge", opts.codeChallenge);
|
|
428
|
+
u.searchParams.set("code_challenge_method", opts.codeChallengeMethod || "S256");
|
|
429
|
+
if (opts.resource)
|
|
430
|
+
u.searchParams.set("resource", opts.resource);
|
|
431
|
+
return u.toString();
|
|
432
|
+
}
|
|
433
|
+
function renderConsentPage(opts) {
|
|
434
|
+
const scopes = opts.scope ? opts.scope.split(/[\s,]+/).filter(Boolean) : ["read", "write"];
|
|
435
|
+
const hasWrite = scopes.some((s) => s.toLowerCase().includes("write"));
|
|
436
|
+
const returnUrl = buildAuthorizeReturnUrl(opts);
|
|
437
|
+
const googleSignInUrl = `${AURA_AUTH_BASE}/login/google?next=${encodeURIComponent(returnUrl)}`;
|
|
438
|
+
const auraLoginUrl = `${AURA_AUTH_BASE}/login?next=${encodeURIComponent(returnUrl)}`;
|
|
439
|
+
const auraRegisterUrl = `${AURA_AUTH_BASE}/register?next=${encodeURIComponent(returnUrl)}`;
|
|
440
|
+
const tab = opts.activeTab === "apikey" ? "apikey" : "account";
|
|
441
|
+
const hiddenFields = `
|
|
442
|
+
<input type="hidden" name="client_id" value="${escapeHtml(opts.clientId)}" />
|
|
443
|
+
<input type="hidden" name="redirect_uri" value="${escapeHtml(opts.redirectUri)}" />
|
|
444
|
+
<input type="hidden" name="state" value="${escapeHtml(opts.state)}" />
|
|
445
|
+
<input type="hidden" name="scope" value="${escapeHtml(opts.scope)}" />
|
|
446
|
+
<input type="hidden" name="code_challenge" value="${escapeHtml(opts.codeChallenge)}" />
|
|
447
|
+
<input type="hidden" name="code_challenge_method" value="${escapeHtml(opts.codeChallengeMethod)}" />
|
|
448
|
+
<input type="hidden" name="resource" value="${escapeHtml(opts.resource)}" />
|
|
449
|
+
<input type="hidden" name="csrf_token" value="${escapeHtml(opts.csrfToken)}" />`;
|
|
450
|
+
const roleLabel = opts.ssoUser
|
|
451
|
+
? opts.ssoUser.role === "owner" || opts.ssoUser.role === "admin"
|
|
452
|
+
? "Workspace Owner"
|
|
453
|
+
: "Aura Merchant"
|
|
454
|
+
: "";
|
|
455
|
+
const authSectionHtml = opts.ssoUser
|
|
456
|
+
? `
|
|
457
|
+
<div class="sso-identity">
|
|
458
|
+
<div class="avatar">${escapeHtml(opts.ssoUser.email.charAt(0).toUpperCase())}</div>
|
|
459
|
+
<div class="id-meta">
|
|
460
|
+
<div class="id-email" title="${escapeHtml(opts.ssoUser.email)}">${escapeHtml(opts.ssoUser.email)}</div>
|
|
461
|
+
<div class="id-sub"><span class="role-chip">${escapeHtml(roleLabel)}</span> · <a href="${escapeHtml(auraLoginUrl)}">Switch account</a></div>
|
|
462
|
+
</div>
|
|
463
|
+
</div>
|
|
464
|
+
|
|
465
|
+
<form method="POST" action="/oauth/authorize" autocomplete="off">
|
|
466
|
+
${hiddenFields}
|
|
467
|
+
<input type="hidden" name="auth_mode" value="sso" />
|
|
468
|
+
<div class="actions">
|
|
469
|
+
<button type="submit" name="decision" value="deny" class="btn btn-secondary" formnovalidate>Cancel</button>
|
|
470
|
+
<button type="submit" name="decision" value="approve" class="btn btn-primary">Allow Access</button>
|
|
471
|
+
</div>
|
|
472
|
+
</form>`
|
|
473
|
+
: `
|
|
474
|
+
<a href="${escapeHtml(googleSignInUrl)}" class="btn-google">
|
|
475
|
+
<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true">
|
|
476
|
+
<path fill="#4285F4" d="M23.52 12.27c0-.85-.08-1.67-.22-2.45H12v4.64h6.47a5.53 5.53 0 0 1-2.4 3.63v3h3.88c2.27-2.09 3.57-5.17 3.57-8.82z"/>
|
|
477
|
+
<path fill="#34A853" d="M12 24c3.24 0 5.95-1.07 7.94-2.91l-3.88-3c-1.08.72-2.45 1.15-4.06 1.15-3.12 0-5.77-2.11-6.71-4.94H1.28v3.1A12 12 0 0 0 12 24z"/>
|
|
478
|
+
<path fill="#FBBC05" d="M5.29 14.3a7.2 7.2 0 0 1 0-4.6v-3.1H1.28a12 12 0 0 0 0 10.8z"/>
|
|
479
|
+
<path fill="#EA4335" d="M12 4.75c1.76 0 3.34.6 4.58 1.79l3.44-3.44C17.94 1.19 15.24 0 12 0A12 12 0 0 0 1.28 6.6l4.01 3.1C6.23 6.86 8.88 4.75 12 4.75z"/>
|
|
480
|
+
</svg>
|
|
481
|
+
<span>Continue with Google</span>
|
|
482
|
+
</a>
|
|
483
|
+
|
|
484
|
+
<div class="divider"><span>or continue with</span></div>
|
|
485
|
+
|
|
486
|
+
<div class="tabs" role="tablist">
|
|
487
|
+
<button type="button" id="tab-account" class="tab ${tab === "account" ? "active" : ""}" onclick="switchTab('account')">Aura Account</button>
|
|
488
|
+
<button type="button" id="tab-apikey" class="tab ${tab === "apikey" ? "active" : ""}" onclick="switchTab('apikey')">API Key</button>
|
|
489
|
+
</div>
|
|
490
|
+
|
|
491
|
+
<form id="form-account" method="POST" action="/oauth/authorize" style="display:${tab === "account" ? "block" : "none"}" autocomplete="on">
|
|
492
|
+
${hiddenFields}
|
|
493
|
+
<input type="hidden" name="auth_mode" value="password" />
|
|
494
|
+
<div class="field">
|
|
495
|
+
<label for="email">Work Email</label>
|
|
496
|
+
<input id="email" name="email" type="email" placeholder="you@company.com" autocomplete="email" required />
|
|
497
|
+
</div>
|
|
498
|
+
<div class="field">
|
|
499
|
+
<label for="password">Password</label>
|
|
500
|
+
<div class="input-wrap">
|
|
501
|
+
<input id="password" name="password" type="password" placeholder="Enter your password" autocomplete="current-password" required />
|
|
502
|
+
<button type="button" class="toggle-btn" onclick="toggleVis('password', this)">Show</button>
|
|
503
|
+
</div>
|
|
504
|
+
</div>
|
|
505
|
+
<div class="actions">
|
|
506
|
+
<button type="submit" name="decision" value="deny" class="btn btn-secondary" formnovalidate>Cancel</button>
|
|
507
|
+
<button type="submit" name="decision" value="approve" class="btn btn-primary">Sign In & Allow</button>
|
|
508
|
+
</div>
|
|
509
|
+
<div class="sub-link">New to Aura Courier? <a href="${escapeHtml(auraRegisterUrl)}">Create a free account</a></div>
|
|
510
|
+
</form>
|
|
511
|
+
|
|
512
|
+
<form id="form-apikey" method="POST" action="/oauth/authorize" style="display:${tab === "apikey" ? "block" : "none"}" autocomplete="off">
|
|
513
|
+
${hiddenFields}
|
|
514
|
+
<input type="hidden" name="auth_mode" value="apikey" />
|
|
515
|
+
<div class="field">
|
|
516
|
+
<label for="api_key">Merchant API Key</label>
|
|
517
|
+
<div class="input-wrap">
|
|
518
|
+
<input id="api_key" name="api_key" type="password" placeholder="Paste your Aura Courier API key" required />
|
|
519
|
+
<button type="button" class="toggle-btn" onclick="toggleVis('api_key', this)">Show</button>
|
|
520
|
+
</div>
|
|
521
|
+
<div class="hint">Generate or manage API keys anytime from your <a href="https://client.auraajenticai.cloud" target="_blank" rel="noopener">Aura Cloud Console</a>.</div>
|
|
522
|
+
</div>
|
|
523
|
+
<div class="actions">
|
|
524
|
+
<button type="submit" name="decision" value="deny" class="btn btn-secondary" formnovalidate>Cancel</button>
|
|
525
|
+
<button type="submit" name="decision" value="approve" class="btn btn-primary">Authorize & Connect</button>
|
|
526
|
+
</div>
|
|
527
|
+
</form>
|
|
528
|
+
|
|
529
|
+
<form method="POST" action="/oauth/authorize" class="sandbox-row">
|
|
530
|
+
${hiddenFields}
|
|
531
|
+
<input type="hidden" name="auth_mode" value="sandbox" />
|
|
532
|
+
<button type="submit" name="decision" value="sandbox" class="sandbox-btn">
|
|
533
|
+
Evaluating the integration? <span>Continue in Read-Only Sandbox →</span>
|
|
534
|
+
</button>
|
|
535
|
+
</form>`;
|
|
536
|
+
return `<!DOCTYPE html>
|
|
537
|
+
<html lang="en">
|
|
538
|
+
<head>
|
|
539
|
+
<meta charset="utf-8" />
|
|
540
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
541
|
+
<title>Authorize ${escapeHtml(opts.clientName)} — Aura Courier</title>
|
|
542
|
+
<link rel="icon" type="image/svg+xml" href="/assets/logo.svg" />
|
|
543
|
+
<style>
|
|
544
|
+
:root {
|
|
545
|
+
--bg: #070b14;
|
|
546
|
+
--surface: #0e1525;
|
|
547
|
+
--surface-2: rgba(255, 255, 255, 0.035);
|
|
548
|
+
--border: rgba(148, 163, 184, 0.16);
|
|
549
|
+
--border-strong: rgba(56, 189, 248, 0.34);
|
|
550
|
+
--accent: #06b6d4;
|
|
551
|
+
--emerald: #10b981;
|
|
552
|
+
--rose: #fb7185;
|
|
553
|
+
--text: #f8fafc;
|
|
554
|
+
--muted: #94a3b8;
|
|
555
|
+
--dim: #64748b;
|
|
556
|
+
}
|
|
557
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
558
|
+
body {
|
|
559
|
+
background:
|
|
560
|
+
radial-gradient(900px 520px at 50% -12%, rgba(6, 182, 212, 0.14), transparent 62%),
|
|
561
|
+
radial-gradient(640px 420px at 85% 95%, rgba(16, 185, 129, 0.09), transparent 55%),
|
|
562
|
+
var(--bg);
|
|
563
|
+
color: var(--text);
|
|
564
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Inter', 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
|
|
565
|
+
min-height: 100vh;
|
|
566
|
+
display: flex;
|
|
567
|
+
align-items: center;
|
|
568
|
+
justify-content: center;
|
|
569
|
+
padding: 20px;
|
|
570
|
+
-webkit-font-smoothing: antialiased;
|
|
571
|
+
}
|
|
572
|
+
.card {
|
|
573
|
+
width: 100%;
|
|
574
|
+
max-width: 448px;
|
|
575
|
+
background: var(--surface);
|
|
576
|
+
border: 1px solid var(--border);
|
|
577
|
+
border-radius: 20px;
|
|
578
|
+
padding: 28px;
|
|
579
|
+
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(255, 255, 255, 0.03) inset;
|
|
580
|
+
}
|
|
581
|
+
.header {
|
|
582
|
+
display: flex;
|
|
583
|
+
align-items: center;
|
|
584
|
+
gap: 13px;
|
|
585
|
+
margin-bottom: 20px;
|
|
586
|
+
}
|
|
587
|
+
.logo-wrap {
|
|
588
|
+
width: 44px;
|
|
589
|
+
height: 44px;
|
|
590
|
+
border-radius: 11px;
|
|
591
|
+
overflow: hidden;
|
|
592
|
+
flex-shrink: 0;
|
|
593
|
+
box-shadow: 0 6px 20px rgba(6, 182, 212, 0.22);
|
|
594
|
+
}
|
|
595
|
+
.logo-wrap svg { display: block; width: 44px; height: 44px; }
|
|
596
|
+
.header-text h1 { font-size: 17px; font-weight: 700; letter-spacing: -0.02em; color: #fff; }
|
|
597
|
+
.header-text p { font-size: 12.5px; color: var(--muted); margin-top: 2px; }
|
|
598
|
+
.client-bar {
|
|
599
|
+
display: flex;
|
|
600
|
+
align-items: center;
|
|
601
|
+
justify-content: space-between;
|
|
602
|
+
gap: 12px;
|
|
603
|
+
background: rgba(6, 182, 212, 0.07);
|
|
604
|
+
border: 1px solid rgba(6, 182, 212, 0.22);
|
|
605
|
+
border-radius: 13px;
|
|
606
|
+
padding: 11px 14px;
|
|
607
|
+
margin-bottom: 16px;
|
|
608
|
+
}
|
|
609
|
+
.client-info { min-width: 0; flex: 1; }
|
|
610
|
+
.client-title { font-size: 13.5px; font-weight: 650; color: #fff; }
|
|
611
|
+
.client-host {
|
|
612
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
613
|
+
font-size: 11px;
|
|
614
|
+
color: #67e8f9;
|
|
615
|
+
margin-top: 2px;
|
|
616
|
+
white-space: nowrap;
|
|
617
|
+
overflow: hidden;
|
|
618
|
+
text-overflow: ellipsis;
|
|
619
|
+
}
|
|
620
|
+
.badge {
|
|
621
|
+
display: inline-flex;
|
|
622
|
+
align-items: center;
|
|
623
|
+
gap: 5px;
|
|
624
|
+
font-size: 10.5px;
|
|
625
|
+
font-weight: 600;
|
|
626
|
+
color: #34d399;
|
|
627
|
+
background: rgba(16, 185, 129, 0.12);
|
|
628
|
+
border: 1px solid rgba(16, 185, 129, 0.3);
|
|
629
|
+
padding: 4px 9px;
|
|
630
|
+
border-radius: 999px;
|
|
631
|
+
white-space: nowrap;
|
|
632
|
+
flex-shrink: 0;
|
|
633
|
+
}
|
|
634
|
+
.perms {
|
|
635
|
+
background: var(--surface-2);
|
|
636
|
+
border: 1px solid var(--border);
|
|
637
|
+
border-radius: 13px;
|
|
638
|
+
padding: 13px 15px;
|
|
639
|
+
margin-bottom: 18px;
|
|
640
|
+
}
|
|
641
|
+
.perms-label {
|
|
642
|
+
font-size: 10.5px;
|
|
643
|
+
font-weight: 700;
|
|
644
|
+
letter-spacing: 0.06em;
|
|
645
|
+
text-transform: uppercase;
|
|
646
|
+
color: var(--muted);
|
|
647
|
+
margin-bottom: 9px;
|
|
648
|
+
}
|
|
649
|
+
.perms ul { list-style: none; display: grid; gap: 8px; font-size: 12.5px; color: #cbd5e1; }
|
|
650
|
+
.perms li { display: flex; align-items: flex-start; gap: 9px; line-height: 1.45; }
|
|
651
|
+
.perms svg { flex-shrink: 0; margin-top: 2px; color: var(--emerald); }
|
|
652
|
+
.err {
|
|
653
|
+
background: rgba(244, 63, 94, 0.11);
|
|
654
|
+
border: 1px solid rgba(244, 63, 94, 0.38);
|
|
655
|
+
color: #fecdd3;
|
|
656
|
+
border-radius: 11px;
|
|
657
|
+
padding: 10px 13px;
|
|
658
|
+
font-size: 12.5px;
|
|
659
|
+
margin-bottom: 15px;
|
|
660
|
+
line-height: 1.45;
|
|
661
|
+
}
|
|
662
|
+
.sso-identity {
|
|
663
|
+
display: flex;
|
|
664
|
+
align-items: center;
|
|
665
|
+
gap: 12px;
|
|
666
|
+
background: var(--surface-2);
|
|
667
|
+
border: 1px solid var(--border);
|
|
668
|
+
border-radius: 13px;
|
|
669
|
+
padding: 12px 14px;
|
|
670
|
+
margin-bottom: 18px;
|
|
671
|
+
}
|
|
672
|
+
.avatar {
|
|
673
|
+
width: 36px;
|
|
674
|
+
height: 36px;
|
|
675
|
+
border-radius: 10px;
|
|
676
|
+
background: linear-gradient(135deg, #06b6d4, #2563eb);
|
|
677
|
+
color: #fff;
|
|
678
|
+
font-weight: 700;
|
|
679
|
+
font-size: 14px;
|
|
680
|
+
display: grid;
|
|
681
|
+
place-items: center;
|
|
682
|
+
flex-shrink: 0;
|
|
683
|
+
}
|
|
684
|
+
.id-meta { min-width: 0; flex: 1; }
|
|
685
|
+
.id-email { font-size: 13.5px; font-weight: 600; color: #fff; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
|
686
|
+
.id-sub { font-size: 11.5px; color: var(--muted); margin-top: 2px; }
|
|
687
|
+
.id-sub a { color: #67e8f9; text-decoration: none; }
|
|
688
|
+
.id-sub a:hover { text-decoration: underline; }
|
|
689
|
+
.role-chip { color: #34d399; font-weight: 600; }
|
|
690
|
+
.btn-google {
|
|
691
|
+
width: 100%;
|
|
692
|
+
display: flex;
|
|
693
|
+
align-items: center;
|
|
694
|
+
justify-content: center;
|
|
695
|
+
gap: 10px;
|
|
696
|
+
background: #ffffff;
|
|
697
|
+
color: #0f172a;
|
|
698
|
+
font-size: 13.5px;
|
|
699
|
+
font-weight: 650;
|
|
700
|
+
text-decoration: none;
|
|
701
|
+
padding: 11px 14px;
|
|
702
|
+
border-radius: 11px;
|
|
703
|
+
border: 1px solid rgba(255, 255, 255, 0.2);
|
|
704
|
+
transition: background 0.15s, transform 0.1s;
|
|
705
|
+
}
|
|
706
|
+
.btn-google:hover { background: #f1f5f9; }
|
|
707
|
+
.divider {
|
|
708
|
+
display: flex;
|
|
709
|
+
align-items: center;
|
|
710
|
+
gap: 12px;
|
|
711
|
+
margin: 15px 0 13px;
|
|
712
|
+
color: var(--dim);
|
|
713
|
+
font-size: 11.5px;
|
|
714
|
+
}
|
|
715
|
+
.divider::before, .divider::after { content: ''; flex: 1; height: 1px; background: var(--border); }
|
|
716
|
+
.tabs {
|
|
717
|
+
display: grid;
|
|
718
|
+
grid-template-columns: 1fr 1fr;
|
|
719
|
+
gap: 4px;
|
|
720
|
+
background: rgba(2, 6, 17, 0.7);
|
|
721
|
+
border: 1px solid var(--border);
|
|
722
|
+
border-radius: 11px;
|
|
723
|
+
padding: 3px;
|
|
724
|
+
margin-bottom: 14px;
|
|
725
|
+
}
|
|
726
|
+
.tab {
|
|
727
|
+
background: transparent;
|
|
728
|
+
border: none;
|
|
729
|
+
color: var(--muted);
|
|
730
|
+
font-size: 12.5px;
|
|
731
|
+
font-weight: 600;
|
|
732
|
+
padding: 8px 10px;
|
|
733
|
+
border-radius: 8px;
|
|
734
|
+
cursor: pointer;
|
|
735
|
+
transition: background 0.15s, color 0.15s;
|
|
736
|
+
}
|
|
737
|
+
.tab.active { background: rgba(56, 189, 248, 0.14); color: #fff; }
|
|
738
|
+
.field { margin-bottom: 12px; }
|
|
739
|
+
label { display: block; font-size: 12px; font-weight: 600; color: #cbd5e1; margin-bottom: 6px; }
|
|
740
|
+
.input-wrap { position: relative; }
|
|
741
|
+
input[type="email"], input[type="password"], input[type="text"] {
|
|
742
|
+
width: 100%;
|
|
743
|
+
background: #060a14;
|
|
744
|
+
border: 1px solid rgba(148, 163, 184, 0.24);
|
|
745
|
+
border-radius: 10px;
|
|
746
|
+
padding: 10.5px 13px;
|
|
747
|
+
color: #fff;
|
|
748
|
+
font-size: 13.5px;
|
|
749
|
+
outline: none;
|
|
750
|
+
transition: border-color 0.15s, box-shadow 0.15s;
|
|
751
|
+
}
|
|
752
|
+
.input-wrap input { padding-right: 54px; }
|
|
753
|
+
input:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(6, 182, 212, 0.15); }
|
|
754
|
+
.toggle-btn {
|
|
755
|
+
position: absolute;
|
|
756
|
+
right: 9px;
|
|
757
|
+
top: 50%;
|
|
758
|
+
transform: translateY(-50%);
|
|
759
|
+
background: transparent;
|
|
760
|
+
border: none;
|
|
761
|
+
color: var(--muted);
|
|
762
|
+
font-size: 11.5px;
|
|
763
|
+
font-weight: 600;
|
|
764
|
+
cursor: pointer;
|
|
765
|
+
padding: 4px 6px;
|
|
766
|
+
}
|
|
767
|
+
.hint { font-size: 11.5px; color: var(--muted); margin-top: 6px; line-height: 1.45; }
|
|
768
|
+
.hint a { color: #67e8f9; text-decoration: none; }
|
|
769
|
+
.hint a:hover { text-decoration: underline; }
|
|
770
|
+
.actions { display: grid; grid-template-columns: 1fr 1.65fr; gap: 10px; margin-top: 14px; }
|
|
771
|
+
.btn {
|
|
772
|
+
border-radius: 11px;
|
|
773
|
+
padding: 11.5px 14px;
|
|
774
|
+
font-size: 13.5px;
|
|
775
|
+
font-weight: 650;
|
|
776
|
+
cursor: pointer;
|
|
777
|
+
border: none;
|
|
778
|
+
transition: opacity 0.15s, transform 0.1s;
|
|
779
|
+
}
|
|
780
|
+
.btn:active { transform: scale(0.99); }
|
|
781
|
+
.btn-secondary {
|
|
782
|
+
background: rgba(255, 255, 255, 0.05);
|
|
783
|
+
border: 1px solid rgba(255, 255, 255, 0.14);
|
|
784
|
+
color: #cbd5e1;
|
|
785
|
+
}
|
|
786
|
+
.btn-secondary:hover { background: rgba(255, 255, 255, 0.09); }
|
|
787
|
+
.btn-primary {
|
|
788
|
+
background: linear-gradient(135deg, #06b6d4, #10b981);
|
|
789
|
+
color: #03111a;
|
|
790
|
+
font-weight: 750;
|
|
791
|
+
}
|
|
792
|
+
.btn-primary:hover { opacity: 0.94; }
|
|
793
|
+
.sub-link { text-align: center; font-size: 12px; color: var(--muted); margin-top: 12px; }
|
|
794
|
+
.sub-link a { color: #67e8f9; text-decoration: none; font-weight: 500; }
|
|
795
|
+
.sub-link a:hover { text-decoration: underline; }
|
|
796
|
+
.sandbox-row {
|
|
797
|
+
margin-top: 16px;
|
|
798
|
+
padding-top: 14px;
|
|
799
|
+
border-top: 1px solid var(--border);
|
|
800
|
+
text-align: center;
|
|
801
|
+
}
|
|
802
|
+
.sandbox-btn {
|
|
803
|
+
background: transparent;
|
|
804
|
+
border: none;
|
|
805
|
+
color: var(--muted);
|
|
806
|
+
font-size: 12px;
|
|
807
|
+
cursor: pointer;
|
|
808
|
+
padding: 4px 6px;
|
|
809
|
+
}
|
|
810
|
+
.sandbox-btn span { color: #67e8f9; font-weight: 600; }
|
|
811
|
+
.sandbox-btn:hover span { text-decoration: underline; }
|
|
812
|
+
.foot {
|
|
813
|
+
margin-top: 16px;
|
|
814
|
+
text-align: center;
|
|
815
|
+
font-size: 11px;
|
|
816
|
+
color: var(--dim);
|
|
817
|
+
}
|
|
818
|
+
.foot a { color: var(--muted); text-decoration: none; }
|
|
819
|
+
.foot a:hover { color: #fff; }
|
|
820
|
+
</style>
|
|
821
|
+
</head>
|
|
822
|
+
<body>
|
|
823
|
+
<div class="card">
|
|
824
|
+
<div class="header">
|
|
825
|
+
<div class="logo-wrap">${INLINE_LOGO_SVG}</div>
|
|
826
|
+
<div class="header-text">
|
|
827
|
+
<h1>Authorize ${escapeHtml(opts.clientName)}</h1>
|
|
828
|
+
<p>Aura Courier MCP · Enterprise Logistics Hub</p>
|
|
829
|
+
</div>
|
|
830
|
+
</div>
|
|
831
|
+
|
|
832
|
+
<div class="client-bar">
|
|
833
|
+
<div class="client-info">
|
|
834
|
+
<div class="client-title">${escapeHtml(opts.clientName)}</div>
|
|
835
|
+
<div class="client-host" title="${escapeHtml(opts.redirectHost)}">${escapeHtml(opts.redirectHost)}</div>
|
|
836
|
+
</div>
|
|
837
|
+
<span class="badge">
|
|
838
|
+
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
|
|
839
|
+
OAuth 2.1
|
|
840
|
+
</span>
|
|
841
|
+
</div>
|
|
842
|
+
|
|
843
|
+
<div class="perms">
|
|
844
|
+
<div class="perms-label">Permissions Requested</div>
|
|
845
|
+
<ul>
|
|
846
|
+
<li>
|
|
847
|
+
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>
|
|
848
|
+
<span><strong>Read logistics data:</strong> Track consignments, check COD balances, assess fraud risk, geocode addresses, and compare carrier rates.</span>
|
|
849
|
+
</li>
|
|
850
|
+
${hasWrite
|
|
851
|
+
? `<li>
|
|
852
|
+
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>
|
|
853
|
+
<span><strong>Manage parcels:</strong> Create, update, and cancel shipments across connected carriers (within your workspace permissions).</span>
|
|
854
|
+
</li>`
|
|
855
|
+
: ""}
|
|
856
|
+
</ul>
|
|
857
|
+
</div>
|
|
858
|
+
|
|
859
|
+
${opts.errorMessage ? `<div class="err">${escapeHtml(opts.errorMessage)}</div>` : ""}
|
|
860
|
+
|
|
861
|
+
${authSectionHtml}
|
|
862
|
+
|
|
863
|
+
<div class="foot">
|
|
864
|
+
Protected by <a href="https://auraajenticai.cloud" target="_blank" rel="noopener">Aura Ajentic AI</a> · <a href="/privacy" target="_blank" rel="noopener">Privacy</a> · <a href="/terms" target="_blank" rel="noopener">Terms</a> · <a href="/guide" target="_blank" rel="noopener">Docs</a>
|
|
865
|
+
</div>
|
|
866
|
+
</div>
|
|
867
|
+
<script>
|
|
868
|
+
function switchTab(mode) {
|
|
869
|
+
var isAcc = mode === 'account';
|
|
870
|
+
document.getElementById('tab-account').className = 'tab' + (isAcc ? ' active' : '');
|
|
871
|
+
document.getElementById('tab-apikey').className = 'tab' + (!isAcc ? ' active' : '');
|
|
872
|
+
document.getElementById('form-account').style.display = isAcc ? 'block' : 'none';
|
|
873
|
+
document.getElementById('form-apikey').style.display = !isAcc ? 'block' : 'none';
|
|
874
|
+
}
|
|
875
|
+
function toggleVis(id, btn) {
|
|
876
|
+
var el = document.getElementById(id);
|
|
877
|
+
if (!el) return;
|
|
878
|
+
el.type = el.type === 'password' ? 'text' : 'password';
|
|
879
|
+
btn.textContent = el.type === 'password' ? 'Show' : 'Hide';
|
|
880
|
+
}
|
|
881
|
+
</script>
|
|
882
|
+
</body>
|
|
883
|
+
</html>`;
|
|
884
|
+
}
|
|
885
|
+
function resolveClientMeta(clientId, redirectUri) {
|
|
886
|
+
if (!clientId) {
|
|
887
|
+
return { valid: false, clientName: "Unknown Client", authMethod: "none", error: "Missing client_id." };
|
|
888
|
+
}
|
|
889
|
+
if (!isAllowedRedirectUri(redirectUri)) {
|
|
890
|
+
return {
|
|
891
|
+
valid: false,
|
|
892
|
+
clientName: "Unknown Client",
|
|
893
|
+
authMethod: "none",
|
|
894
|
+
error: "redirect_uri is missing or not in the trusted OAuth redirect allowlist.",
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
if (clientId.startsWith("aura_dcr_")) {
|
|
898
|
+
const dcr = decodeDcrClientId(clientId);
|
|
899
|
+
if (!dcr) {
|
|
900
|
+
return {
|
|
901
|
+
valid: false,
|
|
902
|
+
clientName: "Unknown Client",
|
|
903
|
+
authMethod: "none",
|
|
904
|
+
error: "Invalid or tampered dynamically registered client_id.",
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
if (!dcr.r.includes(redirectUri)) {
|
|
908
|
+
return {
|
|
909
|
+
valid: false,
|
|
910
|
+
clientName: dcr.n || "MCP Client",
|
|
911
|
+
authMethod: dcr.m,
|
|
912
|
+
error: "redirect_uri does not match the client's registered redirect_uris.",
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
return { valid: true, clientName: dcr.n || "MCP Client", authMethod: dcr.m };
|
|
916
|
+
}
|
|
917
|
+
let inferredName = clientId.slice(0, 48);
|
|
918
|
+
try {
|
|
919
|
+
const h = new URL(redirectUri).hostname.toLowerCase();
|
|
920
|
+
if (h.includes("googleusercontent.com") || h.includes("google.com"))
|
|
921
|
+
inferredName = "Google Gemini";
|
|
922
|
+
else if (h.includes("claude.ai") || h.includes("claude.com") || h.includes("anthropic.com"))
|
|
923
|
+
inferredName = "Claude";
|
|
924
|
+
else if (h.includes("chatgpt.com") || h.includes("openai.com"))
|
|
925
|
+
inferredName = "ChatGPT";
|
|
926
|
+
}
|
|
927
|
+
catch { }
|
|
928
|
+
return { valid: true, clientName: inferredName, authMethod: "none" };
|
|
929
|
+
}
|
|
930
|
+
export function registerOAuthRoutes(app) {
|
|
931
|
+
// 1. RFC 9728 — OAuth 2.0 Protected Resource Metadata (root + /mcp path-inserted variant)
|
|
932
|
+
const protectedResourceHandler = (req, res) => {
|
|
933
|
+
const origin = getPublicOrigin(req);
|
|
934
|
+
res.setHeader("Cache-Control", "public, max-age=300");
|
|
935
|
+
return res.json({
|
|
936
|
+
resource: `${origin}/mcp`,
|
|
937
|
+
authorization_servers: [origin],
|
|
938
|
+
bearer_methods_supported: ["header"],
|
|
939
|
+
scopes_supported: ["read", "write"],
|
|
940
|
+
resource_name: "Aura Courier MCP",
|
|
941
|
+
resource_documentation: `${origin}/guide`,
|
|
942
|
+
});
|
|
943
|
+
};
|
|
944
|
+
app.get("/.well-known/oauth-protected-resource", protectedResourceHandler);
|
|
945
|
+
app.get("/.well-known/oauth-protected-resource/mcp", protectedResourceHandler);
|
|
946
|
+
// 2. RFC 8414 — OAuth 2.0 Authorization Server Metadata (+ OIDC discovery fallback)
|
|
947
|
+
const authServerMetadataHandler = (req, res) => {
|
|
948
|
+
const origin = getPublicOrigin(req);
|
|
949
|
+
res.setHeader("Cache-Control", "public, max-age=300");
|
|
950
|
+
return res.json({
|
|
951
|
+
issuer: origin,
|
|
952
|
+
authorization_endpoint: `${origin}/oauth/authorize`,
|
|
953
|
+
token_endpoint: `${origin}/oauth/token`,
|
|
954
|
+
registration_endpoint: `${origin}/oauth/register`,
|
|
955
|
+
revocation_endpoint: `${origin}/oauth/revoke`,
|
|
956
|
+
response_types_supported: ["code"],
|
|
957
|
+
response_modes_supported: ["query"],
|
|
958
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
959
|
+
token_endpoint_auth_methods_supported: ["none", "client_secret_post", "client_secret_basic"],
|
|
960
|
+
code_challenge_methods_supported: ["S256"],
|
|
961
|
+
scopes_supported: ["read", "write"],
|
|
962
|
+
service_documentation: `${origin}/guide`,
|
|
963
|
+
});
|
|
964
|
+
};
|
|
965
|
+
app.get("/.well-known/oauth-authorization-server", authServerMetadataHandler);
|
|
966
|
+
app.get("/.well-known/oauth-authorization-server/mcp", authServerMetadataHandler);
|
|
967
|
+
app.get("/.well-known/openid-configuration", authServerMetadataHandler);
|
|
968
|
+
// 3. RFC 7591 — Dynamic Client Registration (stateless HMAC-signed client_id, restart-proof)
|
|
969
|
+
app.post("/oauth/register", (req, res) => {
|
|
970
|
+
res.setHeader("Cache-Control", "no-store");
|
|
971
|
+
const body = (req.body || {});
|
|
972
|
+
const rawUris = body.redirect_uris;
|
|
973
|
+
if (!Array.isArray(rawUris) || rawUris.length === 0 || rawUris.length > 8) {
|
|
974
|
+
return res.status(400).json({
|
|
975
|
+
error: "invalid_client_metadata",
|
|
976
|
+
error_description: "redirect_uris must be a non-empty array (max 8 URIs).",
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
const redirectUris = [];
|
|
980
|
+
for (const u of rawUris) {
|
|
981
|
+
if (typeof u !== "string" || !isAllowedRedirectUri(u.trim())) {
|
|
982
|
+
return res.status(400).json({
|
|
983
|
+
error: "invalid_redirect_uri",
|
|
984
|
+
error_description: `Redirect URI is not permitted: ${String(u)}`,
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
redirectUris.push(u.trim());
|
|
988
|
+
}
|
|
989
|
+
const clientName = typeof body.client_name === "string" && body.client_name.trim()
|
|
990
|
+
? body.client_name.trim().slice(0, 64)
|
|
991
|
+
: "MCP Client";
|
|
992
|
+
const requestedAuthMethod = String(body.token_endpoint_auth_method || "none").trim();
|
|
993
|
+
const authMethod = requestedAuthMethod === "client_secret_post" || requestedAuthMethod === "client_secret_basic"
|
|
994
|
+
? requestedAuthMethod
|
|
995
|
+
: "none";
|
|
996
|
+
const iat = Math.floor(Date.now() / 1000);
|
|
997
|
+
const clientId = encodeDcrClientId({
|
|
998
|
+
n: clientName,
|
|
999
|
+
r: redirectUris,
|
|
1000
|
+
m: authMethod,
|
|
1001
|
+
iat,
|
|
1002
|
+
});
|
|
1003
|
+
const responsePayload = {
|
|
1004
|
+
client_id: clientId,
|
|
1005
|
+
client_id_issued_at: iat,
|
|
1006
|
+
client_name: clientName,
|
|
1007
|
+
redirect_uris: redirectUris,
|
|
1008
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
1009
|
+
response_types: ["code"],
|
|
1010
|
+
token_endpoint_auth_method: authMethod,
|
|
1011
|
+
};
|
|
1012
|
+
if (authMethod !== "none") {
|
|
1013
|
+
responsePayload.client_secret = deriveDcrClientSecret(clientId);
|
|
1014
|
+
responsePayload.client_secret_expires_at = 0;
|
|
1015
|
+
}
|
|
1016
|
+
return res.status(201).json(responsePayload);
|
|
1017
|
+
});
|
|
1018
|
+
// 4. OAuth 2.1 Authorization Endpoint (GET Consent UI — 1-Click SSO, Google Sign-In, Email/Password, API Key, Sandbox)
|
|
1019
|
+
app.get("/oauth/authorize", (req, res) => {
|
|
1020
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1021
|
+
res.setHeader("X-Frame-Options", "DENY");
|
|
1022
|
+
res.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
|
|
1023
|
+
const q = (req.query || {});
|
|
1024
|
+
const responseType = String(q.response_type || "").trim();
|
|
1025
|
+
const clientId = String(q.client_id || "").trim();
|
|
1026
|
+
const redirectUri = String(q.redirect_uri || "").trim();
|
|
1027
|
+
const state = String(q.state || "").trim();
|
|
1028
|
+
const scope = String(q.scope || "read write").trim();
|
|
1029
|
+
const codeChallenge = String(q.code_challenge || "").trim();
|
|
1030
|
+
const codeChallengeMethod = String(q.code_challenge_method || "S256").trim();
|
|
1031
|
+
const resource = String(q.resource || "").trim();
|
|
1032
|
+
const clientCheck = resolveClientMeta(clientId, redirectUri);
|
|
1033
|
+
if (!clientCheck.valid) {
|
|
1034
|
+
return res.status(400).json({
|
|
1035
|
+
error: "invalid_request",
|
|
1036
|
+
error_description: clientCheck.error || "Invalid client_id or redirect_uri.",
|
|
1037
|
+
});
|
|
1038
|
+
}
|
|
1039
|
+
if (responseType !== "code") {
|
|
1040
|
+
return redirectWithOAuthError(res, redirectUri, "unsupported_response_type", "Only response_type=code is supported.", state);
|
|
1041
|
+
}
|
|
1042
|
+
if (!codeChallenge || codeChallenge.length < 43 || codeChallenge.length > 128) {
|
|
1043
|
+
return redirectWithOAuthError(res, redirectUri, "invalid_request", "PKCE code_challenge (S256) is required by OAuth 2.1.", state);
|
|
1044
|
+
}
|
|
1045
|
+
if (codeChallengeMethod !== "S256") {
|
|
1046
|
+
return redirectWithOAuthError(res, redirectUri, "invalid_request", "Only PKCE code_challenge_method=S256 is supported.", state);
|
|
1047
|
+
}
|
|
1048
|
+
const origin = getPublicOrigin(req);
|
|
1049
|
+
let redirectHost = redirectUri;
|
|
1050
|
+
try {
|
|
1051
|
+
redirectHost = new URL(redirectUri).host || redirectUri;
|
|
1052
|
+
}
|
|
1053
|
+
catch { }
|
|
1054
|
+
const csrfToken = signCsrfToken({
|
|
1055
|
+
clientId,
|
|
1056
|
+
redirectUri,
|
|
1057
|
+
codeChallenge,
|
|
1058
|
+
state,
|
|
1059
|
+
});
|
|
1060
|
+
const ssoUser = verifyAuraSsoCookie(req);
|
|
1061
|
+
return res.status(200).type("html").send(renderConsentPage({
|
|
1062
|
+
origin,
|
|
1063
|
+
clientName: clientCheck.clientName,
|
|
1064
|
+
redirectHost,
|
|
1065
|
+
clientId,
|
|
1066
|
+
redirectUri,
|
|
1067
|
+
state,
|
|
1068
|
+
scope,
|
|
1069
|
+
codeChallenge,
|
|
1070
|
+
codeChallengeMethod: "S256",
|
|
1071
|
+
resource: resource || `${origin}/mcp`,
|
|
1072
|
+
csrfToken,
|
|
1073
|
+
ssoUser,
|
|
1074
|
+
}));
|
|
1075
|
+
});
|
|
1076
|
+
// 5. OAuth 2.1 Authorization Endpoint (POST Consent Submission)
|
|
1077
|
+
app.post("/oauth/authorize", async (req, res) => {
|
|
1078
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1079
|
+
res.setHeader("X-Frame-Options", "DENY");
|
|
1080
|
+
res.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
|
|
1081
|
+
const b = (req.body || {});
|
|
1082
|
+
const clientId = String(b.client_id || "").trim();
|
|
1083
|
+
const redirectUri = String(b.redirect_uri || "").trim();
|
|
1084
|
+
const state = String(b.state || "").trim();
|
|
1085
|
+
const scope = String(b.scope || "read write").trim();
|
|
1086
|
+
const codeChallenge = String(b.code_challenge || "").trim();
|
|
1087
|
+
const codeChallengeMethod = String(b.code_challenge_method || "S256").trim();
|
|
1088
|
+
const resource = String(b.resource || "").trim();
|
|
1089
|
+
const csrfToken = String(b.csrf_token || "").trim();
|
|
1090
|
+
const decision = String(b.decision || "approve").trim().toLowerCase();
|
|
1091
|
+
const authMode = String(b.auth_mode || (b.api_key ? "apikey" : "sso")).trim().toLowerCase();
|
|
1092
|
+
const clientCheck = resolveClientMeta(clientId, redirectUri);
|
|
1093
|
+
if (!clientCheck.valid) {
|
|
1094
|
+
return res.status(400).json({
|
|
1095
|
+
error: "invalid_request",
|
|
1096
|
+
error_description: clientCheck.error || "Invalid client_id or redirect_uri.",
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
if (!codeChallenge ||
|
|
1100
|
+
codeChallengeMethod !== "S256" ||
|
|
1101
|
+
!verifyCsrfToken(csrfToken, { clientId, redirectUri, codeChallenge, state })) {
|
|
1102
|
+
return redirectWithOAuthError(res, redirectUri, "invalid_request", "Authorization session expired or invalid. Please retry connecting.", state);
|
|
1103
|
+
}
|
|
1104
|
+
if (decision === "deny") {
|
|
1105
|
+
return redirectWithOAuthError(res, redirectUri, "access_denied", "The user denied the authorization request.", state);
|
|
1106
|
+
}
|
|
1107
|
+
const origin = getPublicOrigin(req);
|
|
1108
|
+
let redirectHost = redirectUri;
|
|
1109
|
+
try {
|
|
1110
|
+
redirectHost = new URL(redirectUri).host || redirectUri;
|
|
1111
|
+
}
|
|
1112
|
+
catch { }
|
|
1113
|
+
const ssoUser = verifyAuraSsoCookie(req);
|
|
1114
|
+
const renderFailure = (errorMessage, activeTab = "account") => {
|
|
1115
|
+
const freshCsrf = signCsrfToken({ clientId, redirectUri, codeChallenge, state });
|
|
1116
|
+
return res.status(200).type("html").send(renderConsentPage({
|
|
1117
|
+
origin,
|
|
1118
|
+
clientName: clientCheck.clientName,
|
|
1119
|
+
redirectHost,
|
|
1120
|
+
clientId,
|
|
1121
|
+
redirectUri,
|
|
1122
|
+
state,
|
|
1123
|
+
scope,
|
|
1124
|
+
codeChallenge,
|
|
1125
|
+
codeChallengeMethod: "S256",
|
|
1126
|
+
resource: resource || `${origin}/mcp`,
|
|
1127
|
+
csrfToken: freshCsrf,
|
|
1128
|
+
ssoUser,
|
|
1129
|
+
activeTab,
|
|
1130
|
+
errorMessage,
|
|
1131
|
+
}));
|
|
1132
|
+
};
|
|
1133
|
+
let resolvedTenantId = "";
|
|
1134
|
+
let resolvedAdmin = false;
|
|
1135
|
+
let resolvedScopes = [];
|
|
1136
|
+
if (decision === "sandbox" || authMode === "sandbox") {
|
|
1137
|
+
// Strictly Read-Only Sandbox mode for evaluators / Antigravity Marketplace / Gemini reviewers
|
|
1138
|
+
resolvedTenantId = "public_ro";
|
|
1139
|
+
resolvedAdmin = false;
|
|
1140
|
+
resolvedScopes = ["read"];
|
|
1141
|
+
}
|
|
1142
|
+
else if (authMode === "sso") {
|
|
1143
|
+
if (!ssoUser) {
|
|
1144
|
+
return renderFailure("Your Aura session has expired. Please sign in again to continue.", "account");
|
|
1145
|
+
}
|
|
1146
|
+
const mapped = mapSsoUserToAuth(ssoUser);
|
|
1147
|
+
resolvedTenantId = mapped.tenantId;
|
|
1148
|
+
resolvedAdmin = mapped.isAdmin;
|
|
1149
|
+
resolvedScopes = mapped.scopes;
|
|
1150
|
+
}
|
|
1151
|
+
else if (authMode === "password") {
|
|
1152
|
+
const email = String(b.email || "").trim();
|
|
1153
|
+
const password = String(b.password || "");
|
|
1154
|
+
if (!email || !password) {
|
|
1155
|
+
return renderFailure("Please enter both your email address and password.", "account");
|
|
1156
|
+
}
|
|
1157
|
+
const loginRes = await authenticateWithAuraPassword(email, password);
|
|
1158
|
+
if (!loginRes.ok || !loginRes.user) {
|
|
1159
|
+
return renderFailure(loginRes.error || "Invalid email or password.", "account");
|
|
1160
|
+
}
|
|
1161
|
+
const mapped = mapSsoUserToAuth(loginRes.user);
|
|
1162
|
+
resolvedTenantId = mapped.tenantId;
|
|
1163
|
+
resolvedAdmin = mapped.isAdmin;
|
|
1164
|
+
resolvedScopes = mapped.scopes;
|
|
1165
|
+
}
|
|
1166
|
+
else {
|
|
1167
|
+
// Developer / Merchant API Key authentication (Master, Dynamic PG, Env, or Partner keys)
|
|
1168
|
+
const apiKey = String(b.api_key || "").trim();
|
|
1169
|
+
if (!apiKey) {
|
|
1170
|
+
return renderFailure("Please enter a valid Aura Courier API key.", "apikey");
|
|
1171
|
+
}
|
|
1172
|
+
const syntheticReq = {
|
|
1173
|
+
headers: { authorization: `Bearer ${apiKey}` },
|
|
1174
|
+
query: {},
|
|
1175
|
+
};
|
|
1176
|
+
const authCtx = await resolveAuthContextAsync(syntheticReq);
|
|
1177
|
+
if (!authCtx.authenticated) {
|
|
1178
|
+
return renderFailure(authCtx.deniedReason || "Invalid API key. Please verify your key in Aura Cloud Console and try again.", "apikey");
|
|
1179
|
+
}
|
|
1180
|
+
resolvedTenantId = authCtx.tenantId;
|
|
1181
|
+
resolvedAdmin = authCtx.isAdmin;
|
|
1182
|
+
resolvedScopes = authCtx.scopes;
|
|
1183
|
+
}
|
|
1184
|
+
const grantedScopes = normalizeScopes(scope, resolvedScopes);
|
|
1185
|
+
const nowSec = Math.floor(Date.now() / 1000);
|
|
1186
|
+
const codeClaims = {
|
|
1187
|
+
cid: clientId,
|
|
1188
|
+
ru: redirectUri,
|
|
1189
|
+
cc: codeChallenge,
|
|
1190
|
+
ccm: "S256",
|
|
1191
|
+
scp: grantedScopes,
|
|
1192
|
+
sub: resolvedTenantId,
|
|
1193
|
+
adm: resolvedAdmin,
|
|
1194
|
+
res: resource || `${origin}/mcp`,
|
|
1195
|
+
typ: "code",
|
|
1196
|
+
iat: nowSec,
|
|
1197
|
+
exp: nowSec + AUTH_CODE_TTL_SEC,
|
|
1198
|
+
jti: randomBytes(16).toString("base64url"),
|
|
1199
|
+
};
|
|
1200
|
+
const code = signJwt(codeClaims, "code");
|
|
1201
|
+
const callback = new URL(redirectUri);
|
|
1202
|
+
callback.searchParams.set("code", code);
|
|
1203
|
+
if (state)
|
|
1204
|
+
callback.searchParams.set("state", state);
|
|
1205
|
+
return res.redirect(302, callback.toString());
|
|
1206
|
+
});
|
|
1207
|
+
// 6. OAuth 2.1 Token Endpoint (Authorization Code + PKCE S256 & Non-Rotating Refresh Token)
|
|
1208
|
+
app.post("/oauth/token", (req, res) => {
|
|
1209
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1210
|
+
res.setHeader("Pragma", "no-cache");
|
|
1211
|
+
const b = (req.body || {});
|
|
1212
|
+
const grantType = String(b.grant_type || "").trim();
|
|
1213
|
+
const { clientId, clientSecret } = extractClientCredentials(req);
|
|
1214
|
+
if (clientId && clientId.startsWith("aura_dcr_")) {
|
|
1215
|
+
const dcr = decodeDcrClientId(clientId);
|
|
1216
|
+
if (!dcr) {
|
|
1217
|
+
return res.status(401).json({
|
|
1218
|
+
error: "invalid_client",
|
|
1219
|
+
error_description: "Unknown or invalid client_id.",
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
if (dcr.m !== "none") {
|
|
1223
|
+
const expectedSecret = deriveDcrClientSecret(clientId);
|
|
1224
|
+
if (!clientSecret || !safeEqualStr(clientSecret, expectedSecret)) {
|
|
1225
|
+
return res.status(401).json({
|
|
1226
|
+
error: "invalid_client",
|
|
1227
|
+
error_description: "Invalid client_secret.",
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
const origin = getPublicOrigin(req);
|
|
1233
|
+
if (grantType === "authorization_code") {
|
|
1234
|
+
const code = String(b.code || "").trim();
|
|
1235
|
+
const codeVerifier = String(b.code_verifier || "").trim();
|
|
1236
|
+
const redirectUri = typeof b.redirect_uri === "string" ? b.redirect_uri.trim() : "";
|
|
1237
|
+
if (!code || !codeVerifier) {
|
|
1238
|
+
return res.status(400).json({
|
|
1239
|
+
error: "invalid_request",
|
|
1240
|
+
error_description: "Both code and PKCE code_verifier are required.",
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
const codeClaims = verifyJwt(code, "code", "code");
|
|
1244
|
+
if (!codeClaims) {
|
|
1245
|
+
return res.status(400).json({
|
|
1246
|
+
error: "invalid_grant",
|
|
1247
|
+
error_description: "Authorization code is invalid or expired.",
|
|
1248
|
+
});
|
|
1249
|
+
}
|
|
1250
|
+
if (usedAuthCodes.has(codeClaims.jti)) {
|
|
1251
|
+
return res.status(400).json({
|
|
1252
|
+
error: "invalid_grant",
|
|
1253
|
+
error_description: "Authorization code has already been used.",
|
|
1254
|
+
});
|
|
1255
|
+
}
|
|
1256
|
+
if (clientId && codeClaims.cid !== clientId) {
|
|
1257
|
+
return res.status(400).json({
|
|
1258
|
+
error: "invalid_grant",
|
|
1259
|
+
error_description: "client_id does not match authorization code.",
|
|
1260
|
+
});
|
|
1261
|
+
}
|
|
1262
|
+
if (redirectUri && codeClaims.ru !== redirectUri) {
|
|
1263
|
+
return res.status(400).json({
|
|
1264
|
+
error: "invalid_grant",
|
|
1265
|
+
error_description: "redirect_uri does not match authorization code.",
|
|
1266
|
+
});
|
|
1267
|
+
}
|
|
1268
|
+
if (!verifyPkceS256(codeVerifier, codeClaims.cc)) {
|
|
1269
|
+
return res.status(400).json({
|
|
1270
|
+
error: "invalid_grant",
|
|
1271
|
+
error_description: "PKCE S256 code_verifier verification failed.",
|
|
1272
|
+
});
|
|
1273
|
+
}
|
|
1274
|
+
usedAuthCodes.set(codeClaims.jti, Date.now() + AUTH_CODE_TTL_SEC * 1000 * 2);
|
|
1275
|
+
const nowSec = Math.floor(Date.now() / 1000);
|
|
1276
|
+
const accessClaims = {
|
|
1277
|
+
iss: origin,
|
|
1278
|
+
aud: codeClaims.res || `${origin}/mcp`,
|
|
1279
|
+
sub: codeClaims.sub,
|
|
1280
|
+
adm: codeClaims.adm,
|
|
1281
|
+
scp: codeClaims.scp,
|
|
1282
|
+
cid: codeClaims.cid,
|
|
1283
|
+
typ: "at",
|
|
1284
|
+
iat: nowSec,
|
|
1285
|
+
exp: nowSec + ACCESS_TOKEN_TTL_SEC,
|
|
1286
|
+
jti: randomBytes(16).toString("base64url"),
|
|
1287
|
+
};
|
|
1288
|
+
const refreshClaims = {
|
|
1289
|
+
iss: origin,
|
|
1290
|
+
aud: codeClaims.res || `${origin}/mcp`,
|
|
1291
|
+
sub: codeClaims.sub,
|
|
1292
|
+
adm: codeClaims.adm,
|
|
1293
|
+
scp: codeClaims.scp,
|
|
1294
|
+
cid: codeClaims.cid,
|
|
1295
|
+
typ: "rt",
|
|
1296
|
+
iat: nowSec,
|
|
1297
|
+
exp: nowSec + REFRESH_TOKEN_TTL_SEC,
|
|
1298
|
+
jti: randomBytes(16).toString("base64url"),
|
|
1299
|
+
};
|
|
1300
|
+
const accessToken = signJwt(accessClaims, "access");
|
|
1301
|
+
const refreshToken = signJwt(refreshClaims, "refresh");
|
|
1302
|
+
return res.status(200).json({
|
|
1303
|
+
access_token: accessToken,
|
|
1304
|
+
token_type: "Bearer",
|
|
1305
|
+
expires_in: ACCESS_TOKEN_TTL_SEC,
|
|
1306
|
+
refresh_token: refreshToken,
|
|
1307
|
+
scope: codeClaims.scp.join(" "),
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
if (grantType === "refresh_token") {
|
|
1311
|
+
const refreshToken = String(b.refresh_token || "").trim();
|
|
1312
|
+
if (!refreshToken) {
|
|
1313
|
+
return res.status(400).json({
|
|
1314
|
+
error: "invalid_request",
|
|
1315
|
+
error_description: "refresh_token is required.",
|
|
1316
|
+
});
|
|
1317
|
+
}
|
|
1318
|
+
const rtClaims = verifyOAuthRefreshToken(refreshToken);
|
|
1319
|
+
if (!rtClaims) {
|
|
1320
|
+
return res.status(400).json({
|
|
1321
|
+
error: "invalid_grant",
|
|
1322
|
+
error_description: "Refresh token is invalid, expired, or revoked.",
|
|
1323
|
+
});
|
|
1324
|
+
}
|
|
1325
|
+
if (clientId && rtClaims.cid !== clientId) {
|
|
1326
|
+
return res.status(400).json({
|
|
1327
|
+
error: "invalid_grant",
|
|
1328
|
+
error_description: "client_id does not match refresh token.",
|
|
1329
|
+
});
|
|
1330
|
+
}
|
|
1331
|
+
const nowSec = Math.floor(Date.now() / 1000);
|
|
1332
|
+
const accessClaims = {
|
|
1333
|
+
iss: origin,
|
|
1334
|
+
aud: rtClaims.aud || `${origin}/mcp`,
|
|
1335
|
+
sub: rtClaims.sub,
|
|
1336
|
+
adm: rtClaims.adm,
|
|
1337
|
+
scp: rtClaims.scp,
|
|
1338
|
+
cid: rtClaims.cid,
|
|
1339
|
+
typ: "at",
|
|
1340
|
+
iat: nowSec,
|
|
1341
|
+
exp: nowSec + ACCESS_TOKEN_TTL_SEC,
|
|
1342
|
+
jti: randomBytes(16).toString("base64url"),
|
|
1343
|
+
};
|
|
1344
|
+
const accessToken = signJwt(accessClaims, "access");
|
|
1345
|
+
// Non-rotating refresh_token preserves long-lived Google Gemini MCP connections
|
|
1346
|
+
return res.status(200).json({
|
|
1347
|
+
access_token: accessToken,
|
|
1348
|
+
token_type: "Bearer",
|
|
1349
|
+
expires_in: ACCESS_TOKEN_TTL_SEC,
|
|
1350
|
+
refresh_token: refreshToken,
|
|
1351
|
+
scope: rtClaims.scp.join(" "),
|
|
1352
|
+
});
|
|
1353
|
+
}
|
|
1354
|
+
return res.status(400).json({
|
|
1355
|
+
error: "unsupported_grant_type",
|
|
1356
|
+
error_description: "Supported grant_types: authorization_code, refresh_token.",
|
|
1357
|
+
});
|
|
1358
|
+
});
|
|
1359
|
+
// 7. RFC 7009 — Token Revocation Endpoint
|
|
1360
|
+
app.post("/oauth/revoke", (req, res) => {
|
|
1361
|
+
res.setHeader("Cache-Control", "no-store");
|
|
1362
|
+
const b = (req.body || {});
|
|
1363
|
+
const token = String(b.token || "").trim();
|
|
1364
|
+
if (token) {
|
|
1365
|
+
const at = verifyOAuthAccessToken(token);
|
|
1366
|
+
if (at?.jti) {
|
|
1367
|
+
revokedTokenIds.set(at.jti, at.exp * 1000 + 60_000);
|
|
1368
|
+
}
|
|
1369
|
+
const rt = verifyOAuthRefreshToken(token);
|
|
1370
|
+
if (rt?.jti) {
|
|
1371
|
+
revokedTokenIds.set(rt.jti, rt.exp * 1000 + 60_000);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
return res.status(200).json({ revoked: true });
|
|
1375
|
+
});
|
|
1376
|
+
}
|