@lango-project/lango-server 0.1.2 → 0.2.2
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/README.md +115 -12
- package/dist/.lango/localization.mjs +108 -0
- package/dist/.lango/runtime.mjs +33 -7
- package/dist/.lango/vendor/i18next.LICENSE +21 -0
- package/dist/.lango/vendor/i18next.mjs +2434 -0
- package/dist/cli/.lango/localization.mjs +108 -0
- package/dist/cli/.lango/runtime.mjs +33 -7
- package/dist/cli/.lango/vendor/i18next.LICENSE +21 -0
- package/dist/cli/.lango/vendor/i18next.mjs +2434 -0
- package/dist/cli/error_details.mjs +45 -0
- package/dist/cli/error_details.mjs.map +1 -0
- package/dist/cli/options.mjs +2 -2
- package/dist/cli/options.mjs.map +1 -1
- package/dist/cli/server.mjs +64 -21
- package/dist/cli/server.mjs.map +1 -1
- package/dist/cli/static_files.mjs +123 -25
- package/dist/cli/static_files.mjs.map +1 -1
- package/dist/cli/trace.mjs +53 -0
- package/dist/cli/trace.mjs.map +1 -0
- package/dist/error_details.mjs +45 -0
- package/dist/error_details.mjs.map +1 -0
- package/dist/options.mjs +2 -2
- package/dist/options.mjs.map +1 -1
- package/dist/request_identity.mjs +22 -0
- package/dist/request_identity.mjs.map +1 -0
- package/dist/runtime.mjs +99 -10
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs +64 -21
- package/dist/server.mjs.map +1 -1
- package/dist/server_context.mjs +14 -1
- package/dist/server_context.mjs.map +1 -1
- package/dist/static_files.mjs +123 -25
- package/dist/static_files.mjs.map +1 -1
- package/dist/token.mjs +26 -13
- package/dist/token.mjs.map +1 -1
- package/dist/trace.mjs +53 -0
- package/dist/trace.mjs.map +1 -0
- package/dist/worker.mjs +1 -0
- package/dist/worker.mjs.map +1 -1
- package/package.json +2 -2
- package/src/error_details.lango +21 -0
- package/src/options.lango +2 -2
- package/src/request_identity.lango +9 -0
- package/src/runtime.lango +88 -5
- package/src/server.lango +42 -5
- package/src/server_context.lango +10 -2
- package/src/static_files.lango +102 -23
- package/src/token.lango +13 -3
- package/src/trace.lango +23 -0
- package/src/worker.lango +1 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import {
|
|
2
|
+
contextGet as __contextGet,
|
|
3
|
+
contextSet as __contextSet,
|
|
4
|
+
contextRestore as __contextRestore,
|
|
5
|
+
requireBoolean as __requireBoolean,
|
|
6
|
+
normalize as __normalize,
|
|
7
|
+
boundary as __boundary,
|
|
8
|
+
requireArity as __requireArity,
|
|
9
|
+
} from "./.lango/runtime.mjs";
|
|
10
|
+
|
|
11
|
+
export function trace(message) {
|
|
12
|
+
const __contextScope = [];
|
|
13
|
+
try {
|
|
14
|
+
__requireArity(arguments.length, [0], "trace");
|
|
15
|
+
message = __boundary(message);
|
|
16
|
+
if (__requireBoolean(__normalize(__contextGet("log").verbose) === true)) {
|
|
17
|
+
__normalize(__contextGet("log").debug(message));
|
|
18
|
+
}
|
|
19
|
+
return null;
|
|
20
|
+
return null;
|
|
21
|
+
} finally {
|
|
22
|
+
__contextRestore(__contextScope);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function responseLog(id, method, path, status) {
|
|
27
|
+
const __contextScope = [];
|
|
28
|
+
try {
|
|
29
|
+
__requireArity(arguments.length, [0, 1, 2, 3], "responseLog");
|
|
30
|
+
id = __boundary(id);
|
|
31
|
+
method = __boundary(method);
|
|
32
|
+
path = __boundary(path);
|
|
33
|
+
status = __boundary(status);
|
|
34
|
+
let message = `HTTP ${method} ${path} completed status=${status}`;
|
|
35
|
+
if (__requireBoolean(id !== null)) {
|
|
36
|
+
message = `[${id}] ${message}`;
|
|
37
|
+
}
|
|
38
|
+
if (__requireBoolean(status >= 500)) {
|
|
39
|
+
__normalize(__contextGet("log").err(message));
|
|
40
|
+
} else {
|
|
41
|
+
if (__requireBoolean(status >= 400)) {
|
|
42
|
+
__normalize(__contextGet("log").warn(message));
|
|
43
|
+
} else {
|
|
44
|
+
trace(message);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return null;
|
|
48
|
+
return null;
|
|
49
|
+
} finally {
|
|
50
|
+
__contextRestore(__contextScope);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=trace.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trace.mjs","sources":["trace.lango"],"sourcesContent":["export trace(message)\nexport responseLog(id, method, path, status)\n\ntrace(message)\n context log\n if log.verbose? == true\n log.debug(message)\n return null\n\n\nresponseLog(id, method, path, status)\n context log\n message = \"HTTP ${method} ${path} completed status=${status}\"\n if id != null\n message = \"[${id}] ${message}\"\n if status >= 500\n log.err(message)\n else\n if status >= 400\n log.warn(message)\n else\n trace(message)\n return null\n"],"names":[],"mappings":";;;;;;;;;;AAGA;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import {
|
|
2
|
+
isNumber as __isNumber,
|
|
3
|
+
isString as __isString,
|
|
4
|
+
isBool as __isBool,
|
|
5
|
+
isObject as __isObject,
|
|
6
|
+
isArray as __isArray,
|
|
7
|
+
requireBoolean as __requireBoolean,
|
|
8
|
+
normalize as __normalize,
|
|
9
|
+
boundary as __boundary,
|
|
10
|
+
requireArity as __requireArity,
|
|
11
|
+
} from "./.lango/runtime.mjs";
|
|
12
|
+
|
|
13
|
+
export function errorDetails(error) {
|
|
14
|
+
__requireArity(arguments.length, [0], "errorDetails");
|
|
15
|
+
error = __boundary(error);
|
|
16
|
+
if (__requireBoolean(__isObject(error))) {
|
|
17
|
+
if (__requireBoolean(__requireBoolean(__isString(__normalize(error.stack))) && __requireBoolean(__normalize(error.stack) !== ""))) {
|
|
18
|
+
return __normalize(error.stack);
|
|
19
|
+
}
|
|
20
|
+
if (__requireBoolean(__requireBoolean(__isString(__normalize(error.message))) && __requireBoolean(__normalize(error.message) !== ""))) {
|
|
21
|
+
return __normalize(error.message);
|
|
22
|
+
}
|
|
23
|
+
if (__requireBoolean(__isString(__normalize(error.code)))) {
|
|
24
|
+
return __normalize(error.code);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return `${error}`;
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function errorMessage(error) {
|
|
32
|
+
__requireArity(arguments.length, [0], "errorMessage");
|
|
33
|
+
error = __boundary(error);
|
|
34
|
+
if (__requireBoolean(__isObject(error))) {
|
|
35
|
+
if (__requireBoolean(__requireBoolean(__isString(__normalize(error.message))) && __requireBoolean(__normalize(error.message) !== ""))) {
|
|
36
|
+
return __normalize(error.message);
|
|
37
|
+
}
|
|
38
|
+
if (__requireBoolean(__isString(__normalize(error.code)))) {
|
|
39
|
+
return __normalize(error.code);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return `${error}`;
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
//# sourceMappingURL=error_details.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error_details.mjs","sources":["error_details.lango"],"sourcesContent":["export errorDetails(error)\nexport errorMessage(error)\n\nerrorDetails(error)\n if is_object(error)\n if is_string(error.stack) and error.stack != \"\"\n return error.stack\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n\n\nerrorMessage(error)\n if is_object(error)\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;"}
|
package/dist/options.mjs
CHANGED
|
@@ -38,7 +38,7 @@ export function options(root, supplied = null) {
|
|
|
38
38
|
__requireArity(arguments.length, [0], "options");
|
|
39
39
|
root = __boundary(root);
|
|
40
40
|
supplied = __boundary(supplied);
|
|
41
|
-
let result = { root: __normalize(path.resolve(root)), host: "127.0.0.1", port: 3000, workers: 2, maxQueue: 64, bodyLimit:
|
|
41
|
+
let result = { root: __normalize(path.resolve(root)), host: "127.0.0.1", port: 3000, workers: 2, maxQueue: 64, bodyLimit: 2097152, bodyTimeoutMs: 30000, requestTimeoutMs: 30000, eventTimeoutMs: 5000, startupTimeoutMs: 30000, shutdownTimeoutMs: 30000, issuer: "lango-server", audience: "lango-client", ttlSeconds: 900, key: null, keys: { }, activeKeyId: "current", requestEvent: false, database: null, redis: null, static: null };
|
|
42
42
|
if (__requireBoolean(supplied !== null)) {
|
|
43
43
|
for (const [key, value] of __entries(supplied)) {
|
|
44
44
|
if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(result, key)))) || __requireBoolean(key === "root"))) {
|
|
@@ -115,7 +115,7 @@ export function deployment(directory) {
|
|
|
115
115
|
}
|
|
116
116
|
seen.push(name);
|
|
117
117
|
if (name === "static") {
|
|
118
|
-
attributes(tag, ["path", "directory", "index"]);
|
|
118
|
+
attributes(tag, ["path", "directory", "index", "fallback", "runtime"]);
|
|
119
119
|
settings.static = __normalize(tag.attributes());
|
|
120
120
|
continue;
|
|
121
121
|
} else if (name === "http") {
|
package/dist/options.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./longpoll_options\"\n redisOptions(spec)\nimport \"./database_options\"\n databaseOptions(root, spec, workers)\nimport \"./static_files\"\n staticOptions(root, spec)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport contains(items, value)\nexport options(root, supplied = null)\nexport deployment(directory)\nexport attributes(tag, allowed)\n\nattributes(tag, allowed)\n for tag.attributes() as key: value\n if !allowed.includes(key)\n throw \"Unknown ${tag.tag()} attribute: ${key}\"\n return null\n\noptions(root, supplied = null)\n result = {\n root: path/resolve(root)\n host: \"127.0.0.1\"\n port: 3000\n workers: 2\n maxQueue: 64\n bodyLimit:
|
|
1
|
+
{"version":3,"file":"options.mjs","sources":["options.lango"],"sourcesContent":["import \"./longpoll_options\"\n redisOptions(spec)\nimport \"./database_options\"\n databaseOptions(root, spec, workers)\nimport \"./static_files\"\n staticOptions(root, spec)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Object\nimport js global Number\nimport js global process\n\nexport contains(items, value)\nexport options(root, supplied = null)\nexport deployment(directory)\nexport attributes(tag, allowed)\n\nattributes(tag, allowed)\n for tag.attributes() as key: value\n if !allowed.includes(key)\n throw \"Unknown ${tag.tag()} attribute: ${key}\"\n return null\n\noptions(root, supplied = null)\n result = {\n root: path/resolve(root)\n host: \"127.0.0.1\"\n port: 3000\n workers: 2\n maxQueue: 64\n bodyLimit: 2097152\n bodyTimeoutMs: 30000\n requestTimeoutMs: 30000\n eventTimeoutMs: 5000\n startupTimeoutMs: 30000\n shutdownTimeoutMs: 30000\n issuer: \"lango-server\"\n audience: \"lango-client\"\n ttlSeconds: 900\n key: null\n keys: {}\n activeKeyId: \"current\"\n requestEvent: false\n database: null\n redis: null\n static: null\n }\n if supplied != null\n for supplied as key: value\n if !Object/hasOwn(result, key) or key == \"root\"\n throw \"Unknown server option: ${key}\"\n result[key] = value\n if !is_string(result.host) or result.host == \"\"\n throw \"Host must be a nonempty string\"\n for [\"port\", \"workers\", \"maxQueue\", \"bodyLimit\", \"bodyTimeoutMs\", \"requestTimeoutMs\", \"eventTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\", \"ttlSeconds\"] as key\n value = result[key]\n if !is_number(value) or !Number/isSafeInteger(value) or value < 0\n throw \"Invalid server option: ${key}\"\n if key != \"port\" and key != \"maxQueue\" and value == 0\n throw \"Server option must be positive: ${key}\"\n if key.endsWith(\"Ms\") and value > 2147483647\n throw \"Timeout exceeds timer limit: ${key}\"\n if result.port > 65535 or result.workers > 128 or result.ttlSeconds > 86400\n throw \"Server option exceeds supported limit\"\n if !is_bool(result.requestEvent)\n throw \"requestEvent must be boolean\"\n for [\"issuer\", \"audience\", \"activeKeyId\"] as key\n if !is_string(result[key]) or result[key] == \"\"\n throw \"Missing JWT option: ${key}\"\n if !is_object(result.keys) or is_array(result.keys)\n throw \"JWT keys must be a map\"\n keys = Object/assign(Object/create(null), result.keys)\n if result.key != null\n keys[result.activeKeyId] = result.key\n if !Object/hasOwn(keys, result.activeKeyId)\n throw \"JWT signing key is required\"\n for keys as id: secret\n if !is_string(secret) or secret.length < 32\n throw \"JWT keys must contain at least 32 characters\"\n result.keys = keys\n result.key = null\n result.database = databaseOptions(result.root, result.database, result.workers)\n result.redis = redisOptions(result.redis)\n result.static = staticOptions(result.root, result.static)\n return result\n\ndeployment(directory)\n file = path/join(directory, \"deploy.xml\")\n root = xml2obj(fs/readFileSync(file, \"utf8\"))\n if root.tag() != \"deploy\"\n throw \"Expected deploy root\"\n attributes(root, [])\n settings = {}\n seen = []\n for root.children() as tag\n name = tag.tag()\n if seen.includes(name) or tag.children().length != 0 or tag.innerText().trim() != \"\"\n throw \"Duplicate or nonempty deployment section: ${name}\"\n seen.add(name)\n switch name\n case \"static\"\n attributes(tag, [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"])\n settings.static = tag.attributes()\n continue\n case \"http\"\n attributes(tag, [\"host\", \"port\", \"bodyLimit\", \"bodyTimeoutMs\"])\n case \"workers\"\n attributes(tag, [\"workers\", \"maxQueue\", \"requestTimeoutMs\", \"startupTimeoutMs\", \"shutdownTimeoutMs\"])\n case \"events\"\n attributes(tag, [\"requestEvent\", \"eventTimeoutMs\"])\n case \"redis\"\n attributes(tag, [\"connectionEnv\", \"namespace\", \"maxPendingPolls\"])\n settings.redis = tag.attributes()\n continue\n case \"database\"\n attributes(tag, [\"type\", \"file\", \"connectionEnv\", \"busyTimeoutMs\", \"queryTimeoutMs\", \"connectTimeoutSeconds\"])\n settings.database = tag.attributes()\n continue\n case \"jwt\"\n attributes(tag, [\"issuer\", \"audience\", \"ttlSeconds\", \"keyEnv\", \"keysFile\", \"activeKeyId\"])\n else\n throw \"Unknown deployment section: ${name}\"\n for tag.attributes() as key: value\n if key == \"keyEnv\"\n settings.key = process.env[value]\n if settings.key == null\n throw \"JWT key environment variable is missing: ${value}\"\n else\n if key == \"keysFile\"\n settings.keys = from_json(fs/readFileSync(path/resolve(directory, value), \"utf8\"))\n else\n if contains([\"host\", \"issuer\", \"audience\", \"activeKeyId\"], key)\n settings[key] = value\n else\n if key == \"requestEvent\"\n if value != \"true\" and value != \"false\"\n throw \"requestEvent must be true or false\"\n settings[key] = value == \"true\"\n else\n settings[key] = Number(value)\n return options(directory, settings)\n\ncontains(items, value)\n return items.includes(value)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAiBA;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+DA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA;;;;;;;;"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import {
|
|
2
|
+
requireBoolean as __requireBoolean,
|
|
3
|
+
normalize as __normalize,
|
|
4
|
+
boundary as __boundary,
|
|
5
|
+
requireArity as __requireArity,
|
|
6
|
+
} from "./.lango/runtime.mjs";
|
|
7
|
+
|
|
8
|
+
export function requestIdentity(id, token) {
|
|
9
|
+
__requireArity(arguments.length, [0, 1], "requestIdentity");
|
|
10
|
+
id = __boundary(id);
|
|
11
|
+
token = __boundary(token);
|
|
12
|
+
let identity = `[${id}] [clientId=${__normalize(token.clientId)}]`;
|
|
13
|
+
for (const name of ["sessionId", "userId"]) {
|
|
14
|
+
let value = __normalize(token.get(name));
|
|
15
|
+
if (__requireBoolean(value !== null)) {
|
|
16
|
+
identity = `${identity} [${name}=${value}]`;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return identity;
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=request_identity.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"request_identity.mjs","sources":["request_identity.lango"],"sourcesContent":["export requestIdentity(id, token)\n\nrequestIdentity(id, token)\n identity = \"[${id}] [clientId=${token.clientId?}]\"\n for [\"sessionId\", \"userId\"] as name\n value = token.get(name)\n if value != null\n identity = \"${identity} [${name}=${value}]\"\n return identity\n"],"names":[],"mappings":";;;;;;;AAEA;;;;;;;;;;;;;;;"}
|
package/dist/runtime.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { trace } from "./trace.mjs";
|
|
1
2
|
import { routePattern, matchPath, moreSpecific } from "./route_pattern.mjs";
|
|
2
3
|
import { ServerContext } from "./server_context.mjs";
|
|
3
4
|
import { Database } from "./database.mjs";
|
|
@@ -5,6 +6,8 @@ import { Token } from "./token.mjs";
|
|
|
5
6
|
import { Tokens } from "./tokens.mjs";
|
|
6
7
|
import { Response } from "./response.mjs";
|
|
7
8
|
import { HttpFailure } from "./http_failure.mjs";
|
|
9
|
+
import { requestIdentity } from "./request_identity.mjs";
|
|
10
|
+
import { errorDetails, errorMessage } from "./error_details.mjs";
|
|
8
11
|
import * as threads from "node:worker_threads";
|
|
9
12
|
import {
|
|
10
13
|
hostGlobal as __hostGlobal,
|
|
@@ -43,7 +46,12 @@ export class Runtime {
|
|
|
43
46
|
constructor(definition) {
|
|
44
47
|
__requireArity(arguments.length, [0], "constructor");
|
|
45
48
|
definition = __boundary(definition);
|
|
46
|
-
|
|
49
|
+
let refresh = __withArity((tokens) => {
|
|
50
|
+
tokens = __boundary(tokens);
|
|
51
|
+
return this.refreshTokens(tokens);
|
|
52
|
+
return null;
|
|
53
|
+
}, [0], "closure");
|
|
54
|
+
this.#serverContext = new ServerContext(__normalize(definition.routes), refresh);
|
|
47
55
|
this.#definition = definition;
|
|
48
56
|
this.#routes = [];
|
|
49
57
|
this.#events = { };
|
|
@@ -53,6 +61,7 @@ export class Runtime {
|
|
|
53
61
|
this.#database = new Database(definition.settings.database, definition.settings.root);
|
|
54
62
|
}
|
|
55
63
|
preload() {
|
|
64
|
+
trace(`Worker ${__normalize(threads.threadId)}: preparing database, middleware, routes and events`);
|
|
56
65
|
let definitions = __normalize(this.#definition.routes);
|
|
57
66
|
let pending = __normalize(this.#database.open());
|
|
58
67
|
if (__requireBoolean(__normalize(this.#definition.middlewares) !== null)) {
|
|
@@ -158,6 +167,7 @@ export class Runtime {
|
|
|
158
167
|
__requireArity(arguments.length, [0], "target");
|
|
159
168
|
spec = __boundary(spec);
|
|
160
169
|
let file = __normalize(spec.module);
|
|
170
|
+
trace(`Worker ${__normalize(threads.threadId)}: resolving ${file} export ${__normalize(spec.handler)}`);
|
|
161
171
|
if (__requireBoolean(__includes(file, __normalize(this.#modules)))) {
|
|
162
172
|
return __normalize(__hostGlobal(["Promise"]).resolve(exported(__normalize(this.#modules[file]), __normalize(spec.handler))));
|
|
163
173
|
}
|
|
@@ -207,10 +217,12 @@ export class Runtime {
|
|
|
207
217
|
claims = __normalize(this.#tokens.read(__normalize(__contextGet("request").headers.authorization)));
|
|
208
218
|
}
|
|
209
219
|
} catch (error) {
|
|
220
|
+
__normalize(__contextGet("log").warn(`[${__normalize(__contextGet("request").id)}] ${__normalize(__contextGet("request").method)} ${__normalize(__contextGet("request").path)} Authorization rejected before handler: ${errorMessage(error)}`));
|
|
210
221
|
return failure(401, "Unauthorized");
|
|
211
222
|
}
|
|
212
223
|
let matched = this.#match(__normalize(__contextGet("request").path));
|
|
213
224
|
if (__requireBoolean(matched === null)) {
|
|
225
|
+
trace(`[${__normalize(__contextGet("request").id)}] No route matched ${__normalize(__contextGet("request").path)}`);
|
|
214
226
|
return failure(404, "RouteNotFound");
|
|
215
227
|
}
|
|
216
228
|
let route = __normalize(matched.route);
|
|
@@ -231,6 +243,7 @@ export class Runtime {
|
|
|
231
243
|
return failure(400, "InvalidPath");
|
|
232
244
|
}
|
|
233
245
|
__contextScope.push(__contextSet("token", new Token(claims)));
|
|
246
|
+
trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Matched route ${matched.route.path}; fresh=${fresh}`);
|
|
234
247
|
__contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
|
|
235
248
|
return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
|
|
236
249
|
const __contextScope = [];
|
|
@@ -262,6 +275,7 @@ export class Runtime {
|
|
|
262
275
|
validatedAt = __boundary(validatedAt);
|
|
263
276
|
if (__requireBoolean(__requireBoolean(!__requireBoolean(fresh)) && __requireBoolean(__isNumber(validatedAt)))) {
|
|
264
277
|
stampValidation(claims, validatedAt);
|
|
278
|
+
__normalize(__contextGet("token").renew());
|
|
265
279
|
}
|
|
266
280
|
if (__requireBoolean(__requireBoolean(__normalize(route.auth) !== "anonymous") && __requireBoolean(!__requireBoolean(__normalize(__contextGet("token").hasAuth(__normalize(route.auth))))))) {
|
|
267
281
|
throw { status: 401, error: "Unauthorized" };
|
|
@@ -269,6 +283,7 @@ export class Runtime {
|
|
|
269
283
|
if (__requireBoolean(__normalize(route.kind) === "longpoll")) {
|
|
270
284
|
return null;
|
|
271
285
|
}
|
|
286
|
+
trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Invoking handler; middleware=${__normalize(route.middleware) !== null}`);
|
|
272
287
|
let handler = __normalize(route.handler);
|
|
273
288
|
let middleware = __normalize(route.middleware);
|
|
274
289
|
if (__requireBoolean(middleware !== null)) {
|
|
@@ -307,6 +322,7 @@ export class Runtime {
|
|
|
307
322
|
}
|
|
308
323
|
return pollResponse;
|
|
309
324
|
}
|
|
325
|
+
trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Handler completed; serializing response`);
|
|
310
326
|
let body = __normalize(__hostGlobal(["JSON"]).stringify(output));
|
|
311
327
|
if (__requireBoolean(!__requireBoolean(__isString(body)))) {
|
|
312
328
|
throw "Handler result is not JSON serializable";
|
|
@@ -315,36 +331,39 @@ export class Runtime {
|
|
|
315
331
|
let result = __normalize(__contextGet("response").result(body));
|
|
316
332
|
let updated = this.#tokenClaims(__contextGet("token"), claims, __normalize(result.status) < 400);
|
|
317
333
|
result.headers["x-lango-token"] = __normalize(this.#tokens.sign(updated));
|
|
318
|
-
if (__requireBoolean(__requireBoolean(__normalize(this.#definition.settings.requestEvent)) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
|
|
334
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(task.internal) !== true) && __requireBoolean(__normalize(this.#definition.settings.requestEvent))) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
|
|
319
335
|
return this.#audit(__normalize(__contextGet("request").id), result, __normalize(task.body), body, updated);
|
|
320
336
|
}
|
|
337
|
+
trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Request completed status=${__normalize(result.status)}`);
|
|
321
338
|
return result;
|
|
322
339
|
return null;
|
|
323
340
|
} finally {
|
|
324
341
|
__contextRestore(__contextScope);
|
|
325
342
|
}
|
|
326
|
-
})(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3) => (error) => {
|
|
343
|
+
})(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4) => (error) => {
|
|
327
344
|
const __contextScope = [];
|
|
328
345
|
try {
|
|
329
346
|
__contextScope.push(__contextSet("server", __capturedContext0));
|
|
330
347
|
__contextScope.push(__contextSet("request", __capturedContext1));
|
|
331
348
|
__contextScope.push(__contextSet("log", __capturedContext2));
|
|
332
349
|
__contextScope.push(__contextSet("db", __capturedContext3));
|
|
350
|
+
__contextScope.push(__contextSet("token", __capturedContext4));
|
|
333
351
|
error = __boundary(error);
|
|
334
352
|
closeScope(__contextGet("db"), false);
|
|
335
353
|
if (__requireBoolean(__isKindof(error, HttpFailure))) {
|
|
336
354
|
return __normalize(error.result());
|
|
337
355
|
}
|
|
338
356
|
if (__requireBoolean(__requireBoolean(error === "TokenExpired") || __requireBoolean(__requireBoolean(__isObject(error)) && __requireBoolean(__normalize(error.status) === 401)))) {
|
|
357
|
+
__normalize(__contextGet("log").warn(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} ${__normalize(__contextGet("request").method)} ${__normalize(__contextGet("request").path)} Authorization or validation rejected: Unauthorized`));
|
|
339
358
|
return failure(401, "Unauthorized");
|
|
340
359
|
}
|
|
341
|
-
__normalize(__contextGet("log").err(
|
|
360
|
+
__normalize(__contextGet("log").err(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Request failed: ${errorDetails(error)}`));
|
|
342
361
|
return failure(500, "InternalServerError");
|
|
343
362
|
return null;
|
|
344
363
|
} finally {
|
|
345
364
|
__contextRestore(__contextScope);
|
|
346
365
|
}
|
|
347
|
-
})(__contextGet("server"), __contextGet("request"), __contextGet("log"), __contextGet("db")), [0], "closure")).finally(((__capturedContext0) => () => {
|
|
366
|
+
})(__contextGet("server"), __contextGet("request"), __contextGet("log"), __contextGet("db"), __contextGet("token")), [0], "closure")).finally(((__capturedContext0) => () => {
|
|
348
367
|
const __contextScope = [];
|
|
349
368
|
try {
|
|
350
369
|
__contextScope.push(__contextSet("db", __capturedContext0));
|
|
@@ -372,6 +391,70 @@ export class Runtime {
|
|
|
372
391
|
return updated;
|
|
373
392
|
return null;
|
|
374
393
|
}
|
|
394
|
+
refreshTokens(tokens) {
|
|
395
|
+
const __contextScope = [];
|
|
396
|
+
try {
|
|
397
|
+
__requireArity(arguments.length, [0], "refreshTokens");
|
|
398
|
+
tokens = __boundary(tokens);
|
|
399
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isArray(tokens))) || __requireBoolean(__normalize(tokens.length) === 0)) || __requireBoolean(__normalize(tokens.length) > 64))) {
|
|
400
|
+
throw "Token refresh requires 1 to 64 tokens";
|
|
401
|
+
}
|
|
402
|
+
let seen = [];
|
|
403
|
+
for (const encoded of tokens) {
|
|
404
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(encoded))) || __requireBoolean(encoded === "")) || __requireBoolean(__normalize(encoded.length) > 16384)) || __requireBoolean(__normalize(seen.includes(encoded))))) {
|
|
405
|
+
throw "Invalid refresh token";
|
|
406
|
+
}
|
|
407
|
+
seen.push(encoded);
|
|
408
|
+
}
|
|
409
|
+
let owner = __normalize(__contextGet("token").clientId);
|
|
410
|
+
let results = [];
|
|
411
|
+
let pending = __normalize(__hostGlobal(["Promise"]).resolve(null));
|
|
412
|
+
for (const encoded of tokens) {
|
|
413
|
+
let child = __normalize(__hostGlobal(["Object"]).assign({ }, __contextGet("request"), { headers: __normalize(__hostGlobal(["Object"]).assign({ }, __normalize(__contextGet("request").headers), { authorization: `Bearer ${encoded}` })) }));
|
|
414
|
+
pending = this.#refreshOne(pending, results, encoded, owner, child);
|
|
415
|
+
}
|
|
416
|
+
return pending.then(__withArity((ignored) => {
|
|
417
|
+
ignored = __boundary(ignored);
|
|
418
|
+
return results;
|
|
419
|
+
return null;
|
|
420
|
+
}, [0], "closure"));
|
|
421
|
+
return null;
|
|
422
|
+
} finally {
|
|
423
|
+
__contextRestore(__contextScope);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
#refreshOne(pending, results, encoded, owner, child) {
|
|
427
|
+
__requireArity(arguments.length, [0, 1, 2, 3, 4], "refreshOne");
|
|
428
|
+
pending = __boundary(pending);
|
|
429
|
+
results = __boundary(results);
|
|
430
|
+
encoded = __boundary(encoded);
|
|
431
|
+
owner = __boundary(owner);
|
|
432
|
+
child = __boundary(child);
|
|
433
|
+
return pending.then(__withArity((ignored) => {
|
|
434
|
+
ignored = __boundary(ignored);
|
|
435
|
+
let checked = null;
|
|
436
|
+
try {
|
|
437
|
+
checked = __normalize(this.#tokens.read(`Bearer ${encoded}`));
|
|
438
|
+
} catch (error) {
|
|
439
|
+
return failure(401, "Unauthorized");
|
|
440
|
+
}
|
|
441
|
+
if (__requireBoolean(__normalize(checked.clientId) !== owner)) {
|
|
442
|
+
return failure(401, "Unauthorized");
|
|
443
|
+
}
|
|
444
|
+
return this.handle({ request: child, body: "{}", internal: true });
|
|
445
|
+
return null;
|
|
446
|
+
}, [0], "closure")).then(__withArity((result) => {
|
|
447
|
+
result = __boundary(result);
|
|
448
|
+
let updated = null;
|
|
449
|
+
if (__requireBoolean(__normalize(result.status) < 400)) {
|
|
450
|
+
updated = result.headers["x-lango-token"];
|
|
451
|
+
}
|
|
452
|
+
__add(results, { previous: encoded, token: updated, status: __normalize(result.status) });
|
|
453
|
+
return null;
|
|
454
|
+
return null;
|
|
455
|
+
}, [0], "closure"));
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
375
458
|
#event(name, input) {
|
|
376
459
|
const __contextScope = [];
|
|
377
460
|
try {
|
|
@@ -381,6 +464,7 @@ export class Runtime {
|
|
|
381
464
|
if (__requireBoolean(!__requireBoolean(__includes(name, __normalize(this.#events))))) {
|
|
382
465
|
return null;
|
|
383
466
|
}
|
|
467
|
+
trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Running event ${name}`);
|
|
384
468
|
let handler = __normalize(this.#events[name]);
|
|
385
469
|
__normalize(threads.parentPort.postMessage({ kind: "event", id: __normalize(__contextGet("request").id) }));
|
|
386
470
|
return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
|
|
@@ -418,9 +502,12 @@ export class Runtime {
|
|
|
418
502
|
const __contextScope = [];
|
|
419
503
|
try {
|
|
420
504
|
let claims = __normalize(__contextGet("token").snapshot());
|
|
421
|
-
if (__requireBoolean(
|
|
505
|
+
if (__requireBoolean(__finite(__normalize(__hostGlobal(["Date"]).now()) - __normalize(claims.validatedAt)) < 1000)) {
|
|
422
506
|
return null;
|
|
423
507
|
}
|
|
508
|
+
if (__requireBoolean(!__requireBoolean(__includes("validate", __normalize(this.#events))))) {
|
|
509
|
+
return __normalize(__hostGlobal(["Date"]).now());
|
|
510
|
+
}
|
|
424
511
|
let original = __normalize(__hostGlobal(["JSON"]).stringify(claims));
|
|
425
512
|
__contextScope.push(__contextSet("token", new Token(claims, true)));
|
|
426
513
|
return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
|
|
@@ -477,7 +564,7 @@ export class Runtime {
|
|
|
477
564
|
__contextScope.push(__contextSet("token", new Token(claims, true)));
|
|
478
565
|
__contextScope.push(__contextSet("response", __normalize(__hostGlobal(["Object"]).freeze({ }))));
|
|
479
566
|
let metadata = { input: input, output: output, status: __normalize(result.status) };
|
|
480
|
-
__normalize(threads.parentPort.postMessage({ kind: "prepared", id: id, result: result }));
|
|
567
|
+
__normalize(threads.parentPort.postMessage({ kind: "prepared", logIdentity: requestIdentity(id, __contextGet("token")), id: id, result: result }));
|
|
481
568
|
return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
|
|
482
569
|
const __contextScope = [];
|
|
483
570
|
try {
|
|
@@ -504,20 +591,22 @@ export class Runtime {
|
|
|
504
591
|
} finally {
|
|
505
592
|
__contextRestore(__contextScope);
|
|
506
593
|
}
|
|
507
|
-
})(__contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1) => (error) => {
|
|
594
|
+
})(__contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3) => (error) => {
|
|
508
595
|
const __contextScope = [];
|
|
509
596
|
try {
|
|
510
597
|
__contextScope.push(__contextSet("log", __capturedContext0));
|
|
511
598
|
__contextScope.push(__contextSet("db", __capturedContext1));
|
|
599
|
+
__contextScope.push(__contextSet("request", __capturedContext2));
|
|
600
|
+
__contextScope.push(__contextSet("token", __capturedContext3));
|
|
512
601
|
error = __boundary(error);
|
|
513
602
|
closeScope(__contextGet("db"), false);
|
|
514
|
-
__normalize(__contextGet("log").err("Request event failed
|
|
603
|
+
__normalize(__contextGet("log").err(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Request event failed: ${errorDetails(error)}`));
|
|
515
604
|
return null;
|
|
516
605
|
return null;
|
|
517
606
|
} finally {
|
|
518
607
|
__contextRestore(__contextScope);
|
|
519
608
|
}
|
|
520
|
-
})(__contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity((ignored) => {
|
|
609
|
+
})(__contextGet("log"), __contextGet("db"), __contextGet("request"), __contextGet("token")), [0], "closure")).then(__withArity((ignored) => {
|
|
521
610
|
ignored = __boundary(ignored);
|
|
522
611
|
return result;
|
|
523
612
|
return null;
|
package/dist/runtime.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\n matchPath(pattern, path)\n moreSpecific(candidate, current)\nimport js global decodeURIComponent\nimport \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\nimport \"./http_failure\"\n class HttpFailure\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n\nRuntime(definition)\n @serverContext = new ServerContext(definition.routes)\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @modules = {}\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n\nRuntime:preload()\n definitions = @definition.routes\n pending = @database.open()\n if @definition.middlewares != null\n for @definition.middlewares as name: spec\n pending = prepareMiddleware(pending, name, spec)\n for definitions as route\n pending = prepareRoute(pending, route)\n events = @definition.events\n for events as name: target\n pending = prepareEvent(pending, name, target)\n return chain pending\n catch(error)\n close()\n throw error\n\nRuntime:close()\n @database.close()\n return null\n\nRuntime:prepareMiddleware(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n capture spec\n @middlewares[name] = handler\n if spec.validate != null\n return target({\n module: spec.module\n handler: spec.validate\n })\n return null\n then(validator)\n if validator != null\n return validator(@serverContext.routes())\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n prepared = Object/assign({}, route)\n prepared.pattern = routePattern(route.path)\n @routes.add(prepared)\n return pending\n return chain pending\n then(ignored)\n capture route\n return target(route)\n then(handler)\n capture route\n middleware = null\n name = route.middleware\n if name != null\n if !Object/hasOwn(@middlewares, name)\n throw \"Middleware is not registered: ${name}\"\n middleware = @middlewares[name]\n @routes.add({\n path: route.path\n pattern: routePattern(route.path)\n auth: route.auth\n handler: handler\n middleware: middleware\n })\n return null\n\nRuntime:prepareEvent(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @events[name] = handler\n return null\n\nRuntime:target(spec)\n file = spec.module\n if file in @modules\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n\nRuntime:match(path)\n best = null\n parameters = null\n pattern = null\n for @routes as route\n captured = matchPath(route.pattern, path)\n if captured != null and moreSpecific(route.pattern, pattern)\n best = route\n parameters = captured\n pattern = route.pattern\n if best == null\n return null\n return {\n route: best\n parameters: parameters\n }\n\nRuntime:handle(task)\n Object/freeze(task.request.headers)\n context server = @serverContext\n context request = Object/freeze(task.request)\n context response = new Response()\n context log\n fresh = request.headers.authorization == null\n claims = null\n try\n if fresh\n claims = @tokens.create()\n else\n claims = @tokens.read(request.headers.authorization)\n catch error\n return failure(401, \"Unauthorized\")\n matched = match(request.path)\n if matched == null\n return failure(404, \"RouteNotFound\")\n route = matched.route\n input = null\n try\n input = JSON/parse(task.body)\n if !is_object(input) or is_array(input)\n return failure(400, \"InputMustBeObject\")\n catch error\n return failure(400, \"InvalidJson\")\n try\n for matched.parameters as name: value\n input[name] = decodeURIComponent(value)\n catch error\n return failure(400, \"InvalidPath\")\n context token = new Token(claims)\n context db = @database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture fresh\n capture input\n if fresh\n return event(\"register\", input)\n return validate()\n then(validatedAt)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture route\n capture input\n capture claims\n capture fresh\n if !fresh and is_number(validatedAt)\n stampValidation(claims, validatedAt)\n if route.auth != \"anonymous\" and !token.hasAuth(route.auth)\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if route.kind == \"longpoll\"\n return null\n handler = route.handler\n middleware = route.middleware\n if middleware != null\n return middleware(handler, request.path, input)\n return handler(input)\n then(output)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture task\n capture claims\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = tokenClaims(token, claims, true)\n encoded = @tokens.sign(authorizedClaims)\n if task.pollResult == null\n return {\n status: 200\n authorization: encoded\n }\n if task.pollResult.resyncRequired\n response.status(409)\n pollBody = JSON/stringify(task.pollResult)\n pollResponse = response.result(pollBody)\n pollResponse.headers[\"x-lango-token\"] = encoded\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, pollResponse, task.body, pollBody, authorizedClaims)\n return pollResponse\n body = JSON/stringify(output)\n if !is_string(body)\n throw \"Handler result is not JSON serializable\"\n closeScope(db, true)\n result = response.result(body)\n updated = tokenClaims(token, claims, result.status < 400)\n result.headers[\"x-lango-token\"] = @tokens.sign(updated)\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n return result\n catch(error)\n capture server\n capture request\n capture log\n capture db\n capture HttpFailure\n closeScope(db, false)\n if is_kindof(error, HttpFailure)\n return error.result()\n if error == \"TokenExpired\" or (is_object(error) and error.status == 401)\n return failure(401, \"Unauthorized\")\n log.err(\"[${request.id}] Request failed\")\n return failure(500, \"InternalServerError\")\n finally\n capture db\n closeScope(db, false)\n\nRuntime:tokenClaims(token, claims, allowRenewal)\n updated = token.snapshot()\n updated.validatedAt = claims.validatedAt\n if allowRenewal and token.renewalRequested()\n updated = @tokens.renew(updated)\n return updated\n\nRuntime:event(name, input)\n if !(name in @events)\n return null\n context server\n context request\n context response\n context token\n context log\n context db\n handler = @events[name]\n threads/parentPort/postMessage({\n kind: \"event\"\n id: request.id\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture handler\n capture input\n return handler(input)\n finally\n capture server\n capture request\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate()\n context db\n context token\n context response\n context server\n context request\n context log\n claims = token.snapshot()\n if !(\"validate\" in @events) or Date/now() - claims.validatedAt < 1000\n return null\n original = JSON/stringify(claims)\n context token = new Token(claims, true)\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture response\n capture server\n capture request\n capture log\n capture db\n return event(\"validate\", null)\n then(valid)\n capture token\n capture original\n capture claims\n if !is_bool(valid)\n throw \"Validate must return boolean\"\n if !valid\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if JSON/stringify(token.snapshot()) != original\n throw \"Validate cannot change the token\"\n claims.validatedAt = Date/now()\n return claims.validatedAt\n\nRuntime:audit(id, result, input, output, claims)\n context db = @database.scope()\n context server\n context request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture server\n capture request\n capture response\n capture log\n capture db\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n capture db\n closeScope(db, true)\n return null\n catch(error)\n capture log\n capture db\n closeScope(db, false)\n log.err(\"Request event failed\")\n return null\n then(ignored)\n capture result\n return result\n finally\n capture db\n closeScope(db, false)\n\nfailure(status, code)\n headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n if status == 401\n headers[\"www-authenticate\"] = \"Bearer\"\n return {\n status: status\n headers: headers\n body: JSON/stringify({\n error: code\n })\n }\n\nstampValidation(claims, validatedAt)\n claims.validatedAt = validatedAt\n return null\n\ncloseScope(db, strict)\n if db != null\n dirty = db.finish()\n if dirty and strict\n throw \"UnclosedTransaction\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwGA;;;;;;;;;;;AA4QA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"runtime.mjs","sources":["runtime.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\nimport \"./route_pattern\"\n routePattern(path)\n matchPath(pattern, path)\n moreSpecific(candidate, current)\nimport js global decodeURIComponent\nimport \"./server_context\"\n class ServerContext\nimport \"./database\"\n class Database\nimport js global Promise\nimport js global JSON\nimport js global Object\nimport js global Date\nimport js \"node:worker_threads\" as threads\nimport \"./token\"\n class Token\nimport \"./tokens\"\n class Tokens\nimport \"./response\"\n class Response\nimport \"./http_failure\"\n class HttpFailure\nimport \"./request_identity\"\n requestIdentity(id, token)\nimport \"./error_details\"\n errorDetails(error)\n errorMessage(error)\n\nexport class Runtime(definition)\n methods\n preload()\n handle(task)\n close()\n refreshTokens(tokens)\n\nRuntime(definition)\n refresh = (tokens)\n return refreshTokens(tokens)\n @serverContext = new ServerContext(definition.routes, refresh)\n @definition = definition\n @routes = []\n @events = {}\n @tokens = new Tokens(definition.settings)\n @modules = {}\n @middlewares = Object/create(null)\n @database = new Database(definition.settings.database, definition.settings.root)\n\nRuntime:preload()\n trace(\"Worker ${threads.threadId}: preparing database, middleware, routes and events\")\n definitions = @definition.routes\n pending = @database.open()\n if @definition.middlewares != null\n for @definition.middlewares as name: spec\n pending = prepareMiddleware(pending, name, spec)\n for definitions as route\n pending = prepareRoute(pending, route)\n events = @definition.events\n for events as name: target\n pending = prepareEvent(pending, name, target)\n return chain pending\n catch(error)\n close()\n throw error\n\nRuntime:close()\n @database.close()\n return null\n\nRuntime:prepareMiddleware(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n capture spec\n @middlewares[name] = handler\n if spec.validate != null\n return target({\n module: spec.module\n handler: spec.validate\n })\n return null\n then(validator)\n if validator != null\n return validator(@serverContext.routes())\n return null\n\nRuntime:prepareRoute(pending, route)\n if route.kind == \"longpoll\"\n prepared = Object/assign({}, route)\n prepared.pattern = routePattern(route.path)\n @routes.add(prepared)\n return pending\n return chain pending\n then(ignored)\n capture route\n return target(route)\n then(handler)\n capture route\n middleware = null\n name = route.middleware\n if name != null\n if !Object/hasOwn(@middlewares, name)\n throw \"Middleware is not registered: ${name}\"\n middleware = @middlewares[name]\n @routes.add({\n path: route.path\n pattern: routePattern(route.path)\n auth: route.auth\n handler: handler\n middleware: middleware\n })\n return null\n\nRuntime:prepareEvent(pending, name, spec)\n return chain pending\n then(ignored)\n capture spec\n return target(spec)\n then(handler)\n capture name\n @events[name] = handler\n return null\n\nRuntime:target(spec)\n file = spec.module\n trace(\"Worker ${threads.threadId}: resolving ${file} export ${spec.handler}\")\n if file in @modules\n return Promise/resolve(exported(@modules[file], spec.handler))\n return chain import_module(file)\n then(mod)\n capture file\n capture spec\n @modules[file] = mod\n return exported(mod, spec.handler)\n\nexported(mod, name)\n if !Object/hasOwn(mod, name) or !is_kindof(mod[name], Function)\n throw \"Handler is not exported: ${name}\"\n return mod[name]\n\nRuntime:match(path)\n best = null\n parameters = null\n pattern = null\n for @routes as route\n captured = matchPath(route.pattern, path)\n if captured != null and moreSpecific(route.pattern, pattern)\n best = route\n parameters = captured\n pattern = route.pattern\n if best == null\n return null\n return {\n route: best\n parameters: parameters\n }\n\nRuntime:handle(task)\n Object/freeze(task.request.headers)\n context server = @serverContext\n context request = Object/freeze(task.request)\n context response = new Response()\n context log\n fresh = request.headers.authorization == null\n claims = null\n try\n if fresh\n claims = @tokens.create()\n else\n claims = @tokens.read(request.headers.authorization)\n catch error\n log.warn(\"[${request.id}] ${request.method} ${request.path} Authorization rejected before handler: ${errorMessage(error)}\")\n return failure(401, \"Unauthorized\")\n matched = match(request.path)\n if matched == null\n trace(\"[${request.id}] No route matched ${request.path}\")\n return failure(404, \"RouteNotFound\")\n route = matched.route\n input = null\n try\n input = JSON/parse(task.body)\n if !is_object(input) or is_array(input)\n return failure(400, \"InputMustBeObject\")\n catch error\n return failure(400, \"InvalidJson\")\n try\n for matched.parameters as name: value\n input[name] = decodeURIComponent(value)\n catch error\n return failure(400, \"InvalidPath\")\n context token = new Token(claims)\n trace(\"${requestIdentity(request.id, token)} Matched route ${matched.route.path}; fresh=${fresh}\")\n context db = @database.scope()\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture fresh\n capture input\n if fresh\n return event(\"register\", input)\n return validate()\n then(validatedAt)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture route\n capture input\n capture claims\n capture fresh\n if !fresh and is_number(validatedAt)\n stampValidation(claims, validatedAt)\n token.renew()\n if route.auth != \"anonymous\" and !token.hasAuth(route.auth)\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if route.kind == \"longpoll\"\n return null\n trace(\"${requestIdentity(request.id, token)} Invoking handler; middleware=${route.middleware != null}\")\n handler = route.handler\n middleware = route.middleware\n if middleware != null\n return middleware(handler, request.path, input)\n return handler(input)\n then(output)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture task\n capture claims\n if task.authorize == true\n closeScope(db, true)\n authorizedClaims = tokenClaims(token, claims, true)\n encoded = @tokens.sign(authorizedClaims)\n if task.pollResult == null\n return {\n status: 200\n authorization: encoded\n }\n if task.pollResult.resyncRequired\n response.status(409)\n pollBody = JSON/stringify(task.pollResult)\n pollResponse = response.result(pollBody)\n pollResponse.headers[\"x-lango-token\"] = encoded\n if @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, pollResponse, task.body, pollBody, authorizedClaims)\n return pollResponse\n trace(\"${requestIdentity(request.id, token)} Handler completed; serializing response\")\n body = JSON/stringify(output)\n if !is_string(body)\n throw \"Handler result is not JSON serializable\"\n closeScope(db, true)\n result = response.result(body)\n updated = tokenClaims(token, claims, result.status < 400)\n result.headers[\"x-lango-token\"] = @tokens.sign(updated)\n if task.internal != true and @definition.settings.requestEvent and \"request\" in @events\n return audit(request.id, result, task.body, body, updated)\n trace(\"${requestIdentity(request.id, token)} Request completed status=${result.status}\")\n return result\n catch(error)\n capture server\n capture request\n capture log\n capture db\n capture HttpFailure\n capture token\n closeScope(db, false)\n if is_kindof(error, HttpFailure)\n return error.result()\n if error == \"TokenExpired\" or (is_object(error) and error.status == 401)\n log.warn(\"${requestIdentity(request.id, token)} ${request.method} ${request.path} Authorization or validation rejected: Unauthorized\")\n return failure(401, \"Unauthorized\")\n log.err(\"${requestIdentity(request.id, token)} Request failed: ${errorDetails(error)}\")\n return failure(500, \"InternalServerError\")\n finally\n capture db\n closeScope(db, false)\n\nRuntime:tokenClaims(token, claims, allowRenewal)\n updated = token.snapshot()\n updated.validatedAt = claims.validatedAt\n if allowRenewal and token.renewalRequested()\n updated = @tokens.renew(updated)\n return updated\n\nRuntime:refreshTokens(tokens)\n context request\n context token\n if !is_array(tokens) or tokens.length == 0 or tokens.length > 64\n throw \"Token refresh requires 1 to 64 tokens\"\n seen = []\n for tokens as encoded\n if !is_string(encoded) or encoded == \"\" or encoded.length > 16384 or seen.includes(encoded)\n throw \"Invalid refresh token\"\n seen.add(encoded)\n owner = token.clientId?\n results = []\n pending = Promise/resolve(null)\n for tokens as encoded\n child = Object/assign({}, request, {\n headers: Object/assign({}, request.headers, {\n authorization: \"Bearer ${encoded}\"\n })\n })\n pending = refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture results\n return results\n\nRuntime:refreshOne(pending, results, encoded, owner, child)\n return chain pending\n then(ignored)\n capture encoded\n capture owner\n capture child\n checked = null\n try\n checked = @tokens.read(\"Bearer ${encoded}\")\n catch error\n return failure(401, \"Unauthorized\")\n if checked.clientId != owner\n return failure(401, \"Unauthorized\")\n return handle({\n request: child\n body: \"{}\"\n internal: true\n })\n then(result)\n capture results\n capture encoded\n updated = null\n if result.status < 400\n updated = result.headers[\"x-lango-token\"]\n results.add({\n previous: encoded\n token: updated\n status: result.status\n })\n return null\n\nRuntime:event(name, input)\n if !(name in @events)\n return null\n context server\n context request\n context response\n context token\n context log\n context db\n trace(\"${requestIdentity(request.id, token)} Running event ${name}\")\n handler = @events[name]\n threads/parentPort/postMessage({\n kind: \"event\"\n id: request.id\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture server\n capture request\n capture response\n capture token\n capture log\n capture db\n capture handler\n capture input\n return handler(input)\n finally\n capture server\n capture request\n capture threads\n threads/parentPort/postMessage({\n kind: \"handler\"\n id: request.id\n })\n\nRuntime:validate()\n context db\n context token\n context response\n context server\n context request\n context log\n claims = token.snapshot()\n if Date/now() - claims.validatedAt < 1000\n return null\n if !(\"validate\" in @events)\n return Date/now()\n original = JSON/stringify(claims)\n context token = new Token(claims, true)\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture response\n capture server\n capture request\n capture log\n capture db\n return event(\"validate\", null)\n then(valid)\n capture token\n capture original\n capture claims\n if !is_bool(valid)\n throw \"Validate must return boolean\"\n if !valid\n throw {\n status: 401\n error: \"Unauthorized\"\n }\n if JSON/stringify(token.snapshot()) != original\n throw \"Validate cannot change the token\"\n claims.validatedAt = Date/now()\n return claims.validatedAt\n\nRuntime:audit(id, result, input, output, claims)\n context db = @database.scope()\n context server\n context request\n context log\n context token = new Token(claims, true)\n context response = Object/freeze({})\n metadata = {\n input: input\n output: output\n status: result.status\n }\n threads/parentPort/postMessage({\n kind: \"prepared\"\n logIdentity: requestIdentity(id, token)\n id: id\n result: result\n })\n return chain Promise/resolve(null)\n then(ignored)\n capture token\n capture server\n capture request\n capture response\n capture log\n capture db\n capture metadata\n return event(\"request\", Object/freeze(metadata))\n then(ignored)\n capture db\n closeScope(db, true)\n return null\n catch(error)\n capture log\n capture db\n capture request\n capture token\n closeScope(db, false)\n log.err(\"${requestIdentity(request.id, token)} Request event failed: ${errorDetails(error)}\")\n return null\n then(ignored)\n capture result\n return result\n finally\n capture db\n closeScope(db, false)\n\nfailure(status, code)\n headers = {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n if status == 401\n headers[\"www-authenticate\"] = \"Bearer\"\n return {\n status: status\n headers: headers\n body: JSON/stringify({\n error: code\n })\n }\n\nstampValidation(claims, validatedAt)\n claims.validatedAt = validatedAt\n return null\n\ncloseScope(db, strict)\n if db != null\n dirty = db.finish()\n if dirty and strict\n throw \"UnclosedTransaction\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6GA;;;;;;;;;;;AAmVA;;;;;;;;;;;;AAeA;;;;;;;;;AAIA;;;;;;;;;;;;;;;"}
|