@lango-project/lango-server 0.2.5 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,96 @@
1
+ # Browser startup and session expiration
2
+
3
+ Managed browser identity requires persistent SQL storage, a required HTTPS
4
+ origin and the existing `client` setting. A short-lived access JWT and the
5
+ server-owned HttpOnly cookie have different lifetimes. An expired access JWT
6
+ never authorizes a request or becomes valid again.
7
+
8
+ ## Bootstrap middleware
9
+
10
+ Mark a startup middleware explicitly:
11
+
12
+ ```lango
13
+ builder.addMiddleware("application-start", {
14
+ module: "@app/startup"
15
+ handler: "start"
16
+ bootstrap: true
17
+ })
18
+ ```
19
+
20
+ XML middleware declarations accept `bootstrap="true"`. A bootstrap middleware
21
+ can serve only exact anonymous endpoints without password freshness requirements.
22
+ Server enforces this before listening. It does not recognize UI names or assume
23
+ a particular URL. Lango UI's `configure()` registers this flag automatically;
24
+ handwritten `ui-start` declarations must include it.
25
+
26
+ The browser framework sends its cached opaque token as `X-Lango-Startup-Token`
27
+ on bootstrap, instead of using it as Authorization. Application client code does
28
+ not inspect JWT claims, manage cookies or choose a recovery mode.
29
+
30
+ * With managed identity, Server ignores this optional hint and uses the live
31
+ cookie record. A valid cookie produces clean claims for the same clientId and
32
+ forces Validate, even if a previous JWT was recently validated. Old permissions,
33
+ user identity, form claims and password timestamps are not copied from the hint.
34
+ * Without managed identity, Server verifies the hint as an ordinary JWT. This
35
+ preserves existing JWT-only deployments and local HTTP development. Expired,
36
+ malformed and incorrectly signed hints are rejected.
37
+ * A supplied Authorization header is always verified, including on bootstrap.
38
+ Cookie binding must match. An expired Authorization token is not replaced by a
39
+ cookie fallback; updated clients avoid sending it at startup.
40
+ * A missing cookie creates a new anonymous client. Unknown, expired, malformed
41
+ and mismatched cookies are rejected. A JWT hint cannot recover somebody else's
42
+ clientId or replace a rejected cookie. Hints on non-bootstrap endpoints are
43
+ rejected with `400 InvalidStartupRequest`.
44
+
45
+ Cookie continuity does not automatically restore application login. Validate is
46
+ still readonly; the application's existing guard can restore a remembered grant
47
+ from its authoritative database records before invoking the Start handler.
48
+ Revocation, account bans and selected-client logout must be checked there.
49
+ `authenticatedAt` must remain the original password-authentication timestamp;
50
+ token issuance, cookie continuity and renewal do not refresh it. UI creates a new
51
+ sessionId for each successful startup.
52
+
53
+ ## Expiration during use
54
+
55
+ After signature, issuer, audience and claim-shape checks, an expired token yields
56
+ `401` with `{ "error": "SessionExpired" }` and the reserved response header
57
+ `X-Lango-Session: expired`. Invalid signatures and other credential failures do
58
+ not receive this marker. Expiration detected while completing a request uses the
59
+ same result. Never infer that a failed response proves no side effect committed.
60
+
61
+ Lango Client freezes forms sharing that exact token, cancels their activities
62
+ and queued sends, and keeps their existing values visible. Unrelated tokens keep
63
+ working. Late responses and Ping renewals cannot revive frozen forms. The user
64
+ gets an explicit Reload page action; the original business request is not
65
+ automatically repeated. Reload starts a new bootstrap; it does not replay the old
66
+ form submission or promise to preserve the draft after navigation.
67
+ Fetch-level HTTP redirects are rejected, including same-origin redirects: they
68
+ cannot forward the startup hint or implicitly replay a POST. UI navigation uses
69
+ the explicit server commands instead.
70
+
71
+ The client removes only stored values equal to the expired token. A newer token
72
+ from another form or authentication generation is retained. Ping results can also
73
+ carry `reason: "SessionExpired"` for an individual expired token.
74
+
75
+ Expected expiration produces one informational HTTP completion record containing
76
+ the request ID and `reason=SessionExpired`. Signature, cookie, origin, validation
77
+ and authorization failures retain their warning/error handling. JWTs and cookie
78
+ secrets are not logged.
79
+
80
+ ## Replicas and deployment
81
+
82
+ All replicas share the existing `_lango_clients` SQL table, application grant
83
+ tables, and consistent JWT signing/verification configuration. Every bootstrap
84
+ reads the live cookie record and current application authorization. No additional
85
+ process-local session authority, sticky routing, Redis, or replica messaging is
86
+ introduced. The same cookie can bootstrap on another replica; revocation and
87
+ cookie rotation are observed through the shared database.
88
+
89
+ Deploy the matching Server, UI and browser Client versions together, publishing
90
+ Server first, then UI and Client. Refresh copied browser assets and update any
91
+ handwritten startup middleware declarations. Keep the HTTPS origin and persistent
92
+ client configuration enabled behind the TLS ingress.
93
+
94
+ HTTP/JWT-only development still rejects expired tokens and requires an explicit
95
+ reload. Without a valid persistent cookie it cannot securely recover the previous
96
+ anonymous clientId or remembered login from an expired JWT or a localStorage ID.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lango-project/lango-server",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "A small JSON HTTP server for Lango applications.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -33,11 +33,12 @@
33
33
  "clean": "lango run tools/clean.lango",
