@erseco/autofirma-intermediate-server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,184 @@
1
+ // src/protocol.ts
2
+ var MESSAGES = {
3
+ "ERR-00": "No se ha indicado c\xF3digo de operaci\xF3n",
4
+ "ERR-01": "C\xF3digo de operaci\xF3n no soportado",
5
+ "ERR-02": "No se han proporcionado los datos de la operaci\xF3n",
6
+ "ERR-05": "No se ha proporcionado un identificador para los datos",
7
+ "ERR-06": "El identificador para los datos es inv\xE1lido",
8
+ "ERR-07": "Los datos solicitados o enviados son inv\xE1lidos",
9
+ "ERR-18": "No se ha podido enviar la firma generada a la Web de origen",
10
+ "ERR-20": "No se ha indicado la versi\xF3n de la sintaxis de la operaci\xF3n"
11
+ };
12
+ function protocolError(code) {
13
+ return `${code}:=${MESSAGES[code]}`;
14
+ }
15
+ var ProtocolError = {
16
+ missingOperation: protocolError("ERR-00"),
17
+ unsupportedOperation: protocolError("ERR-01"),
18
+ missingData: protocolError("ERR-02"),
19
+ missingIdentifier: protocolError("ERR-05"),
20
+ invalidIdentifier: protocolError("ERR-06"),
21
+ invalidData: protocolError("ERR-07"),
22
+ storageFailure: protocolError("ERR-18"),
23
+ missingSyntaxVersion: protocolError("ERR-20")
24
+ };
25
+
26
+ // src/server.ts
27
+ var SYNTAX_VERSION = "1_0";
28
+ var HEADERS = {
29
+ "Cache-Control": "no-store",
30
+ "Content-Type": "text/plain; charset=UTF-8",
31
+ "X-Content-Type-Options": "nosniff"
32
+ };
33
+ var IDENTIFIER = /^[A-Za-z0-9_-]{1,128}$/;
34
+ var encoder = new TextEncoder();
35
+ var IntermediateServer = class {
36
+ constructor(store, options = {}) {
37
+ this.store = store;
38
+ this.maxPayloadBytes = options.maxPayloadBytes ?? 20 * 1024 * 1024;
39
+ this.ttlSeconds = options.ttlSeconds ?? 120;
40
+ if (!Number.isInteger(this.maxPayloadBytes) || this.maxPayloadBytes < 1) {
41
+ throw new RangeError("Maximum payload size must be a positive integer.");
42
+ }
43
+ if (!Number.isInteger(this.ttlSeconds) || this.ttlSeconds < 1) {
44
+ throw new RangeError("TTL must be a positive integer.");
45
+ }
46
+ this.maxRequestBytes = this.maxPayloadBytes * 3 + 64 * 1024;
47
+ }
48
+ store;
49
+ maxPayloadBytes;
50
+ ttlSeconds;
51
+ /**
52
+ * Límite del cuerpo HTTP completo. La codificación de formulario puede
53
+ * triplicar el tamaño del dato (`+` pasa a `%2B`), más margen para el resto
54
+ * de campos. Por encima no se sigue leyendo.
55
+ */
56
+ maxRequestBytes;
57
+ /**
58
+ * Atiende una petición de la Fetch API: Hono, Bun, Deno, Cloudflare Workers
59
+ * y cualquier runtime con `Request`/`Response` estándar.
60
+ */
61
+ async fetch(request) {
62
+ const parameters = new URLSearchParams(new URL(request.url).search);
63
+ if (request.method !== "GET" && request.method !== "HEAD") {
64
+ const body = await readLimited(request.body, this.maxRequestBytes);
65
+ if (body === null) {
66
+ return toFetchResponse(respond(ProtocolError.invalidData));
67
+ }
68
+ for (const [name, value2] of new URLSearchParams(body)) {
69
+ parameters.set(name, value2);
70
+ }
71
+ }
72
+ return toFetchResponse(await this.handle(parameters));
73
+ }
74
+ /** Atiende unos parámetros ya leídos. Un fallo del almacenamiento sale como `ERR-…`. */
75
+ async handle(parameters) {
76
+ return respond(await this.body(parameters));
77
+ }
78
+ async body(parameters) {
79
+ const operation = value(parameters, "op")?.toLowerCase();
80
+ if (!operation) {
81
+ return ProtocolError.missingOperation;
82
+ }
83
+ if (operation === "check") {
84
+ return "OK";
85
+ }
86
+ const version = value(parameters, "v");
87
+ if (version === null) {
88
+ return ProtocolError.missingSyntaxVersion;
89
+ }
90
+ if (version !== SYNTAX_VERSION) {
91
+ return ProtocolError.unsupportedOperation;
92
+ }
93
+ if (operation !== "put" && operation !== "get") {
94
+ return ProtocolError.unsupportedOperation;
95
+ }
96
+ const identifier = value(parameters, "id");
97
+ if (!identifier) {
98
+ return ProtocolError.missingIdentifier;
99
+ }
100
+ if (!IDENTIFIER.test(identifier)) {
101
+ return ProtocolError.invalidIdentifier;
102
+ }
103
+ return operation === "put" ? this.put(identifier, value(parameters, "dat")) : this.get(identifier);
104
+ }
105
+ async put(identifier, data) {
106
+ let payload = data;
107
+ if (!payload) {
108
+ payload = ProtocolError.missingData;
109
+ } else if (encoder.encode(payload).byteLength > this.maxPayloadBytes) {
110
+ payload = ProtocolError.invalidData;
111
+ }
112
+ try {
113
+ await this.store.put(identifier, payload, this.ttlSeconds);
114
+ } catch (error) {
115
+ if (isStorageError(error)) {
116
+ return ProtocolError.storageFailure;
117
+ }
118
+ throw error;
119
+ }
120
+ return "OK";
121
+ }
122
+ async get(identifier) {
123
+ try {
124
+ return await this.store.consume(identifier) ?? ProtocolError.invalidIdentifier;
125
+ } catch (error) {
126
+ if (isStorageError(error)) {
127
+ return ProtocolError.invalidData;
128
+ }
129
+ throw error;
130
+ }
131
+ }
132
+ };
133
+ function isStorageError(error) {
134
+ return error instanceof Error && error.name === "StorageError";
135
+ }
136
+ function respond(body) {
137
+ return { status: 200, headers: { ...HEADERS }, body };
138
+ }
139
+ function toFetchResponse(response) {
140
+ return new Response(response.body, {
141
+ status: response.status,
142
+ headers: response.headers
143
+ });
144
+ }
145
+ async function readLimited(stream, limit) {
146
+ if (stream === null) {
147
+ return "";
148
+ }
149
+ const decoder = new TextDecoder();
150
+ const reader = stream.getReader();
151
+ let size = 0;
152
+ let text = "";
153
+ for (; ; ) {
154
+ const { done, value: value2 } = await reader.read();
155
+ if (done) {
156
+ return text + decoder.decode();
157
+ }
158
+ size += value2.byteLength;
159
+ if (size > limit) {
160
+ await reader.cancel();
161
+ return null;
162
+ }
163
+ text += decoder.decode(value2, { stream: true });
164
+ }
165
+ }
166
+ function value(parameters, name) {
167
+ if (parameters instanceof URLSearchParams) {
168
+ return parameters.get(name);
169
+ }
170
+ if (!Object.hasOwn(parameters, name)) {
171
+ return null;
172
+ }
173
+ const raw = parameters[name];
174
+ return typeof raw === "string" || typeof raw === "number" ? String(raw) : null;
175
+ }
176
+
177
+ export {
178
+ protocolError,
179
+ ProtocolError,
180
+ SYNTAX_VERSION,
181
+ IntermediateServer,
182
+ respond
183
+ };
184
+ //# sourceMappingURL=chunk-ZHQSGSOI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/protocol.ts","../src/server.ts"],"sourcesContent":["/**\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":";AAOA,IAAM,WAAW;AAAA,EACf,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AAAA,EACV,UAAU;AACZ;AAIO,SAAS,cAAc,MAAiC;AAC7D,SAAO,GAAG,IAAI,KAAK,SAAS,IAAI,CAAC;AACnC;AAEO,IAAM,gBAAgB;AAAA,EAC3B,kBAAkB,cAAc,QAAQ;AAAA,EACxC,sBAAsB,cAAc,QAAQ;AAAA,EAC5C,aAAa,cAAc,QAAQ;AAAA,EACnC,mBAAmB,cAAc,QAAQ;AAAA,EACzC,mBAAmB,cAAc,QAAQ;AAAA,EACzC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"]}
package/dist/fs.cjs ADDED
@@ -0,0 +1,145 @@
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/fs.ts
21
+ var fs_exports = {};
22
+ __export(fs_exports, {
23
+ FilesystemStore: () => FilesystemStore
24
+ });
25
+ module.exports = __toCommonJS(fs_exports);
26
+ var import_node_crypto = require("crypto");
27
+ var import_promises = require("fs/promises");
28
+ var import_node_path = require("path");
29
+
30
+ // src/store.ts
31
+ var systemClock = () => Math.floor(Date.now() / 1e3);
32
+ var StorageError = class extends Error {
33
+ name = "StorageError";
34
+ };
35
+ function assertPositiveTtl(ttlSeconds) {
36
+ if (!Number.isInteger(ttlSeconds) || ttlSeconds < 1) {
37
+ throw new RangeError("TTL must be a positive integer.");
38
+ }
39
+ }
40
+
41
+ // src/fs.ts
42
+ var EXPIRY_LENGTH = 20;
43
+ var FilesystemStore = class _FilesystemStore {
44
+ constructor(directory, clock) {
45
+ this.directory = directory;
46
+ this.clock = clock;
47
+ }
48
+ directory;
49
+ clock;
50
+ /** Crea el directorio con permisos 0700 si no existe. No admite enlaces. */
51
+ static async open(directory, clock = systemClock) {
52
+ const existing = await (0, import_promises.lstat)(directory).catch(() => null);
53
+ if (existing?.isSymbolicLink()) {
54
+ throw new StorageError(
55
+ "The storage directory cannot be a symbolic link."
56
+ );
57
+ }
58
+ if (existing === null) {
59
+ await (0, import_promises.mkdir)(directory, { recursive: true, mode: 448 });
60
+ }
61
+ return new _FilesystemStore(await (0, import_promises.realpath)(directory), clock);
62
+ }
63
+ async put(identifier, payload, ttlSeconds) {
64
+ assertPositiveTtl(ttlSeconds);
65
+ const expiry = String(this.clock() + ttlSeconds).padStart(
66
+ EXPIRY_LENGTH,
67
+ "0"
68
+ );
69
+ const temporary = (0, import_node_path.join)(
70
+ this.directory,
71
+ `.write-${(0, import_node_crypto.randomBytes)(8).toString("hex")}`
72
+ );
73
+ try {
74
+ const handle = await (0, import_promises.open)(temporary, "wx", 384);
75
+ try {
76
+ await handle.writeFile(`${expiry}
77
+ ${payload}`);
78
+ } finally {
79
+ await handle.close();
80
+ }
81
+ await (0, import_promises.rename)(temporary, this.path(identifier));
82
+ } catch (error) {
83
+ await (0, import_promises.unlink)(temporary).catch(() => void 0);
84
+ throw new StorageError("Unable to store the message.", { cause: error });
85
+ }
86
+ }
87
+ async consume(identifier) {
88
+ const path = this.path(identifier);
89
+ const claimed = `${path}.consume-${(0, import_node_crypto.randomBytes)(8).toString("hex")}`;
90
+ try {
91
+ await (0, import_promises.rename)(path, claimed);
92
+ } catch {
93
+ return null;
94
+ }
95
+ try {
96
+ if ((await (0, import_promises.lstat)(claimed)).isSymbolicLink()) {
97
+ return null;
98
+ }
99
+ return this.payload(await (0, import_promises.readFile)(claimed, "utf8"));
100
+ } catch (error) {
101
+ throw new StorageError("Unable to read the claimed message.", {
102
+ cause: error
103
+ });
104
+ } finally {
105
+ await (0, import_promises.unlink)(claimed).catch(() => void 0);
106
+ }
107
+ }
108
+ async purgeExpired() {
109
+ let purged = 0;
110
+ for (const name of await (0, import_promises.readdir)(this.directory)) {
111
+ if (!name.includes(".message")) {
112
+ continue;
113
+ }
114
+ const path = (0, import_node_path.join)(this.directory, name);
115
+ const stats = await (0, import_promises.lstat)(path);
116
+ if (stats.isFile() && this.payload(await (0, import_promises.readFile)(path, "utf8")) !== null) {
117
+ continue;
118
+ }
119
+ if (stats.isFile() || stats.isSymbolicLink()) {
120
+ await (0, import_promises.unlink)(path);
121
+ purged++;
122
+ }
123
+ }
124
+ return purged;
125
+ }
126
+ path(identifier) {
127
+ return (0, import_node_path.join)(
128
+ this.directory,
129
+ `${(0, import_node_crypto.createHash)("sha256").update(identifier).digest("hex")}.message`
130
+ );
131
+ }
132
+ /** Devuelve el mensaje, o `null` si el registro caducó o está mal formado. */
133
+ payload(record) {
134
+ const expiry = record.slice(0, EXPIRY_LENGTH);
135
+ if (record[EXPIRY_LENGTH] !== "\n" || !/^\d+$/.test(expiry)) {
136
+ return null;
137
+ }
138
+ return Number(expiry) <= this.clock() ? null : record.slice(EXPIRY_LENGTH + 1);
139
+ }
140
+ };
141
+ // Annotate the CommonJS export names for ESM import in node:
142
+ 0 && (module.exports = {
143
+ FilesystemStore
144
+ });
145
+ //# sourceMappingURL=fs.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fs.ts","../src/store.ts"],"sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\nimport {\n lstat,\n mkdir,\n open,\n readFile,\n readdir,\n realpath,\n rename,\n unlink,\n} from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n assertPositiveTtl,\n StorageError,\n systemClock,\n type Clock,\n type Store,\n} from \"./store.ts\";\n\nconst EXPIRY_LENGTH = 20;\n\n/**\n * Almacenamiento en disco para un único nodo o un volumen compartido.\n *\n * Usa el mismo formato que `FilesystemStore` del servidor PHP: un fichero\n * `sha256(id).message` con la caducidad en 20 dígitos, un salto de línea y el\n * mensaje. Los dos servidores pueden compartir directorio.\n */\nexport class FilesystemStore implements Store {\n private constructor(\n private readonly directory: string,\n private readonly clock: Clock,\n ) {}\n\n /** Crea el directorio con permisos 0700 si no existe. No admite enlaces. */\n static async open(\n directory: string,\n clock: Clock = systemClock,\n ): Promise<FilesystemStore> {\n const existing = await lstat(directory).catch(() => null);\n if (existing?.isSymbolicLink()) {\n throw new StorageError(\n \"The storage directory cannot be a symbolic link.\",\n );\n }\n if (existing === null) {\n await mkdir(directory, { recursive: true, mode: 0o700 });\n }\n return new FilesystemStore(await realpath(directory), clock);\n }\n\n async put(\n identifier: string,\n payload: string,\n ttlSeconds: number,\n ): Promise<void> {\n assertPositiveTtl(ttlSeconds);\n const expiry = String(this.clock() + ttlSeconds).padStart(\n EXPIRY_LENGTH,\n \"0\",\n );\n const temporary = join(\n this.directory,\n `.write-${randomBytes(8).toString(\"hex\")}`,\n );\n try {\n // `wx` falla si el fichero existe: nadie puede colar un enlace previo.\n const handle = await open(temporary, \"wx\", 0o600);\n try {\n await handle.writeFile(`${expiry}\\n${payload}`);\n } finally {\n await handle.close();\n }\n // El rename es atómico: un lector ve el mensaje entero o no lo ve.\n await rename(temporary, this.path(identifier));\n } catch (error) {\n await unlink(temporary).catch(() => undefined);\n throw new StorageError(\"Unable to store the message.\", { cause: error });\n }\n }\n\n async consume(identifier: string): Promise<string | null> {\n const path = this.path(identifier);\n const claimed = `${path}.consume-${randomBytes(8).toString(\"hex\")}`;\n // Solo una petición gana el rename: así nadie recibe el mensaje dos veces.\n try {\n await rename(path, claimed);\n } catch {\n return null;\n }\n try {\n if ((await lstat(claimed)).isSymbolicLink()) {\n return null;\n }\n return this.payload(await readFile(claimed, \"utf8\"));\n } catch (error) {\n throw new StorageError(\"Unable to read the claimed message.\", {\n cause: error,\n });\n } finally {\n await unlink(claimed).catch(() => undefined);\n }\n }\n\n async purgeExpired(): Promise<number> {\n let purged = 0;\n for (const name of await readdir(this.directory)) {\n if (!name.includes(\".message\")) {\n continue;\n }\n const path = join(this.directory, name);\n const stats = await lstat(path);\n if (\n stats.isFile() &&\n this.payload(await readFile(path, \"utf8\")) !== null\n ) {\n continue;\n }\n if (stats.isFile() || stats.isSymbolicLink()) {\n await unlink(path);\n purged++;\n }\n }\n return purged;\n }\n\n private path(identifier: string): string {\n return join(\n this.directory,\n `${createHash(\"sha256\").update(identifier).digest(\"hex\")}.message`,\n );\n }\n\n /** Devuelve el mensaje, o `null` si el registro caducó o está mal formado. */\n private payload(record: string): string | null {\n const expiry = record.slice(0, EXPIRY_LENGTH);\n if (record[EXPIRY_LENGTH] !== \"\\n\" || !/^\\d+$/.test(expiry)) {\n return null;\n }\n return Number(expiry) <= this.clock()\n ? null\n : record.slice(EXPIRY_LENGTH + 1);\n }\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 < 1) {\n throw new RangeError(\"TTL must be a positive integer.\");\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAwC;AACxC,sBASO;AACP,uBAAqB;;;ACRd,IAAM,cAAqB,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAG7D,IAAM,eAAN,cAA2B,MAAM;AAAA,EAC7B,OAAO;AAClB;AAgEO,SAAS,kBAAkB,YAA0B;AAC1D,MAAI,CAAC,OAAO,UAAU,UAAU,KAAK,aAAa,GAAG;AACnD,UAAM,IAAI,WAAW,iCAAiC;AAAA,EACxD;AACF;;;ADxDA,IAAM,gBAAgB;AASf,IAAM,kBAAN,MAAM,iBAAiC;AAAA,EACpC,YACW,WACA,OACjB;AAFiB;AACA;AAAA,EAChB;AAAA,EAFgB;AAAA,EACA;AAAA;AAAA,EAInB,aAAa,KACX,WACA,QAAe,aACW;AAC1B,UAAM,WAAW,UAAM,uBAAM,SAAS,EAAE,MAAM,MAAM,IAAI;AACxD,QAAI,UAAU,eAAe,GAAG;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AACA,QAAI,aAAa,MAAM;AACrB,gBAAM,uBAAM,WAAW,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAAA,IACzD;AACA,WAAO,IAAI,iBAAgB,UAAM,0BAAS,SAAS,GAAG,KAAK;AAAA,EAC7D;AAAA,EAEA,MAAM,IACJ,YACA,SACA,YACe;AACf,sBAAkB,UAAU;AAC5B,UAAM,SAAS,OAAO,KAAK,MAAM,IAAI,UAAU,EAAE;AAAA,MAC/C;AAAA,MACA;AAAA,IACF;AACA,UAAM,gBAAY;AAAA,MAChB,KAAK;AAAA,MACL,cAAU,gCAA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MAAM,OAAO,KACb,KAAK,QAAQ,UAAM,0BAAS,MAAM,MAAM,CAAC,MAAM,MAC/C;AACA;AAAA,MACF;AACA,UAAI,MAAM,OAAO,KAAK,MAAM,eAAe,GAAG;AAC5C,kBAAM,wBAAO,IAAI;AACjB;AAAA,MACF;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA,EAEQ,KAAK,YAA4B;AACvC,eAAO;AAAA,MACL,KAAK;AAAA,MACL,OAAG,+BAAW,QAAQ,EAAE,OAAO,UAAU,EAAE,OAAO,KAAK,CAAC;AAAA,IAC1D;AAAA,EACF;AAAA;AAAA,EAGQ,QAAQ,QAA+B;AAC7C,UAAM,SAAS,OAAO,MAAM,GAAG,aAAa;AAC5C,QAAI,OAAO,aAAa,MAAM,QAAQ,CAAC,QAAQ,KAAK,MAAM,GAAG;AAC3D,aAAO;AAAA,IACT;AACA,WAAO,OAAO,MAAM,KAAK,KAAK,MAAM,IAChC,OACA,OAAO,MAAM,gBAAgB,CAAC;AAAA,EACpC;AACF;","names":[]}
package/dist/fs.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ import { type Clock, type Store } from "./store.ts";
2
+ /**
3
+ * Almacenamiento en disco para un único nodo o un volumen compartido.
4
+ *
5
+ * Usa el mismo formato que `FilesystemStore` del servidor PHP: un fichero
6
+ * `sha256(id).message` con la caducidad en 20 dígitos, un salto de línea y el
7
+ * mensaje. Los dos servidores pueden compartir directorio.
8
+ */
9
+ export declare class FilesystemStore implements Store {
10
+ private readonly directory;
11
+ private readonly clock;
12
+ private constructor();
13
+ /** Crea el directorio con permisos 0700 si no existe. No admite enlaces. */
14
+ static open(directory: string, clock?: Clock): Promise<FilesystemStore>;
15
+ put(identifier: string, payload: string, ttlSeconds: number): Promise<void>;
16
+ consume(identifier: string): Promise<string | null>;
17
+ purgeExpired(): Promise<number>;
18
+ private path;
19
+ /** Devuelve el mensaje, o `null` si el registro caducó o está mal formado. */
20
+ private payload;
21
+ }
package/dist/fs.js ADDED
@@ -0,0 +1,122 @@
1
+ import {
2
+ StorageError,
3
+ assertPositiveTtl,
4
+ systemClock
5
+ } from "./chunk-EJ62BDQ2.js";
6
+
7
+ // src/fs.ts
8
+ import { createHash, randomBytes } from "crypto";
9
+ import {
10
+ lstat,
11
+ mkdir,
12
+ open,
13
+ readFile,
14
+ readdir,
15
+ realpath,
16
+ rename,
17
+ unlink
18
+ } from "fs/promises";
19
+ import { join } from "path";
20
+ var EXPIRY_LENGTH = 20;
21
+ var FilesystemStore = class _FilesystemStore {
22
+ constructor(directory, clock) {
23
+ this.directory = directory;
24
+ this.clock = clock;
25
+ }
26
+ directory;
27
+ clock;
28
+ /** Crea el directorio con permisos 0700 si no existe. No admite enlaces. */
29
+ static async open(directory, clock = systemClock) {
30
+ const existing = await lstat(directory).catch(() => null);
31
+ if (existing?.isSymbolicLink()) {
32
+ throw new StorageError(
33
+ "The storage directory cannot be a symbolic link."
34
+ );
35
+ }
36
+ if (existing === null) {
37
+ await mkdir(directory, { recursive: true, mode: 448 });
38
+ }
39
+ return new _FilesystemStore(await realpath(directory), clock);
40
+ }
41
+ async put(identifier, payload, ttlSeconds) {
42
+ assertPositiveTtl(ttlSeconds);
43
+ const expiry = String(this.clock() + ttlSeconds).padStart(
44
+ EXPIRY_LENGTH,
45
+ "0"
46
+ );
47
+ const temporary = join(
48
+ this.directory,
49
+ `.write-${randomBytes(8).toString("hex")}`
50
+ );
51
+ try {
52
+ const handle = await open(temporary, "wx", 384);
53
+ try {
54
+ await handle.writeFile(`${expiry}
55
+ ${payload}`);
56
+ } finally {
57
+ await handle.close();
58
+ }
59
+ await rename(temporary, this.path(identifier));
60
+ } catch (error) {
61
+ await unlink(temporary).catch(() => void 0);
62
+ throw new StorageError("Unable to store the message.", { cause: error });
63
+ }
64
+ }
65
+ async consume(identifier) {
66
+ const path = this.path(identifier);
67
+ const claimed = `${path}.consume-${randomBytes(8).toString("hex")}`;
68
+ try {
69
+ await rename(path, claimed);
70
+ } catch {
71
+ return null;
72
+ }
73
+ try {
74
+ if ((await lstat(claimed)).isSymbolicLink()) {
75
+ return null;
76
+ }
77
+ return this.payload(await readFile(claimed, "utf8"));
78
+ } catch (error) {
79
+ throw new StorageError("Unable to read the claimed message.", {
80
+ cause: error
81
+ });
82
+ } finally {
83
+ await unlink(claimed).catch(() => void 0);
84
+ }
85
+ }
86
+ async purgeExpired() {
87
+ let purged = 0;
88
+ for (const name of await readdir(this.directory)) {
89
+ if (!name.includes(".message")) {
90
+ continue;
91
+ }
92
+ const path = join(this.directory, name);
93
+ const stats = await lstat(path);
94
+ if (stats.isFile() && this.payload(await readFile(path, "utf8")) !== null) {
95
+ continue;
96
+ }
97
+ if (stats.isFile() || stats.isSymbolicLink()) {
98
+ await unlink(path);
99
+ purged++;
100
+ }
101
+ }
102
+ return purged;
103
+ }
104
+ path(identifier) {
105
+ return join(
106
+ this.directory,
107
+ `${createHash("sha256").update(identifier).digest("hex")}.message`
108
+ );
109
+ }
110
+ /** Devuelve el mensaje, o `null` si el registro caducó o está mal formado. */
111
+ payload(record) {
112
+ const expiry = record.slice(0, EXPIRY_LENGTH);
113
+ if (record[EXPIRY_LENGTH] !== "\n" || !/^\d+$/.test(expiry)) {
114
+ return null;
115
+ }
116
+ return Number(expiry) <= this.clock() ? null : record.slice(EXPIRY_LENGTH + 1);
117
+ }
118
+ };
119
+ export {
120
+ FilesystemStore
121
+ };
122
+ //# sourceMappingURL=fs.js.map
package/dist/fs.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/fs.ts"],"sourcesContent":["import { createHash, randomBytes } from \"node:crypto\";\nimport {\n lstat,\n mkdir,\n open,\n readFile,\n readdir,\n realpath,\n rename,\n unlink,\n} from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport {\n assertPositiveTtl,\n StorageError,\n systemClock,\n type Clock,\n type Store,\n} from \"./store.ts\";\n\nconst EXPIRY_LENGTH = 20;\n\n/**\n * Almacenamiento en disco para un único nodo o un volumen compartido.\n *\n * Usa el mismo formato que `FilesystemStore` del servidor PHP: un fichero\n * `sha256(id).message` con la caducidad en 20 dígitos, un salto de línea y el\n * mensaje. Los dos servidores pueden compartir directorio.\n */\nexport class FilesystemStore implements Store {\n private constructor(\n private readonly directory: string,\n private readonly clock: Clock,\n ) {}\n\n /** Crea el directorio con permisos 0700 si no existe. No admite enlaces. */\n static async open(\n directory: string,\n clock: Clock = systemClock,\n ): Promise<FilesystemStore> {\n const existing = await lstat(directory).catch(() => null);\n if (existing?.isSymbolicLink()) {\n throw new StorageError(\n \"The storage directory cannot be a symbolic link.\",\n );\n }\n if (existing === null) {\n await mkdir(directory, { recursive: true, mode: 0o700 });\n }\n return new FilesystemStore(await realpath(directory), clock);\n }\n\n async put(\n identifier: string,\n payload: string,\n ttlSeconds: number,\n ): Promise<void> {\n assertPositiveTtl(ttlSeconds);\n const expiry = String(this.clock() + ttlSeconds).padStart(\n EXPIRY_LENGTH,\n \"0\",\n );\n const temporary = join(\n this.directory,\n `.write-${randomBytes(8).toString(\"hex\")}`,\n );\n try {\n // `wx` falla si el fichero existe: nadie puede colar un enlace previo.\n const handle = await open(temporary, \"wx\", 0o600);\n try {\n await handle.writeFile(`${expiry}\\n${payload}`);\n } finally {\n await handle.close();\n }\n // El rename es atómico: un lector ve el mensaje entero o no lo ve.\n await rename(temporary, this.path(identifier));\n } catch (error) {\n await unlink(temporary).catch(() => undefined);\n throw new StorageError(\"Unable to store the message.\", { cause: error });\n }\n }\n\n async consume(identifier: string): Promise<string | null> {\n const path = this.path(identifier);\n const claimed = `${path}.consume-${randomBytes(8).toString(\"hex\")}`;\n // Solo una petición gana el rename: así nadie recibe el mensaje dos veces.\n try {\n await rename(path, claimed);\n } catch {\n return null;\n }\n try {\n if ((await lstat(claimed)).isSymbolicLink()) {\n return null;\n }\n return this.payload(await readFile(claimed, \"utf8\"));\n } catch (error) {\n throw new StorageError(\"Unable to read the claimed message.\", {\n cause: error,\n });\n } finally {\n await unlink(claimed).catch(() => undefined);\n }\n }\n\n async purgeExpired(): Promise<number> {\n let purged = 0;\n for (const name of await readdir(this.directory)) {\n if (!name.includes(\".message\")) {\n continue;\n }\n const path = join(this.directory, name);\n const stats = await lstat(path);\n if (\n stats.isFile() &&\n this.payload(await readFile(path, \"utf8\")) !== null\n ) {\n continue;\n }\n if (stats.isFile() || stats.isSymbolicLink()) {\n await unlink(path);\n purged++;\n }\n }\n return purged;\n }\n\n private path(identifier: string): string {\n return join(\n this.directory,\n `${createHash(\"sha256\").update(identifier).digest(\"hex\")}.message`,\n );\n }\n\n /** Devuelve el mensaje, o `null` si el registro caducó o está mal formado. */\n private payload(record: string): string | null {\n const expiry = record.slice(0, EXPIRY_LENGTH);\n if (record[EXPIRY_LENGTH] !== \"\\n\" || !/^\\d+$/.test(expiry)) {\n return null;\n }\n return Number(expiry) <= this.clock()\n ? null\n : record.slice(EXPIRY_LENGTH + 1);\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,YAAY,mBAAmB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,YAAY;AASrB,IAAM,gBAAgB;AASf,IAAM,kBAAN,MAAM,iBAAiC;AAAA,EACpC,YACW,WACA,OACjB;AAFiB;AACA;AAAA,EAChB;AAAA,EAFgB;AAAA,EACA;AAAA;AAAA,EAInB,aAAa,KACX,WACA,QAAe,aACW;AAC1B,UAAM,WAAW,MAAM,MAAM,SAAS,EAAE,MAAM,MAAM,IAAI;AACxD,QAAI,UAAU,eAAe,GAAG;AAC9B,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AACA,QAAI,aAAa,MAAM;AACrB,YAAM,MAAM,WAAW,EAAE,WAAW,MAAM,MAAM,IAAM,CAAC;AAAA,IACzD;AACA,WAAO,IAAI,iBAAgB,MAAM,SAAS,SAAS,GAAG,KAAK;AAAA,EAC7D;AAAA,EAEA,MAAM,IACJ,YACA,SACA,YACe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