@pagaqr/mcp 0.0.0-stage → 0.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +15 -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 +99 -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 +837 -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
package/CHANGELOG.md ADDED
@@ -0,0 +1,15 @@
1
+ # @pagaqr/mcp
2
+
3
+ ## 0.7.1
4
+
5
+ ### Fixed
6
+
7
+ - El Check de la tienda generada coteja el SQL que aplica el adaptador PostgreSQL instalado, así que detiene el build si una migración pierde la restricción de confirmación única.
8
+
9
+ ## 0.7.0
10
+
11
+ ### Minor Changes
12
+
13
+ - Preparar el corte público del SDK, los adaptadores, el checkout, Check y el
14
+ asistente de instalación. Empacar cada artefacto con licencia, aviso de
15
+ atribución e inventario de dependencias.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,9 @@
1
+ PagaQR
2
+ Copyright 2026 Jorge Hernández Montero y Erasmo Rodríguez Gómez
3
+
4
+ Este producto incluye software desarrollado por los autores de PagaQR,
5
+ distribuido bajo la Licencia Apache, versión 2.0 (ver LICENSE).
6
+
7
+ PagaQR se integra con el API de pey (https://pey.mx) y con CoDi de Banco de
8
+ México. "pey" y "CoDi" son marcas de sus respectivos titulares; PagaQR no es un
9
+ producto oficial de pey ni de Banco de México.
package/README.md CHANGED
@@ -1,3 +1,100 @@
1
- # Temporary Holding Version
1
+ # @pagaqr/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Servidor MCP local de diagnóstico e instalación asistida para una tienda PagaQR.
4
+
5
+ En este corte, compila el MCP desde el repositorio y configura tu cliente
6
+ para lanzar `packages/mcp/dist/cli.js` con Node por `stdio`. Usa una ruta
7
+ absoluta al ejecutable. El binario de la tienda instalada se llama
8
+ `pagaqr-mcp`. [Instalación desde el repositorio](../../README.md#con-el-mcp).
9
+
10
+ Indica el directorio de la tienda y, si quieres consultar la configuración
11
+ de producción, indica la URL pública exacta del webhook.
12
+
13
+ ```sh
14
+ pagaqr-mcp --project /ruta/a/tienda --webhook-url https://tienda.example.com/api/pagaqr/webhooks/pey
15
+ ```
16
+
17
+ Si omites `--project`, usa el directorio de trabajo del proceso. Si omites `--webhook-url`, la herramienta reporta `not_configured`. La URL que entrega debe ser la que tú confirmaste para producción. Usa HTTPS, un nombre de host y la ruta pública, sin credenciales, consultas ni fragmentos.
18
+
19
+ - `diagnose_installation` indica qué paquetes oficiales están declarados y cuáles tienen metadatos instalados en el `node_modules` de ese proyecto. Devuelve nombres y estados fijos en JSON.
20
+ - `canonical_webhook_url` devuelve el endpoint configurado al iniciar como dato JSON.
21
+
22
+ Las herramientas de diagnóstico reciben cero argumentos. La lectura se limita a `package.json` y a los manifiestos de los paquetes oficiales bajo `node_modules`. La ejecución usa stdio y lectura local. El operador configura el webhook en el portal de pey.
23
+
24
+ El servidor fija la ruta real del proyecto al iniciar, incluso si la ruta pasa por un enlace. Si el cliente arranca Node con `--permission`, resuelve las rutas reales antes de iniciar el proceso y usa esas rutas en sus concesiones y en `--project`. El modo de instalación también necesita permiso de escritura en la raíz real del proyecto y permiso de lectura para el árbol de instalación del MCP, que contiene la plantilla y sus dependencias. Incluye las rutas reales de las dependencias enlazadas.
25
+
26
+ ## Captura humana en desarrollo
27
+
28
+ Habilita las herramientas del instalador al lanzar el servidor con
29
+ `pagaqr-mcp --install --project /ruta/a/tienda`. `local_key_capture` entrega
30
+ una instrucción fija. Ejecuta el comando tú, en la raíz de la tienda, en una
31
+ terminal interactiva:
32
+
33
+ ```sh
34
+ pagaqr-capture
35
+ pagaqr-capture --webhook
36
+ ```
37
+
38
+ Si compilaste desde el clon, ejecuta los equivalentes con la ruta absoluta
39
+ a `packages/mcp/dist/capture-cli.js` desde la terminal de la tienda.
40
+
41
+ ```sh
42
+ node /ruta/a/pagaqr/packages/mcp/dist/capture-cli.js
43
+ node /ruta/a/pagaqr/packages/mcp/dist/capture-cli.js --webhook
44
+ ```
45
+
46
+ El primero guarda `PEY_API_KEY` y el segundo `PEY_WEBHOOK_SECRET`. Escribe
47
+ un solo valor en la entrada oculta y pulsa Enter. Ctrl+C cancela la captura.
48
+ Usa un repositorio donde `.env.local` esté ignorado. La captura conserva
49
+ otras variables y rechaza una variable ya declarada. En Unix restringe los
50
+ permisos del archivo a 0600. En Windows usa un directorio cuya ACL controles.
51
+
52
+ Escribe la llave de pey y el secreto del webhook únicamente en la terminal
53
+ local. Deja ambos fuera del chat, de mensajes y de argumentos del comando.
54
+ Protege el portapapeles y las transcripciones del emulador. Mantén
55
+ `.env.local` fuera del índice y limita el acceso directo del asistente a
56
+ ese archivo. En producción, el operador carga ambos valores directamente
57
+ en las variables del despliegue.
58
+
59
+ ## Catálogo y preparación de la tienda
60
+
61
+ Con `--install`, `installation_catalog` muestra las versiones y el estado de cada combinación. El perfil `next-postgres` prepara Next App Router, React y PostgreSQL con las versiones exactas del workspace. Las combinaciones publicadas se listan cuando se validen. Las versiones internas de desarrollo del perfil aún no corresponden a una instalación desde npm.
62
+
63
+ Llama a `apply_installation_template` con `{"profile":"next-postgres"}`. Crea `pagaqr-installation/` con una tienda Next y PostgreSQL, el checkout real `@pagaqr/checkout-react`, la CSP con nonce y las rutas de la demo. Incluye el catálogo de ejemplo, el carrito, la página del pedido y la cronología. La carpeta debe estar libre. Se conservan el manifiesto y el archivo local de entorno del proyecto original.
64
+
65
+ Sigue el README de la tienda generada para instalar sus paquetes desde la misma revisión, preparar PostgreSQL y arrancar. Ejecuta la captura desde la carpeta generada para que Next lea su `.env.local`. En el entorno de prueba, la tienda usa `PEY_WEBHOOK_SECRET` de la captura cuando `PEY_WEBHOOK_SECRETS` está ausente. En producción, configura la lista plural en el desplegador y registra `/api/pagaqr/webhooks/pey` en pey.
66
+
67
+ Aplica la plantilla desde un proyecto local cuyos permisos de escritura controles. Las comprobaciones de identidad del directorio protegen contra sustituciones entre llamadas. Durante la aplicación, mantén la raíz bajo control del operador. Si un fallo de disco impide comprobar la identidad de una entrada, el instalador detiene la operación y conserva esa entrada para que la revises antes de volver a aplicar el perfil.
68
+
69
+ - **Responsable:** carril B.
70
+
71
+ ## Procedencia de los paquetes
72
+
73
+ Consulta la [guía de verificación de versiones](https://github.com/pagaqr/pagaqr/blob/main/docs/runbooks/publicar-paquetes.md#verificar-y-completar-una-versión) para cotejar con npm las firmas, el flujo de release y el commit de una versión exacta.
74
+
75
+ ## Bitácora local de invocaciones
76
+
77
+ Agrega `--audit-log` cuando autorices escribir en la raíz del proyecto. Esto registra fecha, herramienta conocida y resultado en `.pagaqr-invocations.jsonl`. Configura el archivo como ignorado y rota o archiva la bitácora antes de que llegue a 1 MiB. El modo de diagnóstico por defecto conserva su permiso de solo lectura.
78
+
79
+ ## Aviso de la tienda instalada
80
+
81
+ El catálogo marca `privacyNotice: merchant_configuration_required`. Completa las cinco variables `PAGAQR_PRIVACY_*` de la tienda generada y revisa el aviso con la [guía del checkout](https://github.com/pagaqr/pagaqr/blob/main/docs/compliance/privacidad-del-checkout.md). La tienda publica su propio aviso y exige su versión para el push.
82
+
83
+ ## Asistente de instalación para personas
84
+
85
+ Cuando se publique `pagaqr-setup`, [verifica la procedencia](../../docs/runbooks/publicar-paquetes.md#verificar-y-completar-una-versión) de esa versión.
86
+ En la raíz de la tienda, ejecuta en tu terminal
87
+
88
+ ```sh
89
+ npx -y -p @pagaqr/mcp pagaqr-setup
90
+ ```
91
+
92
+ Captura con entrada oculta la llave de pey, el token de Vercel y la URL de
93
+ dueño. Con tu confirmación, registra la cuenta bancaria, prepara el rol de
94
+ aplicación, migra, carga en Vercel las variables de la tienda y verifica.
95
+ El alta de la cuenta puede quedar pendiente de activación por pey.
96
+
97
+ El asistente de IA debe pedirte que hagas este paso. La IA se abstiene de
98
+ ejecutar el comando, escribir en la terminal y leer o pedir los secretos.
99
+ La URL de dueño y el token de Vercel se quedan en la sesión local.
100
+ Usa `--revisar` en tu terminal para consultar el estado sin aplicar cambios.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ import { argv, cwd, exit, stderr, stdin, stdout } from "node:process";
3
+ import { captureLocal } from "./capture-local.js";
4
+ const messages = {
5
+ saved: "Guardado en .env.local para desarrollo.\n",
6
+ blocked: "Captura local rechazada. Verifica Git y el destino .env.local.\n",
7
+ exists: "La variable ya está declarada en .env.local.\n",
8
+ cancelled: "Captura local cancelada.\n",
9
+ terminal_required: "Abre una terminal local interactiva para capturar.\n",
10
+ };
11
+ async function start() {
12
+ const args = argv.slice(2);
13
+ const webhook = args.length === 1 && args[0] === "--webhook";
14
+ if (args.length !== 0 && !webhook)
15
+ throw new Error("Invalid capture flags");
16
+ const result = await captureLocal({
17
+ project: cwd(),
18
+ variable: webhook ? "PEY_WEBHOOK_SECRET" : "PEY_API_KEY",
19
+ terminal: stdin,
20
+ prompt: () => {
21
+ stderr.write("Escribe el valor local (entrada oculta) y pulsa Enter: ");
22
+ },
23
+ });
24
+ if (result === "saved")
25
+ stdout.write(messages.saved);
26
+ else {
27
+ stderr.write(messages[result]);
28
+ exit(2);
29
+ }
30
+ }
31
+ void start().catch(() => {
32
+ stderr.write("Captura local rechazada. Usa el comando sin valores en argumentos.\n");
33
+ exit(2);
34
+ });
@@ -0,0 +1,9 @@
1
+ import type { SaveStatus, SecretVariable } from "./capture-store.js";
2
+ import type { MaskedTerminal } from "./masked-terminal.js";
3
+ export type CaptureStatus = SaveStatus | "cancelled" | "terminal_required";
4
+ export declare function captureLocal(options: {
5
+ project: string;
6
+ variable: SecretVariable;
7
+ terminal: MaskedTerminal;
8
+ prompt: () => void;
9
+ }): Promise<CaptureStatus>;
@@ -0,0 +1,18 @@
1
+ import { captureRoot, saveLocalSecret } from "./capture-store.js";
2
+ import { readMasked } from "./masked-terminal.js";
3
+ export async function captureLocal(options) {
4
+ if (!options.terminal.isTTY)
5
+ return "terminal_required";
6
+ const root = captureRoot(options.project);
7
+ if (!root)
8
+ return "blocked";
9
+ const value = await readMasked(options.terminal, options.prompt);
10
+ if (!value)
11
+ return "cancelled";
12
+ try {
13
+ return saveLocalSecret(root, options.variable, value);
14
+ }
15
+ finally {
16
+ value.fill(0);
17
+ }
18
+ }
@@ -0,0 +1,7 @@
1
+ export type SecretVariable = "PEY_API_KEY" | "PEY_WEBHOOK_SECRET";
2
+ export type SaveStatus = "saved" | "blocked" | "exists";
3
+ export declare function gitIgnores(root: string, path?: string): boolean;
4
+ export declare function gitWorkingTree(root: string): boolean;
5
+ export declare function gitFileProtection(root: string, path: string): "ignored" | "tracked" | "unprotected";
6
+ export declare function captureRoot(directory: string): string | undefined;
7
+ export declare function saveLocalSecret(root: string, variable: SecretVariable, secret: Buffer): SaveStatus;
@@ -0,0 +1,175 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, ftruncateSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, rmdirSync, writeSync, } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { env, platform } from "node:process";
5
+ import { parseEnv } from "node:util";
6
+ const DOTENV = ".env.local";
7
+ const LOCK = ".pagaqr-capture-lock";
8
+ const MAX_FILE_BYTES = 64 * 1024;
9
+ const GIT_ENV = new Set([
10
+ "PATH",
11
+ "PATHEXT",
12
+ "SYSTEMROOT",
13
+ "WINDIR",
14
+ "HOME",
15
+ "USERPROFILE",
16
+ "HOMEDRIVE",
17
+ "HOMEPATH",
18
+ "TMP",
19
+ "TEMP",
20
+ "LANG",
21
+ "LC_ALL",
22
+ "LOCALAPPDATA",
23
+ ]);
24
+ function runGit(root, args) {
25
+ const environment = Object.fromEntries(Object.entries(env).filter(([key]) => GIT_ENV.has(key.toUpperCase())));
26
+ return spawnSync("git", ["--no-optional-locks", ...args], {
27
+ cwd: root,
28
+ env: { ...environment, LC_ALL: "C" },
29
+ encoding: "utf8",
30
+ stdio: ["ignore", "pipe", "pipe"],
31
+ windowsHide: true,
32
+ timeout: 5000,
33
+ });
34
+ }
35
+ export function gitIgnores(root, path = DOTENV) {
36
+ // Tracked paths are excluded from ordinary check-ignore results.
37
+ return runGit(root, ["check-ignore", "-q", "--", path]).status === 0;
38
+ }
39
+ export function gitWorkingTree(root) {
40
+ const result = runGit(root, ["rev-parse", "--is-inside-work-tree"]);
41
+ if (result.status === 0)
42
+ return result.stdout.trim() === "true";
43
+ if (result.status === 128 && result.stderr.startsWith("fatal: not a git repository"))
44
+ return false;
45
+ throw new Error("Git could not inspect the working tree");
46
+ }
47
+ export function gitFileProtection(root, path) {
48
+ const ignored = runGit(root, ["check-ignore", "-q", "--", path]);
49
+ if (ignored.status === 0)
50
+ return "ignored";
51
+ if (ignored.status !== 1)
52
+ throw new Error("Git could not inspect the ignore rules");
53
+ const tracked = runGit(root, ["ls-files", "--error-unmatch", "--", path]);
54
+ if (tracked.status === 0)
55
+ return "tracked";
56
+ if (tracked.status === 1)
57
+ return "unprotected";
58
+ throw new Error("Git could not inspect the index");
59
+ }
60
+ export function captureRoot(directory) {
61
+ try {
62
+ const root = realpathSync(directory);
63
+ return gitIgnores(root) ? root : undefined;
64
+ }
65
+ catch {
66
+ return undefined;
67
+ }
68
+ }
69
+ function existing(path) {
70
+ try {
71
+ return lstatSync(path);
72
+ }
73
+ catch (error) {
74
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
75
+ return undefined;
76
+ throw error;
77
+ }
78
+ }
79
+ function regular(info) {
80
+ return info.isFile() && info.nlink === 1 && info.size <= MAX_FILE_BYTES;
81
+ }
82
+ function sameFile(a, b) {
83
+ return a.ino === b.ino && a.dev === b.dev && a.size === b.size && a.mtimeMs === b.mtimeMs;
84
+ }
85
+ function accepted(variable, value) {
86
+ if (variable === "PEY_API_KEY")
87
+ return value.length >= 8 && value.length <= 512 && !/[^A-Za-z0-9_./+=-]/.test(value);
88
+ if (!/^whsec_[A-Za-z0-9+/]+={0,2}$/.test(value))
89
+ return false;
90
+ const encoded = value.slice(6);
91
+ const decoded = Buffer.from(encoded, "base64");
92
+ try {
93
+ return decoded.length >= 24 && decoded.length <= 64 && decoded.toString("base64") === encoded;
94
+ }
95
+ finally {
96
+ decoded.fill(0);
97
+ }
98
+ }
99
+ function appendSetting(root, variable, value) {
100
+ const path = join(root, DOTENV);
101
+ const original = existing(path);
102
+ if (original && !regular(original))
103
+ return "blocked";
104
+ const flags = constants.O_RDWR | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
105
+ const fd = openSync(path, original ? flags : flags | constants.O_CREAT | constants.O_EXCL, 0o600);
106
+ try {
107
+ const opened = fstatSync(fd);
108
+ if (!regular(opened) || (original && !sameFile(original, opened)))
109
+ return "blocked";
110
+ const source = Buffer.alloc(opened.size + 1);
111
+ try {
112
+ if (readSync(fd, source, 0, source.length, 0) !== opened.size)
113
+ return "blocked";
114
+ const previous = source.toString("utf8", 0, opened.size);
115
+ if (Object.hasOwn(parseEnv(previous), variable))
116
+ return "exists";
117
+ const prefix = previous && !previous.endsWith("\n") ? "\n" : "";
118
+ const line = prefix + variable + "=" + value + "\n";
119
+ if (opened.size + Buffer.byteLength(line) > MAX_FILE_BYTES ||
120
+ parseEnv(previous + line)[variable] !== value)
121
+ return "blocked";
122
+ if (!gitIgnores(root))
123
+ return "blocked";
124
+ const latest = lstatSync(path);
125
+ if (!regular(latest) || !sameFile(opened, latest))
126
+ return "blocked";
127
+ if (platform !== "win32")
128
+ fchmodSync(fd, 0o600);
129
+ const bytes = Buffer.from(line);
130
+ let written = 0;
131
+ try {
132
+ // A Windows append-only handle cannot truncate a partial write.
133
+ written = writeSync(fd, bytes, 0, bytes.length, opened.size);
134
+ if (written !== bytes.length)
135
+ throw new Error("Short local write");
136
+ fsyncSync(fd);
137
+ }
138
+ catch {
139
+ if (written > 0 && fstatSync(fd).size === opened.size + written)
140
+ ftruncateSync(fd, opened.size);
141
+ return "blocked";
142
+ }
143
+ finally {
144
+ bytes.fill(0);
145
+ }
146
+ return "saved";
147
+ }
148
+ finally {
149
+ source.fill(0);
150
+ }
151
+ }
152
+ finally {
153
+ closeSync(fd);
154
+ }
155
+ }
156
+ export function saveLocalSecret(root, variable, secret) {
157
+ const value = secret.toString("latin1");
158
+ if (!accepted(variable, value))
159
+ return "blocked";
160
+ try {
161
+ if (!gitIgnores(root))
162
+ return "blocked";
163
+ const lock = join(root, LOCK);
164
+ mkdirSync(lock);
165
+ try {
166
+ return appendSetting(root, variable, value);
167
+ }
168
+ finally {
169
+ rmdirSync(lock);
170
+ }
171
+ }
172
+ catch {
173
+ return "blocked";
174
+ }
175
+ }
@@ -0,0 +1,33 @@
1
+ export declare const catalogue: {
2
+ readonly published: readonly [];
3
+ readonly preview: {
4
+ readonly profile: "next-postgres";
5
+ readonly status: "local_preparation";
6
+ readonly checkout: "ready";
7
+ readonly privacyNotice: "merchant_configuration_required";
8
+ readonly node: "26.14.0";
9
+ readonly dependencies: {
10
+ readonly next: "16.5.0";
11
+ readonly react: "19.3.1";
12
+ readonly "react-dom": "19.3.1";
13
+ readonly pg: "8.23.1";
14
+ readonly "server-only": "0.0.1";
15
+ };
16
+ readonly devDependencies: {
17
+ readonly typescript: "6.0.3";
18
+ readonly vitest: "5.1.2";
19
+ readonly "@pagaqr/check": string | undefined;
20
+ readonly "@types/node": "26.6.11";
21
+ readonly "@types/pg": "8.23.1";
22
+ readonly "@types/react": "19.3.3";
23
+ readonly "@types/react-dom": "19.3.0";
24
+ };
25
+ readonly workspace: {
26
+ readonly pagaqr: string | undefined;
27
+ readonly "@pagaqr/postgres": string | undefined;
28
+ readonly "@pagaqr/checkout-react": string | undefined;
29
+ };
30
+ };
31
+ readonly firstParty: Readonly<Record<string, string>>;
32
+ };
33
+ export declare function usesCatalogue(manifest: Record<string, unknown>, requireExactVersions?: boolean): boolean;