34
34
  "build:clean": "npm run clean && npm run build",
35
35
  "build": "lango build --project",
36
- "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 build src/test/execution_handlers.lango --out .test-output/execution_handlers.mjs && lango test src/test/executor.lango --build-dir .test-output/executor && lango test src/test/jobs.lango --build-dir .test-output/jobs && 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 && npm run test:security",
36
+ "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 build src/test/execution_handlers.lango --out .test-output/execution_handlers.mjs && lango test src/test/executor.lango --build-dir .test-output/executor && lango test src/test/jobs.lango --build-dir .test-output/jobs && 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 && npm run test:security && npm run test:bootstrap",
37
37
  "start": "node dist/cli/server.mjs examples/application",
38
38
  "prepack": "npm run build:clean",
39
39
  "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",
40
40
  "test:longpoll": "lango build src/test/longpoll_handlers.lango --out .test-output/longpoll_handlers.mjs && lango test src/test/longpoll.lango --build-dir .test-output/longpoll && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/standalone.lango --build-dir .test-output/standalone-longpoll",
41
+ "test:bootstrap": "lango build src/test/bootstrap_handlers.lango --out .test-output/bootstrap_handlers.mjs && lango test src/test/bootstrap.lango --build-dir .test-output/bootstrap",
41
42
  "test:middleware": "lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/middleware.lango --build-dir .test-output/middleware",
42
43
  "test:security": "lango build examples/security/handlers.lango --out .test-output/security-handlers.mjs && lango build examples/security/setup.lango --out examples/security/dist/setup.mjs --executable && lango test src/test/security.lango --build-dir .test-output/security",
43
44
  "test:jobs": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango test src/test/jobs.lango --build-dir .test-output/jobs",
@@ -28,7 +28,7 @@ Response:header(name, value)
28
28
  if !is_string(name) or !is_string(value)
29
29
  throw "Header name and value must be strings"
30
30
  name = name.toLowerCase()
31
- if contains(["x-lango-auth-change", "x-lango-need-login", "x-lango-token", "content-length", "transfer-encoding", "connection", "content-type"], name)
31
+ if contains(["x-lango-auth-change", "x-lango-need-login", "x-lango-token", "x-lango-session", "content-length", "transfer-encoding", "connection", "content-type"], name)
32
32
  throw "Reserved response header: ${name}"
33
33
  if name.includes("\r") or name.includes("\n") or value.includes("\r") or value.includes("\n")
34
34
  throw "Invalid response header"
@@ -6,12 +6,15 @@ routeInfo(definitions)
6
6
  kind = route.kind
7
7
  if kind == null
8
8
  kind = "endpoint"
