@erseco/autofirma-intermediate-server 0.0.0-stage → 1.9.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +339 -0
- package/README.md +134 -2
- package/dist/chunk-EJ62BDQ2.js +50 -0
- package/dist/chunk-EJ62BDQ2.js.map +1 -0
- package/dist/chunk-ZHQSGSOI.js +184 -0
- package/dist/chunk-ZHQSGSOI.js.map +1 -0
- package/dist/fs.cjs +145 -0
- package/dist/fs.cjs.map +1 -0
- package/dist/fs.d.ts +21 -0
- package/dist/fs.js +122 -0
- package/dist/fs.js.map +1 -0
- package/dist/index.cjs +261 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +21 -0
- package/dist/index.js.map +1 -0
- package/dist/node.cjs +109 -0
- package/dist/node.cjs.map +1 -0
- package/dist/node.d.ts +13 -0
- package/dist/node.js +51 -0
- package/dist/node.js.map +1 -0
- package/dist/protocol.d.ts +30 -0
- package/dist/server.d.ts +42 -0
- package/dist/store.d.ts +34 -0
- package/package.json +70 -4
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
IntermediateServer: () => IntermediateServer,
|
|
24
|
+
MemoryStore: () => MemoryStore,
|
|
25
|
+
ProtocolError: () => ProtocolError,
|
|
26
|
+
SYNTAX_VERSION: () => SYNTAX_VERSION,
|
|
27
|
+
StorageError: () => StorageError,
|
|
28
|
+
protocolError: () => protocolError,
|
|
29
|
+
systemClock: () => systemClock
|
|
30
|
+
});
|
|
31
|
+
module.exports = __toCommonJS(src_exports);
|
|
32
|
+
|
|
33
|
+
// src/protocol.ts
|
|
34
|
+
var MESSAGES = {
|
|
35
|
+
"ERR-00": "No se ha indicado c\xF3digo de operaci\xF3n",
|
|
36
|
+
"ERR-01": "C\xF3digo de operaci\xF3n no soportado",
|
|
37
|
+
"ERR-02": "No se han proporcionado los datos de la operaci\xF3n",
|
|
38
|
+
"ERR-05": "No se ha proporcionado un identificador para los datos",
|
|
39
|
+
"ERR-06": "El identificador para los datos es inv\xE1lido",
|
|
40
|
+
"ERR-07": "Los datos solicitados o enviados son inv\xE1lidos",
|
|
41
|
+
"ERR-18": "No se ha podido enviar la firma generada a la Web de origen",
|
|
42
|
+
"ERR-20": "No se ha indicado la versi\xF3n de la sintaxis de la operaci\xF3n"
|
|
43
|
+
};
|
|
44
|
+
function protocolError(code) {
|
|
45
|
+
return `${code}:=${MESSAGES[code]}`;
|
|
46
|
+
}
|
|
47
|
+
var ProtocolError = {
|
|
48
|
+
missingOperation: protocolError("ERR-00"),
|
|
49
|
+
unsupportedOperation: protocolError("ERR-01"),
|
|
50
|
+
missingData: protocolError("ERR-02"),
|
|
51
|
+
missingIdentifier: protocolError("ERR-05"),
|
|
52
|
+
invalidIdentifier: protocolError("ERR-06"),
|
|
53
|
+
invalidData: protocolError("ERR-07"),
|
|
54
|
+
storageFailure: protocolError("ERR-18"),
|
|
55
|
+
missingSyntaxVersion: protocolError("ERR-20")
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
// src/server.ts
|
|
59
|
+
var SYNTAX_VERSION = "1_0";
|
|
60
|
+
var HEADERS = {
|
|
61
|
+
"Cache-Control": "no-store",
|
|
62
|
+
"Content-Type": "text/plain; charset=UTF-8",
|
|
63
|
+
"X-Content-Type-Options": "nosniff"
|
|
64
|
+
};
|
|
65
|
+
var IDENTIFIER = /^[A-Za-z0-9_-]{1,128}$/;
|
|
66
|
+
var encoder = new TextEncoder();
|
|
67
|
+
var IntermediateServer = class {
|
|
68
|
+
constructor(store, options = {}) {
|
|
69
|
+
this.store = store;
|
|
70
|
+
this.maxPayloadBytes = options.maxPayloadBytes ?? 20 * 1024 * 1024;
|
|
71
|
+
this.ttlSeconds = options.ttlSeconds ?? 120;
|
|
72
|
+
if (!Number.isInteger(this.maxPayloadBytes) || this.maxPayloadBytes < 1) {
|
|
73
|
+
throw new RangeError("Maximum payload size must be a positive integer.");
|
|
74
|
+
}
|
|
75
|
+
if (!Number.isInteger(this.ttlSeconds) || this.ttlSeconds < 1) {
|
|
76
|
+
throw new RangeError("TTL must be a positive integer.");
|
|
77
|
+
}
|
|
78
|
+
this.maxRequestBytes = this.maxPayloadBytes * 3 + 64 * 1024;
|
|
79
|
+
}
|
|
80
|
+
store;
|
|
81
|
+
maxPayloadBytes;
|
|
82
|
+
ttlSeconds;
|
|
83
|
+
/**
|
|
84
|
+
* Límite del cuerpo HTTP completo. La codificación de formulario puede
|
|
85
|
+
* triplicar el tamaño del dato (`+` pasa a `%2B`), más margen para el resto
|
|
86
|
+
* de campos. Por encima no se sigue leyendo.
|
|
87
|
+
*/
|
|
88
|
+
maxRequestBytes;
|
|
89
|
+
/**
|
|
90
|
+
* Atiende una petición de la Fetch API: Hono, Bun, Deno, Cloudflare Workers
|
|
91
|
+
* y cualquier runtime con `Request`/`Response` estándar.
|
|
92
|
+
*/
|
|
93
|
+
async fetch(request) {
|
|
94
|
+
const parameters = new URLSearchParams(new URL(request.url).search);
|
|
95
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
96
|
+
const body = await readLimited(request.body, this.maxRequestBytes);
|
|
97
|
+
if (body === null) {
|
|
98
|
+
return toFetchResponse(respond(ProtocolError.invalidData));
|
|
99
|
+
}
|
|
100
|
+
for (const [name, value2] of new URLSearchParams(body)) {
|
|
101
|
+
parameters.set(name, value2);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return toFetchResponse(await this.handle(parameters));
|
|
105
|
+
}
|
|
106
|
+
/** Atiende unos parámetros ya leídos. Un fallo del almacenamiento sale como `ERR-…`. */
|
|
107
|
+
async handle(parameters) {
|
|
108
|
+
return respond(await this.body(parameters));
|
|
109
|
+
}
|
|
110
|
+
async body(parameters) {
|
|
111
|
+
const operation = value(parameters, "op")?.toLowerCase();
|
|
112
|
+
if (!operation) {
|
|
113
|
+
return ProtocolError.missingOperation;
|
|
114
|
+
}
|
|
115
|
+
if (operation === "check") {
|
|
116
|
+
return "OK";
|
|
117
|
+
}
|
|
118
|
+
const version = value(parameters, "v");
|
|
119
|
+
if (version === null) {
|
|
120
|
+
return ProtocolError.missingSyntaxVersion;
|
|
121
|
+
}
|
|
122
|
+
if (version !== SYNTAX_VERSION) {
|
|
123
|
+
return ProtocolError.unsupportedOperation;
|
|
124
|
+
}
|
|
125
|
+
if (operation !== "put" && operation !== "get") {
|
|
126
|
+
return ProtocolError.unsupportedOperation;
|
|
127
|
+
}
|
|
128
|
+
const identifier = value(parameters, "id");
|
|
129
|
+
if (!identifier) {
|
|
130
|
+
return ProtocolError.missingIdentifier;
|
|
131
|
+
}
|
|
132
|
+
if (!IDENTIFIER.test(identifier)) {
|
|
133
|
+
return ProtocolError.invalidIdentifier;
|
|
134
|
+
}
|
|
135
|
+
return operation === "put" ? this.put(identifier, value(parameters, "dat")) : this.get(identifier);
|
|
136
|
+
}
|
|
137
|
+
async put(identifier, data) {
|
|
138
|
+
let payload = data;
|
|
139
|
+
if (!payload) {
|
|
140
|
+
payload = ProtocolError.missingData;
|
|
141
|
+
} else if (encoder.encode(payload).byteLength > this.maxPayloadBytes) {
|
|
142
|
+
payload = ProtocolError.invalidData;
|
|
143
|
+
}
|
|
144
|
+
try {
|
|
145
|
+
await this.store.put(identifier, payload, this.ttlSeconds);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (isStorageError(error)) {
|
|
148
|
+
return ProtocolError.storageFailure;
|
|
149
|
+
}
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
return "OK";
|
|
153
|
+
}
|
|
154
|
+
async get(identifier) {
|
|
155
|
+
try {
|
|
156
|
+
return await this.store.consume(identifier) ?? ProtocolError.invalidIdentifier;
|
|
157
|
+
} catch (error) {
|
|
158
|
+
if (isStorageError(error)) {
|
|
159
|
+
return ProtocolError.invalidData;
|
|
160
|
+
}
|
|
161
|
+
throw error;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
function isStorageError(error) {
|
|
166
|
+
return error instanceof Error && error.name === "StorageError";
|
|
167
|
+
}
|
|
168
|
+
function respond(body) {
|
|
169
|
+
return { status: 200, headers: { ...HEADERS }, body };
|
|
170
|
+
}
|
|
171
|
+
function toFetchResponse(response) {
|
|
172
|
+
return new Response(response.body, {
|
|
173
|
+
status: response.status,
|
|
174
|
+
headers: response.headers
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
async function readLimited(stream, limit) {
|
|
178
|
+
if (stream === null) {
|
|
179
|
+
return "";
|
|
180
|
+
}
|
|
181
|
+
const decoder = new TextDecoder();
|
|
182
|
+
const reader = stream.getReader();
|
|
183
|
+
let size = 0;
|
|
184
|
+
let text = "";
|
|
185
|
+
for (; ; ) {
|
|
186
|
+
const { done, value: value2 } = await reader.read();
|
|
187
|
+
if (done) {
|
|
188
|
+
return text + decoder.decode();
|
|
189
|
+
}
|
|
190
|
+
size += value2.byteLength;
|
|
191
|
+
if (size > limit) {
|
|
192
|
+
await reader.cancel();
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
text += decoder.decode(value2, { stream: true });
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
function value(parameters, name) {
|
|
199
|
+
if (parameters instanceof URLSearchParams) {
|
|
200
|
+
return parameters.get(name);
|
|
201
|
+
}
|
|
202
|
+
if (!Object.hasOwn(parameters, name)) {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
const raw = parameters[name];
|
|
206
|
+
return typeof raw === "string" || typeof raw === "number" ? String(raw) : null;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// src/store.ts
|
|
210
|
+
var systemClock = () => Math.floor(Date.now() / 1e3);
|
|
211
|
+
var StorageError = class extends Error {
|
|
212
|
+
name = "StorageError";
|
|
213
|
+
};
|
|
214
|
+
var MemoryStore = class {
|
|
215
|
+
constructor(clock = systemClock) {
|
|
216
|
+
this.clock = clock;
|
|
217
|
+
}
|
|
218
|
+
clock;
|
|
219
|
+
entries = /* @__PURE__ */ new Map();
|
|
220
|
+
async put(identifier, payload, ttlSeconds) {
|
|
221
|
+
assertPositiveTtl(ttlSeconds);
|
|
222
|
+
this.entries.set(identifier, {
|
|
223
|
+
expiresAt: this.clock() + ttlSeconds,
|
|
224
|
+
payload
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
async consume(identifier) {
|
|
228
|
+
const entry = this.entries.get(identifier);
|
|
229
|
+
if (entry === void 0) {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
this.entries.delete(identifier);
|
|
233
|
+
return entry.expiresAt <= this.clock() ? null : entry.payload;
|
|
234
|
+
}
|
|
235
|
+
async purgeExpired() {
|
|
236
|
+
let purged = 0;
|
|
237
|
+
for (const [identifier, entry] of this.entries) {
|
|
238
|
+
if (entry.expiresAt <= this.clock()) {
|
|
239
|
+
this.entries.delete(identifier);
|
|
240
|
+
purged++;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return purged;
|
|
244
|
+
}
|
|
245
|
+
};
|
|
246
|
+
function assertPositiveTtl(ttlSeconds) {
|
|
247
|
+
if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1) {
|
|
248
|
+
throw new RangeError("TTL must be a positive integer.");
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
252
|
+
0 && (module.exports = {
|
|
253
|
+
IntermediateServer,
|
|
254
|
+
MemoryStore,
|
|
255
|
+
ProtocolError,
|
|
256
|
+
SYNTAX_VERSION,
|
|
257
|
+
StorageError,
|
|
258
|
+
protocolError,
|
|
259
|
+
systemClock
|
|
260
|
+
});
|
|
261
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/protocol.ts","../src/server.ts","../src/store.ts"],"sourcesContent":["export {\n ProtocolError,\n protocolError,\n type ProtocolErrorCode,\n} from \"./protocol.ts\";\nexport {\n IntermediateServer,\n SYNTAX_VERSION,\n type IntermediateServerOptions,\n type Parameters,\n type ProtocolResponse,\n} from \"./server.ts\";\nexport {\n MemoryStore,\n StorageError,\n systemClock,\n type Clock,\n type Store,\n} from \"./store.ts\";\n","/**\n * Códigos de error del protocolo `v=1_0` de AutoScript.\n *\n * AutoScript solo entiende estas cadenas: un fallo interno tiene que salir con\n * uno de estos códigos y no como un error HTTP, o quien firma se queda\n * esperando sin explicación. Textos idénticos a los del servidor PHP.\n */\nconst MESSAGES = {\n \"ERR-00\": \"No se ha indicado código de operación\",\n \"ERR-01\": \"Código de operación no soportado\",\n \"ERR-02\": \"No se han proporcionado los datos de la operación\",\n \"ERR-05\": \"No se ha proporcionado un identificador para los datos\",\n \"ERR-06\": \"El identificador para los datos es inválido\",\n \"ERR-07\": \"Los datos solicitados o enviados son inválidos\",\n \"ERR-18\": \"No se ha podido enviar la firma generada a la Web de origen\",\n \"ERR-20\": \"No se ha indicado la versión de la sintaxis de la operación\",\n} as const;\n\nexport type ProtocolErrorCode = keyof typeof MESSAGES;\n\nexport function protocolError(code: ProtocolErrorCode): string {\n return `${code}:=${MESSAGES[code]}`;\n}\n\nexport const ProtocolError = {\n missingOperation: protocolError(\"ERR-00\"),\n unsupportedOperation: protocolError(\"ERR-01\"),\n missingData: protocolError(\"ERR-02\"),\n missingIdentifier: protocolError(\"ERR-05\"),\n invalidIdentifier: protocolError(\"ERR-06\"),\n invalidData: protocolError(\"ERR-07\"),\n storageFailure: protocolError(\"ERR-18\"),\n missingSyntaxVersion: protocolError(\"ERR-20\"),\n} as const;\n","import { ProtocolError } from \"./protocol.ts\";\nimport type { Store } from \"./store.ts\";\n\nexport const SYNTAX_VERSION = \"1_0\";\n\n/** Parámetros ya leídos de la consulta y del formulario. */\nexport type Parameters = URLSearchParams | Readonly<Record<string, unknown>>;\n\nexport interface ProtocolResponse {\n readonly status: number;\n readonly headers: Readonly<Record<string, string>>;\n readonly body: string;\n}\n\nexport interface IntermediateServerOptions {\n /** Tamaño máximo de `dat` en bytes. Por defecto, 20 MiB como AutoScript. */\n readonly maxPayloadBytes?: number;\n /** Tiempo de vida de cada mensaje. Por defecto, 120 segundos. */\n readonly ttlSeconds?: number;\n}\n\nconst HEADERS = {\n \"Cache-Control\": \"no-store\",\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"X-Content-Type-Options\": \"nosniff\",\n} as const;\n\nconst IDENTIFIER = /^[A-Za-z0-9_-]{1,128}$/;\nconst encoder = new TextEncoder();\n\n/**\n * Servidor intermedio de AutoScript (`storage` y `retrieve`), independiente de\n * frameworks. Las dos rutas pueden delegar en la misma instancia.\n */\nexport class IntermediateServer {\n private readonly maxPayloadBytes: number;\n private readonly ttlSeconds: number;\n /**\n * Límite del cuerpo HTTP completo. La codificación de formulario puede\n * triplicar el tamaño del dato (`+` pasa a `%2B`), más margen para el resto\n * de campos. Por encima no se sigue leyendo.\n */\n readonly maxRequestBytes: number;\n\n constructor(\n private readonly store: Store,\n options: IntermediateServerOptions = {},\n ) {\n this.maxPayloadBytes = options.maxPayloadBytes ?? 20 * 1024 * 1024;\n this.ttlSeconds = options.ttlSeconds ?? 120;\n if (!Number.isInteger(this.maxPayloadBytes) || this.maxPayloadBytes < 1) {\n throw new RangeError(\"Maximum payload size must be a positive integer.\");\n }\n if (!Number.isInteger(this.ttlSeconds) || this.ttlSeconds < 1) {\n throw new RangeError(\"TTL must be a positive integer.\");\n }\n this.maxRequestBytes = this.maxPayloadBytes * 3 + 64 * 1024;\n }\n\n /**\n * Atiende una petición de la Fetch API: Hono, Bun, Deno, Cloudflare Workers\n * y cualquier runtime con `Request`/`Response` estándar.\n */\n async fetch(request: Request): Promise<Response> {\n const parameters = new URLSearchParams(new URL(request.url).search);\n if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n const body = await readLimited(request.body, this.maxRequestBytes);\n if (body === null) {\n return toFetchResponse(respond(ProtocolError.invalidData));\n }\n // Los campos del formulario prevalecen sobre los de la consulta.\n for (const [name, value] of new URLSearchParams(body)) {\n parameters.set(name, value);\n }\n }\n return toFetchResponse(await this.handle(parameters));\n }\n\n /** Atiende unos parámetros ya leídos. Un fallo del almacenamiento sale como `ERR-…`. */\n async handle(parameters: Parameters): Promise<ProtocolResponse> {\n return respond(await this.body(parameters));\n }\n\n private async body(parameters: Parameters): Promise<string> {\n const operation = value(parameters, \"op\")?.toLowerCase();\n if (!operation) {\n return ProtocolError.missingOperation;\n }\n if (operation === \"check\") {\n return \"OK\";\n }\n const version = value(parameters, \"v\");\n if (version === null) {\n return ProtocolError.missingSyntaxVersion;\n }\n if (version !== SYNTAX_VERSION) {\n return ProtocolError.unsupportedOperation;\n }\n if (operation !== \"put\" && operation !== \"get\") {\n return ProtocolError.unsupportedOperation;\n }\n\n const identifier = value(parameters, \"id\");\n if (!identifier) {\n return ProtocolError.missingIdentifier;\n }\n if (!IDENTIFIER.test(identifier)) {\n return ProtocolError.invalidIdentifier;\n }\n\n return operation === \"put\"\n ? this.put(identifier, value(parameters, \"dat\"))\n : this.get(identifier);\n }\n\n private async put(identifier: string, data: string | null): Promise<string> {\n // Un dato ausente o excesivo no se rechaza aquí: se guarda el error para\n // que quien recoja el mensaje reciba el motivo, como hace AutoScript.\n let payload = data;\n if (!payload) {\n payload = ProtocolError.missingData;\n } else if (encoder.encode(payload).byteLength > this.maxPayloadBytes) {\n payload = ProtocolError.invalidData;\n }\n\n try {\n await this.store.put(identifier, payload, this.ttlSeconds);\n } catch (error) {\n if (isStorageError(error)) {\n return ProtocolError.storageFailure;\n }\n throw error;\n }\n return \"OK\";\n }\n\n private async get(identifier: string): Promise<string> {\n try {\n return (\n (await this.store.consume(identifier)) ??\n ProtocolError.invalidIdentifier\n );\n } catch (error) {\n if (isStorageError(error)) {\n return ProtocolError.invalidData;\n }\n throw error;\n }\n }\n}\n\n/**\n * Por nombre y no con `instanceof`: en CommonJS cada punto de entrada lleva su\n * propia copia de la clase, y el error de `./fs` no sería instancia de la de\n * `.`.\n */\nfunction isStorageError(error: unknown): boolean {\n return error instanceof Error && error.name === \"StorageError\";\n}\n\nexport function respond(body: string): ProtocolResponse {\n return { status: 200, headers: { ...HEADERS }, body };\n}\n\nfunction toFetchResponse(response: ProtocolResponse): Response {\n return new Response(response.body, {\n status: response.status,\n headers: response.headers,\n });\n}\n\n/** Lee el cuerpo como texto, o devuelve `null` si supera `limit` bytes. */\nasync function readLimited(\n stream: ReadableStream<Uint8Array> | null,\n limit: number,\n): Promise<string | null> {\n if (stream === null) {\n return \"\";\n }\n const decoder = new TextDecoder();\n const reader = stream.getReader();\n let size = 0;\n let text = \"\";\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return text + decoder.decode();\n }\n size += value.byteLength;\n if (size > limit) {\n await reader.cancel();\n return null;\n }\n text += decoder.decode(value, { stream: true });\n }\n}\n\nfunction value(parameters: Parameters, name: string): string | null {\n if (parameters instanceof URLSearchParams) {\n return parameters.get(name);\n }\n if (!Object.hasOwn(parameters, name)) {\n return null;\n }\n const raw = parameters[name];\n return typeof raw === \"string\" || typeof raw === \"number\"\n ? String(raw)\n : null;\n}\n","/** Segundos desde la época Unix. Se inyecta para poder probar la caducidad. */\nexport type Clock = () => number;\n\nexport const systemClock: Clock = () => Math.floor(Date.now() / 1000);\n\n/** Error de almacenamiento: el servidor lo traduce a un código del protocolo. */\nexport class StorageError extends Error {\n override name = \"StorageError\";\n}\n\n/**\n * Almacenamiento temporal de mensajes cifrados.\n *\n * `consume()` debe ser atómico: ningún mensaje puede entregarse dos veces,\n * tampoco con varias peticiones simultáneas o varios nodos.\n */\nexport interface Store {\n put(identifier: string, payload: string, ttlSeconds: number): Promise<void>;\n consume(identifier: string): Promise<string | null>;\n purgeExpired(): Promise<number>;\n}\n\ninterface Entry {\n readonly expiresAt: number;\n readonly payload: string;\n}\n\n/**\n * Almacenamiento en memoria del proceso.\n *\n * Sirve para pruebas y para un único proceso persistente. No vale con varias\n * instancias ni en entornos serverless, donde cada petición puede caer en un\n * proceso distinto.\n */\nexport class MemoryStore implements Store {\n private readonly entries = new Map<string, Entry>();\n\n constructor(private readonly clock: Clock = systemClock) {}\n\n async put(\n identifier: string,\n payload: string,\n ttlSeconds: number,\n ): Promise<void> {\n assertPositiveTtl(ttlSeconds);\n this.entries.set(identifier, {\n expiresAt: this.clock() + ttlSeconds,\n payload,\n });\n }\n\n async consume(identifier: string): Promise<string | null> {\n const entry = this.entries.get(identifier);\n if (entry === undefined) {\n return null;\n }\n this.entries.delete(identifier);\n return entry.expiresAt <= this.clock() ? null : entry.payload;\n }\n\n async purgeExpired(): Promise<number> {\n let purged = 0;\n for (const [identifier, entry] of this.entries) {\n if (entry.expiresAt <= this.clock()) {\n this.entries.delete(identifier);\n purged++;\n }\n }\n return purged;\n }\n}\n\nexport function assertPositiveTtl(ttlSeconds: number): void {\n if (!Number.isInteger(ttlSeconds) || ttlSeconds < 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AM,eAAgC;AACpC,QAAI,SAAS;AACb,eAAW,CAAC,YAAY,KAAK,KAAK,KAAK,SAAS;AAC9C,UAAI,MAAM,aAAa,KAAK,MAAM,GAAG;AACnC,aAAK,QAAQ,OAAO,UAAU;AAC9B;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;AAEO,SAAS,kBAAkB,YAA0B;AAC1D,MAAI,CAAC,OAAO,UAAU,UAAU,KAAK,aAAa,GAAG;AACnD,UAAM,IAAI,WAAW,iCAAiC;AAAA,EACxD;AACF;","names":["value"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
export { ProtocolError, protocolError, type ProtocolErrorCode, } from "./protocol.ts";
|
|
2
|
+
export { IntermediateServer, SYNTAX_VERSION, type IntermediateServerOptions, type Parameters, type ProtocolResponse, } from "./server.ts";
|
|
3
|
+
export { MemoryStore, StorageError, systemClock, type Clock, type Store, } from "./store.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MemoryStore,
|
|
3
|
+
StorageError,
|
|
4
|
+
systemClock
|
|
5
|
+
} from "./chunk-EJ62BDQ2.js";
|
|
6
|
+
import {
|
|
7
|
+
IntermediateServer,
|
|
8
|
+
ProtocolError,
|
|
9
|
+
SYNTAX_VERSION,
|
|
10
|
+
protocolError
|
|
11
|
+
} from "./chunk-ZHQSGSOI.js";
|
|
12
|
+
export {
|
|
13
|
+
IntermediateServer,
|
|
14
|
+
MemoryStore,
|
|
15
|
+
ProtocolError,
|
|
16
|
+
SYNTAX_VERSION,
|
|
17
|
+
StorageError,
|
|
18
|
+
protocolError,
|
|
19
|
+
systemClock
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/node.cjs
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/node.ts
|
|
21
|
+
var node_exports = {};
|
|
22
|
+
__export(node_exports, {
|
|
23
|
+
toNodeHandler: () => toNodeHandler
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(node_exports);
|
|
26
|
+
|
|
27
|
+
// src/protocol.ts
|
|
28
|
+
var MESSAGES = {
|
|
29
|
+
"ERR-00": "No se ha indicado c\xF3digo de operaci\xF3n",
|
|
30
|
+
"ERR-01": "C\xF3digo de operaci\xF3n no soportado",
|
|
31
|
+
"ERR-02": "No se han proporcionado los datos de la operaci\xF3n",
|
|
32
|
+
"ERR-05": "No se ha proporcionado un identificador para los datos",
|
|
33
|
+
"ERR-06": "El identificador para los datos es inv\xE1lido",
|
|
34
|
+
"ERR-07": "Los datos solicitados o enviados son inv\xE1lidos",
|
|
35
|
+
"ERR-18": "No se ha podido enviar la firma generada a la Web de origen",
|
|
36
|
+
"ERR-20": "No se ha indicado la versi\xF3n de la sintaxis de la operaci\xF3n"
|
|
37
|
+
};
|
|
38
|
+
function protocolError(code) {
|
|
39
|
+
return `${code}:=${MESSAGES[code]}`;
|
|
40
|
+
}
|
|
41
|
+
var ProtocolError = {
|
|
42
|
+
missingOperation: protocolError("ERR-00"),
|
|
43
|
+
unsupportedOperation: protocolError("ERR-01"),
|
|
44
|
+
missingData: protocolError("ERR-02"),
|
|
45
|
+
missingIdentifier: protocolError("ERR-05"),
|
|
46
|
+
invalidIdentifier: protocolError("ERR-06"),
|
|
47
|
+
invalidData: protocolError("ERR-07"),
|
|
48
|
+
storageFailure: protocolError("ERR-18"),
|
|
49
|
+
missingSyntaxVersion: protocolError("ERR-20")
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// src/server.ts
|
|
53
|
+
var HEADERS = {
|
|
54
|
+
"Cache-Control": "no-store",
|
|
55
|
+
"Content-Type": "text/plain; charset=UTF-8",
|
|
56
|
+
"X-Content-Type-Options": "nosniff"
|
|
57
|
+
};
|
|
58
|
+
var encoder = new TextEncoder();
|
|
59
|
+
function respond(body) {
|
|
60
|
+
return { status: 200, headers: { ...HEADERS }, body };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/node.ts
|
|
64
|
+
function toNodeHandler(server) {
|
|
65
|
+
return async (request, response) => {
|
|
66
|
+
const parameters = new URLSearchParams(
|
|
67
|
+
new URL(request.url ?? "/", "http://localhost").search
|
|
68
|
+
);
|
|
69
|
+
const form = await readForm(request, server.maxRequestBytes);
|
|
70
|
+
if (form === null) {
|
|
71
|
+
send(response, respond(ProtocolError.invalidData));
|
|
72
|
+
request.destroy();
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
for (const [name, value] of form instanceof URLSearchParams ? form : Object.entries(form)) {
|
|
76
|
+
if (typeof value === "string") {
|
|
77
|
+
parameters.set(name, value);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
send(response, await server.handle(parameters));
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
function send(response, result) {
|
|
84
|
+
response.writeHead(result.status, result.headers);
|
|
85
|
+
response.end(result.body);
|
|
86
|
+
}
|
|
87
|
+
async function readForm(request, limit) {
|
|
88
|
+
if (typeof request.body === "object" && request.body !== null) {
|
|
89
|
+
return request.body;
|
|
90
|
+
}
|
|
91
|
+
if (request.method === "GET" || request.method === "HEAD") {
|
|
92
|
+
return new URLSearchParams();
|
|
93
|
+
}
|
|
94
|
+
const chunks = [];
|
|
95
|
+
let size = 0;
|
|
96
|
+
for await (const chunk of request) {
|
|
97
|
+
size += chunk.byteLength;
|
|
98
|
+
if (size > limit) {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
chunks.push(chunk);
|
|
102
|
+
}
|
|
103
|
+
return new URLSearchParams(Buffer.concat(chunks).toString("utf8"));
|
|
104
|
+
}
|
|
105
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
106
|
+
0 && (module.exports = {
|
|
107
|
+
toNodeHandler
|
|
108
|
+
});
|
|
109
|
+
//# sourceMappingURL=node.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/node.ts","../src/protocol.ts","../src/server.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { ProtocolError } from \"./protocol.ts\";\nimport {\n respond,\n type IntermediateServer,\n type Parameters,\n type ProtocolResponse,\n} from \"./server.ts\";\n\n/** Petición de `node:http`, o de Express si ya ha leído el formulario. */\nexport type NodeRequest = IncomingMessage & { body?: unknown };\n\n/**\n * Adapta el servidor a `node:http` y a Express.\n *\n * Si un middleware como `express.urlencoded()` ya consumió el cuerpo, se usa\n * `req.body`; si no, se lee el flujo directamente.\n */\nexport function toNodeHandler(\n server: IntermediateServer,\n): (request: NodeRequest, response: ServerResponse) => Promise<void> {\n return async (request, response) => {\n const parameters = new URLSearchParams(\n new URL(request.url ?? \"/\", \"http://localhost\").search,\n );\n const form = await readForm(request, server.maxRequestBytes);\n if (form === null) {\n send(response, respond(ProtocolError.invalidData));\n request.destroy();\n return;\n }\n for (const [name, value] of form instanceof URLSearchParams\n ? form\n : Object.entries(form)) {\n if (typeof value === \"string\") {\n parameters.set(name, value);\n }\n }\n send(response, await server.handle(parameters));\n };\n}\n\nfunction send(response: ServerResponse, result: ProtocolResponse): void {\n response.writeHead(result.status, result.headers);\n response.end(result.body);\n}\n\nasync function readForm(\n request: NodeRequest,\n limit: number,\n): Promise<Parameters | null> {\n if (typeof request.body === \"object\" && request.body !== null) {\n return request.body as Readonly<Record<string, unknown>>;\n }\n if (request.method === \"GET\" || request.method === \"HEAD\") {\n return new URLSearchParams();\n }\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n size += (chunk as Buffer).byteLength;\n if (size > limit) {\n return null;\n }\n chunks.push(chunk as Buffer);\n }\n return new URLSearchParams(Buffer.concat(chunks).toString(\"utf8\"));\n}\n","/**\n * Códigos de error del protocolo `v=1_0` de AutoScript.\n *\n * AutoScript solo entiende estas cadenas: un fallo interno tiene que salir con\n * uno de estos códigos y no como un error HTTP, o quien firma se queda\n * esperando sin explicación. Textos idénticos a los del servidor PHP.\n */\nconst MESSAGES = {\n \"ERR-00\": \"No se ha indicado código de operación\",\n \"ERR-01\": \"Código de operación no soportado\",\n \"ERR-02\": \"No se han proporcionado los datos de la operación\",\n \"ERR-05\": \"No se ha proporcionado un identificador para los datos\",\n \"ERR-06\": \"El identificador para los datos es inválido\",\n \"ERR-07\": \"Los datos solicitados o enviados son inválidos\",\n \"ERR-18\": \"No se ha podido enviar la firma generada a la Web de origen\",\n \"ERR-20\": \"No se ha indicado la versión de la sintaxis de la operación\",\n} as const;\n\nexport type ProtocolErrorCode = keyof typeof MESSAGES;\n\nexport function protocolError(code: ProtocolErrorCode): string {\n return `${code}:=${MESSAGES[code]}`;\n}\n\nexport const ProtocolError = {\n missingOperation: protocolError(\"ERR-00\"),\n unsupportedOperation: protocolError(\"ERR-01\"),\n missingData: protocolError(\"ERR-02\"),\n missingIdentifier: protocolError(\"ERR-05\"),\n invalidIdentifier: protocolError(\"ERR-06\"),\n invalidData: protocolError(\"ERR-07\"),\n storageFailure: protocolError(\"ERR-18\"),\n missingSyntaxVersion: protocolError(\"ERR-20\"),\n} as const;\n","import { ProtocolError } from \"./protocol.ts\";\nimport type { Store } from \"./store.ts\";\n\nexport const SYNTAX_VERSION = \"1_0\";\n\n/** Parámetros ya leídos de la consulta y del formulario. */\nexport type Parameters = URLSearchParams | Readonly<Record<string, unknown>>;\n\nexport interface ProtocolResponse {\n readonly status: number;\n readonly headers: Readonly<Record<string, string>>;\n readonly body: string;\n}\n\nexport interface IntermediateServerOptions {\n /** Tamaño máximo de `dat` en bytes. Por defecto, 20 MiB como AutoScript. */\n readonly maxPayloadBytes?: number;\n /** Tiempo de vida de cada mensaje. Por defecto, 120 segundos. */\n readonly ttlSeconds?: number;\n}\n\nconst HEADERS = {\n \"Cache-Control\": \"no-store\",\n \"Content-Type\": \"text/plain; charset=UTF-8\",\n \"X-Content-Type-Options\": \"nosniff\",\n} as const;\n\nconst IDENTIFIER = /^[A-Za-z0-9_-]{1,128}$/;\nconst encoder = new TextEncoder();\n\n/**\n * Servidor intermedio de AutoScript (`storage` y `retrieve`), independiente de\n * frameworks. Las dos rutas pueden delegar en la misma instancia.\n */\nexport class IntermediateServer {\n private readonly maxPayloadBytes: number;\n private readonly ttlSeconds: number;\n /**\n * Límite del cuerpo HTTP completo. La codificación de formulario puede\n * triplicar el tamaño del dato (`+` pasa a `%2B`), más margen para el resto\n * de campos. Por encima no se sigue leyendo.\n */\n readonly maxRequestBytes: number;\n\n constructor(\n private readonly store: Store,\n options: IntermediateServerOptions = {},\n ) {\n this.maxPayloadBytes = options.maxPayloadBytes ?? 20 * 1024 * 1024;\n this.ttlSeconds = options.ttlSeconds ?? 120;\n if (!Number.isInteger(this.maxPayloadBytes) || this.maxPayloadBytes < 1) {\n throw new RangeError(\"Maximum payload size must be a positive integer.\");\n }\n if (!Number.isInteger(this.ttlSeconds) || this.ttlSeconds < 1) {\n throw new RangeError(\"TTL must be a positive integer.\");\n }\n this.maxRequestBytes = this.maxPayloadBytes * 3 + 64 * 1024;\n }\n\n /**\n * Atiende una petición de la Fetch API: Hono, Bun, Deno, Cloudflare Workers\n * y cualquier runtime con `Request`/`Response` estándar.\n */\n async fetch(request: Request): Promise<Response> {\n const parameters = new URLSearchParams(new URL(request.url).search);\n if (request.method !== \"GET\" && request.method !== \"HEAD\") {\n const body = await readLimited(request.body, this.maxRequestBytes);\n if (body === null) {\n return toFetchResponse(respond(ProtocolError.invalidData));\n }\n // Los campos del formulario prevalecen sobre los de la consulta.\n for (const [name, value] of new URLSearchParams(body)) {\n parameters.set(name, value);\n }\n }\n return toFetchResponse(await this.handle(parameters));\n }\n\n /** Atiende unos parámetros ya leídos. Un fallo del almacenamiento sale como `ERR-…`. */\n async handle(parameters: Parameters): Promise<ProtocolResponse> {\n return respond(await this.body(parameters));\n }\n\n private async body(parameters: Parameters): Promise<string> {\n const operation = value(parameters, \"op\")?.toLowerCase();\n if (!operation) {\n return ProtocolError.missingOperation;\n }\n if (operation === \"check\") {\n return \"OK\";\n }\n const version = value(parameters, \"v\");\n if (version === null) {\n return ProtocolError.missingSyntaxVersion;\n }\n if (version !== SYNTAX_VERSION) {\n return ProtocolError.unsupportedOperation;\n }\n if (operation !== \"put\" && operation !== \"get\") {\n return ProtocolError.unsupportedOperation;\n }\n\n const identifier = value(parameters, \"id\");\n if (!identifier) {\n return ProtocolError.missingIdentifier;\n }\n if (!IDENTIFIER.test(identifier)) {\n return ProtocolError.invalidIdentifier;\n }\n\n return operation === \"put\"\n ? this.put(identifier, value(parameters, \"dat\"))\n : this.get(identifier);\n }\n\n private async put(identifier: string, data: string | null): Promise<string> {\n // Un dato ausente o excesivo no se rechaza aquí: se guarda el error para\n // que quien recoja el mensaje reciba el motivo, como hace AutoScript.\n let payload = data;\n if (!payload) {\n payload = ProtocolError.missingData;\n } else if (encoder.encode(payload).byteLength > this.maxPayloadBytes) {\n payload = ProtocolError.invalidData;\n }\n\n try {\n await this.store.put(identifier, payload, this.ttlSeconds);\n } catch (error) {\n if (isStorageError(error)) {\n return ProtocolError.storageFailure;\n }\n throw error;\n }\n return \"OK\";\n }\n\n private async get(identifier: string): Promise<string> {\n try {\n return (\n (await this.store.consume(identifier)) ??\n ProtocolError.invalidIdentifier\n );\n } catch (error) {\n if (isStorageError(error)) {\n return ProtocolError.invalidData;\n }\n throw error;\n }\n }\n}\n\n/**\n * Por nombre y no con `instanceof`: en CommonJS cada punto de entrada lleva su\n * propia copia de la clase, y el error de `./fs` no sería instancia de la de\n * `.`.\n */\nfunction isStorageError(error: unknown): boolean {\n return error instanceof Error && error.name === \"StorageError\";\n}\n\nexport function respond(body: string): ProtocolResponse {\n return { status: 200, headers: { ...HEADERS }, body };\n}\n\nfunction toFetchResponse(response: ProtocolResponse): Response {\n return new Response(response.body, {\n status: response.status,\n headers: response.headers,\n });\n}\n\n/** Lee el cuerpo como texto, o devuelve `null` si supera `limit` bytes. */\nasync function readLimited(\n stream: ReadableStream<Uint8Array> | null,\n limit: number,\n): Promise<string | null> {\n if (stream === null) {\n return \"\";\n }\n const decoder = new TextDecoder();\n const reader = stream.getReader();\n let size = 0;\n let text = \"\";\n for (;;) {\n const { done, value } = await reader.read();\n if (done) {\n return text + decoder.decode();\n }\n size += value.byteLength;\n if (size > limit) {\n await reader.cancel();\n return null;\n }\n text += decoder.decode(value, { stream: true });\n }\n}\n\nfunction value(parameters: Parameters, name: string): string | null {\n if (parameters instanceof URLSearchParams) {\n return parameters.get(name);\n }\n if (!Object.hasOwn(parameters, name)) {\n return null;\n }\n const raw = parameters[name];\n return typeof raw === \"string\" || typeof raw === \"number\"\n ? String(raw)\n : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,IAAM,WAAW;AAAA,EACf,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;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AgC;AACtE,WAAS,UAAU,OAAO,QAAQ,OAAO,OAAO;AAChD,WAAS,IAAI,OAAO,IAAI;AAC1B;AAEA,eAAe,SACb,SACA,OAC4B;AAC5B,MAAI,OAAO,QAAQ,SAAS,YAAY,QAAQ,SAAS,MAAM;AAC7D,WAAO,QAAQ;AAAA,EACjB;AACA,MAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QAAQ;AACzD,WAAO,IAAI,gBAAgB;AAAA,EAC7B;AACA,QAAM,SAAmB,CAAC;AAC1B,MAAI,OAAO;AACX,mBAAiB,SAAS,SAAS;AACjC,YAAS,MAAiB;AAC1B,QAAI,OAAO,OAAO;AAChB,aAAO;AAAA,IACT;AACA,WAAO,KAAK,KAAe;AAAA,EAC7B;AACA,SAAO,IAAI,gBAAgB,OAAO,OAAO,MAAM,EAAE,SAAS,MAAM,CAAC;AACnE;","names":[]}
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { type IntermediateServer } from "./server.ts";
|
|
3
|
+
/** Petición de `node:http`, o de Express si ya ha leído el formulario. */
|
|
4
|
+
export type NodeRequest = IncomingMessage & {
|
|
5
|
+
body?: unknown;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* Adapta el servidor a `node:http` y a Express.
|
|
9
|
+
*
|
|
10
|
+
* Si un middleware como `express.urlencoded()` ya consumió el cuerpo, se usa
|
|
11
|
+
* `req.body`; si no, se lee el flujo directamente.
|
|
12
|
+
*/
|
|
13
|
+
export declare function toNodeHandler(server: IntermediateServer): (request: NodeRequest, response: ServerResponse) => Promise<void>;
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ProtocolError,
|
|
3
|
+
respond
|
|
4
|
+
} from "./chunk-ZHQSGSOI.js";
|
|
5
|
+
|
|
6
|
+
// src/node.ts
|
|
7
|
+
function toNodeHandler(server) {
|
|
8
|
+
return async (request, response) => {
|
|
9
|
+
const parameters = new URLSearchParams(
|
|
10
|
+
new URL(request.url ?? "/", "http://localhost").search
|
|
11
|
+
);
|
|
12
|
+
const form = await readForm(request, server.maxRequestBytes);
|
|
13
|
+
if (form === null) {
|
|
14
|
+
send(response, respond(ProtocolError.invalidData));
|
|
15
|
+
request.destroy();
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
for (const [name, value] of form instanceof URLSearchParams ? form : Object.entries(form)) {
|
|
19
|
+
if (typeof value === "string") {
|
|
20
|
+
parameters.set(name, value);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
send(response, await server.handle(parameters));
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function send(response, result) {
|
|
27
|
+
response.writeHead(result.status, result.headers);
|
|
28
|
+
response.end(result.body);
|
|
29
|
+
}
|
|
30
|
+
async function readForm(request, limit) {
|
|
31
|
+
if (typeof request.body === "object" && request.body !== null) {
|
|
32
|
+
return request.body;
|
|
33
|
+
}
|
|
34
|
+
if (request.method === "GET" || request.method === "HEAD") {
|
|
35
|
+
return new URLSearchParams();
|
|
36
|
+
}
|
|
37
|
+
const chunks = [];
|
|
38
|
+
let size = 0;
|
|
39
|
+
for await (const chunk of request) {
|
|
40
|
+
size += chunk.byteLength;
|
|
41
|
+
if (size > limit) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
chunks.push(chunk);
|
|
45
|
+
}
|
|
46
|
+
return new URLSearchParams(Buffer.concat(chunks).toString("utf8"));
|
|
47
|
+
}
|
|
48
|
+
export {
|
|
49
|
+
toNodeHandler
|
|
50
|
+
};
|
|
51
|
+
//# sourceMappingURL=node.js.map
|
package/dist/node.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/node.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"node:http\";\nimport { ProtocolError } from \"./protocol.ts\";\nimport {\n respond,\n type IntermediateServer,\n type Parameters,\n type ProtocolResponse,\n} from \"./server.ts\";\n\n/** Petición de `node:http`, o de Express si ya ha leído el formulario. */\nexport type NodeRequest = IncomingMessage & { body?: unknown };\n\n/**\n * Adapta el servidor a `node:http` y a Express.\n *\n * Si un middleware como `express.urlencoded()` ya consumió el cuerpo, se usa\n * `req.body`; si no, se lee el flujo directamente.\n */\nexport function toNodeHandler(\n server: IntermediateServer,\n): (request: NodeRequest, response: ServerResponse) => Promise<void> {\n return async (request, response) => {\n const parameters = new URLSearchParams(\n new URL(request.url ?? \"/\", \"http://localhost\").search,\n );\n const form = await readForm(request, server.maxRequestBytes);\n if (form === null) {\n send(response, respond(ProtocolError.invalidData));\n request.destroy();\n return;\n }\n for (const [name, value] of form instanceof URLSearchParams\n ? form\n : Object.entries(form)) {\n if (typeof value === \"string\") {\n parameters.set(name, value);\n }\n }\n send(response, await server.handle(parameters));\n };\n}\n\nfunction send(response: ServerResponse, result: ProtocolResponse): void {\n response.writeHead(result.status, result.headers);\n response.end(result.body);\n}\n\nasync function readForm(\n request: NodeRequest,\n limit: number,\n): Promise<Parameters | null> {\n if (typeof request.body === \"object\" && request.body !== null) {\n return request.body as Readonly<Record<string, unknown>>;\n }\n if (request.method === \"GET\" || request.method === \"HEAD\") {\n return new URLSearchParams();\n }\n const chunks: Buffer[] = [];\n let size = 0;\n for await (const chunk of request) {\n size += (chunk as Buffer).byteLength;\n if (size > limit) {\n return null;\n }\n chunks.push(chunk as Buffer);\n }\n return new URLSearchParams(Buffer.concat(chunks).toString(\"utf8\"));\n}\n"],"mappings":";;;;;;AAkBO,SAAS,cACd,QACmE;AACnE,SAAO,OAAO,SAAS,aAAa;AAClC,UAAM,aAAa,IAAI;AAAA,MACrB,IAAI,IAAI,QAAQ,OAAO,KAAK,kBAAkB,EAAE;AAAA,IAClD;AACA,UAAM,OAAO,MAAM,SAAS,SAAS,OAAO,eAAe;AAC3D,QAAI,SAAS,MAAM;AACjB,WAAK,UAAU,QAAQ,cAAc,WAAW,CAAC;AACjD,cAAQ,QAAQ;AAChB;AAAA,IACF;AACA,eAAW,CAAC,MAAM,KAAK,KAAK,gBAAgB,kBACxC,OACA,OAAO,QAAQ,IAAI,GAAG;AACxB,UAAI,OAAO,UAAU,UAAU;AAC7B,mBAAW,IAAI,MAAM,KAAK;AAAA,MAC5B;AAAA,IACF;AACA,SAAK,UAAU,MAAM,OAAO,OAAO,UAAU,CAAC;AAAA,EAChD;AACF;AAEA,SAAS,KAAK,UAA0B,QAAgC;AACtE,WAAS,UAAU,OAAO,QAAQ,OAAO,OAAO;AAChD,WAAS,IAAI,OAAO,IAAI;AAC1B;AAEA,eAAe,SACb,SACA,OAC4B;AAC5B,MAAI,OAAO,QAAQ,SAAS,YAAY,QAAQ,SAAS,MAAM;AAC7D,WAAO,QAAQ;AAAA,EACjB;AACA,MAAI,QAAQ,WAAW,SAAS,QAAQ,WAAW,QAAQ;AACzD,WAAO,IAAI,gBAAgB;AAAA,EAC7B;AACA,QAAM,SAAmB,CAAC;AAC1B,MAAI,OAAO;AACX,mBAAiB,SAAS,SAAS;AACjC,YAAS,MAAiB;AAC1B,QAAI,OAAO,OAAO;AAChB,aAAO;AAAA,IACT;AACA,WAAO,KAAK,KAAe;AAAA,EAC7B;AACA,SAAO,IAAI,gBAAgB,OAAO,OAAO,MAAM,EAAE,SAAS,MAAM,CAAC;AACnE;","names":[]}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Códigos de error del protocolo `v=1_0` de AutoScript.
|
|
3
|
+
*
|
|
4
|
+
* AutoScript solo entiende estas cadenas: un fallo interno tiene que salir con
|
|
5
|
+
* uno de estos códigos y no como un error HTTP, o quien firma se queda
|
|
6
|
+
* esperando sin explicación. Textos idénticos a los del servidor PHP.
|
|
7
|
+
*/
|
|
8
|
+
declare const MESSAGES: {
|
|
9
|
+
readonly "ERR-00": "No se ha indicado código de operación";
|
|
10
|
+
readonly "ERR-01": "Código de operación no soportado";
|
|
11
|
+
readonly "ERR-02": "No se han proporcionado los datos de la operación";
|
|
12
|
+
readonly "ERR-05": "No se ha proporcionado un identificador para los datos";
|
|
13
|
+
readonly "ERR-06": "El identificador para los datos es inválido";
|
|
14
|
+
readonly "ERR-07": "Los datos solicitados o enviados son inválidos";
|
|
15
|
+
readonly "ERR-18": "No se ha podido enviar la firma generada a la Web de origen";
|
|
16
|
+
readonly "ERR-20": "No se ha indicado la versión de la sintaxis de la operación";
|
|
17
|
+
};
|
|
18
|
+
export type ProtocolErrorCode = keyof typeof MESSAGES;
|
|
19
|
+
export declare function protocolError(code: ProtocolErrorCode): string;
|
|
20
|
+
export declare const ProtocolError: {
|
|
21
|
+
readonly missingOperation: string;
|
|
22
|
+
readonly unsupportedOperation: string;
|
|
23
|
+
readonly missingData: string;
|
|
24
|
+
readonly missingIdentifier: string;
|
|
25
|
+
readonly invalidIdentifier: string;
|
|
26
|
+
readonly invalidData: string;
|
|
27
|
+
readonly storageFailure: string;
|
|
28
|
+
readonly missingSyntaxVersion: string;
|
|
29
|
+
};
|
|
30
|
+
export {};
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { Store } from "./store.ts";
|
|
2
|
+
export declare const SYNTAX_VERSION = "1_0";
|
|
3
|
+
/** Parámetros ya leídos de la consulta y del formulario. */
|
|
4
|
+
export type Parameters = URLSearchParams | Readonly<Record<string, unknown>>;
|
|
5
|
+
export interface ProtocolResponse {
|
|
6
|
+
readonly status: number;
|
|
7
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
8
|
+
readonly body: string;
|
|
9
|
+
}
|
|
10
|
+
export interface IntermediateServerOptions {
|
|
11
|
+
/** Tamaño máximo de `dat` en bytes. Por defecto, 20 MiB como AutoScript. */
|
|
12
|
+
readonly maxPayloadBytes?: number;
|
|
13
|
+
/** Tiempo de vida de cada mensaje. Por defecto, 120 segundos. */
|
|
14
|
+
readonly ttlSeconds?: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Servidor intermedio de AutoScript (`storage` y `retrieve`), independiente de
|
|
18
|
+
* frameworks. Las dos rutas pueden delegar en la misma instancia.
|
|
19
|
+
*/
|
|
20
|
+
export declare class IntermediateServer {
|
|
21
|
+
private readonly store;
|
|
22
|
+
private readonly maxPayloadBytes;
|
|
23
|
+
private readonly ttlSeconds;
|
|
24
|
+
/**
|
|
25
|
+
* Límite del cuerpo HTTP completo. La codificación de formulario puede
|
|
26
|
+
* triplicar el tamaño del dato (`+` pasa a `%2B`), más margen para el resto
|
|
27
|
+
* de campos. Por encima no se sigue leyendo.
|
|
28
|
+
*/
|
|
29
|
+
readonly maxRequestBytes: number;
|
|
30
|
+
constructor(store: Store, options?: IntermediateServerOptions);
|
|
31
|
+
/**
|
|
32
|
+
* Atiende una petición de la Fetch API: Hono, Bun, Deno, Cloudflare Workers
|
|
33
|
+
* y cualquier runtime con `Request`/`Response` estándar.
|
|
34
|
+
*/
|
|
35
|
+
fetch(request: Request): Promise<Response>;
|
|
36
|
+
/** Atiende unos parámetros ya leídos. Un fallo del almacenamiento sale como `ERR-…`. */
|
|
37
|
+
handle(parameters: Parameters): Promise<ProtocolResponse>;
|
|
38
|
+
private body;
|
|
39
|
+
private put;
|
|
40
|
+
private get;
|
|
41
|
+
}
|
|
42
|
+
export declare function respond(body: string): ProtocolResponse;
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Segundos desde la época Unix. Se inyecta para poder probar la caducidad. */
|
|
2
|
+
export type Clock = () => number;
|
|
3
|
+
export declare const systemClock: Clock;
|
|
4
|
+
/** Error de almacenamiento: el servidor lo traduce a un código del protocolo. */
|
|
5
|
+
export declare class StorageError extends Error {
|
|
6
|
+
name: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Almacenamiento temporal de mensajes cifrados.
|
|
10
|
+
*
|
|
11
|
+
* `consume()` debe ser atómico: ningún mensaje puede entregarse dos veces,
|
|
12
|
+
* tampoco con varias peticiones simultáneas o varios nodos.
|
|
13
|
+
*/
|
|
14
|
+
export interface Store {
|
|
15
|
+
put(identifier: string, payload: string, ttlSeconds: number): Promise<void>;
|
|
16
|
+
consume(identifier: string): Promise<string | null>;
|
|
17
|
+
purgeExpired(): Promise<number>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Almacenamiento en memoria del proceso.
|
|
21
|
+
*
|
|
22
|
+
* Sirve para pruebas y para un único proceso persistente. No vale con varias
|
|
23
|
+
* instancias ni en entornos serverless, donde cada petición puede caer en un
|
|
24
|
+
* proceso distinto.
|
|
25
|
+
*/
|
|
26
|
+
export declare class MemoryStore implements Store {
|
|
27
|
+
private readonly clock;
|
|
28
|
+
private readonly entries;
|
|
29
|
+
constructor(clock?: Clock);
|
|
30
|
+
put(identifier: string, payload: string, ttlSeconds: number): Promise<void>;
|
|
31
|
+
consume(identifier: string): Promise<string | null>;
|
|
32
|
+
purgeExpired(): Promise<number>;
|
|
33
|
+
}
|
|
34
|
+
export declare function assertPositiveTtl(ttlSeconds: number): void;
|