@bmfk/api 1.0.0 → 1.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.
- package/CHANGELOG.md +47 -0
- package/README.md +12 -5
- package/dist/apiServer/DBService.d.ts +4 -1
- package/dist/apiServer/DBService.js +3 -3
- package/dist/apiServer/db/DBField.d.ts +9 -0
- package/dist/apiServer/db/DBField.js +22 -0
- package/dist/apiServer/db/MysqlAdapter.js +13 -16
- package/dist/apiServer/deployment/DeployerInit.d.ts +6 -0
- package/dist/apiServer/deployment/DeployerInit.js +24 -0
- package/dist/apiServer/deployment/MigrateProject.d.ts +5 -0
- package/dist/apiServer/deployment/MigrateProject.js +65 -1
- package/dist/apiServer/deployment/ProjectConfigWizard.js +52 -7
- package/dist/apiServer/deployment/SetupConfigWizard.js +3 -1
- package/dist/apiServer/documentation/index.html +1 -1
- package/dist/apiServer/helper/Validator.js +1 -1
- package/dist/apiServer/interceptors/InterceptorPayAuth.d.ts +22 -8
- package/dist/apiServer/interceptors/InterceptorPayAuth.js +75 -15
- package/dist/apiServer/monitor/index.html +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,52 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.1.0 — 2026-11-24
|
|
4
|
+
|
|
5
|
+
Security fixes reported by @sorokin-vladimir in #2–#5, reworked so existing PayAuth clients keep working.
|
|
6
|
+
|
|
7
|
+
### Security
|
|
8
|
+
|
|
9
|
+
- `InterceptorPayAuth` **v2** (`PayAuth v=2`): the signed message is `bmfk-payauth-v2`, method, path, key id,
|
|
10
|
+
`ts` (epoch milliseconds only), nonce and `b64`, one per line, so a request is bound to its endpoint and key.
|
|
11
|
+
`InterceptorPayAuth.sign()` builds the header and `b64` for a client.
|
|
12
|
+
- `InterceptorPayAuth` **v1** stays as it was for clients (`b64 + ts + nonce`, `ts` in seconds or
|
|
13
|
+
milliseconds), with the replay fixed on the server: digits moved from the end of `ts` to the start of the
|
|
14
|
+
nonce gave a new nonce with the same signature. Signatures are now remembered with nonces, for the whole
|
|
15
|
+
window, across every endpoint. A key that signs with v1 is logged once; `{ kid, key, v1: false }` turns
|
|
16
|
+
v1 off for that key.
|
|
17
|
+
- `InterceptorPayAuth`: a key that isn't hex, or is shorter than 16 bytes, fails at startup (a per-call
|
|
18
|
+
key refuses the request). A non-hex key used to be decoded to a few bytes or to an empty key, and with an
|
|
19
|
+
empty key anyone could sign.
|
|
20
|
+
- `REQ_DB` fields: options (raw SQL with `system: true`, `ignoreInUpdate`, …) come only from the new
|
|
21
|
+
`dbField(value, options)`. A plain `{ value, system: true }` from request data was put into the SQL as is.
|
|
22
|
+
**Breaking:** a plain object with `value` and only option keys now fails with an error naming the field;
|
|
23
|
+
any other object or array is stored as escaped JSON. `bmfk migrate` rewrites such literals to `dbField()`.
|
|
24
|
+
- `REQ_DB` nested `fields` (`@name` inside a value) fill only a raw fragment (`system: true`): inside an
|
|
25
|
+
escaped value they could close its quotes. `0`, `""`, `false` and `null` are filled in too; they were
|
|
26
|
+
skipped and left `@name` in the SQL.
|
|
27
|
+
- Validation: only the model's own keys are fields. `constructor`, `toString` and other `Object.prototype`
|
|
28
|
+
names passed into the request data unchecked.
|
|
29
|
+
|
|
30
|
+
### Deployer
|
|
31
|
+
|
|
32
|
+
- `bmfk project-config` and `bmfk setup-config` find the deployer made by `bmfk deployer-init` (its
|
|
33
|
+
`bin/Main.js` in the current folder, else `/var/bmfk/bmfk-deployer`). The project config is saved into
|
|
34
|
+
the deployer's projects folder by default, not the current folder, and `setup-config` opens its
|
|
35
|
+
`setup.json`.
|
|
36
|
+
- `bmfk project-config`: when a project requires review, the wizard checks the deployer's `setup.json`.
|
|
37
|
+
It names reviewers that are not there, asks for `review_url` if it is missing (the review page,
|
|
38
|
+
`<deployer address><baseEndPoint>review/html`) and warns when no notifier is set. Uploads are refused
|
|
39
|
+
until all three are in place.
|
|
40
|
+
- `bmfk project-config`: the `deploy.json` it writes has no password placeholder; the wizard points to
|
|
41
|
+
`bmfk deploy-key`, which adds the signing key.
|
|
42
|
+
|
|
43
|
+
## 1.0.1 — 2026-11-24
|
|
44
|
+
|
|
45
|
+
### Release process
|
|
46
|
+
|
|
47
|
+
- Published from CI through an npm Trusted Publisher (OIDC): no npm token exists anywhere. The release
|
|
48
|
+
workflow checks that npm supports it (11.5.1+) and waits for approval on the `npm` environment.
|
|
49
|
+
|
|
3
50
|
## 1.0.0 — 2026-11-23
|
|
4
51
|
|
|
5
52
|
First release of `@bmfk/api`: a TypeScript framework for HTTP API services on Node.js, built so that a
|
package/README.md
CHANGED
|
@@ -186,7 +186,14 @@ getDefaultOptions({ interceptor: new SessionInterceptor(), … });
|
|
|
186
186
|
Two ready-made interceptors handle signed server-to-server requests. Both use a timestamp window and
|
|
187
187
|
nonce replay protection:
|
|
188
188
|
|
|
189
|
-
- **`InterceptorPayAuth`** uses an HMAC-SHA256 signature with a shared key.
|
|
189
|
+
- **`InterceptorPayAuth`** uses an HMAC-SHA256 signature with a shared key. A key is hex, at least
|
|
190
|
+
16 bytes (`crypto.randomBytes(32).toString("hex")`); anything else fails at startup. Version 2
|
|
191
|
+
(`PayAuth v=2, …`) signs, one per line, `bmfk-payauth-v2`, the method, the path, the key id, `ts`
|
|
192
|
+
(epoch milliseconds), the nonce and `b64`; `InterceptorPayAuth.sign()` builds the header and the
|
|
193
|
+
`b64` field for a client. Version 1 (`b64 + ts + nonce`) is still accepted for existing clients and
|
|
194
|
+
logs a warning; turn it off per key once a client has moved: `{ kid, key, v1: false }`. Nonces and
|
|
195
|
+
signatures are remembered across all endpoints for the whole window, so an accepted request can't
|
|
196
|
+
be sent again, to any endpoint. If a proxy rewrites the path, sign the path the server sees.
|
|
190
197
|
- **`InterceptorSignedAuth`** uses Ed25519 key pairs. The caller keeps the private key, and the
|
|
191
198
|
server stores only public keys, so nothing on the server can be stolen and reused. The signature
|
|
192
199
|
covers the method, path, timestamp, nonce, every field and the sha256 of every uploaded file.
|
|
@@ -800,10 +807,10 @@ rejects the whole change, and the previous setup stays in force.
|
|
|
800
807
|
> it, every request appears to come from `127.0.0.1`. Never add `127.0.0.1` to `allowed_ips` on a
|
|
801
808
|
> deployer behind a proxy on the same host: that would let every request through.
|
|
802
809
|
|
|
803
|
-
A project config (`projects_path/<name>.json`). The easiest way to make one is `npx bmfk project-config
|
|
804
|
-
it asks for everything below, generates the token, takes config values as
|
|
805
|
-
result against the deployer's schema, and saves the project config
|
|
806
|
-
permissions `600`.
|
|
810
|
+
A project config (`projects_path/<name>.json`). The easiest way to make one is `npx bmfk project-config`
|
|
811
|
+
in the deployer's folder: it asks for everything below, generates the token, takes config values as
|
|
812
|
+
hidden input, checks the result against the deployer's schema, and saves the project config into the
|
|
813
|
+
deployer's projects folder and a matching `deploy.json`, both with permissions `600`.
|
|
807
814
|
|
|
808
815
|
```jsonc
|
|
809
816
|
{
|
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
import { Req } from "../signal/Signal";
|
|
2
2
|
import { BaseService } from "./BaseService";
|
|
3
3
|
import { IDBAdapter } from "./db/IDBAdapter";
|
|
4
|
+
import type { IDBField } from "./db/DBField";
|
|
5
|
+
export { dbField } from "./db/DBField";
|
|
6
|
+
export type { IDBField } from "./db/DBField";
|
|
4
7
|
export interface IDBQueryField {
|
|
5
8
|
name?: string | null;
|
|
6
9
|
value: string | number | boolean | Date | null | undefined;
|
|
@@ -12,7 +15,7 @@ export interface IDBQueryField {
|
|
|
12
15
|
fields?: Record<string, number | boolean | string | null>;
|
|
13
16
|
}
|
|
14
17
|
export interface IDBQueryFields {
|
|
15
|
-
[key: string]: string | number | boolean | Date |
|
|
18
|
+
[key: string]: string | number | boolean | Date | IDBField | Record<string, unknown> | unknown[] | null | undefined;
|
|
16
19
|
}
|
|
17
20
|
export interface IDBQuery {
|
|
18
21
|
dbid?: string;
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.DBService = exports.REQ_DB_TROLLBACK = exports.REQ_DB_TCOMMIT = exports.REQ_DB_TBEGIN = exports.REQ_DBX = exports.REQ_DB = void 0;
|
|
3
|
+
exports.DBService = exports.REQ_DB_TROLLBACK = exports.REQ_DB_TCOMMIT = exports.REQ_DB_TBEGIN = exports.REQ_DBX = exports.REQ_DB = exports.dbField = void 0;
|
|
4
4
|
const Signal_1 = require("../signal/Signal");
|
|
5
5
|
const BaseService_1 = require("./BaseService");
|
|
6
6
|
const MysqlAdapter_1 = require("./db/MysqlAdapter");
|
|
7
7
|
const PostgresAdapter_1 = require("./db/PostgresAdapter");
|
|
8
|
+
var DBField_1 = require("./db/DBField");
|
|
9
|
+
Object.defineProperty(exports, "dbField", { enumerable: true, get: function () { return DBField_1.dbField; } });
|
|
8
10
|
exports.REQ_DB = new Signal_1.Req(undefined, "REQ_DB");
|
|
9
11
|
exports.REQ_DBX = new Signal_1.Req(undefined, "REQ_DBX");
|
|
10
12
|
exports.REQ_DB_TBEGIN = new Signal_1.Req(undefined, "REQ_DB_TBEGIN");
|
|
@@ -150,8 +152,6 @@ class DBService extends BaseService_1.BaseService {
|
|
|
150
152
|
};
|
|
151
153
|
};
|
|
152
154
|
exports.REQ_DB.listener = async (req) => {
|
|
153
|
-
if (req.fields)
|
|
154
|
-
req.fields = structuredClone(req.fields);
|
|
155
155
|
const executionStartTime = Date.now();
|
|
156
156
|
if (!req.dbid && DBService.allInstances.length === 1 && DBService.allInstances[0].adapter) {
|
|
157
157
|
return await DBService.allInstances[0].adapter.query(req);
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { IDBQueryField } from "../DBService";
|
|
2
|
+
declare const DB_FIELD: unique symbol;
|
|
3
|
+
export type IDBField = IDBQueryField & {
|
|
4
|
+
readonly [DB_FIELD]: true;
|
|
5
|
+
};
|
|
6
|
+
export declare function dbField(value: IDBQueryField["value"], options?: Omit<IDBQueryField, "value" | "__parsedValue">): IDBField;
|
|
7
|
+
export declare function isDBField(v: unknown): v is IDBField;
|
|
8
|
+
export declare function looksLikeFieldOptions(v: unknown): boolean;
|
|
9
|
+
export {};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.dbField = dbField;
|
|
4
|
+
exports.isDBField = isDBField;
|
|
5
|
+
exports.looksLikeFieldOptions = looksLikeFieldOptions;
|
|
6
|
+
const DB_FIELD = Symbol("bmfk.dbField");
|
|
7
|
+
function dbField(value, options = {}) {
|
|
8
|
+
return { ...options, value, [DB_FIELD]: true };
|
|
9
|
+
}
|
|
10
|
+
function isDBField(v) {
|
|
11
|
+
return typeof v === "object" && v !== null && v[DB_FIELD] === true;
|
|
12
|
+
}
|
|
13
|
+
const OPTION_KEYS = new Set(["value", "name", "system", "ignoreInInsert", "ignoreInUpdate", "useInReplace", "fields", "__parsedValue"]);
|
|
14
|
+
function looksLikeFieldOptions(v) {
|
|
15
|
+
if (typeof v !== "object" || v === null || Array.isArray(v))
|
|
16
|
+
return false;
|
|
17
|
+
const proto = Object.getPrototypeOf(v);
|
|
18
|
+
if (proto !== Object.prototype && proto !== null)
|
|
19
|
+
return false;
|
|
20
|
+
const keys = Object.keys(v);
|
|
21
|
+
return keys.includes("value") && keys.every(k => OPTION_KEYS.has(k));
|
|
22
|
+
}
|
|
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
6
|
exports.MysqlAdapter = void 0;
|
|
7
7
|
exports.isError = isError;
|
|
8
|
+
const DBField_1 = require("./DBField");
|
|
8
9
|
const promise_1 = __importDefault(require("mysql2/promise"));
|
|
9
10
|
const fs_1 = __importDefault(require("fs"));
|
|
10
11
|
const LogService_1 = require("../LogService");
|
|
@@ -619,22 +620,21 @@ class MysqlAdapter {
|
|
|
619
620
|
const name = i;
|
|
620
621
|
if (name.startsWith("$__"))
|
|
621
622
|
continue;
|
|
622
|
-
|
|
623
|
-
if (
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
if (queryField.value === undefined) {
|
|
623
|
+
const raw = fields[i];
|
|
624
|
+
if (!(0, DBField_1.isDBField)(raw) && (0, DBField_1.looksLikeFieldOptions)(raw))
|
|
625
|
+
throw new Error(`REQ_DB field "${name}": a plain { value, … } object is not read as field options — ` +
|
|
626
|
+
`use dbField(value, { … }); to store the object as JSON, pass JSON.stringify(it)`);
|
|
627
|
+
const queryField = (0, DBField_1.isDBField)(raw)
|
|
628
|
+
? { ...raw }
|
|
629
|
+
: raw === undefined || raw === null
|
|
630
|
+
? { value: null, system: true }
|
|
631
|
+
: { value: raw, system: false };
|
|
632
|
+
if (queryField.value === undefined || queryField.value === null) {
|
|
632
633
|
queryField.value = null;
|
|
633
634
|
queryField.system = true;
|
|
634
635
|
}
|
|
635
636
|
if (!queryField.name)
|
|
636
637
|
queryField.name = name.replaceAll("`", '').replaceAll('\"', "").replaceAll('\'', "");
|
|
637
|
-
fields[i] = queryField;
|
|
638
638
|
const parsed = MysqlAdapter.prepareQueryFieldValue(queryField);
|
|
639
639
|
values.set(name, parsed + "");
|
|
640
640
|
if (!queryField.name.startsWith("$__"))
|
|
@@ -709,13 +709,10 @@ class MysqlAdapter {
|
|
|
709
709
|
if (typeof value === "boolean")
|
|
710
710
|
value = value ? 1 : 0;
|
|
711
711
|
}
|
|
712
|
-
if (field.fields && typeof field.fields === "object" && value && typeof value === "string" && value.indexOf("@") !== -1) {
|
|
712
|
+
if (system && field.fields && typeof field.fields === "object" && value && typeof value === "string" && value.indexOf("@") !== -1) {
|
|
713
713
|
const nested = new Map();
|
|
714
|
-
for (let key in field.fields)
|
|
715
|
-
if (!field.fields[key])
|
|
716
|
-
continue;
|
|
714
|
+
for (let key in field.fields)
|
|
717
715
|
nested.set(key, promise_1.default.escape(field.fields[key]));
|
|
718
|
-
}
|
|
719
716
|
value = MysqlAdapter.substitute(value, nested);
|
|
720
717
|
}
|
|
721
718
|
field.__parsedValue = value;
|
|
@@ -21,5 +21,11 @@ export declare function deployerInitFiles(a: IDeployerInitAnswers, packageJson:
|
|
|
21
21
|
content: string;
|
|
22
22
|
mode?: number;
|
|
23
23
|
}>;
|
|
24
|
+
export interface IDeployerFolders {
|
|
25
|
+
projectsPath: string;
|
|
26
|
+
setupPath: string;
|
|
27
|
+
baseEndPoint: string;
|
|
28
|
+
}
|
|
29
|
+
export declare function findDeployer(dir: string): IDeployerFolders | null;
|
|
24
30
|
export declare function nginxSnippet(a: IDeployerInitAnswers): string;
|
|
25
31
|
export declare function DeployerInit(args: string[]): Promise<void>;
|
|
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
exports.publicKeyProblem = publicKeyProblem;
|
|
7
7
|
exports.normalizeBase = normalizeBase;
|
|
8
8
|
exports.deployerInitFiles = deployerInitFiles;
|
|
9
|
+
exports.findDeployer = findDeployer;
|
|
9
10
|
exports.nginxSnippet = nginxSnippet;
|
|
10
11
|
exports.DeployerInit = DeployerInit;
|
|
11
12
|
const fs_1 = __importDefault(require("fs"));
|
|
@@ -97,6 +98,29 @@ module.exports = {
|
|
|
97
98
|
[path_1.default.join(a.setupPath, "setup.json")]: { content: JSON.stringify(setup, null, 4) + "\n", mode: 0o600 },
|
|
98
99
|
};
|
|
99
100
|
}
|
|
101
|
+
function findDeployer(dir) {
|
|
102
|
+
let main = "";
|
|
103
|
+
try {
|
|
104
|
+
main = fs_1.default.readFileSync(path_1.default.join(dir, "bin", "Main.js"), "utf-8");
|
|
105
|
+
}
|
|
106
|
+
catch { }
|
|
107
|
+
const str = (key) => {
|
|
108
|
+
const m = main.match(new RegExp(`\\b${key}:\\s*("(?:[^"\\\\]|\\\\.)*")`));
|
|
109
|
+
try {
|
|
110
|
+
return m ? String(JSON.parse(m[1])) : null;
|
|
111
|
+
}
|
|
112
|
+
catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
const projectsPath = str("projects_path"), setupPath = str("setup_path");
|
|
117
|
+
if (projectsPath && setupPath)
|
|
118
|
+
return { projectsPath, setupPath, baseEndPoint: str("baseEndPoint") ?? "/api/" };
|
|
119
|
+
const def = AppDataPath_1.AppData.projectDir("bmfk-deployer");
|
|
120
|
+
if (fs_1.default.existsSync(path_1.default.join(def, "projects")))
|
|
121
|
+
return { projectsPath: path_1.default.join(def, "projects"), setupPath: path_1.default.join(def, "setup"), baseEndPoint: "/api/" };
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
100
124
|
function nginxSnippet(a) {
|
|
101
125
|
return `location ${a.baseEndPoint}pckg/ {
|
|
102
126
|
proxy_pass http://127.0.0.1:${a.port};
|
|
@@ -26,6 +26,11 @@ export declare function migrateModels(text: string, rel: string, ts: TS): {
|
|
|
26
26
|
changes: number;
|
|
27
27
|
notes: string[];
|
|
28
28
|
};
|
|
29
|
+
export declare function migrateFieldOptions(text: string, rel: string, ts: TS): {
|
|
30
|
+
text: string;
|
|
31
|
+
changes: number;
|
|
32
|
+
notes: string[];
|
|
33
|
+
};
|
|
29
34
|
export declare function planMigration(dir: string, exported: Set<string>): IMigrationPlan;
|
|
30
35
|
export declare function MigrateProject(args: string[]): Promise<void>;
|
|
31
36
|
export {};
|
|
@@ -8,6 +8,7 @@ exports.migrateSource = migrateSource;
|
|
|
8
8
|
exports.migratePackageJson = migratePackageJson;
|
|
9
9
|
exports.projectTypeScript = projectTypeScript;
|
|
10
10
|
exports.migrateModels = migrateModels;
|
|
11
|
+
exports.migrateFieldOptions = migrateFieldOptions;
|
|
11
12
|
exports.planMigration = planMigration;
|
|
12
13
|
exports.MigrateProject = MigrateProject;
|
|
13
14
|
const fs_1 = __importDefault(require("fs"));
|
|
@@ -257,11 +258,66 @@ function migrateModels(text, rel, ts) {
|
|
|
257
258
|
out = out.slice(0, e.at) + e.text + out.slice(e.end);
|
|
258
259
|
return { text: out, changes: edits.length / 2, notes };
|
|
259
260
|
}
|
|
261
|
+
const FIELD_OPTION_KEYS = new Set(["value", "name", "system", "ignoreInInsert", "ignoreInUpdate", "useInReplace", "fields", "__parsedValue"]);
|
|
262
|
+
const FIELD_OPTION_MARKERS = ["system", "ignoreInInsert", "ignoreInUpdate", "useInReplace", "fields"];
|
|
263
|
+
function migrateFieldOptions(text, rel, ts) {
|
|
264
|
+
const kind = /\.(tsx|jsx)$/.test(rel) ? ts.ScriptKind.TSX : /\.(js|mjs|cjs)$/.test(rel) ? ts.ScriptKind.JS : ts.ScriptKind.TS;
|
|
265
|
+
const sf = ts.createSourceFile(rel, text, ts.ScriptTarget.Latest, true, kind);
|
|
266
|
+
const notes = [];
|
|
267
|
+
const edits = [];
|
|
268
|
+
const nameOf = (n) => ts.isIdentifier(n) || ts.isStringLiteral(n) || ts.isNumericLiteral(n) ? n.text : null;
|
|
269
|
+
const inFieldsLiteral = (obj) => {
|
|
270
|
+
const prop = obj.parent;
|
|
271
|
+
const owner = prop && ts.isPropertyAssignment(prop) ? prop.parent : null;
|
|
272
|
+
const holder = owner && ts.isObjectLiteralExpression(owner) ? owner.parent : null;
|
|
273
|
+
if (!holder || !ts.isPropertyAssignment(holder) || nameOf(holder.name) !== "fields")
|
|
274
|
+
return false;
|
|
275
|
+
return holder.parent.properties.some((p) => p.name && nameOf(p.name) === "query");
|
|
276
|
+
};
|
|
277
|
+
const visit = (node) => {
|
|
278
|
+
if (ts.isObjectLiteralExpression(node) && node.properties.length) {
|
|
279
|
+
const props = node.properties;
|
|
280
|
+
const names = props.map((p) => (ts.isPropertyAssignment(p) || ts.isShorthandPropertyAssignment(p)) ? nameOf(p.name) : null);
|
|
281
|
+
if (names.every((n) => n !== null && FIELD_OPTION_KEYS.has(n)) && names.includes("value")
|
|
282
|
+
&& (names.some((n) => FIELD_OPTION_MARKERS.includes(n)) || inFieldsLiteral(node))) {
|
|
283
|
+
const valueProp = props[names.indexOf("value")];
|
|
284
|
+
const valueText = ts.isShorthandPropertyAssignment(valueProp) ? "value" : valueProp.initializer.getText(sf);
|
|
285
|
+
const rest = props.filter((p) => p !== valueProp && nameOf(p.name) !== "__parsedValue").map((p) => p.getText(sf));
|
|
286
|
+
edits.push({ at: node.getStart(sf), end: node.getEnd(), text: `dbField(${valueText}${rest.length ? `, { ${rest.join(", ")} }` : ""})` });
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
ts.forEachChild(node, visit);
|
|
291
|
+
};
|
|
292
|
+
visit(sf);
|
|
293
|
+
if (!edits.length)
|
|
294
|
+
return { text, changes: 0, notes };
|
|
295
|
+
let out = text;
|
|
296
|
+
for (const e of edits.sort((a, b) => b.at - a.at))
|
|
297
|
+
out = out.slice(0, e.at) + e.text + out.slice(e.end);
|
|
298
|
+
const named = /import\s+\{([^}]*)\}\s+from\s+(["'])@bmfk\/api\2/.exec(out);
|
|
299
|
+
if (named && /\bdbField\b/.test(named[1])) {
|
|
300
|
+
}
|
|
301
|
+
else if (named) {
|
|
302
|
+
const open = out.indexOf("{", named.index), close = out.indexOf("}", open);
|
|
303
|
+
const inner = out.slice(open + 1, close).replace(/[\s,]*$/, "");
|
|
304
|
+
out = out.slice(0, open + 1) + `${inner}, dbField ` + out.slice(close);
|
|
305
|
+
}
|
|
306
|
+
else if (sf.statements.some((s) => ts.isImportDeclaration(s))) {
|
|
307
|
+
const last = [...sf.statements].reverse().find((s) => ts.isImportDeclaration(s));
|
|
308
|
+
const at = out.indexOf(last.getText(sf)) + last.getText(sf).length;
|
|
309
|
+
out = out.slice(0, at) + `\nimport { dbField } from "${NEW_PKG}";` + out.slice(at);
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
notes.push(`${rel} — dbField() is used now: add it to the ${NEW_PKG} require/import`);
|
|
313
|
+
}
|
|
314
|
+
return { text: out, changes: edits.length, notes };
|
|
315
|
+
}
|
|
260
316
|
function planMigration(dir, exported) {
|
|
261
317
|
const plan = { files: [], notes: [] };
|
|
262
318
|
const ts = projectTypeScript(dir);
|
|
263
319
|
if (!ts)
|
|
264
|
-
plan.notes.push(`validation models were NOT checked: this needs TypeScript 5 in the project — run \`npm i -D typescript@5\` and migrate again (at startup the service also lists number samples that 6.x took as bounds)`);
|
|
320
|
+
plan.notes.push(`validation models and REQ_DB field options were NOT checked: this needs TypeScript 5 in the project — run \`npm i -D typescript@5\` and migrate again (at startup the service also lists number samples that 6.x took as bounds)`);
|
|
265
321
|
const pkgFile = path_1.default.join(dir, "package.json");
|
|
266
322
|
if (fs_1.default.existsSync(pkgFile)) {
|
|
267
323
|
const before = fs_1.default.readFileSync(pkgFile, "utf-8");
|
|
@@ -286,6 +342,12 @@ function planMigration(dir, exported) {
|
|
|
286
342
|
changes += r.changes;
|
|
287
343
|
plan.notes.push(...r.notes);
|
|
288
344
|
}
|
|
345
|
+
if (ts && /\bvalue\b/.test(text) && /\b(system|ignoreInInsert|ignoreInUpdate|useInReplace|fields)\b/.test(text)) {
|
|
346
|
+
const f = migrateFieldOptions(text, rel, ts);
|
|
347
|
+
text = f.text;
|
|
348
|
+
changes += f.changes;
|
|
349
|
+
plan.notes.push(...f.notes);
|
|
350
|
+
}
|
|
289
351
|
if (changes)
|
|
290
352
|
plan.files.push({ file, before, after: text, changes });
|
|
291
353
|
}
|
|
@@ -323,6 +385,8 @@ async function MigrateProject(args) {
|
|
|
323
385
|
console.log(bold("\nAlso check:"));
|
|
324
386
|
console.log(" - MySQL values starting with \"_\" (host, user, database, password) were decrypted by 6.x; 1.0 uses them as written.");
|
|
325
387
|
console.log(" - Services that call each other move to 1.0 together: 6.x and 1.0 can't call each other.");
|
|
388
|
+
console.log(" - REQ_DB field options built at run time (not written as { value, system: … } in the code) need dbField() by hand;");
|
|
389
|
+
console.log(" a plain { value, … } object now fails with an error that names the field.");
|
|
326
390
|
console.log(" - Deploy with a 1.0 deployer: copy setup.json, the project configs and <project>_state_.json into its folders.");
|
|
327
391
|
console.log(" - Node.js 24 or later on the servers.");
|
|
328
392
|
if (!write) {
|
|
@@ -14,6 +14,7 @@ const ConfigService_1 = require("./ConfigService");
|
|
|
14
14
|
const HashPassword_1 = require("./HashPassword");
|
|
15
15
|
const cliCommon_1 = require("./cliCommon");
|
|
16
16
|
const cliPrompt_1 = require("./cliPrompt");
|
|
17
|
+
const DeployerInit_1 = require("./DeployerInit");
|
|
17
18
|
async function ProjectConfigWizard() {
|
|
18
19
|
const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
|
|
19
20
|
if (!process_1.stdin.isTTY) {
|
|
@@ -22,6 +23,22 @@ async function ProjectConfigWizard() {
|
|
|
22
23
|
}
|
|
23
24
|
const section = (title) => console.log("\n" + bold(title));
|
|
24
25
|
console.log(bold("\nNew project config for the deployer") + dim(" (Enter keeps the value in brackets)"));
|
|
26
|
+
const deployer = (0, DeployerInit_1.findDeployer)(process.cwd());
|
|
27
|
+
if (deployer)
|
|
28
|
+
console.log(dim(` Deployer: project configs in ${deployer.projectsPath}, setup.json in ${deployer.setupPath}`));
|
|
29
|
+
else
|
|
30
|
+
console.log(yellow(" No deployer found here (bin/Main.js from deployer-init) — run this in the deployer's folder, or copy the result there."));
|
|
31
|
+
const setupFile = deployer ? path_1.default.join(deployer.setupPath, "setup.json") : null;
|
|
32
|
+
let setupDoc = null;
|
|
33
|
+
if (setupFile && fs_1.default.existsSync(setupFile)) {
|
|
34
|
+
try {
|
|
35
|
+
setupDoc = JSON.parse(fs_1.default.readFileSync(setupFile, "utf-8") || "{}");
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
console.log(yellow(` ⚠ ${setupFile} is not valid JSON — fix it with npx bmfk setup-config`));
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
let reviewUrl = null;
|
|
25
42
|
section("Project");
|
|
26
43
|
const name = await (0, cliPrompt_1.askValid)("Name (e.g. api.gateway.example.com)", "", v => (0, ConfigService_1.projectNameProblem)(v));
|
|
27
44
|
const description = await (0, cliPrompt_1.ask)("Description", "");
|
|
@@ -110,6 +127,24 @@ async function ProjectConfigWizard() {
|
|
|
110
127
|
const mode = (await (0, cliPrompt_1.askValid)(" approval: any (one accept) / all (everyone)", "any", v => v === "any" || v === "all" ? null : "any or all"));
|
|
111
128
|
const ttlHours = Number(await (0, cliPrompt_1.askValid)(" hours to decide", "24", v => /^\d+$/.test(v) && +v >= 1 && +v <= 168 ? null : "1–168"));
|
|
112
129
|
cfg.review = { reviewers, mode, ttlHours };
|
|
130
|
+
if (setupDoc) {
|
|
131
|
+
const known = new Set((Array.isArray(setupDoc.reviewers) ? setupDoc.reviewers : []).map((r) => r?.login));
|
|
132
|
+
const unknown = reviewers.filter(r => !known.has(r));
|
|
133
|
+
if (unknown.length)
|
|
134
|
+
console.log(yellow(` ⚠ Not reviewers in ${setupFile}: ${unknown.join(", ")} — add them with npx bmfk setup-config`));
|
|
135
|
+
if (!/^https?:\/\/[^\s#]+$/.test(String(setupDoc.review_url ?? ""))) {
|
|
136
|
+
console.log(dim(` The review page is <deployer address>${deployer.baseEndPoint}review/html, as reviewers open it.`));
|
|
137
|
+
reviewUrl = await (0, cliPrompt_1.askValid)(" review_url for setup.json (empty = set it later)", "", v => !v || /^https?:\/\/[^\s#]+$/.test(v) ? null : "an http(s) URL without #") || null;
|
|
138
|
+
}
|
|
139
|
+
if (!setupDoc.notifier?.URL || !setupDoc.notifier?.KEY)
|
|
140
|
+
console.log(yellow(" ⚠ No notifier in setup.json: reviewers can't be emailed their links — npx bmfk setup-config."));
|
|
141
|
+
console.log(yellow(" Until reviewers, review_url and the notifier are in setup.json, the deployer refuses this project's uploads."));
|
|
142
|
+
}
|
|
143
|
+
else {
|
|
144
|
+
console.log(yellow(" ⚠ The deployer's setup.json must also have these reviewers, review_url (the review page, e.g.\n" +
|
|
145
|
+
" https://deployer.example.com/api/review/html) and a notifier for the emails — npx bmfk setup-config.\n" +
|
|
146
|
+
" Until then the deployer refuses this project's uploads."));
|
|
147
|
+
}
|
|
113
148
|
}
|
|
114
149
|
const errors = await Validator_1.Validator.validateStructure(ConfigService_1.PROJECT_CONFIG_MODEL, cfg);
|
|
115
150
|
if (errors && errors.length) {
|
|
@@ -119,30 +154,40 @@ async function ProjectConfigWizard() {
|
|
|
119
154
|
process.exit(1);
|
|
120
155
|
}
|
|
121
156
|
section("Deploy client (deploy.json for the project)");
|
|
122
|
-
const host = await (0, cliPrompt_1.ask)(" deployer upload URL",
|
|
157
|
+
const host = await (0, cliPrompt_1.ask)(" deployer upload URL", `https://deployer.example.com${deployer?.baseEndPoint ?? "/api/"}pckg/add`);
|
|
123
158
|
const username = await (0, cliPrompt_1.ask)(" deployer user login", "");
|
|
124
159
|
const projectJson = JSON.stringify(cfg, null, 4);
|
|
125
|
-
const deployJson = JSON.stringify({ name, host, token: plainToken ?? "<the existing token>", username
|
|
160
|
+
const deployJson = JSON.stringify({ name, host, token: plainToken ?? "<the existing token>", username }, null, 4);
|
|
126
161
|
console.log("");
|
|
127
162
|
const save = async (what, content, def) => {
|
|
128
163
|
const target = await (0, cliPrompt_1.ask)(`Save ${what} to (empty = print here)`, def);
|
|
129
164
|
if (!target) {
|
|
130
165
|
console.log("\n" + content + "\n");
|
|
131
|
-
return;
|
|
166
|
+
return null;
|
|
132
167
|
}
|
|
133
168
|
if (fs_1.default.existsSync(target) && !(await (0, cliPrompt_1.yes)(` ${target} exists — overwrite?`, false))) {
|
|
134
169
|
console.log("\n" + content + "\n");
|
|
135
|
-
return;
|
|
170
|
+
return null;
|
|
136
171
|
}
|
|
137
|
-
fs_1.default.mkdirSync(path_1.default.dirname(path_1.default.resolve(target)), { recursive: true });
|
|
172
|
+
fs_1.default.mkdirSync(path_1.default.dirname(path_1.default.resolve(target)), { recursive: true, mode: 0o700 });
|
|
138
173
|
fs_1.default.writeFileSync(target, content + "\n", { encoding: "utf-8", mode: 0o600 });
|
|
139
174
|
console.log(green(` ✓ ${path_1.default.resolve(target)}`) + dim(" (0600)"));
|
|
175
|
+
return path_1.default.resolve(target);
|
|
140
176
|
};
|
|
141
|
-
await save("the project config for the deployer", projectJson, `${name}.json`);
|
|
142
|
-
|
|
177
|
+
const saved = await save("the project config for the deployer", projectJson, deployer ? path_1.default.join(deployer.projectsPath, `${name}.json`) : `${name}.json`);
|
|
178
|
+
if (!saved || !deployer || path_1.default.dirname(saved) !== path_1.default.resolve(deployer.projectsPath))
|
|
179
|
+
console.log(dim(` → copy it to <projects_path>/${name}.json on the deployer; it is picked up without a restart.`));
|
|
180
|
+
if (reviewUrl && setupFile) {
|
|
181
|
+
const tmp = setupFile + ".tmp";
|
|
182
|
+
fs_1.default.writeFileSync(tmp, JSON.stringify({ ...setupDoc, review_url: reviewUrl }, null, 4) + "\n", { encoding: "utf-8", mode: 0o600 });
|
|
183
|
+
fs_1.default.chmodSync(tmp, 0o600);
|
|
184
|
+
fs_1.default.renameSync(tmp, setupFile);
|
|
185
|
+
console.log(green(` ✓ review_url set in ${setupFile}`));
|
|
186
|
+
}
|
|
143
187
|
await save("deploy.json for the project", deployJson, "");
|
|
144
188
|
if (plainToken)
|
|
145
189
|
console.log(yellow(" The token is shown only here and in deploy.json — the deployer keeps its hash. Keep deploy.json out of git."));
|
|
190
|
+
console.log(dim(" Then, on the machine you deploy from: npx bmfk deploy-key deploy.json — and add the printed public key to setup.json."));
|
|
146
191
|
if (cfg.review)
|
|
147
192
|
console.log(dim(" Reviewers must exist in the deployer's setup.json; it says at startup if anything is missing."));
|
|
148
193
|
}
|
|
@@ -16,6 +16,7 @@ const DeployerService_1 = require("./DeployerService");
|
|
|
16
16
|
const HashPassword_1 = require("./HashPassword");
|
|
17
17
|
const cliCommon_1 = require("./cliCommon");
|
|
18
18
|
const cliPrompt_1 = require("./cliPrompt");
|
|
19
|
+
const DeployerInit_1 = require("./DeployerInit");
|
|
19
20
|
async function SetupConfigWizard(target) {
|
|
20
21
|
const { red, green, yellow, dim, bold } = (0, cliCommon_1.palette)();
|
|
21
22
|
if (!process_1.stdin.isTTY) {
|
|
@@ -25,8 +26,9 @@ async function SetupConfigWizard(target) {
|
|
|
25
26
|
let file = target ?? (["setup.json", "projects/setup.json"].find(f => fs_1.default.existsSync(f)) ?? "");
|
|
26
27
|
if (target && fs_1.default.existsSync(target) && fs_1.default.statSync(target).isDirectory())
|
|
27
28
|
file = path_1.default.join(target, "setup.json");
|
|
29
|
+
const deployer = !file ? (0, DeployerInit_1.findDeployer)(process.cwd()) : null;
|
|
28
30
|
console.log(bold("\nDeployer setup.json") + dim(" (the deployer re-reads it on change)"));
|
|
29
|
-
file = path_1.default.resolve(file || await (0, cliPrompt_1.ask)("File", "setup.json"));
|
|
31
|
+
file = path_1.default.resolve(file || await (0, cliPrompt_1.ask)("File", deployer ? path_1.default.join(deployer.setupPath, "setup.json") : "setup.json"));
|
|
30
32
|
let doc = { users: [] };
|
|
31
33
|
if (fs_1.default.existsSync(file)) {
|
|
32
34
|
try {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<!doctype html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
|
-
<!-- Build: 2026-11-
|
|
4
|
+
<!-- Build: 2026-11-24T11:36:27.783Z | Version: 1.0.0 -->
|
|
5
5
|
<script>var __ver = "1.0.0";</script>
|
|
6
6
|
<meta charset="UTF-8" />
|
|
7
7
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
|
@@ -1,19 +1,33 @@
|
|
|
1
1
|
import { IInterceptor } from "../APIService";
|
|
2
2
|
import { IRequest } from "../structures/Interfaces";
|
|
3
|
+
export interface IPayAuthKey {
|
|
4
|
+
kid: string;
|
|
5
|
+
key: string;
|
|
6
|
+
v1?: boolean;
|
|
7
|
+
}
|
|
3
8
|
export declare class InterceptorPayAuth implements IInterceptor<any> {
|
|
4
9
|
private static readonly TS_PAST_SEC;
|
|
5
10
|
private static readonly TS_FUTURE_SEC;
|
|
6
11
|
private static readonly NONCE_TTL_MS;
|
|
7
12
|
private static readonly NONCE_MAX;
|
|
8
|
-
private
|
|
13
|
+
private static seen;
|
|
14
|
+
private static warnedV1;
|
|
9
15
|
private authorizationsPreset;
|
|
10
|
-
constructor(authorizations?:
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
+
constructor(authorizations?: IPayAuthKey[]);
|
|
17
|
+
private static keyProblem;
|
|
18
|
+
private static purge;
|
|
19
|
+
intercept(req: IRequest, authorizations?: IPayAuthKey[]): Promise<any>;
|
|
20
|
+
static message(method: string, path: string, kid: string, ts: string, nonce: string, b64: string): string;
|
|
21
|
+
private static pathOf;
|
|
22
|
+
static sign(o: {
|
|
16
23
|
key: string;
|
|
17
24
|
kid: string;
|
|
18
|
-
|
|
25
|
+
method: string;
|
|
26
|
+
url: string;
|
|
27
|
+
data: unknown;
|
|
28
|
+
nonce?: string;
|
|
29
|
+
}): {
|
|
30
|
+
authorization: string;
|
|
31
|
+
b64: string;
|
|
32
|
+
};
|
|
19
33
|
}
|
|
@@ -7,6 +7,7 @@ exports.InterceptorPayAuth = void 0;
|
|
|
7
7
|
const crypto_1 = __importDefault(require("crypto"));
|
|
8
8
|
const Validator_1 = require("../helper/Validator");
|
|
9
9
|
const DefaultErrors_1 = __importDefault(require("../structures/DefaultErrors"));
|
|
10
|
+
const LogService_1 = require("../LogService");
|
|
10
11
|
const _TAuthParams = {
|
|
11
12
|
v: 0,
|
|
12
13
|
ts: "",
|
|
@@ -16,27 +17,42 @@ const _TAuthParams = {
|
|
|
16
17
|
$__alg_optional: true,
|
|
17
18
|
sig: ""
|
|
18
19
|
};
|
|
20
|
+
const V2 = "bmfk-payauth-v2";
|
|
19
21
|
class InterceptorPayAuth {
|
|
20
22
|
static TS_PAST_SEC = 300;
|
|
21
23
|
static TS_FUTURE_SEC = 60;
|
|
22
24
|
static NONCE_TTL_MS = (InterceptorPayAuth.TS_PAST_SEC + InterceptorPayAuth.TS_FUTURE_SEC) * 1000;
|
|
23
|
-
static NONCE_MAX =
|
|
24
|
-
|
|
25
|
+
static NONCE_MAX = 200_000;
|
|
26
|
+
static seen = new Map();
|
|
27
|
+
static warnedV1 = new Set();
|
|
25
28
|
authorizationsPreset;
|
|
26
29
|
constructor(authorizations) {
|
|
30
|
+
for (const a of authorizations ?? []) {
|
|
31
|
+
const problem = InterceptorPayAuth.keyProblem(a.key);
|
|
32
|
+
if (problem)
|
|
33
|
+
throw new Error(`InterceptorPayAuth: key of "${a.kid}" ${problem}`);
|
|
34
|
+
}
|
|
27
35
|
this.authorizationsPreset = authorizations;
|
|
28
36
|
}
|
|
29
|
-
|
|
30
|
-
|
|
37
|
+
static keyProblem(key) {
|
|
38
|
+
if (typeof key !== "string" || !/^[0-9a-fA-F]*$/.test(key) || key.length % 2 !== 0)
|
|
39
|
+
return "must be hex";
|
|
40
|
+
if (key.length < 32)
|
|
41
|
+
return "must be at least 16 bytes (32 hex characters)";
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
static purge(nowMs) {
|
|
45
|
+
const seen = InterceptorPayAuth.seen;
|
|
46
|
+
for (const [k, expiresAt] of seen) {
|
|
31
47
|
if (expiresAt > nowMs)
|
|
32
48
|
break;
|
|
33
|
-
|
|
49
|
+
seen.delete(k);
|
|
34
50
|
}
|
|
35
|
-
while (
|
|
36
|
-
const oldest =
|
|
51
|
+
while (seen.size > InterceptorPayAuth.NONCE_MAX) {
|
|
52
|
+
const oldest = seen.keys().next().value;
|
|
37
53
|
if (oldest === undefined)
|
|
38
54
|
break;
|
|
39
|
-
|
|
55
|
+
seen.delete(oldest);
|
|
40
56
|
}
|
|
41
57
|
}
|
|
42
58
|
async intercept(req, authorizations) {
|
|
@@ -76,8 +92,13 @@ class InterceptorPayAuth {
|
|
|
76
92
|
const errors = await Validator_1.Validator.validateStructure(_TAuthParams, params);
|
|
77
93
|
if (errors)
|
|
78
94
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Malformed authorization header", stack: errors };
|
|
79
|
-
|
|
80
|
-
|
|
95
|
+
const version = String(params.v);
|
|
96
|
+
if (version !== "1" && version !== "2")
|
|
97
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Unsupported version: v=1 or v=2" };
|
|
98
|
+
if (version === "2" ? !/^\d{13}$/.test(params.ts) : !/^\d{10}$/.test(params.ts) && !/^\d{13}$/.test(params.ts))
|
|
99
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: version === "2"
|
|
100
|
+
? "ts must be Unix epoch milliseconds (13 digits), UTC"
|
|
101
|
+
: "ts must be Unix epoch seconds (10 digits) or milliseconds (13 digits), UTC" };
|
|
81
102
|
const nowMs = Date.now();
|
|
82
103
|
const nowSec = Math.floor(nowMs / 1000);
|
|
83
104
|
const tsSec = params.ts.length === 13
|
|
@@ -86,8 +107,10 @@ class InterceptorPayAuth {
|
|
|
86
107
|
const delta = tsSec - nowSec;
|
|
87
108
|
if (delta < -InterceptorPayAuth.TS_PAST_SEC || delta > InterceptorPayAuth.TS_FUTURE_SEC)
|
|
88
109
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: `ts out of window: off by ${delta}s (server epoch ${nowSec})` };
|
|
89
|
-
|
|
90
|
-
|
|
110
|
+
const nonceKey = `n\0${params.kid}\0${params.nonce}`;
|
|
111
|
+
const sigKey = `s\0${params.kid}\0${String(params.sig).toLowerCase()}`;
|
|
112
|
+
InterceptorPayAuth.purge(nowMs);
|
|
113
|
+
if (InterceptorPayAuth.seen.has(nonceKey) || InterceptorPayAuth.seen.has(sigKey))
|
|
91
114
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Duplicate nonce" };
|
|
92
115
|
if (!authorizations || authorizations.length === 0) {
|
|
93
116
|
if (this.authorizationsPreset && this.authorizationsPreset.length > 0)
|
|
@@ -99,12 +122,27 @@ class InterceptorPayAuth {
|
|
|
99
122
|
if (i.kid === params.kid) {
|
|
100
123
|
if (params.alg && params.alg.toLowerCase() === "hmac-sha256") {
|
|
101
124
|
if (b64) {
|
|
102
|
-
const
|
|
103
|
-
|
|
125
|
+
const problem = InterceptorPayAuth.keyProblem(i.key);
|
|
126
|
+
if (problem) {
|
|
127
|
+
(0, LogService_1.logError)(`InterceptorPayAuth: key of "${i.kid}" ${problem} — request refused`);
|
|
128
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Key not usable" };
|
|
129
|
+
}
|
|
130
|
+
if (version === "1" && i.v1 === false)
|
|
131
|
+
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "PayAuth v1 is turned off for this key: sign with v=2" };
|
|
132
|
+
const message = version === "2"
|
|
133
|
+
? InterceptorPayAuth.message(String(req.method ?? "").toUpperCase(), InterceptorPayAuth.pathOf(req), params.kid, params.ts, params.nonce, b64)
|
|
134
|
+
: b64 + params.ts + params.nonce;
|
|
135
|
+
const sig = crypto_1.default.createHmac("sha256", Buffer.from(i.key, "hex")).update(message).digest("hex");
|
|
104
136
|
const got = Buffer.from(String(params.sig), "utf-8");
|
|
105
137
|
const want = Buffer.from(sig, "utf-8");
|
|
106
138
|
if (got.length === want.length && crypto_1.default.timingSafeEqual(got, want)) {
|
|
107
|
-
|
|
139
|
+
const expiresAt = nowMs + InterceptorPayAuth.NONCE_TTL_MS;
|
|
140
|
+
InterceptorPayAuth.seen.set(nonceKey, expiresAt);
|
|
141
|
+
InterceptorPayAuth.seen.set(sigKey, expiresAt);
|
|
142
|
+
if (version === "1" && !InterceptorPayAuth.warnedV1.has(i.kid)) {
|
|
143
|
+
InterceptorPayAuth.warnedV1.add(i.kid);
|
|
144
|
+
(0, LogService_1.logWarn)(`InterceptorPayAuth: "${i.kid}" signs with PayAuth v1 — move it to v2 (InterceptorPayAuth.sign()), then set v1: false on its key`);
|
|
145
|
+
}
|
|
108
146
|
return i;
|
|
109
147
|
}
|
|
110
148
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Signature mismatch" };
|
|
@@ -120,5 +158,27 @@ class InterceptorPayAuth {
|
|
|
120
158
|
}
|
|
121
159
|
throw { ...DefaultErrors_1.default.UNAUTHORIZED, details: "Key not found" };
|
|
122
160
|
}
|
|
161
|
+
static message(method, path, kid, ts, nonce, b64) {
|
|
162
|
+
return [V2, method, path, kid, ts, nonce, b64].join("\n");
|
|
163
|
+
}
|
|
164
|
+
static pathOf(req) {
|
|
165
|
+
const raw = req.raw ?? {};
|
|
166
|
+
const url = String(raw.originalUrl ?? raw.url ?? req.endpoint ?? "");
|
|
167
|
+
try {
|
|
168
|
+
return new URL(url, "http://localhost").pathname;
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return url;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
static sign(o) {
|
|
175
|
+
const b64 = Buffer.from(JSON.stringify(o.data ?? {}), "utf-8").toString("base64");
|
|
176
|
+
const ts = String(Date.now());
|
|
177
|
+
const nonce = o.nonce ?? crypto_1.default.randomBytes(18).toString("base64url");
|
|
178
|
+
const path = new URL(o.url, "http://localhost").pathname;
|
|
179
|
+
const message = InterceptorPayAuth.message(o.method.toUpperCase(), path, o.kid, ts, nonce, b64);
|
|
180
|
+
const sig = crypto_1.default.createHmac("sha256", Buffer.from(o.key, "hex")).update(message).digest("hex");
|
|
181
|
+
return { authorization: `PayAuth v=2, ts=${ts}, nonce=${nonce}, kid=${o.kid}, alg=hmac-sha256, sig=${sig}`, b64 };
|
|
182
|
+
}
|
|
123
183
|
}
|
|
124
184
|
exports.InterceptorPayAuth = InterceptorPayAuth;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<!doctype html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
|
-
<!-- Build: 2026-11-
|
|
4
|
+
<!-- Build: 2026-11-24T11:36:24.768Z | Version: 1.0.0 -->
|
|
5
5
|
<script>var __ver = "1.0.0";</script>
|
|
6
6
|
<meta charset="UTF-8" />
|
|
7
7
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
package/dist/index.d.ts
CHANGED
|
@@ -12,11 +12,12 @@ export type { TValidatorType, IStructureOptions, IValidatorOptions } from "./api
|
|
|
12
12
|
export { InterceptorSignedAuth } from "./apiServer/interceptors/InterceptorSignedAuth";
|
|
13
13
|
export type { ISignedAuthResult, ISignedAuthVerdict } from "./apiServer/interceptors/InterceptorSignedAuth";
|
|
14
14
|
export { InterceptorPayAuth } from "./apiServer/interceptors/InterceptorPayAuth";
|
|
15
|
+
export type { IPayAuthKey } from "./apiServer/interceptors/InterceptorPayAuth";
|
|
15
16
|
export { LogService, LOG_LEVEL, getDefaultLogOptions, logInfo, logWarn, logError, logCrit, logDB, logAPI, S_LOG, REQ_LOG } from "./apiServer/LogService";
|
|
16
17
|
export type { ILogItem, ILogServiceOptions } from "./apiServer/LogService";
|
|
17
18
|
export { Trace, TRACE_HEADER } from "./apiServer/helper/Trace";
|
|
18
|
-
export { DBService, REQ_DB, REQ_DBX, REQ_DB_TBEGIN, REQ_DB_TCOMMIT, REQ_DB_TROLLBACK } from "./apiServer/DBService";
|
|
19
|
-
export type { IDBQuery, IDBQueryField, IDBQueryFields, IDBBulkQuery, IDBBulkQueryItem, IDBError, IDBResult, IDBSericeOptions, DBAdapterOptions } from "./apiServer/DBService";
|
|
19
|
+
export { DBService, REQ_DB, REQ_DBX, REQ_DB_TBEGIN, REQ_DB_TCOMMIT, REQ_DB_TROLLBACK, dbField } from "./apiServer/DBService";
|
|
20
|
+
export type { IDBQuery, IDBQueryField, IDBQueryFields, IDBField, IDBBulkQuery, IDBBulkQueryItem, IDBError, IDBResult, IDBSericeOptions, DBAdapterOptions } from "./apiServer/DBService";
|
|
20
21
|
export { MysqlAdapter, isError as isDBError } from "./apiServer/db/MysqlAdapter";
|
|
21
22
|
export { PostgresAdapter } from "./apiServer/db/PostgresAdapter";
|
|
22
23
|
export type { IDBAdapter } from "./apiServer/db/IDBAdapter";
|
package/dist/index.js
CHANGED
|
@@ -3,8 +3,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.
|
|
7
|
-
exports.ZipUtils = exports.JSONStableStringify = exports.YYYYMMDDHH_toDate = exports.YYYYMMDDHH = exports.UID = exports.DataProvider = exports.Req = exports.Signal = exports.getBlueGreenStateSync = exports.getBlueGreenActiveState = exports.onLiveChange = exports.S_BLUEGREEN_STATE_CHANGED = exports.Activate = exports.Deploy = exports.ProcessMonitor = exports.S_MONITOR_RESTART_REQUESTED = exports.S_MONITOR_REGISTRATE_ACTION = exports.S_TIMEFRAME_TASK_EXECUTED = exports.REQ_TIMEFRAME_TASK_ADD = exports.TimeframeService = exports.WS_CLOSE_INTERNAL = exports.WS_CLOSE_RATE_LIMIT = exports.WS_CLOSE_AUTH_TIMEOUT = exports.WS_CLOSE_UNAUTHORIZED = void 0;
|
|
6
|
+
exports.S_WS_ON_MESSAGE = exports.S_WS_ON_CONNECTED = exports.WebSocketConnection = exports.WebSocketServer = exports.REQ_MICROSERVICE_CALL = exports.MicroserviceClient = exports.MemoryJobStore = exports.MicroserviceHost = exports.Http = exports.PostgresAdapter = exports.isDBError = exports.MysqlAdapter = exports.dbField = exports.REQ_DB_TROLLBACK = exports.REQ_DB_TCOMMIT = exports.REQ_DB_TBEGIN = exports.REQ_DBX = exports.REQ_DB = exports.DBService = exports.TRACE_HEADER = exports.Trace = exports.REQ_LOG = exports.S_LOG = exports.logAPI = exports.logDB = exports.logCrit = exports.logError = exports.logWarn = exports.logInfo = exports.getDefaultLogOptions = exports.LOG_LEVEL = exports.LogService = exports.InterceptorPayAuth = exports.InterceptorSignedAuth = exports.ValidationReport = exports.Validator = exports.ErrorUtils = exports.DefaultErrors = exports.LocalRequest = exports.BaseEndpoint = exports.BaseService = exports.S_APP_STARTED = exports.REQ_WS_SERVER = exports.REQ_INTERNAL_CALL = exports.REQ_HTTP_SERVER = exports.REQ_HTTP_REQUESTS_COUNT = exports.REQ_HTTP_LOG = exports.getDefaultOptions = exports.Initializer = exports.APIService = void 0;
|
|
7
|
+
exports.ZipUtils = exports.JSONStableStringify = exports.YYYYMMDDHH_toDate = exports.YYYYMMDDHH = exports.UID = exports.DataProvider = exports.Req = exports.Signal = exports.getBlueGreenStateSync = exports.getBlueGreenActiveState = exports.onLiveChange = exports.S_BLUEGREEN_STATE_CHANGED = exports.Activate = exports.Deploy = exports.ProcessMonitor = exports.S_MONITOR_RESTART_REQUESTED = exports.S_MONITOR_REGISTRATE_ACTION = exports.S_TIMEFRAME_TASK_EXECUTED = exports.REQ_TIMEFRAME_TASK_ADD = exports.TimeframeService = exports.WS_CLOSE_INTERNAL = exports.WS_CLOSE_RATE_LIMIT = exports.WS_CLOSE_AUTH_TIMEOUT = exports.WS_CLOSE_UNAUTHORIZED = exports.S_WS_ON_CLOSE = void 0;
|
|
8
8
|
var APIService_1 = require("./apiServer/APIService");
|
|
9
9
|
Object.defineProperty(exports, "APIService", { enumerable: true, get: function () { return APIService_1.APIService; } });
|
|
10
10
|
Object.defineProperty(exports, "Initializer", { enumerable: true, get: function () { return APIService_1.Initializer; } });
|
|
@@ -53,6 +53,7 @@ Object.defineProperty(exports, "REQ_DBX", { enumerable: true, get: function () {
|
|
|
53
53
|
Object.defineProperty(exports, "REQ_DB_TBEGIN", { enumerable: true, get: function () { return DBService_1.REQ_DB_TBEGIN; } });
|
|
54
54
|
Object.defineProperty(exports, "REQ_DB_TCOMMIT", { enumerable: true, get: function () { return DBService_1.REQ_DB_TCOMMIT; } });
|
|
55
55
|
Object.defineProperty(exports, "REQ_DB_TROLLBACK", { enumerable: true, get: function () { return DBService_1.REQ_DB_TROLLBACK; } });
|
|
56
|
+
Object.defineProperty(exports, "dbField", { enumerable: true, get: function () { return DBService_1.dbField; } });
|
|
56
57
|
var MysqlAdapter_1 = require("./apiServer/db/MysqlAdapter");
|
|
57
58
|
Object.defineProperty(exports, "MysqlAdapter", { enumerable: true, get: function () { return MysqlAdapter_1.MysqlAdapter; } });
|
|
58
59
|
Object.defineProperty(exports, "isDBError", { enumerable: true, get: function () { return MysqlAdapter_1.isError; } });
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bmfk/api",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "TypeScript framework for HTTP API services: validated endpoints, signed microservice calls, a 2FA operations console and a deployer with blue-green releases",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Igor Bloom",
|