@pagaqr/mcp 0.0.0-stage → 0.7.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +9 -0
  4. package/README.md +99 -2
  5. package/dist/capture-cli.d.ts +2 -0
  6. package/dist/capture-cli.js +34 -0
  7. package/dist/capture-local.d.ts +9 -0
  8. package/dist/capture-local.js +18 -0
  9. package/dist/capture-store.d.ts +7 -0
  10. package/dist/capture-store.js +175 -0
  11. package/dist/catalogue.d.ts +33 -0
  12. package/dist/catalogue.js +78 -0
  13. package/dist/cli.d.ts +2 -0
  14. package/dist/cli.js +27 -0
  15. package/dist/diagnose.d.ts +23 -0
  16. package/dist/diagnose.js +93 -0
  17. package/dist/index.d.ts +9 -0
  18. package/dist/index.js +134 -0
  19. package/dist/invocation-log.d.ts +9 -0
  20. package/dist/invocation-log.js +70 -0
  21. package/dist/masked-terminal.d.ts +4 -0
  22. package/dist/masked-terminal.js +71 -0
  23. package/dist/next-postgres.json +92 -0
  24. package/dist/sbom.cdx.json +523 -0
  25. package/dist/setup/database.d.ts +7 -0
  26. package/dist/setup/database.js +83 -0
  27. package/dist/setup/notice.d.ts +2 -0
  28. package/dist/setup/notice.js +2 -0
  29. package/dist/setup/run.d.ts +25 -0
  30. package/dist/setup/run.js +215 -0
  31. package/dist/setup/runtime.js +718 -0
  32. package/dist/setup/state.d.ts +7 -0
  33. package/dist/setup/state.js +81 -0
  34. package/dist/setup/step.d.ts +59 -0
  35. package/dist/setup/step.js +9 -0
  36. package/dist/setup/steps/pey.d.ts +8 -0
  37. package/dist/setup/steps/pey.js +271 -0
  38. package/dist/setup/steps/vercel.d.ts +5 -0
  39. package/dist/setup/steps/vercel.js +375 -0
  40. package/dist/setup/store-secrets.d.ts +3 -0
  41. package/dist/setup/store-secrets.js +67 -0
  42. package/dist/setup/terminal-guard.d.ts +9 -0
  43. package/dist/setup/terminal-guard.js +17 -0
  44. package/dist/setup/verify.d.ts +34 -0
  45. package/dist/setup/verify.js +144 -0
  46. package/dist/setup-cli.d.ts +2 -0
  47. package/dist/setup-cli.js +70 -0
  48. package/dist/template.d.ts +4 -0
  49. package/dist/template.js +119 -0
  50. package/dist/webhook.d.ts +1 -0
  51. package/dist/webhook.js +30 -0
  52. package/package.json +51 -3