9
- result.add({
9
+ info = {
10
10
  path: route.path
11
11
  kind: kind
12
12
  auth: route.auth
13
13
  policy: route.policy
14
14
  reauthSeconds: route.reauthSeconds
15
15
  middleware: route.middleware
16
- })
16
+ }
17
+ if route.bootstrap == true
18
+ info.bootstrap = true
19
+ result.add(info)
17
20
  return result
package/src/routes.lango CHANGED
@@ -99,17 +99,27 @@ Routes:addMiddleware(name, spec)
99
99
  if !is_object(spec) or is_array(spec)
100
100
  throw "Middleware requires a module and exported handler"
101
101
  for spec as key: value
102
- if key != "module" and key != "handler" and key != "validate"
102
+ if key != "module" and key != "handler" and key != "validate" and key != "bootstrap"
103
103
  throw "Unknown middleware option: ${key}"
104
104
  if !is_string(spec.handler) or spec.handler == ""
105
105
  throw "Middleware handler is required"
106
106
  if spec.validate != null and (!is_string(spec.validate) or spec.validate == "")
107
107
  throw "Middleware validate must name an exported function"
108
+ bootstrap = spec.bootstrap
109
+ if bootstrap == "true"
110
+ bootstrap = true
111
+ if bootstrap == "false"
112
+ bootstrap = false
113
+ if bootstrap != null and !is_bool(bootstrap)
114
+ throw "Middleware bootstrap must be boolean"
108
115
  @middlewares[name] = {
109
116
  module: resolveModule(spec.module, @root)
110
117
  handler: spec.handler
111
118
  validate: spec.validate
112
119
  }
120
+ if bootstrap == true
121
+ middleware = @middlewares[name]
122
+ middleware.bootstrap = true
113
123
  return @this
114
124
 
115
125
  Routes:middlewares()
@@ -143,7 +153,13 @@ Routes:xml(file)
143
153
  return @this
144
154
 
145
155
  Routes:definitions()
146
- return from_json(to_json(@items))
156
+ definitions = from_json(to_json(@items))
157
+ for definitions as route
158
+ if route.middleware != null and Object/hasOwn(@middlewares, route.middleware)
159
+ spec = @middlewares[route.middleware]
160
+ if spec.bootstrap == true
161
+ route.bootstrap = true
162
+ return definitions
147
163
 
148
164
  Routes:events()
149
165
  return from_json(to_json(@events))
@@ -256,7 +272,7 @@ Routes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack,
256
272
  leaf(tag)
257
273
  includeAt(spec, directory, prefix, stack, auth, policy, reauthSeconds)
258
274
  case "middleware"
259
- attributes(tag, ["name", "module", "handler", "validate"])
275
+ attributes(tag, ["name", "module", "handler", "validate", "bootstrap"])
260
276
  leaf(tag)
261
277
  if !allowEvents
262
278
  throw "Middleware declarations are only allowed in the application's root routes.xml"
@@ -264,6 +280,7 @@ Routes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack,
264
280
  module: resolveModule(spec.module, directory)
265
281
  handler: spec.handler
266
282
  validate: spec.validate
283
+ bootstrap: spec.bootstrap
267
284
  })
268
285
  case "event"
269
286
  attributes(tag, ["name", "module", "handler"])
package/src/runtime.lango CHANGED
@@ -133,11 +133,17 @@ Runtime:prepareRoute(pending, route)
133
133
  then(handler)
134
134
  capture route
135
135
  middleware = null
136
+ bootstrap = false
136
137
  name = route.middleware
137
138
  if name != null
138
139
  if !Object/hasOwn(@middlewares, name)
139
140
  throw "Middleware is not registered: ${name}"
140
141
  middleware = @middlewares[name]
142
+ specs = @definition.middlewares
143
+ spec = specs[name]
144
+ bootstrap = spec.bootstrap == true
145
+ if bootstrap and (route.policy != "anonymous" or route.reauthSeconds > 0 or route.path.includes("*") or route.path.includes("{") or route.path.includes("}"))
146
+ throw "Bootstrap middleware requires an exact anonymous endpoint without reauthentication"
141
147
  @routes.add({
142
148
  path: route.path
143
149
  pattern: routePattern(route.path)
@@ -147,6 +153,7 @@ Runtime:prepareRoute(pending, route)
147
153
  legacyAuth: route.legacyAuth
148
154
  handler: handler
149
155
  middleware: middleware
156
+ bootstrap: bootstrap
150
157
  })
