@lango-project/lango-server 0.1.1 → 0.2.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.
Files changed (61) hide show
  1. package/README.md +149 -18
  2. package/dist/.lango/localization.mjs +108 -0
  3. package/dist/.lango/runtime.mjs +25 -6
  4. package/dist/.lango/vendor/i18next.LICENSE +21 -0
  5. package/dist/.lango/vendor/i18next.mjs +2434 -0
  6. package/dist/cli/.lango/localization.mjs +108 -0
  7. package/dist/cli/.lango/runtime.mjs +25 -6
  8. package/dist/cli/.lango/vendor/i18next.LICENSE +21 -0
  9. package/dist/cli/.lango/vendor/i18next.mjs +2434 -0
  10. package/dist/cli/endpoint.mjs +2 -6
  11. package/dist/cli/endpoint.mjs.map +1 -1
  12. package/dist/cli/longpoll_options.mjs +1 -1
  13. package/dist/cli/longpoll_options.mjs.map +1 -1
  14. package/dist/cli/options.mjs +2 -2
  15. package/dist/cli/options.mjs.map +1 -1
  16. package/dist/cli/route_pattern.mjs +129 -0
  17. package/dist/cli/route_pattern.mjs.map +1 -0
  18. package/dist/cli/routes.mjs +25 -13
  19. package/dist/cli/routes.mjs.map +1 -1
  20. package/dist/cli/static_files.mjs +121 -25
  21. package/dist/cli/static_files.mjs.map +1 -1
  22. package/dist/endpoint.mjs +2 -6
  23. package/dist/endpoint.mjs.map +1 -1
  24. package/dist/http_failure.mjs +45 -0
  25. package/dist/http_failure.mjs.map +1 -0
  26. package/dist/longpoll_options.mjs +1 -1
  27. package/dist/longpoll_options.mjs.map +1 -1
  28. package/dist/options.mjs +2 -2
  29. package/dist/options.mjs.map +1 -1
  30. package/dist/response.mjs +8 -0
  31. package/dist/response.mjs.map +1 -1
  32. package/dist/route_info.mjs +22 -0
  33. package/dist/route_info.mjs.map +1 -0
  34. package/dist/route_pattern.mjs +129 -0
  35. package/dist/route_pattern.mjs.map +1 -0
  36. package/dist/routes.mjs +25 -13
  37. package/dist/routes.mjs.map +1 -1
  38. package/dist/runtime.mjs +132 -22
  39. package/dist/runtime.mjs.map +1 -1
  40. package/dist/server_context.mjs +25 -2
  41. package/dist/server_context.mjs.map +1 -1
  42. package/dist/static_files.mjs +121 -25
  43. package/dist/static_files.mjs.map +1 -1
  44. package/dist/token.mjs +38 -13
  45. package/dist/token.mjs.map +1 -1
  46. package/dist/tokens.mjs +16 -1
  47. package/dist/tokens.mjs.map +1 -1
  48. package/package.json +3 -3
  49. package/src/endpoint.lango +3 -4
  50. package/src/http_failure.lango +26 -0
  51. package/src/longpoll_options.lango +1 -1
  52. package/src/options.lango +2 -2
  53. package/src/response.lango +6 -0
  54. package/src/route_info.lango +15 -0
  55. package/src/route_pattern.lango +86 -0
  56. package/src/routes.lango +20 -8
  57. package/src/runtime.lango +119 -19
  58. package/src/server_context.lango +19 -3
  59. package/src/static_files.lango +99 -23
  60. package/src/token.lango +24 -3
  61. package/src/tokens.lango +11 -1
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,15 +18,20 @@ 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
19
26
  preload()
20
27
  handle(task)
21
28
  close()
29
+ refreshTokens(tokens)
22
30
 
23
31
  Runtime(definition)
24
- @serverContext = new ServerContext()
32
+ refresh = (tokens)
33
+ return refreshTokens(tokens)
34
+ @serverContext = new ServerContext(definition.routes, refresh)
25
35
  @definition = definition
26
36
  @routes = []
27
37
  @events = {}