@@ -0,0 +1,375 @@
1
+ // The Vercel step, the last one: publishes in Production every variable the earlier steps provided and redeploys the
2
+ // latest production deployment so the store reads them. Values never leave the requests; the person only sees names.
3
+ import { createHmac } from "node:crypto";
4
+ import { setTimeout } from "node:timers/promises";
5
+ import { canonicalWebhookUrl } from "../../webhook.js";
6
+ const API = "https://api.vercel.com";
7
+ const PROJECT_KEY = "vercel.projectId";
8
+ const TEAM_KEY = "vercel.teamId";
9
+ const REDEPLOY_KEY = "vercel.redeployId";
10
+ const CONFIG_KEY = "vercel.redeployConfig";
11
+ const PUBLISHED_KEY = "vercel.publishedId";
12
+ const WAIT_MS = 25 * 60_000;
13
+ const POLL_MS = 3_000;
14
+ const PERSONAL = "Mi cuenta personal";
15
+ class HttpFailure extends Error {
16
+ status;
17
+ constructor(status) {
18
+ super(`HTTP ${status}`);
19
+ this.status = status;
20
+ }
21
+ }
22
+ /** The account has no project yet: the store must be published once before this step. */
23
+ class NoProject extends Error {
24
+ }
25
+ class WrongDomain extends Error {
26
+ }
27
+ function record(value) {
28
+ return typeof value === "object" && value !== null && !Array.isArray(value)
29
+ ? value
30
+ : {};
31
+ }
32
+ function list(value) {
33
+ return Array.isArray(value) ? value.map(record) : [];
34
+ }
35
+ function send(context) {
36
+ return context["fetch"];
37
+ }
38
+ function withTeam(path, teamId) {
39
+ if (!teamId)
40
+ return `${API}${path}`;
41
+ return `${API}${path}${path.includes("?") ? "&" : "?"}teamId=${encodeURIComponent(teamId)}`;
42
+ }
43
+ async function call(context, method, path, body) {
44
+ const response = await send(context)(withTeam(path, context.recall(TEAM_KEY)), {
45
+ method,
46
+ headers: {
47
+ authorization: `Bearer ${await context.secret("VERCEL_TOKEN")}`,
48
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
49
+ },
50
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
51
+ signal: AbortSignal.any([context.signal, AbortSignal.timeout(20_000)]),
52
+ redirect: "error",
53
+ });
54
+ if (response.status < 200 || response.status > 299)
55
+ throw new HttpFailure(response.status);
56
+ try {
57
+ return record(await response.json());
58
+ }
59
+ catch {
60
+ return {};
61
+ }
62
+ }
63
+ /** Only the status code reaches the person: Vercel's error bodies may echo what was sent. */
64
+ function failure(cause) {
65
+ if (cause instanceof WrongDomain) {
66
+ return {
67
+ kind: "blocked",
68
+ reason: "El dominio indicado no está verificado para Production en el proyecto elegido.",
69
+ next: "En Vercel abre el proyecto de tu tienda y comprueba su dominio en Settings → Domains.",
70
+ };
71
+ }
72
+ if (!(cause instanceof HttpFailure))
73
+ throw cause;
74
+ if (cause.status === 401) {
75
+ return {
76
+ kind: "blocked",
77
+ reason: "Vercel no aceptó el token (respuesta 401). Puede que haya vencido o que lo hayas copiado incompleto.",
78
+ next: "Crea un token nuevo en vercel.com/account/settings/tokens y vuelve a correr el asistente.",
79
+ };
80
+ }
81
+ if (cause.status === 403) {
82
+ return {
83
+ kind: "blocked",
84
+ reason: "El token de Vercel no tiene permiso sobre este proyecto (respuesta 403).",
85
+ next: "En vercel.com/account/settings/tokens crea un token nuevo y, en «Scope», elige solo el equipo donde está tu tienda, con una fecha de vencimiento corta. Vuelve a correr el asistente con ese token.",
86
+ };
87
+ }
88
+ return {
89
+ kind: "blocked",
90
+ reason: `Vercel no respondió como se esperaba (respuesta ${cause.status}).`,
91
+ next: "Espera unos minutos y vuelve a correr el asistente.",
92
+ };
93
+ }
94
+ /** Picks the team and project with the person the first time; later runs reuse what was remembered. */
95
+ async function chooseProject(context) {
96
+ const remembered = context.recall(PROJECT_KEY);
97
+ if (remembered) {
98
+ const project = await call(context, "GET", `/v9/projects/${encodeURIComponent(remembered)}`);
99
+ return { id: remembered, name: typeof project["name"] === "string" ? project["name"] : remembered };
100
+ }
101
+ const teams = list((await call(context, "GET", "/v2/teams"))["teams"]).filter((team) => typeof team["id"] === "string" && typeof team["name"] === "string");
102
+ if (teams.length > 0 && !context.recall(TEAM_KEY)) {
103
+ const names = teams.map((team) => team["name"]);
104
+ const choice = await context.ask("¿En qué cuenta de Vercel está tu tienda?", [PERSONAL, ...names]);
105
+ const team = teams.find((candidate) => candidate["name"] === choice);
106
+ if (team)
107
+ context.remember(TEAM_KEY, team["id"]);
108
+ }
109
+ const projects = list((await call(context, "GET", "/v10/projects?limit=100"))["projects"])
110
+ .filter((project) => typeof project["id"] === "string" && typeof project["name"] === "string")
111
+ .map((project) => ({ id: project["id"], name: project["name"] }));
112
+ const first = projects[0];
113
+ if (!first)
114
+ throw new NoProject();
115
+ const name = projects.length === 1
116
+ ? first.name
117
+ : await context.ask("¿Cuál de estos proyectos de Vercel es tu tienda?", projects.map((project) => project.name));
118
+ const project = projects.find((candidate) => candidate.name === name) ?? first;
119
+ return project;
120
+ }
121
+ function noProject() {
122
+ return {
123
+ kind: "blocked",
124
+ reason: "No encontré ningún proyecto en esa cuenta de Vercel.",
125
+ next: "Publica primero tu tienda en Vercel (tu asistente de IA te puede guiar) y vuelve a correr el asistente.",
126
+ };
127
+ }
128
+ function eligibleOrigin(domain, project) {
129
+ const name = domain["name"];
130
+ if (typeof name !== "string" ||
131
+ domain["projectId"] !== project.id ||
132
+ domain["verified"] !== true ||
133
+ domain["redirect"] ||
134
+ domain["gitBranch"] ||
135
+ domain["customEnvironmentId"])
136
+ return undefined;
137
+ const origin = "https://" + name;
138
+ return canonicalWebhookUrl(origin + "/api/pagaqr/webhooks/pey") ? origin : undefined;
139
+ }
140
+ async function productionOrigin(context, project) {
141
+ const path = `/v9/projects/${encodeURIComponent(project.id)}/domains`;
142
+ const expected = context.provided().get("PAGAQR_STORE_ORIGIN")?.value;
143
+ if (expected) {
144
+ const host = new URL(expected).hostname;
145
+ try {
146
+ const domain = await call(context, "GET", path + "/" + encodeURIComponent(host));
147
+ if (eligibleOrigin(domain, project) === expected)
148
+ return expected;
149
+ }
150
+ catch (cause) {
151
+ if (!(cause instanceof HttpFailure) || cause.status !== 404)
152
+ throw cause;
153
+ }
154
+ }
155
+ else {
156
+ const domains = list((await call(context, "GET", path))["domains"]);
157
+ const origin = domains
158
+ .map((domain) => eligibleOrigin(domain, project))
159
+ .find((item) => item !== undefined);
160
+ if (origin)
161
+ return origin;
162
+ }
163
+ throw new WrongDomain();
164
+ }
165
+ async function storedVariables(context, project) {
166
+ const envs = list((await call(context, "GET", `/v10/projects/${encodeURIComponent(project.id)}/env`))["envs"]);
167
+ const stored = new Map();
168
+ for (const env of envs) {
169
+ const target = env["target"];
170
+ const inProduction = Array.isArray(target) ? target.includes("production") : target === "production";
171
+ if (!inProduction || typeof env["key"] !== "string")
172
+ continue;
173
+ stored.set(env["key"], {
174
+ type: typeof env["type"] === "string" ? env["type"] : "encrypted",
175
+ ...(typeof env["value"] === "string" && env["type"] === "plain" ? { value: env["value"] } : {}),
176
+ });
177
+ }
178
+ return stored;
179
+ }
180
+ /** Names to write: new ones, sensitive ones (Vercel never shows them back) and plain ones whose value changed. */
181
+ function toWrite(provided, stored) {
182
+ const create = [];
183
+ const update = [];
184
+ for (const [name, wanted] of [...provided].sort(([a], [b]) => a.localeCompare(b))) {
185
+ const current = stored.get(name);
186
+ if (!current)
187
+ create.push(name);
188
+ else if (wanted.sensitive || current.value === undefined || current.value !== wanted.value)
189
+ update.push(name);
190
+ }
191
+ return { create, update };
192
+ }
193
+ async function survey(context) {
194
+ const project = await chooseProject(context);
195
+ const origin = await productionOrigin(context, project);
196
+ context.remember(PROJECT_KEY, project.id);
197
+ context.provide("PAGAQR_STORE_ORIGIN", { value: origin, sensitive: false });
198
+ const provided = [...context.provided()].sort(([a], [b]) => a.localeCompare(b));
199
+ // The saved fingerprint is keyed with the token so it does not disclose or allow guessing a variable.
200
+ const config = createHmac("sha256", await context.secret("VERCEL_TOKEN"))
201
+ .update(JSON.stringify([project.id, provided.map(([key, field]) => [key, field.value, field.sensitive])]))
202
+ .digest("hex");
203
+ const stored = await storedVariables(context, project);
204
+ return { project, origin, provided, config, ...toWrite(new Map(provided), stored) };
205
+ }
206
+ function pendingOf(create, update, project) {
207
+ return {
208
+ kind: "pending",
209
+ changes: [
210
+ ...create.map((name) => `Agregar ${name} a tu proyecto ${project.name} en Vercel`),
211
+ ...update.map((name) => `Actualizar ${name} en tu proyecto ${project.name} en Vercel`),
212
+ `Volver a publicar ${project.name} para que use los datos nuevos`,
213
+ ],
214
+ };
215
+ }
216
+ async function deployment(context, idOrHost) {
217
+ try {
218
+ return await call(context, "GET", "/v13/deployments/" + encodeURIComponent(idOrHost));
219
+ }
220
+ catch (cause) {
221
+ if (cause instanceof HttpFailure && cause.status === 404)
222
+ return undefined;
223
+ throw cause;
224
+ }
225
+ }
226
+ async function publishedDeployment(context, projectId, host) {
227
+ try {
228
+ const alias = await call(context, "GET", "/v4/aliases/" + encodeURIComponent(host));
229
+ if (alias["alias"] === host &&
230
+ alias["projectId"] === projectId &&
231
+ !alias["redirect"] &&
232
+ !alias["deletedAt"] &&
233
+ typeof alias["deploymentId"] === "string")
234
+ return alias["deploymentId"];
235
+ }
236
+ catch (cause) {
237
+ if (!(cause instanceof HttpFailure) || cause.status !== 404)
238
+ throw cause;
239
+ }
240
+ return undefined;
241
+ }
242
+ async function publication(context, projectId, host, id) {
243
+ const build = await deployment(context, id);
244
+ if (!build || build["id"] !== id)
245
+ return "missing";
246
+ if (build["readyState"] === "ERROR" || build["readyState"] === "CANCELED" || build["aliasError"])
247
+ return "failed";
248
+ if (build["readyState"] === "READY" &&
249
+ build["aliasAssigned"] === true &&
250
+ (build["readySubstate"] === undefined || build["readySubstate"] === "PROMOTED") &&
251
+ (await publishedDeployment(context, projectId, host)) === id)
252
+ return "published";
253
+ return "waiting";
254
+ }
255
+ function published(origin) {
256
+ return { kind: "done", summary: `Tu tienda ya está publicada con sus datos de cobro en ${origin}` };
257
+ }
258
+ async function previousPublication(context, projectId, host, id) {
259
+ const state = await publication(context, projectId, host, id);
260
+ return state === "waiting" && context.recall(PUBLISHED_KEY) === id ? "superseded" : state;
261
+ }
262
+ async function waitForPublication(context, projectId, origin, id, pause) {
263
+ const host = new URL(origin).hostname;
264
+ const deadline = Date.now() + WAIT_MS;
265
+ do {
266
+ const status = await publication(context, projectId, host, id);
267
+ if (status === "published") {
268
+ context.remember(PUBLISHED_KEY, id);
269
+ return published(origin);
270
+ }
271
+ if (status === "failed") {
272
+ return {
273
+ kind: "blocked",
274
+ reason: "Vercel no pudo publicar el nuevo despliegue.",
275
+ next: "Revisa el despliegue en Vercel y vuelve a correr el asistente.",
276
+ };
277
+ }
278
+ await pause(context.signal);
279
+ } while (Date.now() < deadline);
280
+ return {
281
+ kind: "blocked",
282
+ reason: "Vercel todavía no publicó el nuevo despliegue en el dominio de tu tienda.",
283
+ next: "Revisa el estado en Vercel. Vuelve a correr el asistente para continuar la verificación.",
284
+ };
285
+ }
286
+ export function createVercelStep(pause = (signal) => setTimeout(POLL_MS, undefined, { signal })) {
287
+ return {
288
+ id: "vercel",
289
+ title: "Publicar los datos de cobro en tu tienda de Vercel",
290
+ async inspect(context) {
291
+ try {
292
+ const { project, origin, config, create, update } = await survey(context);
293
+ const previous = context.recall(REDEPLOY_KEY);
294
+ if (previous && context.recall(CONFIG_KEY) === config && create.length === 0) {
295
+ const status = await previousPublication(context, project.id, new URL(origin).hostname, previous);
296
+ if (status === "published") {
297
+ context.remember(PUBLISHED_KEY, previous);
298
+ return published(origin);
299
+ }
300
+ if (status === "waiting")
301
+ return {
302
+ kind: "pending",
303
+ changes: ["Esperar a que Vercel publique el despliegue en el dominio confirmado"],
304
+ };
305
+ }
306
+ return pendingOf(create, update, project);
307
+ }
308
+ catch (cause) {
309
+ if (cause instanceof NoProject)
310
+ return noProject();
311
+ return failure(cause);
312
+ }
313
+ },
314
+ async apply(context) {
315
+ try {
316
+ const { project, origin, provided, config, create, update } = await survey(context);
317
+ const host = new URL(origin).hostname;
318
+ const previous = context.recall(REDEPLOY_KEY);
319
+ if (previous) {
320
+ const state = await previousPublication(context, project.id, host, previous);
321
+ const sameConfig = context.recall(CONFIG_KEY) === config && create.length === 0;
322
+ if (sameConfig && state === "published") {
323
+ context.remember(PUBLISHED_KEY, previous);
324
+ return published(origin);
325
+ }
326
+ if (sameConfig && state === "waiting")
327
+ return waitForPublication(context, project.id, origin, previous, pause);
328
+ if (state === "waiting")
329
+ return {
330
+ kind: "blocked",
331
+ reason: "Vercel está publicando una configuración anterior.",
332
+ next: "Espera a que termine su despliegue antes de aplicar cambios adicionales.",
333
+ };
334
+ }
335
+ const source = await publishedDeployment(context, project.id, host);
336
+ if (!source) {
337
+ return {
338
+ kind: "blocked",
339
+ reason: `Tu proyecto ${project.name} todavía no tiene una versión publicada en el dominio confirmado.`,
340
+ next: "Publica la tienda una vez en Vercel y vuelve a correr el asistente.",
341
+ };
342
+ }
343
+ const names = new Set([...create, ...update]);
344
+ const variables = provided
345
+ .filter(([name]) => names.has(name))
346
+ .map(([key, { value, sensitive }]) => ({
347
+ key,
348
+ value,
349
+ type: sensitive ? "sensitive" : "encrypted",
350
+ target: ["production"],
351
+ }));
352
+ if (variables.length > 0) {
353
+ await call(context, "POST", `/v10/projects/${encodeURIComponent(project.id)}/env?upsert=true`, variables);
354
+ }
355
+ const result = await call(context, "POST", "/v13/deployments", {
356
+ name: project.name,
357
+ deploymentId: source,
358
+ target: "production",
359
+ });
360
+ const id = result["id"];
361
+ if (typeof id !== "string" || !/^dpl_[A-Za-z0-9_-]+$/.test(id) || id === source)
362
+ throw new Error("Vercel did not return a new deployment ID");
363
+ context.remember(REDEPLOY_KEY, id);
364
+ context.remember(CONFIG_KEY, config);
365
+ return waitForPublication(context, project.id, origin, id, pause);
366
+ }
367
+ catch (cause) {
368
+ if (cause instanceof NoProject)
369
+ return noProject();
370
+ return failure(cause);
371
+ }
372
+ },
373
+ };
374
+ }
375
+ export const vercelStep = createVercelStep();
@@ -0,0 +1,3 @@
1
+ import type { SetupStep } from "./step.js";
2
+ import type { SetupMemory } from "./run.js";
3
+ export declare function storeSecretsStep(privateFile: SetupMemory): SetupStep;
@@ -0,0 +1,67 @@
1
+ import { randomBytes } from "node:crypto";
2
+ const SECRETS = ["PAGAQR_PHONE_KEY_SECRET", "CRON_SECRET"];
3
+ const PUBLIC_FIELDS = {
4
+ PAGAQR_MERCHANT_NAME: "Nombre comercial que verá el comprador",
5
+ PAGAQR_PRIVACY_CONTROLLER: "Nombre del responsable del aviso de privacidad",
6
+ PAGAQR_PRIVACY_ADDRESS: "Domicilio del responsable del aviso",
7
+ PAGAQR_PRIVACY_CONTACT: "Correo para ejercer derechos de privacidad",
8
+ PAGAQR_PRIVACY_NOTICE_VERSION: "Versión del aviso, por ejemplo aviso-1",
9
+ PAGAQR_PRIVACY_NOTICE_TEXT: "Texto de tu aviso de privacidad (pégalo en una línea)",
10
+ };
11
+ export function storeSecretsStep(privateFile) {
12
+ function publish(context, fields) {
13
+ for (const name of [...SECRETS, ...Object.keys(PUBLIC_FIELDS)]) {
14
+ const value = fields.get(name);
15
+ if (value)
16
+ context.provide(name, { value, sensitive: SECRETS.includes(name) });
17
+ }
18
+ return {
19
+ kind: "done",
20
+ summary: "Las llaves de la tienda y la configuración pública están listas.",
21
+ };
22
+ }
23
+ return {
24
+ id: "store-secrets",
25
+ title: "Configurar las llaves y el aviso de la tienda",
26
+ inspect(context) {
27
+ const fields = privateFile.read();
28
+ const ready = SECRETS.every((key) => /^[0-9a-f]{64}$/.test(fields.get(key) ?? "")) &&
29
+ Object.keys(PUBLIC_FIELDS).every((key) => Boolean(fields.get(key)));
30
+ return Promise.resolve(ready
31
+ ? publish(context, fields)
32
+ : {
33
+ kind: "pending",
34
+ changes: [
35
+ "Generar las llaves propias de la tienda y guardarlas en un archivo local privado que Git ignora.",
36
+ "Registrar el nombre de la tienda y los datos públicos de su aviso de privacidad.",
37
+ ],
38
+ });
39
+ },
40
+ async apply(context) {
41
+ const fields = new Map(privateFile.read());
42
+ for (const name of SECRETS) {
43
+ const value = fields.get(name);
44
+ if (value === undefined)
45
+ fields.set(name, randomBytes(32).toString("hex"));
46
+ else if (!/^[0-9a-f]{64}$/.test(value))
47
+ throw new Error("Invalid local store key");
48
+ }
49
+ for (const [name, prompt] of Object.entries(PUBLIC_FIELDS)) {
50
+ if (fields.get(name))
51
+ continue;
52
+ const value = (await context.ask(prompt)).trim();
53
+ if (!value ||
54
+ (name === "PAGAQR_PRIVACY_NOTICE_VERSION" && !/^[A-Za-z0-9_.-]{1,64}$/.test(value)) ||
55
+ (name === "PAGAQR_MERCHANT_NAME" && value.length > 120))
56
+ return {
57
+ kind: "blocked",
58
+ reason: "Un dato de la tienda falta o tiene formato inválido.",
59
+ next: "Revisa los datos del aviso y vuelve a ejecutar el instalador.",
60
+ };
61
+ fields.set(name, value);
62
+ }
63
+ privateFile.save(fields);
64
+ return publish(context, fields);
65
+ },
66
+ };
67
+ }
@@ -0,0 +1,9 @@
1
+ import type { SecretName } from "./step.js";
2
+ export declare const SECRET_NAMES: readonly SecretName[];
3
+ export interface SetupInvocation {
4
+ readonly stdinTTY: boolean;
5
+ readonly stdoutTTY: boolean;
6
+ readonly args: readonly string[];
7
+ readonly env: Readonly<Record<string, string | undefined>>;
8
+ }
9
+ export declare function setupRefusal(input: SetupInvocation): string | undefined;
@@ -0,0 +1,17 @@
1
+ export const SECRET_NAMES = ["PEY_API_KEY", "VERCEL_TOKEN", "DATABASE_OWNER_URL"];
2
+ export function setupRefusal(input) {
3
+ if (!input.stdinTTY || !input.stdoutTTY)
4
+ return "Abre una terminal local interactiva para instalar PagaQR.";
5
+ if (input.args.length > 1 || input.args.some((arg) => arg !== "--revisar"))
6
+ return "Usa pagaqr-setup sin argumentos o con --revisar. Escribe las credenciales solo en la entrada oculta.";
7
+ for (const [key, value] of Object.entries(input.env)) {
8
+ const name = key.toUpperCase();
9
+ if (name === "CI" && value)
10
+ return "PagaQR se instala en tu terminal local, fuera de CI.";
11
+ if (SECRET_NAMES.some((secret) => secret === name) && value !== undefined)
12
+ return "Quita las credenciales del entorno y vuelve a abrir el instalador.";
13
+ if (name === "NODE_TLS_REJECT_UNAUTHORIZED" && value === "0")
14
+ return "Habilita la verificación TLS antes de abrir el instalador.";
15
+ }
16
+ return undefined;
17
+ }
@@ -0,0 +1,34 @@
1
+ import { diagnoseInstallation } from "../diagnose.js";
2
+ import type { SetupStep } from "./step.js";
3
+ import type { SetupMemory } from "./run.js";
4
+ interface Result {
5
+ readonly passed: boolean;
6
+ readonly results: readonly {
7
+ readonly name: string;
8
+ readonly ok: boolean;
9
+ }[];
10
+ }
11
+ interface DiagnosticOrder {
12
+ readonly id: string;
13
+ readonly cookie: string;
14
+ readonly cookieVerified: boolean;
15
+ }
16
+ interface DiagnosticAttempt {
17
+ readonly key: string;
18
+ readonly cookie: string;
19
+ }
20
+ export type VerifyDeployment = (origin: string, options: {
21
+ fetcher: typeof globalThis.fetch;
22
+ signal: AbortSignal;
23
+ product?: {
24
+ id: string;
25
+ cents: number;
26
+ };
27
+ diagnosticOrder?: {
28
+ read(): DiagnosticOrder | undefined;
29
+ attempt(create: () => DiagnosticAttempt): DiagnosticAttempt;
30
+ save(order: DiagnosticOrder): void;
31
+ };
32
+ }) => Promise<Result>;
33
+ export declare function verifyStep(check: VerifyDeployment, diagnose?: typeof diagnoseInstallation, privateFile?: SetupMemory): SetupStep;
34
+ export {};
@@ -0,0 +1,144 @@
1
+ import { createHash } from "node:crypto";
2
+ import { diagnoseInstallation } from "../diagnose.js";
3
+ const VERIFIED = "verificar.deployment";
4
+ const CHECKPOINT = "verificar.order";
5
+ function verificationId(context, origin) {
6
+ return createHash("sha256")
7
+ .update(JSON.stringify([origin, context.environment, context.recall("vercel.redeployId")]))
8
+ .digest("hex");
9
+ }
10
+ const alreadyVerified = {
11
+ kind: "done",
12
+ summary: "Este despliegue de la tienda ya pasó las comprobaciones.",
13
+ };
14
+ export function verifyStep(check, diagnose = diagnoseInstallation, privateFile) {
15
+ let local = new Map();
16
+ const memory = privateFile ?? {
17
+ read: () => local,
18
+ save: (facts) => {
19
+ local = facts;
20
+ },
21
+ };
22
+ function checkpoint(scope) {
23
+ const data = memory.read().get(CHECKPOINT);
24
+ if (!data)
25
+ return {};
26
+ const value = JSON.parse(data);
27
+ if (!value || typeof value !== "object" || !("scope" in value) || value.scope !== scope)
28
+ return {};
29
+ if ("complete" in value && value.complete === true)
30
+ return { complete: true };
31
+ const attempt = "attempt" in value ? value.attempt : undefined;
32
+ if (attempt &&
33
+ typeof attempt === "object" &&
34
+ "key" in attempt &&
35
+ typeof attempt.key === "string" &&
36
+ /^[A-Za-z0-9_-]{43}$/.test(attempt.key) &&
37
+ "cookie" in attempt &&
38
+ typeof attempt.cookie === "string" &&
39
+ /^(?:__Host-)?pagaqr_buyer=[A-Za-z0-9_-]{22}$/.test(attempt.cookie))
40
+ return { attempt: { key: attempt.key, cookie: attempt.cookie } };
41
+ const order = "order" in value ? value.order : undefined;
42
+ if (order &&
43
+ typeof order === "object" &&
44
+ "id" in order &&
45
+ typeof order.id === "string" &&
46
+ /^[A-Za-z0-9_-]{1,128}$/.test(order.id) &&
47
+ "cookie" in order &&
48
+ typeof order.cookie === "string" &&
49
+ /^[^\r\n;=]+=[^\r\n;]+$/.test(order.cookie) &&
50
+ "cookieVerified" in order &&
51
+ typeof order.cookieVerified === "boolean")
52
+ return { order: { id: order.id, cookie: order.cookie, cookieVerified: order.cookieVerified } };
53
+ throw new Error("Invalid diagnostic order checkpoint");
54
+ }
55
+ function saveCheckpoint(scope, result) {
56
+ const facts = new Map(memory.read());
57
+ facts.set(CHECKPOINT, JSON.stringify({ scope, ...result }));
58
+ memory.save(facts);
59
+ }
60
+ function isVerified(context, scope) {
61
+ return context.recall(VERIFIED) === scope || checkpoint(scope).complete === true;
62
+ }
63
+ return {
64
+ id: "verificar",
65
+ title: "Comprobar la tienda publicada",
66
+ inspect(context) {
67
+ const report = diagnose(context.projectDir)();
68
+ const installed = ["pagaqr", "@pagaqr/postgres", "@pagaqr/checkout-react", "@pagaqr/check"].every((name) => report.packages.some((item) => item.name === name && item.installed === "present"));
69
+ if (report.project !== "found" || !installed)
70
+ return Promise.resolve({
71
+ kind: "blocked",
72
+ reason: "Faltan paquetes de PagaQR en la tienda local.",
73
+ next: "Instala las dependencias de la plantilla y vuelve a ejecutar el instalador desde su carpeta.",
74
+ });
75
+ const origin = context.provided().get("PAGAQR_STORE_ORIGIN")?.value;
76
+ if (origin && isVerified(context, verificationId(context, origin)))
77
+ return Promise.resolve(alreadyVerified);
78
+ return Promise.resolve({
79
+ kind: "pending",
80
+ changes: ["Comprobar la tienda pública. Se crea o reutiliza un pedido de diagnóstico sin cobrarlo."],
81
+ });
82
+ },
83
+ async apply(context) {
84
+ const origin = context.provided().get("PAGAQR_STORE_ORIGIN")?.value;
85
+ const mode = context.environment === "test";
86
+ if (!origin)
87
+ throw new Error("Store origin is missing");
88
+ const id = verificationId(context, origin);
89
+ if (isVerified(context, id))
90
+ return alreadyVerified;
91
+ const result = await check(origin, {
92
+ fetcher: context.fetch,
93
+ signal: context.signal,
94
+ diagnosticOrder: {
95
+ read: () => checkpoint(id).order,
96
+ attempt: (create) => {
97
+ const saved = checkpoint(id).attempt;
98
+ if (saved)
99
+ return saved;
100
+ const attempt = create();
101
+ saveCheckpoint(id, { attempt });
102
+ return attempt;
103
+ },
104
+ save: (order) => saveCheckpoint(id, { order }),
105
+ },
106
+ ...(mode ? { product: { id: "prueba-de-cobro", cents: 1 } } : {}),
107
+ });
108
+ if (!result.passed || result.results.length === 0)
109
+ return {
110
+ kind: "blocked",
111
+ reason: "Fallaron las comprobaciones de la tienda publicada: " +
112
+ result.results
113
+ .filter((item) => !item.ok)
114
+ .map((item) => item.name)
115
+ .join(", "),
116
+ next: "Espera a que Production termine de desplegar. Revisa la configuración y vuelve a ejecutar el instalador.",
117
+ };
118
+ saveCheckpoint(id, { complete: true });
119
+ context.remember(VERIFIED, id);
120
+ if (mode) {
121
+ const wantsTest = await context.ask("¿Quieres comprobar un pago de un centavo con tu banco?", [
122
+ "sí",
123
+ "ahora no",
124
+ ]);
125
+ if (wantsTest === "sí") {
126
+ const paid = await context.ask("Abre " +
127
+ origin +
128
+ " en tu navegador. Agrega una unidad de Prueba de cobro, crea el pedido y paga $0.01 por CoDi una sola vez. ¿Tu pedido aparece como Pagado?", ["sí", "sigue pendiente"]);
129
+ if (paid !== "sí")
130
+ return {
131
+ kind: "blocked",
132
+ reason: "El cobro de prueba sigue pendiente de confirmación.",
133
+ next: "Conserva la pestaña del pedido y espera la conciliación antes de intentar otro pago.",
134
+ };
135
+ return { kind: "done", summary: "La tienda pasó el verificador y confirmaste el cobro de prueba." };
136
+ }
137
+ }
138
+ return {
139
+ kind: "done",
140
+ summary: "La tienda pasó las " + String(result.results.length) + " comprobaciones de despliegue.",
141
+ };
142
+ },
143
+ };
144
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};