151
158
  return null
152
159
 
@@ -190,19 +197,31 @@ Runtime:handle(task)
190
197
  context log
191
198
  if !originAllowed(@definition.settings.origin, request)
192
199
  return failure(403, "OriginRejected")
193
- fresh = request.headers.authorization == null
200
+ matched = match(request.path)
201
+ bootstrap = false
202
+ if matched != null
203
+ selectedRoute = matched.route
204
+ bootstrap = selectedRoute.bootstrap == true
205
+ authorization = request.headers.authorization
206
+ hint = request.headers["x-lango-startup-token"]
207
+ if authorization == null and bootstrap and @clients == null and hint != null
208
+ authorization = "Bearer ${hint}"
209
+ fresh = authorization == null
194
210
  claims = null
195
211
  try
196
212
  if !fresh
197
- claims = @tokens.read(request.headers.authorization)
213
+ claims = @tokens.read(authorization)
198
214
  catch error
215
+ if error == "TokenExpired"
216
+ return expiredSession()
199
217
  log.warn("[${request.id}] ${request.method} ${request.path} Authorization rejected before handler: ${errorMessage(error)}")
200
218
  return failure(401, "Unauthorized")
201
- matched = match(request.path)
202
219
  if matched == null
203
220
  trace("[${request.id}] No route matched ${request.path}")
204
221
  return failure(404, "RouteNotFound")
205
222
  route = matched.route
223
+ if hint != null and !bootstrap
224
+ return failure(400, "InvalidStartupRequest")
206
225
  metadata = routeInfo([route])
207
226
  selected = Object/freeze(metadata[0])