@@ -57,12 +67,24 @@ Runtime:prepareMiddleware(pending, name, spec)
57
67
  return target(spec)
58
68
  then(handler)
59
69
  capture name
70
+ capture spec
60
71
  @middlewares[name] = handler
72
+ if spec.validate != null
73
+ return target({
74
+ module: spec.module
75
+ handler: spec.validate
76
+ })
77
+ return null
78
+ then(validator)
79
+ if validator != null
80
+ return validator(@serverContext.routes())
61
81
  return null
62
82
 
63
83
  Runtime:prepareRoute(pending, route)
64
84
  if route.kind == "longpoll"
65
- @routes.add(route)
85
+ prepared = Object/assign({}, route)
86
+ prepared.pattern = routePattern(route.path)
87
+ @routes.add(prepared)
66
88
  return pending
67
89
  return chain pending
68
90
  then(ignored)
@@ -78,6 +100,7 @@ Runtime:prepareRoute(pending, route)
78
100
  middleware = @middlewares[name]
79
101
  @routes.add({
80
102
  path: route.path
103
+ pattern: routePattern(route.path)
81
104
  auth: route.auth
82
105
  handler: handler
83
106
  middleware: middleware
@@ -112,16 +135,20 @@ exported(mod, name)
112
135
 
113
136
  Runtime:match(path)
114
137
  best = null
115
- length = -1
138
+ parameters = null
139
+ pattern = null
116
140
  for @routes as route
117
- if route.path == path
118
- return route
119
- if route.path.endsWith("/*")
120
- prefix = route.path.slice(0, -1)
121
- if path.startsWith(prefix) and prefix.length > length
122
- best = route
123
- length = prefix.length
124
- return best
141
+ captured = matchPath(route.pattern, path)
142
+ if captured != null and moreSpecific(route.pattern, pattern)
143
+ best = route
144
+ parameters = captured
145
+ pattern = route.pattern
146
+ if best == null
147
+ return null
148
+ return {
149
+ route: best
150
+ parameters: parameters
151
+ }
125
152
 
126
153
  Runtime:handle(task)
127
154
  Object/freeze(task.request.headers)
@@ -138,9 +165,10 @@ Runtime:handle(task)
138
165
  claims = @tokens.read(request.headers.authorization)
139
166
  catch error
140
167
  return failure(401, "Unauthorized")
141
- route = match(request.path)
142
- if route == null
168
+ matched = match(request.path)
169
+ if matched == null
143
170
  return failure(404, "RouteNotFound")
171
+ route = matched.route
144
172
  input = null
145
173
  try
146
174
  input = JSON/parse(task.body)
@@ -148,6 +176,11 @@ Runtime:handle(task)
148
176
  return failure(400, "InputMustBeObject")
149
177
  catch error
150
178
  return failure(400, "InvalidJson")
179
+ try
180
+ for matched.parameters as name: value
181
+ input[name] = decodeURIComponent(value)
182
+ catch error
183
+ return failure(400, "InvalidPath")
151
184
  context token = new Token(claims)
152
185
  context db = @database.scope()
153
186
  return chain Promise/resolve(null)
@@ -176,6 +209,7 @@ Runtime:handle(task)
176
209
  capture fresh
177
210
  if !fresh and is_number(validatedAt)
178
211
  stampValidation(claims, validatedAt)
212
+ token.renew()
179
213
  if route.auth != "anonymous" and !token.hasAuth(route.auth)
180
214
  throw {
181
215
  status: 401
@@ -199,8 +233,7 @@ Runtime:handle(task)
199
233
  capture claims
200
234
  if task.authorize == true
201
235
  closeScope(db, true)
202
- authorizedClaims = token.snapshot()
203
- authorizedClaims.validatedAt = claims.validatedAt
236
+ authorizedClaims = tokenClaims(token, claims, true)
204
237
  encoded = @tokens.sign(authorizedClaims)
205
238
  if task.pollResult == null
206
239
  return {
@@ -220,10 +253,9 @@ Runtime:handle(task)
220
253
  throw "Handler result is not JSON serializable"
221
254
  closeScope(db, true)
222
255
  result = response.result(body)
223
- updated = token.snapshot()
224
- updated.validatedAt = claims.validatedAt
256
+ updated = tokenClaims(token, claims, result.status < 400)
225
257
  result.headers["x-lango-token"] = @tokens.sign(updated)
226
- if @definition.settings.requestEvent and "request" in @events
258
+ if task.internal != true and @definition.settings.requestEvent and "request" in @events
227
259
  return audit(request.id, result, task.body, body, updated)
228
260
  return result
229
261
  catch(error)
@@ -231,7 +263,10 @@ Runtime:handle(task)
231
263
  capture request
232
264
  capture log
233
265
  capture db
266
+ capture HttpFailure
234
267
  closeScope(db, false)
268
+ if is_kindof(error, HttpFailure)
269
+ return error.result()
235
270
  if error == "TokenExpired" or (is_object(error) and error.status == 401)
236
271
  return failure(401, "Unauthorized")
237
272
  log.err("[${request.id}] Request failed")
@@ -240,6 +275,69 @@ Runtime:handle(task)
240
275
  capture db
241
276
  closeScope(db, false)
242
277
 
278
+ Runtime:tokenClaims(token, claims, allowRenewal)
279
+ updated = token.snapshot()
280
+ updated.validatedAt = claims.validatedAt
281
+ if allowRenewal and token.renewalRequested()
282
+ updated = @tokens.renew(updated)
283
+ return updated
284
+
285
+ Runtime:refreshTokens(tokens)
286
+ context request
287
+ context token
288
+ if !is_array(tokens) or tokens.length == 0 or tokens.length > 64
289
+ throw "Token refresh requires 1 to 64 tokens"
290
+ seen = []
291
+ for tokens as encoded
292
+ if !is_string(encoded) or encoded == "" or encoded.length > 16384 or seen.includes(encoded)
293
+ throw "Invalid refresh token"
294
+ seen.add(encoded)
295
+ owner = token.clientId?
296
+ results = []
297
+ pending = Promise/resolve(null)
298
+ for tokens as encoded
299
+ child = Object/assign({}, request, {
300
+ headers: Object/assign({}, request.headers, {
301
+ authorization: "Bearer ${encoded}"
302
+ })
303
+ })
304
+ pending = refreshOne(pending, results, encoded, owner, child)
305
+ return chain pending
306
+ then(ignored)
307
+ capture results
308
+ return results
309
+
310
+ Runtime:refreshOne(pending, results, encoded, owner, child)
311
+ return chain pending
312
+ then(ignored)
313
+ capture encoded
314
+ capture owner
315
+ capture child
316
+ checked = null
317
+ try
318
+ checked = @tokens.read("Bearer ${encoded}")
319
+ catch error
320
+ return failure(401, "Unauthorized")
321
+ if checked.clientId != owner
322
+ return failure(401, "Unauthorized")
323
+ return handle({
324
+ request: child
325
+ body: "{}"
326
+ internal: true
327
+ })
328
+ then(result)
329
+ capture results
330
+ capture encoded
331
+ updated = null
332
+ if result.status < 400
333
+ updated = result.headers["x-lango-token"]
334
+ results.add({
335
+ previous: encoded
336
+ token: updated
337
+ status: result.status
338
+ })
339
+ return null
340
+
243
341
  Runtime:event(name, input)
244
342
  if !(name in @events)
245
343
  return null
@@ -282,8 +380,10 @@ Runtime:validate()
282
380
  context request
283
381
  context log
284
382
  claims = token.snapshot()
285
- if !("validate" in @events) or Date/now() - claims.validatedAt < 1000
383
+ if Date/now() - claims.validatedAt < 1000
286
384
  return null
385
+ if !("validate" in @events)
386
+ return Date/now()
287
387
  original = JSON/stringify(claims)
288
388
  context token = new Token(claims, true)
289
389
  return chain Promise/resolve(null)
@@ -2,14 +2,30 @@ 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, refresh = null)
7
9
  methods
8
10
  publish(path, key, data)
9
11
  cursor(path, key)
12
+ routes()
13
+ refreshTokens(tokens)
10
14
 
11
- ServerContext()
12
- return null
15
+ ServerContext(definitions = null, refresh = null)
16
+ if definitions == null
17
+ definitions = []
18
+ @routes = routeInfo(definitions)
19
+ @refresh = refresh
20
+
21
+ ServerContext:refreshTokens(tokens)
22
+ if @refresh == null
23
+ throw "Token refresh is unavailable"
24
+ refresh = @refresh
25
+ return refresh(tokens)
26
+
27
+ ServerContext:routes()
28
+ return from_json(to_json(@routes))
13
29
 
14
30
  ServerContext:publish(path, key, data)
15
31
  return invoke("publish", path, key, data)
@@ -2,6 +2,8 @@ import js "node:fs" as fs
2
2
  import js "node:path" as path
3
3
  import js "serve-static" as files
4
4
  import js global RegExp
5
+ import js global decodeURIComponent
6
+ import js global String
5
7
 
6
8
  export staticOptions(root, spec)
7
9
  export class StaticFiles(settings)
@@ -13,7 +15,7 @@ staticOptions(root, spec)
13
15
  return null
14
16
  if !is_object(spec) or is_array(spec)
15
17
  throw "static must be a map"
16
- allowed = ["path", "directory", "index"]
18
+ allowed = ["path", "directory", "index", "fallback", "runtime"]
17
19
  for spec as key: value
18
20
  if !allowed.includes(key)
19
21
  throw "Unknown static option: ${key}"
@@ -32,22 +34,42 @@ staticOptions(root, spec)
32
34
  index = "index.html"
33
35
  if !is_string(index) or index == "" or index.startsWith(".") or index.includes("/") or index.includes("\\")
34
36
  throw "Static index must be a file name"
37
+ fallback = spec.fallback
38
+ if fallback != null and (!is_string(fallback) or fallback == "" or fallback.startsWith(".") or fallback.includes("/") or fallback.includes("\\"))
39
+ throw "Static fallback must be a file name"
40
+ runtime = spec.runtime
41
+ if runtime == null or runtime == "false"
42
+ runtime = false
43
+ if runtime == "true"
44
+ runtime = true
45
+ if !is_bool(runtime)
46
+ throw "Static runtime must be boolean"
35
47
  return {
36
48
  path: mount
37
49
  directory: path/resolve(root, spec.directory)
38
50
  index: index
51
+ fallback: fallback
52
+ runtime: runtime
39
53
  }
40
54
 
41
55
  StaticFiles(settings)
42
56
  @settings = settings
43
57
  if !fs/statSync(settings.directory).isDirectory()
44
58
  throw "Static directory must be a directory"
59
+ if settings.fallback != null and !fs/statSync(path/join(settings.directory, settings.fallback)).isFile()
60
+ throw "Static fallback must be a file"
45
61
  @serve = files/default(settings.directory, {
46
62
  index: settings.index
47
63
  dotfiles: "deny"
48
64
  fallthrough: false
49
65
  redirect: false
50
66
  })
67
+ @runtime = files/default(settings.directory, {
68
+ index: false
69
+ dotfiles: "allow"
70
+ fallthrough: false
71
+ redirect: false
72
+ })
51
73
 
52
74
  StaticFiles:receive(req, res, failed)
53
75
  mount = @settings.path
@@ -60,31 +82,85 @@ StaticFiles:receive(req, res, failed)
60
82
  req.url = url.slice(mount.length)
61
83
  if req.url == "" or req.url.startsWith("?")
62
84
  req.url = "/${req.url}"
85
+ local = req.url.split("?")[0]
86
+ decoded = null
87
+ try
88
+ decoded = decodeURIComponent(local)
89
+ catch error
90
+ failed(400, "InvalidPath")
91
+ return null
92
+ if decoded.includes("\\") or decoded.includes(String/fromCharCode(0))
93
+ failed(400, "InvalidPath")
94
+ return null
95
+ segments = decoded.split("/")
96
+ runtime = false
97
+ for segments as index: segment
98
+ if segment.startsWith(".")
99
+ if index == 1 and segment == ".lango" and @settings.runtime
100
+ runtime = true
101
+ else
102
+ failed(403, "Forbidden")
103
+ return null
63
104
  done = (error)
105
+ capture req
64
106
  capture res
65
107
  capture failed
66
- if res.headersSent
67
- res.destroy()
68
- return null
69
- status = 404
70
- code = "NotFound"
71
- if error != null
72
- switch error.status
73
- case 400
74
- status = 400
75
- code = "InvalidPath"
76
- case 403
77
- status = 403
78
- code = "Forbidden"
79
- case 416
80
- status = 416
81
- code = "RangeNotSatisfiable"
82
- case 404
83
- status = 404
84
- else
85
- status = 500
86
- code = "InternalServerError"
87
- failed(status, code)
108
+ capture decoded
109
+ failure(req, res, failed, error, decoded)
88
110
  serve = @serve
111
+ if runtime
112
+ serve = @runtime
89
113
  serve(req, res, done)
90
114
  return null
115
+
116
+ StaticFiles:failure(req, res, failed, error, pathname = null)
117
+ if res.headersSent
118
+ res.destroy()
119
+ return null
120
+ status = 404
121
+ code = "NotFound"
122
+ if error != null
123
+ switch error.status
124
+ case 400
125
+ status = 400
126
+ code = "InvalidPath"
127
+ case 403
128
+ status = 403
129
+ code = "Forbidden"
130
+ case 416
131
+ status = 416
132
+ code = "RangeNotSatisfiable"
133
+ case 404
134
+ status = 404
135
+ else
136
+ status = 500
137
+ code = "InternalServerError"
138
+ if status == 404 and pathname != null and @settings.fallback != null and !pathname.startsWith("/.lango") and path/posix/extname(pathname) == "" and acceptsHTML(req.headers.accept)
139
+ req.url = "/${@settings.fallback}"
140
+ done = (error)
141
+ capture req
142
+ capture res
143
+ capture failed
144
+ failure(req, res, failed, error)
145
+ serve = @serve
146
+ serve(req, res, done)
147
+ return null
148
+ failed(status, code)
149
+ return null
150
+
151
+ acceptsHTML(value)
152
+ if !is_string(value)
153
+ return false
154
+ zero = new RegExp("^q\\s*=\\s*0(?:\\.0*)?$", "i")
155
+ for value.split(",") as range
156
+ parts = range.split(";")
157
+ media = parts[0]
158
+ type = media.trim().toLowerCase()
159
+ if type == "text/html" or type == "application/xhtml+xml"
160
+ allowed = true
161
+ for parts.slice(1) as parameter
162
+ if zero.test(parameter.trim())
163
+ allowed = false
164
+ if allowed
165
+ return true
166
+ return false
package/src/token.lango CHANGED
@@ -4,9 +4,9 @@ import js global Object
4
4
 
5
5
  export class Token(claims, readonly = false)
6
6
  properties
7
- clientId
8
- auth
9
- expiresAt
7
+ clientId?
8
+ auth?
9
+ expiresAt?
10
10
  methods
11
11
  AddAuth(permission)
12
12
  clearAuth()
@@ -14,13 +14,26 @@ 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
27
+ Object/freeze(@this)
28
+
29
+ Token:clientId?
30
+ return @clientId
31
+
32
+ Token:auth?
33
+ return @auth
34
+
35
+ Token:expiresAt?
36
+ return @expiresAt
24
37
 
25
38
  Token:AddAuth(permission)
26
39
  writable()
@@ -64,6 +77,14 @@ Token:snapshot()
64
77
  claims.auth = @auth
65
78
  return claims
66
79
 
80
+ Token:renew()
81
+ writable()
82
+ @renew = true
83
+ return @this
84
+
85
+ Token:renewalRequested()
86
+ return @renew
87
+
67
88
  Token:writable()
68
89
  if @readonly
69
90
  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 < claims.iat * 1000 or claims.validatedAt > Date/now()
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()