@fire-spark/ai 0.0.0-stage → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,912 @@
1
+ import { createLocalJWKSet, createRemoteJWKSet, jwtVerify } from "jose";
2
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from "node:crypto";
3
+ import { Provider, errors } from "oidc-provider";
4
+ import { lookup } from "node:dns/promises";
5
+ import { Socket, isIP } from "node:net";
6
+ import { IncomingMessage, ServerResponse } from "node:http";
7
+ //#region src/auth/adapter.ts
8
+ const grantable = /* @__PURE__ */ new Set([
9
+ "AccessToken",
10
+ "AuthorizationCode",
11
+ "RefreshToken",
12
+ "DeviceCode"
13
+ ]);
14
+ const hashSecret = (secret) => {
15
+ return createHash("sha256").update(secret).digest("hex");
16
+ };
17
+ const clientRow = (payload) => {
18
+ const clientId = payload.client_id;
19
+ if (typeof clientId !== "string" || !clientId) return null;
20
+ const redirects = Array.isArray(payload.redirect_uris) ? payload.redirect_uris.filter((item) => typeof item === "string") : [];
21
+ const name = typeof payload.client_name === "string" ? payload.client_name : "";
22
+ const secret = payload.client_secret;
23
+ return {
24
+ clientId,
25
+ source: clientId.startsWith("https://") ? "cimd" : "dcr",
26
+ name,
27
+ redirectUris: redirects,
28
+ status: "ACTIVE",
29
+ secretHash: typeof secret === "string" ? hashSecret(secret) : null
30
+ };
31
+ };
32
+ const createAdapter = (store) => {
33
+ return class AgentAdapter {
34
+ name;
35
+ constructor(name) {
36
+ this.name = name;
37
+ }
38
+ async upsert(id, payload, expiresIn) {
39
+ const record = {
40
+ payload,
41
+ grantId: typeof payload.grantId === "string" ? payload.grantId : void 0,
42
+ uid: typeof payload.uid === "string" ? payload.uid : void 0,
43
+ userCode: typeof payload.userCode === "string" ? payload.userCode : void 0,
44
+ expiresAt: typeof expiresIn === "number" ? Math.floor(Date.now() / 1e3) + expiresIn : void 0
45
+ };
46
+ await store.upsert(this.name, id, record);
47
+ if (this.name !== "Client") return;
48
+ const row = clientRow(payload);
49
+ if (row) await store.upsertClient(row);
50
+ }
51
+ async find(id) {
52
+ if (this.name === "Client") {
53
+ if ((await store.findClient(id))?.status === "BLOCKED") return void 0;
54
+ }
55
+ const record = await this.usable(await store.find(this.name, id));
56
+ if (!record) return void 0;
57
+ return record.payload;
58
+ }
59
+ async findByUid(uid) {
60
+ return (await this.usable(await store.findByUid(this.name, uid)))?.payload;
61
+ }
62
+ async findByUserCode(userCode) {
63
+ const found = await store.findByUserCode(this.name, userCode);
64
+ return (await this.usable(found))?.payload;
65
+ }
66
+ async usable(record) {
67
+ if (!record) return void 0;
68
+ const now = Math.floor(Date.now() / 1e3);
69
+ if (record.expiresAt && record.expiresAt < now) return void 0;
70
+ if (!(this.name === "RefreshToken" || this.name === "AuthorizationCode")) return record;
71
+ const payload = record.payload;
72
+ const accountId = payload.accountId;
73
+ const clientId = payload.clientId;
74
+ if (typeof accountId !== "string" || typeof clientId !== "string") return record;
75
+ if ((await store.findGrant(clientId, accountId))?.revoked) return void 0;
76
+ return record;
77
+ }
78
+ async consume(id) {
79
+ const record = await store.find(this.name, id);
80
+ if (!record) return;
81
+ const payload = record.payload;
82
+ payload.consumed = Math.floor(Date.now() / 1e3);
83
+ await store.consume(this.name, id);
84
+ await store.upsert(this.name, id, {
85
+ ...record,
86
+ payload
87
+ });
88
+ }
89
+ async destroy(id) {
90
+ await store.destroy(this.name, id);
91
+ }
92
+ async revokeByGrantId(grantId) {
93
+ if (!grantable.has(this.name)) return;
94
+ await store.revokeByGrantId(grantId);
95
+ }
96
+ };
97
+ };
98
+ //#endregion
99
+ //#region src/auth/policy.ts
100
+ const hostMatches = (host, domain) => {
101
+ const name = domain.toLowerCase();
102
+ return host === name || host.endsWith(`.${name}`);
103
+ };
104
+ const domainAllowed = (host, policy) => {
105
+ const name = host.toLowerCase();
106
+ if (policy.blockedDomains.some((domain) => hostMatches(name, domain))) return false;
107
+ if (policy.allowedDomains.length === 0) return true;
108
+ return policy.allowedDomains.some((domain) => hostMatches(name, domain));
109
+ };
110
+ const loopback = (host) => {
111
+ return host === "localhost" || host === "127.0.0.1" || host === "::1";
112
+ };
113
+ const urlAllowed = (raw, policy) => {
114
+ let url;
115
+ try {
116
+ url = new URL(raw);
117
+ } catch {
118
+ return false;
119
+ }
120
+ if (url.username || url.password) return false;
121
+ const host = url.hostname.toLowerCase();
122
+ if (url.protocol === "http:") {
123
+ if (!loopback(host)) return false;
124
+ } else if (url.protocol !== "https:") return false;
125
+ return domainAllowed(host, policy);
126
+ };
127
+ //#endregion
128
+ //#region src/auth/ssrf.ts
129
+ var SsrfError = class extends Error {
130
+ constructor(message) {
131
+ super(message);
132
+ this.name = "SsrfError";
133
+ }
134
+ };
135
+ const ipv4 = (address) => {
136
+ const parts = address.split(".").map((part) => Number(part));
137
+ if (parts.length !== 4) return null;
138
+ if (parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return null;
139
+ return parts;
140
+ };
141
+ const isBlockedAddress = (address) => {
142
+ const version = isIP(address);
143
+ if (version === 4) {
144
+ const parts = ipv4(address);
145
+ if (!parts) return true;
146
+ const [a, b] = parts;
147
+ if (a === 0 || a === 10 || a === 127) return true;
148
+ if (a === 100 && b >= 64 && b <= 127) return true;
149
+ if (a === 169 && b === 254) return true;
150
+ if (a === 172 && b >= 16 && b <= 31) return true;
151
+ if (a === 192 && b === 168) return true;
152
+ if (a >= 224) return true;
153
+ return false;
154
+ }
155
+ if (version === 6) {
156
+ const lower = address.toLowerCase();
157
+ if (lower === "::" || lower === "::1") return true;
158
+ if (lower.startsWith("fe8") || lower.startsWith("fe9")) return true;
159
+ if (lower.startsWith("fea") || lower.startsWith("feb")) return true;
160
+ if (lower.startsWith("fc") || lower.startsWith("fd")) return true;
161
+ if (lower.startsWith("ff")) return true;
162
+ if (lower.startsWith("::ffff:")) return isBlockedAddress(lower.slice(7));
163
+ return false;
164
+ }
165
+ return true;
166
+ };
167
+ const dnsLookup = async (hostname) => {
168
+ return (await lookup(hostname, {
169
+ all: true,
170
+ verbatim: true
171
+ })).map((record) => record.address);
172
+ };
173
+ const hostOf = (hostname) => {
174
+ if (hostname.startsWith("[") && hostname.endsWith("]")) return hostname.slice(1, -1);
175
+ return hostname;
176
+ };
177
+ /** https only, no credentials, no private or link-local address. */
178
+ const assertPublicHttps = async (raw, resolve = dnsLookup) => {
179
+ let url;
180
+ try {
181
+ url = new URL(raw);
182
+ } catch {
183
+ throw new SsrfError("invalid url");
184
+ }
185
+ if (url.protocol !== "https:") throw new SsrfError("https only");
186
+ if (url.username || url.password || url.hash) throw new SsrfError("url");
187
+ const host = hostOf(url.hostname);
188
+ if (!host || host === "localhost" || host.endsWith(".local")) throw new SsrfError("blocked host");
189
+ if (/^\d+$/.test(host)) throw new SsrfError("blocked host");
190
+ const addresses = isIP(host) ? [host] : await resolve(host).catch(() => []);
191
+ if (!addresses.length) throw new SsrfError("dns");
192
+ for (const address of addresses) if (isBlockedAddress(address)) throw new SsrfError("blocked address");
193
+ return url;
194
+ };
195
+ const safeFetch = async (url, init, resolve) => {
196
+ await assertPublicHttps(url, resolve);
197
+ const timeout = AbortSignal.timeout(5e3);
198
+ return fetch(url, {
199
+ ...init,
200
+ redirect: "manual",
201
+ signal: timeout
202
+ });
203
+ };
204
+ //#endregion
205
+ //#region src/auth/provider.ts
206
+ const registrationAllowed = (body, policy) => {
207
+ if (!policy.allowDcr) return false;
208
+ const redirects = body.redirect_uris;
209
+ if (!Array.isArray(redirects) || redirects.length === 0) return false;
210
+ return redirects.every((item) => typeof item === "string" && urlAllowed(item, policy));
211
+ };
212
+ const createAgentProvider = (config) => {
213
+ const Adapter = createAdapter(config.store);
214
+ const scopes = config.scopes.join(" ");
215
+ const provider = new Provider(config.issuer, {
216
+ adapter: Adapter,
217
+ jwks: config.jwks,
218
+ clients: [],
219
+ cookies: { keys: config.cookieKeys },
220
+ pkce: { required: () => true },
221
+ issueRefreshToken: async () => true,
222
+ rotateRefreshToken: () => true,
223
+ scopes: config.scopes,
224
+ clientDefaults: {
225
+ grant_types: ["authorization_code", "refresh_token"],
226
+ response_types: ["code"],
227
+ token_endpoint_auth_method: "none"
228
+ },
229
+ ttl: {
230
+ AccessToken: config.accessTokenTtlSeconds,
231
+ AuthorizationCode: 60,
232
+ RefreshToken: config.refreshTokenTtlSeconds,
233
+ Interaction: 600,
234
+ Session: 3600,
235
+ Grant: config.refreshTokenTtlSeconds
236
+ },
237
+ interactions: { url(_ctx, interaction) {
238
+ return `/auth/interaction/${interaction.uid}`;
239
+ } },
240
+ extraTokenClaims(_ctx, token) {
241
+ return {
242
+ customer_id: token.accountId,
243
+ client_id: token.clientId,
244
+ merchant_id: config.merchantId
245
+ };
246
+ },
247
+ fetch: (url, init) => {
248
+ return safeFetch(String(url), init ?? {}, config.lookup);
249
+ },
250
+ findAccount(_ctx, id) {
251
+ return {
252
+ accountId: id,
253
+ async claims() {
254
+ return { sub: id };
255
+ }
256
+ };
257
+ },
258
+ renderError(ctx, _out, error) {
259
+ ctx.status = 400;
260
+ ctx.body = error.message;
261
+ },
262
+ features: {
263
+ devInteractions: { enabled: false },
264
+ revocation: { enabled: true },
265
+ resourceIndicators: {
266
+ enabled: true,
267
+ defaultResource: () => config.mcpUrl,
268
+ getResourceServerInfo(_ctx, indicator) {
269
+ if (indicator !== config.mcpUrl) throw new errors.InvalidTarget("resource");
270
+ return {
271
+ scope: scopes,
272
+ audience: indicator,
273
+ accessTokenFormat: "jwt",
274
+ accessTokenTTL: config.accessTokenTtlSeconds
275
+ };
276
+ }
277
+ },
278
+ registration: {
279
+ enabled: config.policy.allowDcr,
280
+ idFactory(ctx) {
281
+ if (!registrationAllowed(ctx.oidc.body, config.policy)) throw new errors.InvalidClientMetadata("client domain is not allowed");
282
+ return randomBytes(16).toString("base64url");
283
+ }
284
+ },
285
+ clientIdMetadataDocument: {
286
+ ack: "draft-02",
287
+ enabled: config.policy.allowCimd,
288
+ allowFetch(_ctx, clientId) {
289
+ return urlAllowed(clientId, config.policy);
290
+ },
291
+ allowClient(_ctx, client) {
292
+ return (client.redirectUris ?? []).every((uri) => urlAllowed(uri, config.policy));
293
+ }
294
+ }
295
+ },
296
+ routes: {
297
+ authorization: "/authorize",
298
+ token: "/token",
299
+ jwks: "/jwks",
300
+ registration: config.registrationPath ?? "/register",
301
+ revocation: "/revoke"
302
+ }
303
+ });
304
+ provider.on("access_token.issued", (token) => {
305
+ const accountId = token.accountId;
306
+ const clientId = token.clientId;
307
+ if (!accountId || !clientId) return;
308
+ const scope = token.scope ?? "";
309
+ config.store.touchGrant({
310
+ clientId,
311
+ customerId: accountId,
312
+ scopes: scope
313
+ });
314
+ });
315
+ return provider;
316
+ };
317
+ //#endregion
318
+ //#region src/auth/firebase.ts
319
+ const keys = createRemoteJWKSet(new URL("https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com"));
320
+ /**
321
+ * Verifies a Firebase ID token from the merchant's project.
322
+ * `customer_id` wins when the token carries that custom claim.
323
+ * Otherwise the Firebase uid is the customer id, same as the storefront exchange.
324
+ */
325
+ const verifyFirebaseIdToken = async (token, projectId, key = keys) => {
326
+ try {
327
+ const { payload } = await jwtVerify(token, key, {
328
+ issuer: `https://securetoken.google.com/${projectId}`,
329
+ audience: projectId
330
+ });
331
+ if (typeof payload.sub !== "string" || !payload.sub) return null;
332
+ const claim = payload.customer_id;
333
+ const customerId = typeof claim === "string" && claim ? claim : payload.sub;
334
+ return {
335
+ sub: payload.sub,
336
+ customerId
337
+ };
338
+ } catch {
339
+ return null;
340
+ }
341
+ };
342
+ //#endregion
343
+ //#region src/auth/html.ts
344
+ const escapeHtml = (value) => {
345
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("\"", "&quot;");
346
+ };
347
+ const SCOPE_WORDS = {
348
+ "agent:stores:read": "ver tiendas",
349
+ "agent:menus:read": "ver el menú",
350
+ "agent:carts:write": "armar el carrito",
351
+ "agent:carts:validate": "revisar el carrito",
352
+ "agent:orders:write": "crear pedidos",
353
+ "agent:payments:start": "abrir el pago",
354
+ "agent:orders:read": "ver el estado del pedido",
355
+ "agent:cards:read": "ver tarjetas guardadas",
356
+ "agent:cards:charge": "cobrar una tarjeta guardada",
357
+ "agent:cards:consent": "guardar una tarjeta",
358
+ "agent:cards:revoke": "quitar una tarjeta guardada"
359
+ };
360
+ const page = (title, body) => {
361
+ return `<!doctype html><html lang="es-EC"><head><meta charset="utf-8"><title>${title}</title></head><body>${body}</body></html>`;
362
+ };
363
+ const consentHtml = (input) => {
364
+ const brand = escapeHtml(input.brand || "el comercio");
365
+ const client = escapeHtml(input.clientName || "esta aplicación");
366
+ const items = input.scopes.map((scope) => `<li>${escapeHtml(SCOPE_WORDS[scope] ?? scope)}</li>`).join("");
367
+ const body = [
368
+ `<h1>${brand}</h1>`,
369
+ `<p>${client} quiere acceder a tu cuenta.</p>`,
370
+ `<ul>${items}</ul>`,
371
+ "<p>Puedes quitar este acceso cuando quieras desde aquí.</p>",
372
+ `<form method="post" action="/auth/consent">`,
373
+ `<input type="hidden" name="uid" value="${escapeHtml(input.uid)}">`,
374
+ `<button type="submit" name="decision" value="allow">Permitir</button>`,
375
+ `<button type="submit" name="decision" value="deny">Cancelar</button>`,
376
+ "</form>"
377
+ ].join("");
378
+ return page("Permiso", body);
379
+ };
380
+ const firebaseLoginHtml = (input) => {
381
+ const config = JSON.stringify({
382
+ apiKey: input.apiKey,
383
+ authDomain: input.authDomain,
384
+ projectId: input.projectId,
385
+ appId: input.appId
386
+ }).replaceAll("<", "\\u003c");
387
+ const body = [
388
+ "<h1>Entra con tu cuenta</h1>",
389
+ "<p>Usa la misma cuenta de la web, la app o el kiosco.</p>",
390
+ `<form id="login">`,
391
+ `<input name="email" type="email" autocomplete="username" required>`,
392
+ `<input name="password" type="password" autocomplete="current-password" required>`,
393
+ `<button type="submit">Entrar</button>`,
394
+ "</form>",
395
+ `<form id="done" method="post" action="/auth/login">`,
396
+ `<input type="hidden" name="uid" value="${escapeHtml(input.uid)}">`,
397
+ `<input type="hidden" name="id_token" value="">`,
398
+ "</form>",
399
+ `<script type="module">`,
400
+ `import { initializeApp } from "https://www.gstatic.com/firebasejs/11.0.2/firebase-app.js";`,
401
+ `import { getAuth, signInWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/11.0.2/firebase-auth.js";`,
402
+ `const app = initializeApp(${config});`,
403
+ `const auth = getAuth(app);`,
404
+ `document.getElementById("login").addEventListener("submit", async (event) => {`,
405
+ `event.preventDefault();`,
406
+ `const data = new FormData(event.target);`,
407
+ `const cred = await signInWithEmailAndPassword(auth, data.get("email"), data.get("password"));`,
408
+ `const token = await cred.user.getIdToken();`,
409
+ `const done = document.getElementById("done");`,
410
+ `done.querySelector("[name=id_token]").value = token;`,
411
+ `done.submit();`,
412
+ `});`,
413
+ `<\/script>`
414
+ ].join("");
415
+ return page("Entrar", body);
416
+ };
417
+ const testLoginHtml = (uid) => {
418
+ const body = [
419
+ `<form method="post" action="/auth/login">`,
420
+ `<input type="hidden" name="uid" value="${escapeHtml(uid)}">`,
421
+ `<input name="customer_id" required>`,
422
+ `<button type="submit">Entrar</button>`,
423
+ "</form>"
424
+ ].join("");
425
+ return page("Entrar", body);
426
+ };
427
+ //#endregion
428
+ //#region src/auth/oidc.ts
429
+ const isRecord = (value) => {
430
+ return !!value && typeof value === "object" && !Array.isArray(value);
431
+ };
432
+ const sameOrigin = (issuer, raw) => {
433
+ try {
434
+ return new URL(raw).origin === new URL(issuer).origin;
435
+ } catch {
436
+ return false;
437
+ }
438
+ };
439
+ const readLimited = async (response) => {
440
+ const text = await response.text();
441
+ if (text.length > 65536) throw new Error("oidc discovery failed");
442
+ return text;
443
+ };
444
+ const oidcAuthorizeUrl = async (upstream, redirectUri, uid, store, resolve) => {
445
+ const issuer = upstream.issuer.replace(/\/+$/, "");
446
+ const response = await safeFetch(`${issuer}/.well-known/openid-configuration`, { method: "GET" }, resolve);
447
+ if (!response.ok) throw new Error("oidc discovery failed");
448
+ let doc;
449
+ try {
450
+ doc = JSON.parse(await readLimited(response));
451
+ } catch {
452
+ throw new Error("oidc discovery failed");
453
+ }
454
+ const authorize = doc.authorization_endpoint;
455
+ const tokenEndpoint = doc.token_endpoint;
456
+ const jwksUri = doc.jwks_uri;
457
+ if (!authorize || !tokenEndpoint || !jwksUri) throw new Error("oidc discovery failed");
458
+ if (!sameOrigin(issuer, tokenEndpoint)) throw new Error("oidc discovery failed");
459
+ const verifier = randomBytes(32).toString("base64url");
460
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
461
+ const record = {
462
+ payload: {
463
+ verifier,
464
+ tokenEndpoint,
465
+ jwksUri,
466
+ issuer
467
+ },
468
+ uid
469
+ };
470
+ await store.upsert("OidcTxn", uid, record);
471
+ const q1 = {
472
+ response_type: "code",
473
+ client_id: upstream.clientId
474
+ };
475
+ const q2 = {
476
+ redirect_uri: redirectUri,
477
+ scope: "openid",
478
+ state: uid
479
+ };
480
+ const q3 = {
481
+ code_challenge: challenge,
482
+ code_challenge_method: "S256"
483
+ };
484
+ return `${authorize}?${new URLSearchParams({
485
+ ...q1,
486
+ ...q2,
487
+ ...q3
488
+ })}`;
489
+ };
490
+ const oidcCustomerId = async (upstream, redirectUri, uid, code, store, resolve) => {
491
+ const saved = (await store.find("OidcTxn", uid))?.payload;
492
+ if (!isRecord(saved) || typeof saved.verifier !== "string") return "";
493
+ await store.destroy("OidcTxn", uid);
494
+ const tokenEndpoint = saved.tokenEndpoint;
495
+ const jwksUri = saved.jwksUri;
496
+ const issuer = upstream.issuer.replace(/\/+$/, "");
497
+ if (typeof tokenEndpoint !== "string" || typeof jwksUri !== "string") return "";
498
+ if (!sameOrigin(issuer, tokenEndpoint)) return "";
499
+ const t1 = { grant_type: "authorization_code" };
500
+ const t2 = {
501
+ code,
502
+ redirect_uri: redirectUri
503
+ };
504
+ const t3 = { client_id: upstream.clientId };
505
+ const t4 = { client_secret: upstream.clientSecret };
506
+ const t5 = { code_verifier: saved.verifier };
507
+ const fields = {
508
+ ...t1,
509
+ ...t2,
510
+ ...t3,
511
+ ...t4,
512
+ ...t5
513
+ };
514
+ const token = await safeFetch(tokenEndpoint, {
515
+ method: "POST",
516
+ headers: { "content-type": "application/x-www-form-urlencoded" },
517
+ body: new URLSearchParams(fields)
518
+ }, resolve);
519
+ if (!token.ok) return "";
520
+ const tokenText = await token.text();
521
+ if (tokenText.length > 65536) return "";
522
+ let issued;
523
+ try {
524
+ issued = JSON.parse(tokenText);
525
+ } catch {
526
+ return "";
527
+ }
528
+ if (!issued.id_token) return "";
529
+ const jwksResponse = await safeFetch(jwksUri, { method: "GET" }, resolve);
530
+ if (!jwksResponse.ok) return "";
531
+ const jwksText = await jwksResponse.text();
532
+ if (jwksText.length > 65536) return "";
533
+ let jwks;
534
+ try {
535
+ jwks = JSON.parse(jwksText);
536
+ } catch {
537
+ return "";
538
+ }
539
+ const key = createLocalJWKSet(jwks);
540
+ const opts = {
541
+ issuer: upstream.issuer.replace(/\/+$/, ""),
542
+ audience: upstream.clientId
543
+ };
544
+ const verified = await jwtVerify(issued.id_token, key, opts);
545
+ const claim = verified.payload.customer_id;
546
+ if (typeof claim === "string" && claim) return claim;
547
+ return typeof verified.payload.sub === "string" ? verified.payload.sub : "";
548
+ };
549
+ //#endregion
550
+ //#region src/auth/server.ts
551
+ const readBody = async (req) => {
552
+ const chunks = [];
553
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
554
+ return Buffer.concat(chunks).toString("utf8");
555
+ };
556
+ const formOf = (raw) => {
557
+ return Object.fromEntries(new URLSearchParams(raw));
558
+ };
559
+ const send = (res, status, body, type) => {
560
+ res.statusCode = status;
561
+ res.setHeader("content-type", type);
562
+ res.end(body);
563
+ };
564
+ const handleAgentHttp = async (req, res, provider, config) => {
565
+ const url = new URL(req.url ?? "/", config.issuer);
566
+ if (req.method === "GET" && url.pathname.startsWith("/auth/interaction/")) {
567
+ const details = await provider.interactionDetails(req, res);
568
+ if (details.prompt.name === "login") {
569
+ if (config.testLogin) {
570
+ send(res, 200, testLoginHtml(details.uid), "text/html; charset=utf-8");
571
+ return;
572
+ }
573
+ const firebase = config.firebase;
574
+ if (firebase) {
575
+ const html = firebaseLoginHtml({
576
+ uid: details.uid,
577
+ ...firebase
578
+ });
579
+ send(res, 200, html, "text/html; charset=utf-8");
580
+ return;
581
+ }
582
+ if (config.oidc) {
583
+ const redirectUri = `${config.issuer}/auth/oidc/callback`;
584
+ const p1 = [
585
+ config.oidc,
586
+ redirectUri,
587
+ details.uid
588
+ ];
589
+ const p2 = [config.store, config.lookup];
590
+ const target = await oidcAuthorizeUrl(...p1, ...p2);
591
+ res.statusCode = 303;
592
+ res.setHeader("location", target);
593
+ res.end();
594
+ return;
595
+ }
596
+ send(res, 400, "Este comercio no tiene inicio de sesión aquí.", "text/plain");
597
+ return;
598
+ }
599
+ const scope = details.params.scope;
600
+ const scopes = typeof scope === "string" ? scope.split(" ") : config.scopes;
601
+ const clientId = details.params.client_id;
602
+ const name = typeof clientId === "string" ? clientId : "esta aplicación";
603
+ const view1 = {
604
+ brand: config.brand,
605
+ clientName: name
606
+ };
607
+ const view2 = {
608
+ scopes,
609
+ uid: details.uid
610
+ };
611
+ const html = consentHtml({
612
+ ...view1,
613
+ ...view2
614
+ });
615
+ send(res, 200, html, "text/html; charset=utf-8");
616
+ return;
617
+ }
618
+ if (req.method === "GET" && url.pathname === "/auth/oidc/callback") {
619
+ const code = url.searchParams.get("code") ?? "";
620
+ const uid = url.searchParams.get("state") ?? "";
621
+ const upstream = config.oidc;
622
+ const redirectUri = `${config.issuer}/auth/oidc/callback`;
623
+ let customerId = "";
624
+ if (upstream) {
625
+ const a1 = [
626
+ upstream,
627
+ redirectUri,
628
+ uid,
629
+ code
630
+ ];
631
+ const a2 = [config.store, config.lookup];
632
+ customerId = await oidcCustomerId(...a1, ...a2);
633
+ }
634
+ if (!customerId) {
635
+ send(res, 401, "No pude confirmar tu cuenta.", "text/plain");
636
+ return;
637
+ }
638
+ const login = { login: { accountId: customerId } };
639
+ await provider.interactionFinished(req, res, login, { mergeWithLastSubmission: false });
640
+ return;
641
+ }
642
+ if (req.method === "POST" && url.pathname === "/auth/login") {
643
+ const body = formOf(await readBody(req));
644
+ let customerId = "";
645
+ if (config.testLogin && body.customer_id) customerId = body.customer_id;
646
+ if (!customerId && config.firebase && body.id_token) {
647
+ const projectId = config.firebase.projectId;
648
+ customerId = (await verifyFirebaseIdToken(body.id_token, projectId))?.customerId ?? "";
649
+ }
650
+ if (!customerId) {
651
+ send(res, 401, "No pude confirmar tu cuenta.", "text/plain");
652
+ return;
653
+ }
654
+ const login = { login: { accountId: customerId } };
655
+ await provider.interactionFinished(req, res, login, { mergeWithLastSubmission: false });
656
+ return;
657
+ }
658
+ if (req.method === "POST" && url.pathname === "/auth/consent") {
659
+ if (formOf(await readBody(req)).decision !== "allow") {
660
+ await provider.interactionFinished(req, res, { error: "access_denied" });
661
+ return;
662
+ }
663
+ const details = await provider.interactionDetails(req, res);
664
+ const missing = details.prompt.details.missingResourceScopes;
665
+ const accountId = details.session?.accountId ?? "";
666
+ const clientId = details.params.client_id;
667
+ const client = typeof clientId === "string" ? clientId : "";
668
+ const grant = new provider.Grant({
669
+ accountId,
670
+ clientId: client
671
+ });
672
+ const oidcMissing = details.prompt.details.missingOIDCScope;
673
+ if (Array.isArray(oidcMissing)) grant.addOIDCScope(oidcMissing.join(" "));
674
+ if (missing && typeof missing === "object") {
675
+ const entries = Object.entries(missing);
676
+ for (const [indicator, scopes] of entries) grant.addResourceScope(indicator, scopes.join(" "));
677
+ } else if (typeof details.params.resource === "string") {
678
+ const asked = details.params.scope;
679
+ const scope = typeof asked === "string" ? asked : "";
680
+ grant.addResourceScope(details.params.resource, scope);
681
+ }
682
+ const consent = { consent: { grantId: await grant.save() } };
683
+ await provider.interactionFinished(req, res, consent, { mergeWithLastSubmission: true });
684
+ return;
685
+ }
686
+ await provider.callback()(req, res);
687
+ };
688
+ //#endregion
689
+ //#region src/auth/spark.ts
690
+ const keyOf = (secret) => {
691
+ return createHash("sha256").update(secret).digest();
692
+ };
693
+ const sealJson = (secret, value) => {
694
+ const iv = randomBytes(12);
695
+ const cipher = createCipheriv("aes-256-gcm", keyOf(secret), iv);
696
+ const body = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final()]);
697
+ const tag = cipher.getAuthTag();
698
+ return Buffer.concat([
699
+ iv,
700
+ tag,
701
+ body
702
+ ]).toString("base64url");
703
+ };
704
+ const openJson = (secret, sealed) => {
705
+ const raw = Buffer.from(sealed, "base64url");
706
+ const iv = raw.subarray(0, 12);
707
+ const tag = raw.subarray(12, 28);
708
+ const body = raw.subarray(28);
709
+ const decipher = createDecipheriv("aes-256-gcm", keyOf(secret), iv);
710
+ decipher.setAuthTag(tag);
711
+ const json = Buffer.concat([decipher.update(body), decipher.final()]).toString("utf8");
712
+ return JSON.parse(json);
713
+ };
714
+ const blind = (secret, value) => {
715
+ return createHmac("sha256", keyOf(secret)).update(value).digest("hex");
716
+ };
717
+ /** Persists ciphertext in Spark. The raw code and refresh token stay here. */
718
+ var SparkAuthStore = class {
719
+ options;
720
+ constructor(options) {
721
+ this.options = options;
722
+ }
723
+ async call(body) {
724
+ const fetchImpl = this.options.fetchImpl ?? fetch;
725
+ const token = await this.options.token();
726
+ const url = `${this.options.apiUrl}/api/integrations/v1/agent/auth`;
727
+ const auth = { authorization: `Bearer ${token}` };
728
+ const json = { "content-type": "application/json" };
729
+ const headers = {
730
+ ...auth,
731
+ ...json
732
+ };
733
+ const sent = {
734
+ channel_id: this.options.channelId,
735
+ ...body
736
+ };
737
+ const response = await fetchImpl(url, {
738
+ method: "POST",
739
+ headers,
740
+ body: JSON.stringify(sent)
741
+ });
742
+ if (!response.ok) throw new Error("agent_auth_store_failed");
743
+ return await response.json();
744
+ }
745
+ async upsert(model, id, record) {
746
+ const secret = this.options.secret;
747
+ const recordId = blind(secret, `${model}:${id}`);
748
+ const grantId = record.grantId ? blind(secret, record.grantId) : null;
749
+ const uid = record.uid ? blind(secret, record.uid) : null;
750
+ const userCode = record.userCode ? blind(secret, record.userCode) : null;
751
+ const expiresAt = record.expiresAt;
752
+ const expires = expiresAt ? (/* @__PURE__ */ new Date(expiresAt * 1e3)).toISOString() : null;
753
+ const b1 = {
754
+ op: "put_record",
755
+ model,
756
+ record_id: recordId
757
+ };
758
+ const b2 = {
759
+ payload: sealJson(secret, record),
760
+ grant_id: grantId
761
+ };
762
+ const b3 = {
763
+ uid,
764
+ user_code: userCode,
765
+ expires_at: expires
766
+ };
767
+ const b4 = { consumed_at: null };
768
+ await this.call({
769
+ ...b1,
770
+ ...b2,
771
+ ...b3,
772
+ ...b4
773
+ });
774
+ }
775
+ open(data) {
776
+ const payload = data?.payload;
777
+ if (typeof payload !== "string") return void 0;
778
+ return openJson(this.options.secret, payload);
779
+ }
780
+ async find(model, id) {
781
+ const data = (await this.call({
782
+ op: "find_record",
783
+ model,
784
+ record_id: blind(this.options.secret, `${model}:${id}`)
785
+ })).data?.data;
786
+ return this.open(data);
787
+ }
788
+ async findByUid(model, uid) {
789
+ const data = (await this.call({
790
+ op: "find_record_by_uid",
791
+ model,
792
+ uid: blind(this.options.secret, uid)
793
+ })).data?.data;
794
+ return this.open(data);
795
+ }
796
+ async findByUserCode(model, userCode) {
797
+ const data = (await this.call({
798
+ op: "find_record_by_user_code",
799
+ model,
800
+ user_code: blind(this.options.secret, userCode)
801
+ })).data?.data;
802
+ return this.open(data);
803
+ }
804
+ async consume(model, id) {
805
+ const current = await this.find(model, id);
806
+ if (!current) return;
807
+ const payload = current.payload;
808
+ payload.consumed = Math.floor(Date.now() / 1e3);
809
+ await this.upsert(model, id, current);
810
+ }
811
+ async destroy(model, id) {
812
+ await this.call({
813
+ op: "destroy_record",
814
+ model,
815
+ record_id: blind(this.options.secret, `${model}:${id}`)
816
+ });
817
+ }
818
+ async revokeByGrantId(grantId) {
819
+ await this.call({
820
+ op: "revoke_grant_records",
821
+ grant_id: blind(this.options.secret, grantId)
822
+ });
823
+ }
824
+ async upsertClient(row) {
825
+ await this.call({
826
+ op: "upsert_client",
827
+ client_id: row.clientId,
828
+ source: row.source,
829
+ name: row.name,
830
+ redirect_uris: row.redirectUris,
831
+ metadata: {},
832
+ secret_hash: row.secretHash
833
+ });
834
+ }
835
+ async findClient(clientId) {
836
+ const data = (await this.call({
837
+ op: "find_client",
838
+ client_id: clientId
839
+ })).data?.data;
840
+ if (!data || typeof data.client_id !== "string") return void 0;
841
+ const redirects = Array.isArray(data.redirect_uris) ? data.redirect_uris.filter((item) => typeof item === "string") : [];
842
+ return {
843
+ clientId: data.client_id,
844
+ source: data.source === "cimd" ? "cimd" : "dcr",
845
+ name: typeof data.name === "string" ? data.name : "",
846
+ redirectUris: redirects,
847
+ status: data.status === "BLOCKED" ? "BLOCKED" : "ACTIVE",
848
+ secretHash: typeof data.secret_hash === "string" ? data.secret_hash : null
849
+ };
850
+ }
851
+ async touchGrant(row) {
852
+ return { revoked: ((await this.call({
853
+ op: "touch_grant",
854
+ client_id: row.clientId,
855
+ customer_id: row.customerId,
856
+ scopes: row.scopes
857
+ })).data ?? {}).revoked === true };
858
+ }
859
+ async findGrant(clientId, customerId) {
860
+ const data = (await this.call({
861
+ op: "find_grant",
862
+ client_id: clientId,
863
+ customer_id: customerId
864
+ })).data?.data;
865
+ if (!data) return void 0;
866
+ return {
867
+ clientId,
868
+ customerId,
869
+ scopes: typeof data.scopes === "string" ? data.scopes : "",
870
+ revoked: typeof data.revoked_at === "string"
871
+ };
872
+ }
873
+ };
874
+ //#endregion
875
+ //#region src/auth/bridge.ts
876
+ /** Adapts a Web Request to the Node listener oidc-provider expects. */
877
+ const dispatchWeb = async (request, listener) => {
878
+ const url = new URL(request.url);
879
+ const req = new IncomingMessage(new Socket());
880
+ req.method = request.method;
881
+ req.url = `${url.pathname}${url.search}`;
882
+ req.headers = Object.fromEntries(request.headers);
883
+ const raw = await request.arrayBuffer();
884
+ const body = Buffer.from(raw);
885
+ if (body.length) req.headers["content-length"] = String(body.length);
886
+ const res = new ServerResponse(req);
887
+ const chunks = [];
888
+ res.write = ((chunk) => {
889
+ if (chunk) chunks.push(Buffer.from(chunk));
890
+ return true;
891
+ });
892
+ const ended = new Promise((resolve) => {
893
+ res.end = ((chunk) => {
894
+ if (chunk) chunks.push(Buffer.from(chunk));
895
+ resolve();
896
+ return res;
897
+ });
898
+ });
899
+ if (body.length) req.push(body);
900
+ req.push(null);
901
+ await listener(req, res);
902
+ await ended;
903
+ const headers = new Headers();
904
+ for (const [key, value] of Object.entries(res.getHeaders())) if (Array.isArray(value)) for (const item of value) headers.append(key, String(item));
905
+ else if (value !== void 0) headers.set(key, String(value));
906
+ return new Response(Buffer.concat(chunks), {
907
+ status: res.statusCode || 200,
908
+ headers
909
+ });
910
+ };
911
+ //#endregion
912
+ export { SparkAuthStore, createAgentProvider, dispatchWeb, handleAgentHttp };