208
227
  context request = Object/freeze(Object/assign({}, request, {
@@ -226,6 +245,10 @@ Runtime:handle(task)
226
245
  try
227
246
  if @clients != null
228
247
  context clientIdentity = @clients.begin(claims, @tokens)
248
+ if bootstrap and !clientIdentity.fresh
249
+ clientIdentity.claims = @tokens.create(clientIdentity.claims.clientId)
250
+ clientIdentity.claims.clientProof = clientIdentity.hash
251
+ clientIdentity.restored = true
229
252
  claims = clientIdentity.claims
230
253
  fresh = clientIdentity.fresh
231
254
  restored = clientIdentity.restored
@@ -358,7 +381,9 @@ Runtime:process(task, route, input, claims, fresh, restored)
358
381
  closeScope(db, false)
359
382
  if is_kindof(error, HttpFailure)
360
383
  return error.result()
361
- if error == "TokenExpired" or (is_object(error) and error.status == 401)
384
+ if error == "TokenExpired"
385
+ return expiredSession()
386
+ if is_object(error) and error.status == 401
362
387
  log.warn("${requestIdentity(request.id, token)} ${request.method} ${request.path} Authorization or validation rejected: Unauthorized")
363
388
  return failure(401, "Unauthorized")
364
389
  log.err("${requestIdentity(request.id, token)} Request failed: ${errorDetails(error)}")
@@ -405,11 +430,10 @@ Runtime:refreshOne(pending, results, encoded, owner, child)
405
430
  capture encoded
406
431
  capture owner
407
432
  capture child
408
- checked = null
409
- try
410
- checked = @tokens.read("Bearer ${encoded}")
411
- catch error
412
- return failure(401, "Unauthorized")
433
+ read = readRefreshToken(encoded)
434
+ if read.rejection != null
435
+ return read.rejection
436
+ checked = read.claims
413
437
  if checked.clientId != owner
414
438
  return failure(401, "Unauthorized")
415
439
  return handle({
@@ -423,13 +447,29 @@ Runtime:refreshOne(pending, results, encoded, owner, child)
423
447
  updated = null
424
448
  if result.status < 400
425
449
  updated = result.headers["x-lango-token"]
426
- results.add({
450
+ item = {
427
451
  previous: encoded
428
452
  token: updated
429
453
  status: result.status
430
- })
454
+ }
455
+ if result.headers["x-lango-session"] == "expired"
456
+ item.reason = "SessionExpired"
457
+ results.add(item)
431
458
  return null
432
459
 
460
+ Runtime:readRefreshToken(encoded)
461
+ try
462
+ return {
463
+ claims: @tokens.read("Bearer ${encoded}")
464
+ }
465
+ catch error
466
+ rejected = failure(401, "Unauthorized")
467
+ if error == "TokenExpired"
468
+ rejected = expiredSession()
469
+ return {
470
+ rejection: rejected
471
+ }
472
+
433
473
  Runtime:event(name, input)
434
474
  if !(name in @events)
435
475
  return null
@@ -540,6 +580,11 @@ failure(status, code)
540
580
  })
541
581
  }
542
582
 
583
+ expiredSession()
584
+ result = failure(401, "SessionExpired")
585
+ result.headers["x-lango-session"] = "expired"
586
+ return result
587
+
543
588
  stampValidation(claims, validatedAt)
544
589
  claims.validatedAt = validatedAt
545
590
  return null
package/src/server.lango CHANGED
@@ -2,7 +2,7 @@ import "./policy"
2
2
  resolvePolicies(routes, registry)
3
3
  import "./trace"
4
4
  trace(message)
5
- responseLog(id, method, path, status)
5
+ responseLog(id, method, path, status, session = null)
6
6
  import "./longpoll_broker"
7
7
  class LongpollBroker
8
8
  import "./longpoll_session"
@@ -255,7 +255,7 @@ Server:trackResponse(req, res)
255
255
  return null
256
256
  state.done = true
257
257
  if res.writableFinished
258
- responseLog(res.langoRequestId, req.method, target, res.statusCode)
258
+ responseLog(res.langoRequestId, req.method, target, res.statusCode, res.langoSession)
259
259
  else
260
260
  trace("HTTP ${req.method} ${target} connection closed before response completed")
261
261
  record.active = record.active - 1
@@ -580,6 +580,7 @@ write(res, result)
580
580
  if res.destroyed or res.writableEnded
581
581
  return null
582
582
  try
583
+ res.langoSession = result.headers["x-lango-session"]
583
584
  res.writeHead(result.status, result.headers)
584
585
  res.end(result.body)
585
586
  catch error
package/src/tokens.lango CHANGED
@@ -51,10 +51,12 @@ Tokens:read(header)
51
51
  keys = settings.keys
52
52
  if !Object/hasOwn(keys, head.kid)
53
53
  throw "InvalidToken"
54
+ # Classify expiration only after verifying the signature, issuer and audience.
54
55
  claims = jwt/default/verify(encoded, keys[head.kid], {
55
56
  algorithms: ["HS256"]
56
57
  issuer: settings.issuer
57
58
  audience: settings.audience
59
+ ignoreExpiration: true
58
60
  })
59
61
  if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == "" or !is_string(claims.auth)
60
62
  throw "InvalidToken"
@@ -62,6 +64,8 @@ Tokens:read(header)
62
64
  throw "InvalidToken"
63
65
  if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt < 0 or claims.validatedAt > Date/now()
64
66
  throw "InvalidToken"
67
+ if claims.exp * 1000 <= Date/now()
68
+ throw "TokenExpired"
65
69
  return claims
66
70
 
67
71
  Tokens:renew(claims)
package/src/trace.lango CHANGED
@@ -1,5 +1,5 @@
1
1
  export trace(message)
2
- export responseLog(id, method, path, status)
2
+ export responseLog(id, method, path, status, session = null)
3
3
 
4
4
  trace(message)
5
5
  context log
@@ -8,11 +8,14 @@ trace(message)
8
8
  return null
9
9
 
10
10
 
11
- responseLog(id, method, path, status)
11
+ responseLog(id, method, path, status, session = null)
12
12
  context log
13
13
  message = "HTTP ${method} ${path} completed status=${status}"
14
14
  if id != null
15
15
  message = "[${id}] ${message}"
16
+ if status == 401 and session == "expired"
17
+ log.info("${message} reason=SessionExpired")
18
+ return null
16
19
  if status >= 500
17
20
  log.err(message)
18
21
  else