@lango-project/lango-server 0.1.1 → 0.1.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 +86 -7
- package/dist/cli/endpoint.mjs +2 -6
- package/dist/cli/endpoint.mjs.map +1 -1
- package/dist/cli/longpoll_options.mjs +1 -1
- package/dist/cli/longpoll_options.mjs.map +1 -1
- package/dist/cli/route_pattern.mjs +129 -0
- package/dist/cli/route_pattern.mjs.map +1 -0
- package/dist/cli/routes.mjs +25 -13
- package/dist/cli/routes.mjs.map +1 -1
- package/dist/endpoint.mjs +2 -6
- package/dist/endpoint.mjs.map +1 -1
- package/dist/http_failure.mjs +45 -0
- package/dist/http_failure.mjs.map +1 -0
- package/dist/longpoll_options.mjs +1 -1
- package/dist/longpoll_options.mjs.map +1 -1
- package/dist/response.mjs +8 -0
- package/dist/response.mjs.map +1 -1
- package/dist/route_info.mjs +22 -0
- package/dist/route_info.mjs.map +1 -0
- package/dist/route_pattern.mjs +129 -0
- package/dist/route_pattern.mjs.map +1 -0
- package/dist/routes.mjs +25 -13
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +57 -20
- package/dist/runtime.mjs.map +1 -1
- package/dist/server_context.mjs +12 -2
- package/dist/server_context.mjs.map +1 -1
- package/dist/token.mjs +12 -0
- package/dist/token.mjs.map +1 -1
- package/dist/tokens.mjs +16 -1
- package/dist/tokens.mjs.map +1 -1
- package/package.json +2 -2
- package/src/endpoint.lango +3 -4
- package/src/http_failure.lango +26 -0
- package/src/longpoll_options.lango +1 -1
- package/src/response.lango +6 -0
- package/src/route_info.lango +15 -0
- package/src/route_pattern.lango +86 -0
- package/src/routes.lango +20 -8
- package/src/runtime.lango +55 -17
- package/src/server_context.lango +11 -3
- package/src/token.lango +11 -0
- package/src/tokens.lango +11 -1
package/dist/tokens.mjs
CHANGED
|
@@ -2,6 +2,8 @@ import * as jwt from "jsonwebtoken";
|
|
|
2
2
|
import * as crypto from "node:crypto";
|
|
3
3
|
import {
|
|
4
4
|
hostGlobal as __hostGlobal,
|
|
5
|
+
fromJson as __fromJson,
|
|
6
|
+
toJson as __toJson,
|
|
5
7
|
isNumber as __isNumber,
|
|
6
8
|
isString as __isString,
|
|
7
9
|
isBool as __isBool,
|
|
@@ -55,12 +57,25 @@ export class Tokens {
|
|
|
55
57
|
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.iat))))) || __requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.exp)))))) || __requireBoolean(__normalize(claims.exp) <= __normalize(claims.iat))) || __requireBoolean(__finite(__normalize(claims.exp) - __normalize(claims.iat)) > __normalize(settings.ttlSeconds))) || __requireBoolean(__finite(__normalize(claims.iat) * 1000) > __normalize(__hostGlobal(["Date"]).now())))) {
|
|
56
58
|
throw "InvalidToken";
|
|
57
59
|
}
|
|
58
|
-
if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.validatedAt))))) || __requireBoolean(__normalize(claims.validatedAt) <
|
|
60
|
+
if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.validatedAt))))) || __requireBoolean(__normalize(claims.validatedAt) < 0)) || __requireBoolean(__normalize(claims.validatedAt) > __normalize(__hostGlobal(["Date"]).now())))) {
|
|
59
61
|
throw "InvalidToken";
|
|
60
62
|
}
|
|
61
63
|
return claims;
|
|
62
64
|
return null;
|
|
63
65
|
}
|
|
66
|
+
renew(claims) {
|
|
67
|
+
__requireArity(arguments.length, [0], "renew");
|
|
68
|
+
claims = __boundary(claims);
|
|
69
|
+
if (__requireBoolean(__finite(__normalize(claims.exp) * 1000) <= __normalize(__hostGlobal(["Date"]).now()))) {
|
|
70
|
+
throw "TokenExpired";
|
|
71
|
+
}
|
|
72
|
+
let updated = __fromJson(__toJson(claims));
|
|
73
|
+
let now = __normalize(__hostGlobal(["Math"]).floor(__finite(__normalize(__hostGlobal(["Date"]).now()) / 1000)));
|
|
74
|
+
updated.iat = now;
|
|
75
|
+
updated.exp = __numericAdd(now, __normalize(this.#settings.ttlSeconds));
|
|
76
|
+
return updated;
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
64
79
|
sign(claims) {
|
|
65
80
|
__requireArity(arguments.length, [0], "sign");
|
|
66
81
|
claims = __boundary(claims);
|
package/dist/tokens.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create()\n\nTokens(settings)\n @settings = settings\n\nTokens:create()\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId: crypto/randomUUID()\n auth: \"\"\n iat: now\n exp: now + settings.ttlSeconds\n iss: settings.issuer\n aud: settings.audience\n validatedAt: Date/now()\n }\n\nTokens:read(header)\n settings = @settings\n if !is_string(header) or header.length > 16384 or header.slice(0, 7).toLowerCase() != \"bearer \" or header.length == 7\n throw \"InvalidToken\"\n encoded = header.slice(7)\n decoded = jwt/default/decode(encoded, {\n complete: true\n })\n if !is_object(decoded) or !is_object(decoded.header)\n throw \"InvalidToken\"\n head = decoded.header\n if head.alg != \"HS256\" or head.typ != \"JWT\" or !is_string(head.kid) or head.crit != null or head.b64 != null\n throw \"InvalidToken\"\n keys = settings.keys\n if !Object/hasOwn(keys, head.kid)\n throw \"InvalidToken\"\n claims = jwt/default/verify(encoded, keys[head.kid], {\n algorithms: [\"HS256\"]\n issuer: settings.issuer\n audience: settings.audience\n })\n if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == \"\" or !is_string(claims.auth)\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt <
|
|
1
|
+
{"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create()\n renew(claims)\n\nTokens(settings)\n @settings = settings\n\nTokens:create()\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId: crypto/randomUUID()\n auth: \"\"\n iat: now\n exp: now + settings.ttlSeconds\n iss: settings.issuer\n aud: settings.audience\n validatedAt: Date/now()\n }\n\nTokens:read(header)\n settings = @settings\n if !is_string(header) or header.length > 16384 or header.slice(0, 7).toLowerCase() != \"bearer \" or header.length == 7\n throw \"InvalidToken\"\n encoded = header.slice(7)\n decoded = jwt/default/decode(encoded, {\n complete: true\n })\n if !is_object(decoded) or !is_object(decoded.header)\n throw \"InvalidToken\"\n head = decoded.header\n if head.alg != \"HS256\" or head.typ != \"JWT\" or !is_string(head.kid) or head.crit != null or head.b64 != null\n throw \"InvalidToken\"\n keys = settings.keys\n if !Object/hasOwn(keys, head.kid)\n throw \"InvalidToken\"\n claims = jwt/default/verify(encoded, keys[head.kid], {\n algorithms: [\"HS256\"]\n issuer: settings.issuer\n audience: settings.audience\n })\n if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == \"\" or !is_string(claims.auth)\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt < 0 or claims.validatedAt > Date/now()\n throw \"InvalidToken\"\n return claims\n\nTokens:renew(claims)\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n updated = from_json(to_json(claims))\n now = Math/floor(Date/now() / 1000)\n updated.iat = now\n updated.exp = now + @settings.ttlSeconds\n return updated\n\nTokens:sign(claims)\n settings = @settings\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n keys = settings.keys\n return jwt/default/sign(claims, keys[settings.activeKeyId], {\n algorithm: \"HS256\"\n header: {\n typ: \"JWT\"\n kid: settings.activeKeyId\n }\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lango-project/lango-server",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "A small JSON HTTP server for Lango applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
],
|
|
27
27
|
"scripts": {
|
|
28
28
|
"build": "lango run tools/clean.lango && lango build src/library.lango --out dist/library.mjs && lango build src/server.lango --out dist/cli/server.mjs --executable && lango build src/worker.lango --out dist/worker.mjs && lango build examples/application/handlers.lango --out examples/application/dist/handlers.mjs && lango build src/postgres_worker.lango --out dist/postgres_worker.mjs && lango build examples/database/handlers.lango --out examples/database/dist/handlers.mjs",
|
|
29
|
-
"test": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database && lango test src/test/unit.lango --build-dir .test-output/unit && lango test src/test/http.lango --build-dir .test-output/http && lango test src/test/middleware.lango --build-dir .test-output/middleware && lango test src/test/static.lango --build-dir .test-output/static && lango test src/test/standalone.lango --build-dir .test-output/standalone",
|
|
29
|
+
"test": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database && lango test src/test/unit.lango --build-dir .test-output/unit && lango test src/test/route_parameters.lango --build-dir .test-output/route-parameters && lango test src/test/http.lango --build-dir .test-output/http && lango test src/test/middleware.lango --build-dir .test-output/middleware && lango test src/test/static.lango --build-dir .test-output/static && lango test src/test/standalone.lango --build-dir .test-output/standalone",
|
|
30
30
|
"start": "node dist/cli/server.mjs examples/application",
|
|
31
31
|
"prepack": "npm run build",
|
|
32
32
|
"test:postgres": "lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database-postgres",
|
package/src/endpoint.lango
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import "./route_pattern"
|
|
2
|
+
routePattern(path)
|
|
1
3
|
import "./middleware"
|
|
2
4
|
middlewareName(name)
|
|
3
5
|
|
|
@@ -10,10 +12,7 @@ export class Endpoint(spec)
|
|
|
10
12
|
middleware
|
|
11
13
|
|
|
12
14
|
Endpoint(spec)
|
|
13
|
-
|
|
14
|
-
throw "Endpoint requires an absolute URL path"
|
|
15
|
-
if spec.path.includes("*") and (!spec.path.endsWith("/*") or spec.path.indexOf("*") != spec.path.lastIndexOf("*"))
|
|
16
|
-
throw "Only trailing /* wildcards are supported"
|
|
15
|
+
routePattern(spec.path)
|
|
17
16
|
for ["module", "handler"] as key
|
|
18
17
|
if !is_string(spec[key]) or spec[key] == ""
|
|
19
18
|
throw "Endpoint requires ${key}"
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import js global RegExp
|
|
2
|
+
|
|
3
|
+
export class HttpFailure(status, code, headers)
|
|
4
|
+
methods
|
|
5
|
+
result()
|
|
6
|
+
|
|
7
|
+
HttpFailure(status, code, headers)
|
|
8
|
+
if !is_number(status) or status % 1 != 0 or status < 400 or status > 599
|
|
9
|
+
throw "Rejected response requires an error status"
|
|
10
|
+
pattern = new RegExp("^[A-Za-z][A-Za-z0-9_]{0,63}$")
|
|
11
|
+
if !is_string(code) or !pattern.test(code)
|
|
12
|
+
throw "Rejected response requires an error code"
|
|
13
|
+
@status = status
|
|
14
|
+
@code = code
|
|
15
|
+
@headers = from_json(to_json(headers))
|
|
16
|
+
if status == 401
|
|
17
|
+
@headers["www-authenticate"] = "Bearer"
|
|
18
|
+
|
|
19
|
+
HttpFailure:result()
|
|
20
|
+
return {
|
|
21
|
+
status: @status
|
|
22
|
+
headers: from_json(to_json(@headers))
|
|
23
|
+
body: to_json({
|
|
24
|
+
error: @code
|
|
25
|
+
})
|
|
26
|
+
}
|
|
@@ -42,7 +42,7 @@ longpollOptions(spec)
|
|
|
42
42
|
return result
|
|
43
43
|
|
|
44
44
|
validPath(value)
|
|
45
|
-
if !is_string(value) or !value.startsWith("/") or value.includes("*") or value.includes("?") or value.includes("#") or value.includes("\\") or value.includes("//")
|
|
45
|
+
if !is_string(value) or !value.startsWith("/") or value.includes("*") or value.includes("{") or value.includes("}") or value.includes("?") or value.includes("#") or value.includes("\\") or value.includes("//")
|
|
46
46
|
throw "Longpoll requires an exact absolute URL path"
|
|
47
47
|
return null
|
|
48
48
|
|
package/src/response.lango
CHANGED
|
@@ -2,11 +2,14 @@ import js "node:http" as http
|
|
|
2
2
|
|
|
3
3
|
import "./options"
|
|
4
4
|
contains(items, value)
|
|
5
|
+
import "./http_failure"
|
|
6
|
+
class HttpFailure
|
|
5
7
|
export class Response()
|
|
6
8
|
methods
|
|
7
9
|
status(code)
|
|
8
10
|
header(name, value)
|
|
9
11
|
result(body)
|
|
12
|
+
reject(status, code)
|
|
10
13
|
|
|
11
14
|
Response()
|
|
12
15
|
@status = 200
|
|
@@ -40,3 +43,6 @@ Response:result(body)
|
|
|
40
43
|
headers: from_json(to_json(@headers))
|
|
41
44
|
body: body
|
|
42
45
|
}
|
|
46
|
+
|
|
47
|
+
Response:reject(status, code)
|
|
48
|
+
throw new HttpFailure(status, code, @headers)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export routeInfo(definitions)
|
|
2
|
+
|
|
3
|
+
routeInfo(definitions)
|
|
4
|
+
result = []
|
|
5
|
+
for definitions as route
|
|
6
|
+
kind = route.kind
|
|
7
|
+
if kind == null
|
|
8
|
+
kind = "endpoint"
|
|
9
|
+
result.add({
|
|
10
|
+
path: route.path
|
|
11
|
+
kind: kind
|
|
12
|
+
auth: route.auth
|
|
13
|
+
middleware: route.middleware
|
|
14
|
+
})
|
|
15
|
+
return result
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import js global RegExp
|
|
2
|
+
|
|
3
|
+
export routePattern(path)
|
|
4
|
+
export matchPath(pattern, path)
|
|
5
|
+
export moreSpecific(candidate, current)
|
|
6
|
+
|
|
7
|
+
routePattern(path)
|
|
8
|
+
if !is_string(path) or !path.startsWith("/") or path.includes("?") or path.includes("#") or path.includes("\\") or path.includes("//")
|
|
9
|
+
throw "Endpoint requires an absolute URL path"
|
|
10
|
+
if path.includes("*") and (!path.endsWith("/*") or path.indexOf("*") != path.lastIndexOf("*"))
|
|
11
|
+
throw "Only trailing /* wildcards are supported"
|
|
12
|
+
segments = path.split("/")
|
|
13
|
+
segments = segments.slice(1)
|
|
14
|
+
wildcard = path.endsWith("/*")
|
|
15
|
+
if wildcard
|
|
16
|
+
segments.pop()
|
|
17
|
+
names = []
|
|
18
|
+
shape = []
|
|
19
|
+
identifier = new RegExp("^[A-Za-z_][A-Za-z0-9_]*$")
|
|
20
|
+
reserved = ["__proto__", "constructor", "prototype"]
|
|
21
|
+
for segments as segment
|
|
22
|
+
if segment.includes("{") or segment.includes("}")
|
|
23
|
+
if !segment.startsWith("{") or !segment.endsWith("}")
|
|
24
|
+
throw "Path parameters must occupy an entire segment"
|
|
25
|
+
name = segment.slice(1, -1)
|
|
26
|
+
if !identifier.test(name) or reserved.includes(name)
|
|
27
|
+
throw "Invalid path parameter name: ${name}"
|
|
28
|
+
if names.includes(name)
|
|
29
|
+
throw "Duplicate path parameter: ${name}"
|
|
30
|
+
names.add(name)
|
|
31
|
+
shape.add("{}")
|
|
32
|
+
else
|
|
33
|
+
shape.add(segment)
|
|
34
|
+
if wildcard
|
|
35
|
+
shape.add("*")
|
|
36
|
+
key = shape.join("/")
|
|
37
|
+
key = "/${key}"
|
|
38
|
+
return {
|
|
39
|
+
segments: segments
|
|
40
|
+
wildcard: wildcard
|
|
41
|
+
key: key
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
matchPath(pattern, path)
|
|
45
|
+
parts = path.split("/")
|
|
46
|
+
if parts[0] != ""
|
|
47
|
+
return null
|
|
48
|
+
parts = parts.slice(1)
|
|
49
|
+
count = pattern.segments.length
|
|
50
|
+
if pattern.wildcard
|
|
51
|
+
if parts.length <= count
|
|
52
|
+
return null
|
|
53
|
+
else
|
|
54
|
+
if parts.length != count
|
|
55
|
+
return null
|
|
56
|
+
parameters = {}
|
|
57
|
+
for pattern.segments as index: segment
|
|
58
|
+
value = parts[index]
|
|
59
|
+
if segment.startsWith("{")
|
|
60
|
+
if value == ""
|
|
61
|
+
return null
|
|
62
|
+
name = segment.slice(1, -1)
|
|
63
|
+
parameters[name] = value
|
|
64
|
+
else
|
|
65
|
+
if segment != value
|
|
66
|
+
return null
|
|
67
|
+
return parameters
|
|
68
|
+
|
|
69
|
+
moreSpecific(candidate, current)
|
|
70
|
+
if current == null
|
|
71
|
+
return true
|
|
72
|
+
if candidate.wildcard != current.wildcard
|
|
73
|
+
return !candidate.wildcard
|
|
74
|
+
first = candidate.segments
|
|
75
|
+
second = current.segments
|
|
76
|
+
count = first.length
|
|
77
|
+
if second.length < count
|
|
78
|
+
count = second.length
|
|
79
|
+
for range(count) as index
|
|
80
|
+
segment = first[index]
|
|
81
|
+
alternative = second[index]
|
|
82
|
+
literal = !segment.startsWith("{")
|
|
83
|
+
other = !alternative.startsWith("{")
|
|
84
|
+
if literal != other
|
|
85
|
+
return literal
|
|
86
|
+
return first.length > second.length
|
package/src/routes.lango
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import "./route_pattern"
|
|
2
|
+
routePattern(path)
|
|
1
3
|
import "./options"
|
|
2
4
|
contains(items, value)
|
|
3
5
|
import js "node:fs" as fs
|
|
@@ -34,9 +36,7 @@ Routes(root)
|
|
|
34
36
|
|
|
35
37
|
Routes:endpoint(spec)
|
|
36
38
|
item = new Endpoint(spec)
|
|
37
|
-
|
|
38
|
-
if other.path == item.path
|
|
39
|
-
throw "Duplicate endpoint: ${item.path}"
|
|
39
|
+
checkPath(item.path)
|
|
40
40
|
@items.add({
|
|
41
41
|
path: item.path
|
|
42
42
|
module: resolveModule(item.module, @root)
|
|
@@ -46,6 +46,16 @@ Routes:endpoint(spec)
|
|
|
46
46
|
})
|
|
47
47
|
return @this
|
|
48
48
|
|
|
49
|
+
Routes:checkPath(path)
|
|
50
|
+
pattern = routePattern(path)
|
|
51
|
+
for @items as other
|
|
52
|
+
if other.path == path
|
|
53
|
+
throw "Duplicate endpoint: ${path}"
|
|
54
|
+
existing = routePattern(other.path)
|
|
55
|
+
if existing.key == pattern.key
|
|
56
|
+
throw "Conflicting endpoint pattern: ${path}"
|
|
57
|
+
return null
|
|
58
|
+
|
|
49
59
|
Routes:addMiddleware(name, spec)
|
|
50
60
|
middlewareName(name)
|
|
51
61
|
if Object/hasOwn(@middlewares, name)
|
|
@@ -53,13 +63,16 @@ Routes:addMiddleware(name, spec)
|
|
|
53
63
|
if !is_object(spec) or is_array(spec)
|
|
54
64
|
throw "Middleware requires a module and exported handler"
|
|
55
65
|
for spec as key: value
|
|
56
|
-
if key != "module" and key != "handler"
|
|
66
|
+
if key != "module" and key != "handler" and key != "validate"
|
|
57
67
|
throw "Unknown middleware option: ${key}"
|
|
58
68
|
if !is_string(spec.handler) or spec.handler == ""
|
|
59
69
|
throw "Middleware handler is required"
|
|
70
|
+
if spec.validate != null and (!is_string(spec.validate) or spec.validate == "")
|
|
71
|
+
throw "Middleware validate must name an exported function"
|
|
60
72
|
@middlewares[name] = {
|
|
61
73
|
module: resolveModule(spec.module, @root)
|
|
62
74
|
handler: spec.handler
|
|
75
|
+
validate: spec.validate
|
|
63
76
|
}
|
|
64
77
|
return @this
|
|
65
78
|
|
|
@@ -68,9 +81,7 @@ Routes:middlewares()
|
|
|
68
81
|
|
|
69
82
|
Routes:longpoll(spec)
|
|
70
83
|
item = longpollOptions(spec)
|
|
71
|
-
|
|
72
|
-
if other.path == item.path
|
|
73
|
-
throw "Duplicate endpoint: ${item.path}"
|
|
84
|
+
checkPath(item.path)
|
|
74
85
|
@items.add(item)
|
|
75
86
|
return @this
|
|
76
87
|
|
|
@@ -188,13 +199,14 @@ Routes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack,
|
|
|
188
199
|
leaf(tag)
|
|
189
200
|
includeAt(spec, directory, prefix, stack, auth)
|
|
190
201
|
case "middleware"
|
|
191
|
-
attributes(tag, ["name", "module", "handler"])
|
|
202
|
+
attributes(tag, ["name", "module", "handler", "validate"])
|
|
192
203
|
leaf(tag)
|
|
193
204
|
if !allowEvents
|
|
194
205
|
throw "Middleware declarations are only allowed in the application's root routes.xml"
|
|
195
206
|
addMiddleware(spec.name, {
|
|
196
207
|
module: resolveModule(spec.module, directory)
|
|
197
208
|
handler: spec.handler
|
|
209
|
+
validate: spec.validate
|
|
198
210
|
})
|
|
199
211
|
case "event"
|
|
200
212
|
attributes(tag, ["name", "module", "handler"])
|
package/src/runtime.lango
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import "./route_pattern"
|
|
2
|
+
routePattern(path)
|
|
3
|
+
matchPath(pattern, path)
|
|
4
|
+
moreSpecific(candidate, current)
|
|
5
|
+
import js global decodeURIComponent
|
|
1
6
|
import "./server_context"
|
|
2
7
|
class ServerContext
|
|
3
8
|
import "./database"
|
|
@@ -13,6 +18,8 @@ import "./tokens"
|
|
|
13
18
|
class Tokens
|
|
14
19
|
import "./response"
|
|
15
20
|
class Response
|
|
21
|
+
import "./http_failure"
|
|
22
|
+
class HttpFailure
|
|
16
23
|
|
|
17
24
|
export class Runtime(definition)
|
|
18
25
|
methods
|
|
@@ -21,7 +28,7 @@ export class Runtime(definition)
|
|
|
21
28
|
close()
|
|
22
29
|
|
|
23
30
|
Runtime(definition)
|
|
24
|
-
@serverContext = new ServerContext()
|
|
31
|
+
@serverContext = new ServerContext(definition.routes)
|
|
25
32
|
@definition = definition
|
|
26
33
|
@routes = []
|
|
27
34
|
@events = {}
|
|
@@ -57,12 +64,24 @@ Runtime:prepareMiddleware(pending, name, spec)
|
|
|
57
64
|
return target(spec)
|
|
58
65
|
then(handler)
|
|
59
66
|
capture name
|
|
67
|
+
capture spec
|
|
60
68
|
@middlewares[name] = handler
|
|
69
|
+
if spec.validate != null
|
|
70
|
+
return target({
|
|
71
|
+
module: spec.module
|
|
72
|
+
handler: spec.validate
|
|
73
|
+
})
|
|
74
|
+
return null
|
|
75
|
+
then(validator)
|
|
76
|
+
if validator != null
|
|
77
|
+
return validator(@serverContext.routes())
|
|
61
78
|
return null
|
|
62
79
|
|
|
63
80
|
Runtime:prepareRoute(pending, route)
|
|
64
81
|
if route.kind == "longpoll"
|
|
65
|
-
|
|
82
|
+
prepared = Object/assign({}, route)
|
|
83
|
+
prepared.pattern = routePattern(route.path)
|
|
84
|
+
@routes.add(prepared)
|
|
66
85
|
return pending
|
|
67
86
|
return chain pending
|
|
68
87
|
then(ignored)
|
|
@@ -78,6 +97,7 @@ Runtime:prepareRoute(pending, route)
|
|
|
78
97
|
middleware = @middlewares[name]
|
|
79
98
|
@routes.add({
|
|
80
99
|
path: route.path
|
|
100
|
+
pattern: routePattern(route.path)
|
|
81
101
|
auth: route.auth
|
|
82
102
|
handler: handler
|
|
83
103
|
middleware: middleware
|
|
@@ -112,16 +132,20 @@ exported(mod, name)
|
|
|
112
132
|
|
|
113
133
|
Runtime:match(path)
|
|
114
134
|
best = null
|
|
115
|
-
|
|
135
|
+
parameters = null
|
|
136
|
+
pattern = null
|
|
116
137
|
for @routes as route
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
return
|
|
138
|
+
captured = matchPath(route.pattern, path)
|
|
139
|
+
if captured != null and moreSpecific(route.pattern, pattern)
|
|
140
|
+
best = route
|
|
141
|
+
parameters = captured
|
|
142
|
+
pattern = route.pattern
|
|
143
|
+
if best == null
|
|
144
|
+
return null
|
|
145
|
+
return {
|
|
146
|
+
route: best
|
|
147
|
+
parameters: parameters
|
|
148
|
+
}
|
|
125
149
|
|
|
126
150
|
Runtime:handle(task)
|
|
127
151
|
Object/freeze(task.request.headers)
|
|
@@ -138,9 +162,10 @@ Runtime:handle(task)
|
|
|
138
162
|
claims = @tokens.read(request.headers.authorization)
|
|
139
163
|
catch error
|
|
140
164
|
return failure(401, "Unauthorized")
|
|
141
|
-
|
|
142
|
-
if
|
|
165
|
+
matched = match(request.path)
|
|
166
|
+
if matched == null
|
|
143
167
|
return failure(404, "RouteNotFound")
|
|
168
|
+
route = matched.route
|
|
144
169
|
input = null
|
|
145
170
|
try
|
|
146
171
|
input = JSON/parse(task.body)
|
|
@@ -148,6 +173,11 @@ Runtime:handle(task)
|
|
|
148
173
|
return failure(400, "InputMustBeObject")
|
|
149
174
|
catch error
|
|
150
175
|
return failure(400, "InvalidJson")
|
|
176
|
+
try
|
|
177
|
+
for matched.parameters as name: value
|
|
178
|
+
input[name] = decodeURIComponent(value)
|
|
179
|
+
catch error
|
|
180
|
+
return failure(400, "InvalidPath")
|
|
151
181
|
context token = new Token(claims)
|
|
152
182
|
context db = @database.scope()
|
|
153
183
|
return chain Promise/resolve(null)
|
|
@@ -199,8 +229,7 @@ Runtime:handle(task)
|
|
|
199
229
|
capture claims
|
|
200
230
|
if task.authorize == true
|
|
201
231
|
closeScope(db, true)
|
|
202
|
-
authorizedClaims = token
|
|
203
|
-
authorizedClaims.validatedAt = claims.validatedAt
|
|
232
|
+
authorizedClaims = tokenClaims(token, claims, true)
|
|
204
233
|
encoded = @tokens.sign(authorizedClaims)
|
|
205
234
|
if task.pollResult == null
|
|
206
235
|
return {
|
|
@@ -220,8 +249,7 @@ Runtime:handle(task)
|
|
|
220
249
|
throw "Handler result is not JSON serializable"
|
|
221
250
|
closeScope(db, true)
|
|
222
251
|
result = response.result(body)
|
|
223
|
-
updated = token.
|
|
224
|
-
updated.validatedAt = claims.validatedAt
|
|
252
|
+
updated = tokenClaims(token, claims, result.status < 400)
|
|
225
253
|
result.headers["x-lango-token"] = @tokens.sign(updated)
|
|
226
254
|
if @definition.settings.requestEvent and "request" in @events
|
|
227
255
|
return audit(request.id, result, task.body, body, updated)
|
|
@@ -231,7 +259,10 @@ Runtime:handle(task)
|
|
|
231
259
|
capture request
|
|
232
260
|
capture log
|
|
233
261
|
capture db
|
|
262
|
+
capture HttpFailure
|
|
234
263
|
closeScope(db, false)
|
|
264
|
+
if is_kindof(error, HttpFailure)
|
|
265
|
+
return error.result()
|
|
235
266
|
if error == "TokenExpired" or (is_object(error) and error.status == 401)
|
|
236
267
|
return failure(401, "Unauthorized")
|
|
237
268
|
log.err("[${request.id}] Request failed")
|
|
@@ -240,6 +271,13 @@ Runtime:handle(task)
|
|
|
240
271
|
capture db
|
|
241
272
|
closeScope(db, false)
|
|
242
273
|
|
|
274
|
+
Runtime:tokenClaims(token, claims, allowRenewal)
|
|
275
|
+
updated = token.snapshot()
|
|
276
|
+
updated.validatedAt = claims.validatedAt
|
|
277
|
+
if allowRenewal and token.renewalRequested()
|
|
278
|
+
updated = @tokens.renew(updated)
|
|
279
|
+
return updated
|
|
280
|
+
|
|
243
281
|
Runtime:event(name, input)
|
|
244
282
|
if !(name in @events)
|
|
245
283
|
return null
|
package/src/server_context.lango
CHANGED
|
@@ -2,14 +2,22 @@ import js "node:worker_threads" as threads
|
|
|
2
2
|
import js global Promise
|
|
3
3
|
import js global setTimeout
|
|
4
4
|
import js global clearTimeout
|
|
5
|
+
import "./route_info"
|
|
6
|
+
routeInfo(definitions)
|
|
5
7
|
|
|
6
|
-
export class ServerContext()
|
|
8
|
+
export class ServerContext(definitions = null)
|
|
7
9
|
methods
|
|
8
10
|
publish(path, key, data)
|
|
9
11
|
cursor(path, key)
|
|
12
|
+
routes()
|
|
10
13
|
|
|
11
|
-
ServerContext()
|
|
12
|
-
|
|
14
|
+
ServerContext(definitions = null)
|
|
15
|
+
if definitions == null
|
|
16
|
+
definitions = []
|
|
17
|
+
@routes = routeInfo(definitions)
|
|
18
|
+
|
|
19
|
+
ServerContext:routes()
|
|
20
|
+
return from_json(to_json(@routes))
|
|
13
21
|
|
|
14
22
|
ServerContext:publish(path, key, data)
|
|
15
23
|
return invoke("publish", path, key, data)
|
package/src/token.lango
CHANGED
|
@@ -14,10 +14,13 @@ export class Token(claims, readonly = false)
|
|
|
14
14
|
get(name)
|
|
15
15
|
set(name, value)
|
|
16
16
|
snapshot()
|
|
17
|
+
renew()
|
|
18
|
+
renewalRequested()
|
|
17
19
|
|
|
18
20
|
Token(claims, readonly = false)
|
|
19
21
|
@claims = from_json(to_json(claims))
|
|
20
22
|
@readonly = readonly
|
|
23
|
+
@renew = false
|
|
21
24
|
@clientId = claims.clientId
|
|
22
25
|
@auth = claims.auth
|
|
23
26
|
@expiresAt = claims.exp
|
|
@@ -64,6 +67,14 @@ Token:snapshot()
|
|
|
64
67
|
claims.auth = @auth
|
|
65
68
|
return claims
|
|
66
69
|
|
|
70
|
+
Token:renew()
|
|
71
|
+
writable()
|
|
72
|
+
@renew = true
|
|
73
|
+
return @this
|
|
74
|
+
|
|
75
|
+
Token:renewalRequested()
|
|
76
|
+
return @renew
|
|
77
|
+
|
|
67
78
|
Token:writable()
|
|
68
79
|
if @readonly
|
|
69
80
|
throw "Token is read-only during this event"
|
package/src/tokens.lango
CHANGED
|
@@ -10,6 +10,7 @@ export class Tokens(settings)
|
|
|
10
10
|
read(header)
|
|
11
11
|
sign(claims)
|
|
12
12
|
create()
|
|
13
|
+
renew(claims)
|
|
13
14
|
|
|
14
15
|
Tokens(settings)
|
|
15
16
|
@settings = settings
|
|
@@ -52,10 +53,19 @@ Tokens:read(header)
|
|
|
52
53
|
throw "InvalidToken"
|
|
53
54
|
if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()
|
|
54
55
|
throw "InvalidToken"
|
|
55
|
-
if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt <
|
|
56
|
+
if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt < 0 or claims.validatedAt > Date/now()
|
|
56
57
|
throw "InvalidToken"
|
|
57
58
|
return claims
|
|
58
59
|
|
|
60
|
+
Tokens:renew(claims)
|
|
61
|
+
if claims.exp * 1000 <= Date/now()
|
|
62
|
+
throw "TokenExpired"
|
|
63
|
+
updated = from_json(to_json(claims))
|
|
64
|
+
now = Math/floor(Date/now() / 1000)
|
|
65
|
+
updated.iat = now
|
|
66
|
+
updated.exp = now + @settings.ttlSeconds
|
|
67
|
+
return updated
|
|
68
|
+
|
|
59
69
|
Tokens:sign(claims)
|
|
60
70
|
settings = @settings
|
|
61
71
|
if claims.exp * 1000 <= Date/now()
|