@lango-project/lango-server 0.2.0 → 0.2.3

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 (121) hide show
  1. package/README.md +290 -27
  2. package/dist/.lango/runtime.mjs +24 -1
  3. package/dist/body_reader.mjs +15 -14
  4. package/dist/body_reader.mjs.map +1 -1
  5. package/dist/cli/.lango/runtime.mjs +24 -1
  6. package/dist/cli/body_reader.mjs +15 -14
  7. package/dist/cli/body_reader.mjs.map +1 -1
  8. package/dist/cli/client_identity.mjs +250 -0
  9. package/dist/cli/client_identity.mjs.map +1 -0
  10. package/dist/cli/database.mjs +23 -8
  11. package/dist/cli/database.mjs.map +1 -1
  12. package/dist/cli/endpoint.mjs +11 -7
  13. package/dist/cli/endpoint.mjs.map +1 -1
  14. package/dist/cli/error_details.mjs +45 -0
  15. package/dist/cli/error_details.mjs.map +1 -0
  16. package/dist/cli/longpoll_broker.mjs +9 -8
  17. package/dist/cli/longpoll_broker.mjs.map +1 -1
  18. package/dist/cli/longpoll_options.mjs +8 -7
  19. package/dist/cli/longpoll_options.mjs.map +1 -1
  20. package/dist/cli/longpoll_session.mjs +11 -10
  21. package/dist/cli/longpoll_session.mjs.map +1 -1
  22. package/dist/cli/options.mjs +29 -3
  23. package/dist/cli/options.mjs.map +1 -1
  24. package/dist/cli/origin.mjs +87 -0
  25. package/dist/cli/origin.mjs.map +1 -0
  26. package/dist/cli/policy.mjs +121 -0
  27. package/dist/cli/policy.mjs.map +1 -0
  28. package/dist/cli/postgres_adapter.mjs +3 -2
  29. package/dist/cli/postgres_adapter.mjs.map +1 -1
  30. package/dist/cli/routes.mjs +33 -17
  31. package/dist/cli/routes.mjs.map +1 -1
  32. package/dist/cli/server.mjs +148 -101
  33. package/dist/cli/server.mjs.map +1 -1
  34. package/dist/cli/static_files.mjs +7 -4
  35. package/dist/cli/static_files.mjs.map +1 -1
  36. package/dist/cli/trace.mjs +53 -0
  37. package/dist/cli/trace.mjs.map +1 -0
  38. package/dist/client_identity.mjs +250 -0
  39. package/dist/client_identity.mjs.map +1 -0
  40. package/dist/database.mjs +23 -8
  41. package/dist/database.mjs.map +1 -1
  42. package/dist/endpoint.mjs +11 -7
  43. package/dist/endpoint.mjs.map +1 -1
  44. package/dist/error_details.mjs +45 -0
  45. package/dist/error_details.mjs.map +1 -0
  46. package/dist/group.mjs +34 -16
  47. package/dist/group.mjs.map +1 -1
  48. package/dist/http_failure.mjs +9 -2
  49. package/dist/http_failure.mjs.map +1 -1
  50. package/dist/longpoll_broker.mjs +9 -8
  51. package/dist/longpoll_broker.mjs.map +1 -1
  52. package/dist/longpoll_options.mjs +8 -7
  53. package/dist/longpoll_options.mjs.map +1 -1
  54. package/dist/longpoll_session.mjs +11 -10
  55. package/dist/longpoll_session.mjs.map +1 -1
  56. package/dist/options.mjs +29 -3
  57. package/dist/options.mjs.map +1 -1
  58. package/dist/origin.mjs +87 -0
  59. package/dist/origin.mjs.map +1 -0
  60. package/dist/policy.mjs +121 -0
  61. package/dist/policy.mjs.map +1 -0
  62. package/dist/postgres_adapter.mjs +3 -2
  63. package/dist/postgres_adapter.mjs.map +1 -1
  64. package/dist/postgres_worker.mjs +15 -14
  65. package/dist/postgres_worker.mjs.map +1 -1
  66. package/dist/request_identity.mjs +22 -0
  67. package/dist/request_identity.mjs.map +1 -0
  68. package/dist/response.mjs +1 -1
  69. package/dist/response.mjs.map +1 -1
  70. package/dist/route_info.mjs +1 -1
  71. package/dist/route_info.mjs.map +1 -1
  72. package/dist/routes.mjs +33 -17
  73. package/dist/routes.mjs.map +1 -1
  74. package/dist/runtime.mjs +241 -110
  75. package/dist/runtime.mjs.map +1 -1
  76. package/dist/server.mjs +148 -101
  77. package/dist/server.mjs.map +1 -1
  78. package/dist/server_context.mjs +21 -9
  79. package/dist/server_context.mjs.map +1 -1
  80. package/dist/static_files.mjs +7 -4
  81. package/dist/static_files.mjs.map +1 -1
  82. package/dist/token.mjs +34 -7
  83. package/dist/token.mjs.map +1 -1
  84. package/dist/tokens.mjs +11 -2
  85. package/dist/tokens.mjs.map +1 -1
  86. package/dist/trace.mjs +53 -0
  87. package/dist/trace.mjs.map +1 -0
  88. package/dist/worker.mjs +8 -6
  89. package/dist/worker.mjs.map +1 -1
  90. package/docs/security.md +420 -0
  91. package/examples/security/README.md +160 -0
  92. package/examples/security/deploy.xml +12 -0
  93. package/examples/security/handlers.lango +610 -0
  94. package/examples/security/package.json +19 -0
  95. package/examples/security/passwords.lango +61 -0
  96. package/examples/security/routes.xml +14 -0
  97. package/examples/security/schema.lango +91 -0
  98. package/examples/security/setup.lango +30 -0
  99. package/package.json +12 -6
  100. package/src/client_identity.lango +184 -0
  101. package/src/database.lango +15 -4
  102. package/src/endpoint.lango +12 -5
  103. package/src/error_details.lango +21 -0
  104. package/src/group.lango +25 -21
  105. package/src/http_failure.lango +9 -5
  106. package/src/longpoll_options.lango +11 -5
  107. package/src/options.lango +34 -1
  108. package/src/origin.lango +56 -0
  109. package/src/policy.lango +84 -0
  110. package/src/request_identity.lango +9 -0
  111. package/src/response.lango +1 -1
  112. package/src/route_info.lango +2 -0
  113. package/src/routes.lango +30 -15
  114. package/src/runtime.lango +149 -77
  115. package/src/server.lango +48 -7
  116. package/src/server_context.lango +10 -2
  117. package/src/static_files.lango +3 -0
  118. package/src/token.lango +26 -5
  119. package/src/tokens.lango +10 -3
  120. package/src/trace.lango +23 -0
  121. package/src/worker.lango +1 -0
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # Lango Server
2
2
 
3
- A JSON HTTP server written in Lango. Its public package API contains two classes:
4
- `Server` and `Builder`. Application handlers are exported functions identified by
3
+ A JSON HTTP server written in Lango. Its public package API contains the `Server`
4
+ and `Builder` classes. Application handlers are exported functions identified by
5
5
  module and function names. Each request runs in one worker; worker setup stays
6
6
  inside the server.
7
7
 
@@ -76,9 +76,9 @@ never publish token changes. Private exception details are not sent to clients.
76
76
 
77
77
  A worker processes one request at a time, including its Promise and events.
78
78
  Synchronous work does not block the main HTTP loop. Promise callbacks still use
79
- Lango's explicit `capture` rules; capture any contexts needed by later callbacks.
79
+ Lango's explicit `capture` rules for ordinary locals; active contexts propagate automatically.
80
80
  Workers retain their loaded modules between requests. Module-level state is
81
- worker-local, not shared or client-specific. An optional configured SQL database is available through `context db`; application schema and migrations remain application-owned.
81
+ worker-local, not shared or client-specific. An optional configured database is used automatically by SQL; application schema and migrations remain application-owned.
82
82
 
83
83
  ## Static files
84
84
 
@@ -152,7 +152,7 @@ JWT authorization applies to POST handlers; static files are public.
152
152
  ```
153
153
 
154
154
  * Every endpoint has a module and exported function name. A group can supply the
155
- module and auth permission to its children. Includes inherit group auth as a
155
+ module, policy and password freshness to its children. Includes inherit these as
156
156
  default; explicit permissions inside an included file still take precedence.
157
157
  The including group does not supply handler modules across the package boundary. No handler is looked up in the
158
158
  launcher module. Absolute or relative file modules are also accepted for
@@ -334,7 +334,7 @@ a thrown/rejected error fails startup. Validators run without request contexts;
334
334
  they check configuration rather than handling requests.
335
335
 
336
336
  Inside request handlers and middleware, `context server` also provides
337
- `routes()`. It returns a fresh array of `{ path, kind, auth, middleware }` records,
337
+ `routes()`. It returns a fresh array of `{ path, kind, policy, reauthSeconds, auth, middleware }` records,
338
338
  where kind is `endpoint` or `longpoll`. Module paths and handler names are not
339
339
  exposed. Mutating a snapshot cannot change routing. Startup validators receive
340
340
  the same metadata shape, allowing libraries to discover their configured URLs
@@ -369,6 +369,14 @@ in the worker. Request events observe that final serialized result. Middleware,
369
369
  handler and serialization errors follow the existing error/token behavior;
370
370
  request/event deadlines and SQL transaction cleanup still apply.
371
371
 
372
+ Unexpected failures are logged through `context log` with the request ID, the
373
+ request token's `clientId`, and optional `sessionId` and `userId` claims when
374
+ non-null. The original error message and stack trace are included when available. Workers enable Node source
375
+ maps so compiled application errors point to their `.lango` source when matching
376
+ `.mjs.map` files are deployed. Keep these files alongside the compiled modules.
377
+ HTTP clients receive the generic `InternalServerError` response; internal error
378
+ messages and stack traces remain in the server logs.
379
+
372
380
  ## Configuration
373
381
 
374
382
  ```xml
@@ -401,18 +409,56 @@ contain at least 32 characters and should be cryptographically random. Only
401
409
  HS256 is accepted; algorithm, key ID, issuer, audience, expiry, and server-owned
402
410
  timestamps are checked. Keys are never generated or stored by the server.
403
411
 
412
+ ## Origin policy
413
+
414
+ Origin checks are an optional server deployment policy, applied to JSON endpoint
415
+ requests before token processing, lifecycle events and handlers:
416
+
417
+ ```xml
418
+ <origin url="https://app.example.com" required="true"/>
419
+ ```
420
+
421
+ Use `urlEnv="LANGO_ORIGIN"` instead of `url` to read the external origin from an
422
+ environment variable. The two attributes are mutually exclusive. Builder accepts
423
+ `origin: { url: "https://app.example.com", required: true }` in its configuration.
424
+ The URL must be an exact HTTP/HTTPS origin without a trailing slash, credentials,
425
+ path, query or fragment. Configure the externally visible origin when behind a
426
+ proxy; the server never infers it from Host or forwarded headers.
427
+
428
+ `required` defaults to true: missing, literal-null and unrelated Origin headers
429
+ produce 403 `OriginRejected`. With `required=false`, requests without Origin are
430
+ allowed, but a supplied Origin must still match. When Sec-Fetch-Site is present,
431
+ only `same-origin` and `none` are accepted. This is a same-origin policy, not a
432
+ cross-origin/CORS allowlist. Origin is not an authentication credential.
433
+
434
+ Without an origin section, no Origin/Fetch Metadata policy is imposed. Static
435
+ GET/HEAD serving remains independent. The security example enables the policy;
436
+ its application code does not parse or validate these headers.
437
+
404
438
  ## Contexts and authorization
405
439
 
406
440
  Handlers and events can declare `context request`, `response`, `token`, and `log`.
407
441
  Request metadata is read-only: `id`, `method`, `path`, `headers`, `remoteAddress`.
408
- Response supports `status(code)`, `header(name, value)` and `reject(status, code)`;
409
- the handler return value supplies its JSON body. Transport/token headers remain
410
- server-owned. `reject` throws a controlled HTTP failure (400–599) with a short
411
- error code, for example `response.reject(400, "InvalidInput")`. Codes start with
412
- an ASCII letter and contain at most 64 letters, digits or underscores. Configured
413
- response headers are preserved. Rejections roll back open SQL transactions and
414
- send `{ error: code }` without a token; committed side effects are not undone.
415
- Unexpected exceptions still produce a generic 500.
442
+ Response supports `status(code)`, `header(name, value)` and `reject(status, code)`.
443
+ The handler's normal return value supplies its JSON body. To reject a request:
444
+
445
+ ```lango
446
+ restricted(input)
447
+ context response
448
+ response.reject(401, "InvalidCredentials")
449
+ ```
450
+
451
+ `reject` throws a controlled `HttpFailure` and stops the current execution path;
452
+ it does not return a response value. The server sends status 401 and
453
+ `{ "error": "InvalidCredentials" }` for this example. Status must be an integer
454
+ from 400 to 599. Codes start with an ASCII letter and contain at most 64 ASCII
455
+ letters, digits or underscores. Invalid arguments produce a generic 500.
456
+
457
+ Controlled rejections roll back open SQL transactions and publish no token or
458
+ token changes. Already committed side effects are not undone. Response headers
459
+ are preserved, and 401 includes `WWW-Authenticate: Bearer`. This behavior also
460
+ applies to middleware, synchronous helpers and Lango callbacks. Transport/token
461
+ headers remain server-owned. Unexpected exceptions still produce a generic 500.
416
462
 
417
463
  Tokens arrive in `Authorization: Bearer <jwt>` and successful replies contain
418
464
  `X-Lango-Token`. Missing tokens create an anonymous identity with a UUID
@@ -422,17 +468,18 @@ Unauthorized requests do not receive a newly created token.
422
468
 
423
469
  `context token` supports:
424
470
 
425
- * `clientId?`, `auth?`, `expiresAt?`: getter-only identity, comma-separated
426
- permissions and expiry. Direct assignment is rejected, including JavaScript
471
+ * `clientId?`, `auth?`, `policies?`, `expiresAt?`: getter-only identity, comma-separated
472
+ permissions, a copied policy array and expiry. Direct assignment is rejected, including JavaScript
427
473
  attempts to shadow these properties. Use the controlled methods below to update
428
474
  claims or permissions.
429
- * `AddAuth("login")`, `clearAuth()`, `hasAuth("admin")`: exact trimmed membership.
475
+ * `addPolicy("login")`, `clearPolicies()`, `hasPolicy("admin")`: exact trimmed membership.
476
+ `AddAuth`, `clearAuth` and `hasAuth` remain compatibility aliases.
430
477
  * `get(name)`, `set(name, value)`: JSON custom claims; server-owned JWT fields are
431
478
  protected. `get` returns a copy for structured values.
432
479
  * `renew()`: requests renewal after successful serialization and SQL cleanup on
433
480
  a reply with a status below 400. It does not immediately change `expiresAt?`.
434
481
 
435
- Default endpoint auth is `login`. `auth="anonymous"` permits anonymous callers;
482
+ Default endpoint policy is `login`. `policy="anonymous"` permits anonymous callers;
436
483
  other values require that exact permission. `admin` does not imply `login`.
437
484
  The application authenticates credentials and grants permissions. These methods
438
485
  do not authenticate anyone automatically.
@@ -452,17 +499,166 @@ before renewal and signing; an expired token cannot be revived. Failed or
452
499
  rejected requests publish no renewal. Previously issued tokens remain valid
453
500
  until their own expiry unless the application's Validate policy revokes them.
454
501
 
502
+ ## Built-in route policies
503
+
504
+ Policy checks are a built-in Server feature, applied on every request before
505
+ middleware and handlers. They do not require a security middleware registration:
506
+
507
+ ```xml
508
+ <endpoint path="/admin" module="@shop/admin" handler="home"
509
+ policy="admin" reauthSeconds="300"/>
510
+ ```
511
+
512
+ After verifying login credentials, trusted application code grants policies:
513
+
514
+ ```lango
515
+ import js global Date
516
+
517
+ context token
518
+ token.addPolicy("login")
519
+ token.addPolicy("admin")
520
+ token.set("authenticatedAt", Date/now())
521
+ ```
522
+
523
+ `authenticatedAt` must be the actual password-authentication time as epoch
524
+ milliseconds, recorded by trusted server code (for example `Date/now()` after
525
+ `import js global Date`). Never copy this value from client input. Token refresh does not change
526
+ this timestamp. `reauthSeconds` is the maximum permitted age; missing, invalid,
527
+ future or stale timestamps produce 403 `ReauthenticationRequired`. Zero disables
528
+ this extra condition. Membership and freshness checks are independent of the
529
+ Validate event's freshness interval.
530
+
531
+ `policy="anonymous"` explicitly permits anonymous requests. Otherwise one exact
532
+ policy membership is required; there is no implicit role hierarchy. Missing
533
+ `login` gives 401 `LoginRequired`; other missing policies give 403 `Forbidden`.
534
+ Without a policy/auth declaration, the default remains login. Policies and
535
+ reauthSeconds are inherited through groups/includes; an endpoint can override
536
+ them, including explicit `reauthSeconds="0"`.
537
+
538
+ Declare shared requirements in `deploy.xml` to avoid repeating durations:
539
+
540
+ ```xml
541
+ <policies reauthSeconds="43200">
542
+ <policy name="login"/>
543
+ <policy name="admin" reauthSeconds="300"/>
544
+ </policies>
545
+ ```
546
+
547
+ The declaration is a child of `<deploy>`. `anonymous` is built in and exempt from
548
+ freshness. Named policies inherit the section default unless they specify their
549
+ own duration. All protected route policies must be declared when this section is
550
+ present; undefined names fail startup. Without this section, existing route-level
551
+ configuration continues to work. Builder configuration uses `policies: {
552
+ reauthSeconds, items: [{ name, reauthSeconds }] }` with the same rules.
553
+
554
+ An omitted endpoint/group duration inherits the selected policy requirement.
555
+ An explicit duration may shorten it but cannot lengthen or disable a positive
556
+ policy requirement. The effective requirement is resolved before route validators
557
+ and worker startup. `0` at the policy level disables freshness for that policy.
558
+ There is one shared `authenticatedAt`, not a timestamp per policy: any successful
559
+ password verification refreshes the same time for all policy checks. Merely
560
+ visiting a protected endpoint never refreshes it.
561
+
562
+ Login/password-confirmation handlers must remain reachable while authentication
563
+ is stale, normally with `policy="anonymous"`. They must verify credentials and,
564
+ for reauthentication, the current account/grant themselves. Do not try to disable
565
+ a central policy requirement on the password-confirmation endpoint.
566
+
567
+ Only the built-in pre-handler gate returns `x-lango-need-login: 1` with a
568
+ `needLogin` response map (reason, path, policy, reauthSeconds, userId). Missing login
569
+ or stale authentication can then invoke the optional UI needLogin event. Missing
570
+ permissions on an already logged-in token, invalid tokens, bans and ordinary
571
+ handler failures do not carry this marker. The client may replay a challenged
572
+ form request once after login; it never retries network failures. Reauthentication
573
+ replays also send `X-Lango-Expected-User`, which Server compares with the signed
574
+ userId before invoking the handler; a mismatch returns 409 `IdentityChanged`.
575
+
576
+ Builder endpoint/group/longpoll maps accept `policy` and `reauthSeconds` too.
577
+ Handlers/middleware can read frozen `request.route` metadata containing the matched
578
+ path, kind, policy and reauthSeconds (without module/handler internals). The metadata
579
+ comes from server route configuration, independently of request input.
580
+
581
+ Token supports `addPolicy(name)`, `hasPolicy(name)`, `clearPolicies()` and the
582
+ readonly `policies?` snapshot. The existing auth XML/Builder field and
583
+ AddAuth/hasAuth/clearAuth methods remain compatibility aliases over the same signed
584
+ JWT auth claim; no separate permission store is introduced. Conflicting auth and
585
+ policy declarations fail configuration. Legacy auth retains its existing 401
586
+ denial behavior.
587
+
588
+ A signed policy membership is not proof that an account is still enabled or that
589
+ its live DB role is unchanged. Applications with immediate ban/revocation or
590
+ resource-ownership requirements retain those live checks in their guard. Server
591
+ does not assume an application user/grant schema. The security example keeps
592
+ those business checks and transactions in its guard, while route policy selection
593
+ and the generic policy/freshness gate belong to Server.
594
+
595
+ ## Managed client identity
596
+
597
+ Browser deployments can delegate client continuity and cookie binding to Server:
598
+
599
+ ```xml
600
+ <client maxAgeSeconds="2592000"/>
601
+ <origin urlEnv="LANGO_ORIGIN" required="true"/>
602
+ <database type="sqlite" file="data/application.sqlite"/>
603
+ ```
604
+
605
+ Builder accepts `client: { maxAgeSeconds: 2592000 }`. The lifetime defaults to
606
+ 30 days and is refreshed on successful replies. Enabling this feature requires
607
+ persistent database storage and a required HTTPS origin. Without a client section,
608
+ existing JWT-only applications retain their previous behavior.
609
+
610
+ Server generates a 256-bit opaque `__Host-lango-client` cookie with Secure,
611
+ HttpOnly, SameSite=Strict and Path=/ attributes, and no Domain. It stores only the
612
+ credential hash and expiry in its owned `_lango_clients` table. All workers/pods
613
+ must share that database. The table is initialized before workers start; application
614
+ code must not read or update it. The reserved JWT `clientProof` claim binds a
615
+ Bearer token to the matching live cookie record. Application token setters cannot
616
+ change that claim. Unknown, expired, malformed, duplicate or mismatched credentials
617
+ fail before application events/handlers.
618
+
619
+ A first tokenless request without a cookie creates a clientId and invokes Register.
620
+ A tokenless request with a valid cookie gets a clean token for the same clientId:
621
+ permissions and application claims are empty, Register is skipped, and Validate
622
+ runs without its normal freshness shortcut. Invalid/expired supplied JWTs still
623
+ fail; Server never silently falls back to the cookie. Requests are not retried.
624
+ There is no application identity-restoration event or cookie parser to implement.
625
+
626
+ After login or password confirmation, the application requests credential renewal:
627
+
628
+ ```lango
629
+ context server
630
+ server.rotateClient()
631
+ ```
632
+
633
+ Server performs the rotation when preparing a successful response, keeping the
634
+ same clientId. The old cookie and old JWT binding then fail. Failed requests do
635
+ not rotate credentials or publish a token. Pending requests authorized before a
636
+ rotation can have already committed side effects; rejected operations are not
637
+ implicitly retried. Other forms/tabs need an explicit reinitialization flow.
638
+ Rotation is available only within the active managed client request scope.
639
+
640
+ The security example uses this mechanism; its tables retain user/grant/quota/audit
641
+ policy, not cookie storage. Cookie theft remains credential theft: with a remembered
642
+ application grant it may restore a normal login. Cookie flags and identity binding
643
+ do not make active XSS harmless. See [OWASP session management](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html).
644
+
455
645
  ## Events
456
646
 
457
647
  Event modules and function names are strings, resolved during worker startup.
458
648
  Promise results are supported, and events run under the request's contexts.
459
649
 
460
- * **register(input)** runs for a tokenless request after assigning `clientId`,
461
- before endpoint authorization. It can initialize custom token claims. Failure
650
+ * **register(input)** runs for a new client after assigning `clientId`,
651
+ before endpoint authorization. Its input is a shallow copy of the decoded
652
+ request input (including path parameters), with server-observed `ip` and
653
+ `userAgent` fields overriding any same-named JSON/path fields. `ip` is the
654
+ socket peer address; forwarded headers are not trusted. `userAgent` is the
655
+ User-Agent header (null when absent), not an authenticated identity. These
656
+ additions do not change the endpoint's original input. It can initialize custom
657
+ token claims. Failure
462
658
  prevents the handler and publishes no token. Return values are ignored; throw
463
659
  or reject to fail registration. It is not an account-creation
464
- guarantee: callers can omit tokens, so application side effects need their own
465
- policy. No Register event is required.
660
+ guarantee: JWT-only callers can omit tokens, and callers can discard cookies,
661
+ so application side effects need their own policy. No Register event is required.
466
662
  * **validate(input)** receives null and runs after standard JWT verification
467
663
  when the signed `validatedAt` is at least one second old. It receives a read-only
468
664
  token. Only `true` continues; `false` produces 401. Exceptions, invalid return
@@ -483,7 +679,7 @@ Promise results are supported, and events run under the request's contexts.
483
679
  the successful response. Enabling this event exposes application input/output
484
680
  to its configured handler; redact credentials and other sensitive fields there.
485
681
 
486
- Each event has `eventTimeoutMs`. The request deadline covers queueing, Register,
682
+ Each event has `eventTimeoutMs`. The request deadline covers queueing, client verification, Register,
487
683
  Validate, and the handler; Request has its own event deadline after the result is
488
684
  prepared. A hard timeout terminates the worker and the pool replaces it. Tasks
489
685
  are never automatically retried: worker termination cannot roll back completed
@@ -563,7 +759,7 @@ builder.configure({
563
759
  ```
564
760
 
565
761
  Each request worker owns one persistent connection. The server creates a fresh
566
- DB scope before Register/Validate and keeps it available to the handler. Request
762
+ DB scope before client verification/Register/Validate and keeps it available to the handler. Request
567
763
  gets a separate clean scope after the handler result is serialized. Scopes cannot
568
764
  be reused after completion. Physical connections are released on shutdown; worker
569
765
  replacement discards the old connection and creates a new one. If DB configuration
@@ -574,7 +770,6 @@ Application code uses Lango SQL rather than a driver API:
574
770
 
575
771
  ```lango
576
772
  findCustomer(input)
577
- context db
578
773
  row = SQL
579
774
  select id, name from customer where id = :id
580
775
  row.id = input.id
@@ -589,8 +784,11 @@ findCustomer(input)
589
784
 
590
785
  **Build all SQL application modules with lango-js 0.1.13 or newer.** SQL and
591
786
  `start_trans()`, `commit_trans()`, `rollback_trans()`, `trans_state()` use the active
592
- db context across separately compiled runtime copies. Promise callbacks that use
593
- SQL should declare/capture db using the normal context capture rules.
787
+ database context across separately compiled runtime copies. SQL functions do not
788
+ need a `context db` declaration. Declare it only when directly accessing the scope
789
+ object. All active contexts propagate to Lango callbacks automatically, including
790
+ when SQL is used only by a downstream function. No `capture db` is needed.
791
+ A callback cannot reuse a database scope after that scope has closed.
594
792
 
595
793
  Transactions are explicit. The server never implicitly commits a transaction.
596
794
  An open transaction at successful scope completion is rolled back and reported as
@@ -840,3 +1038,68 @@ There is no automatic retry.
840
1038
 
841
1039
  Request auditing runs once for the physical batch response, not once per internal
842
1040
  item; an internal result cannot replace the prepared outer HTTP reply.
1041
+
1042
+
1043
+ ## Verbose diagnostics
1044
+
1045
+ Run `lango-server <application-directory> --verbose` (or `npm start -- --verbose`
1046
+ in a generated UI application). The flag can appear before or after the directory.
1047
+ It enables `LANGO_VERBOSE=1` for the server process and its workers. Normal startup
1048
+ keeps debug logs disabled. `LANGO_VERBOSE=1` also enables diagnostics for a server
1049
+ started through its library API.
1050
+
1051
+ Verbose logs show configuration loading, worker module/export resolution, HTTP
1052
+ request paths, queue/dispatch stages, matched routes, handler invocation and
1053
+ response status. Verified request identity is included once available. Request
1054
+ bodies, authorization headers, signing keys and raw JWTs are not logged.
1055
+
1056
+ ```lango
1057
+ context log
1058
+ if log.verbose?
1059
+ log.debug("Preparing optional diagnostic details")
1060
+ ```
1061
+
1062
+ `log.verbose?` is readonly. `debug()` is filtered automatically, while `info()`,
1063
+ `warn()` and `err()` remain enabled. Rebuild application modules with Lango JS
1064
+ 0.1.17 or newer to give their default log objects the same verbose behavior.
1065
+
1066
+
1067
+ For browser startup, GET / serves the static HTML shell; it does not invoke an
1068
+ application handler. Browser modules subsequently POST / to bootstrap and POST
1069
+ /index (or the selected page path) to request the view. Verbose static logs show
1070
+ the serving directory and HTTP completion status. Invalid JWTs are rejected
1071
+ before handler invocation, with a verbose diagnostic identifying that stage.
1072
+ A client with an expired/replaced stored token can therefore load HTML but fail
1073
+ its bootstrap POST with 401 before any application log statement runs.
1074
+
1075
+
1076
+ HTTP failures are visible without verbose mode: completed 4xx responses use
1077
+ `log.warn()` and completed 5xx responses use `log.err()`, with the method, URL
1078
+ path, status and dispatched request ID where available. Successful responses
1079
+ remain debug-only. JWT rejection reasons are warnings even before a handler is
1080
+ invoked; raw JWTs and unverified claims are not logged as client identity.
1081
+ Expired or invalid tokens can occur during ordinary session lifetimes, but a
1082
+ failed startup is still a logged rejection. Detailed internal failures retain
1083
+ their existing exception and identity logs.
1084
+
1085
+
1086
+ ## Security policy example
1087
+
1088
+ The [security guide](docs/security.md) and [runnable Lango example](examples/security/README.md)
1089
+ cover anonymous browser quotas, client/login attribution, remembered login,
1090
+ password reauthentication, shared login/admin password freshness, global account bans and
1091
+ selected-client revocation. JWTs are bound to a separate HttpOnly browser cookie
1092
+ and live database state; a copied JWT alone is insufficient. The guide explicitly
1093
+ covers cookie theft, XSS and the remaining UI integration boundaries.
1094
+
1095
+ Run `npm run test:security` for the isolated two-worker HTTP regression suite.
1096
+ This is opt-in application policy, not a change to every server application's
1097
+ existing authentication behavior.
1098
+
1099
+
1100
+ Successful JSON responses carry `x-lango-auth-change: v1:<opaque-id>` when the
1101
+ request changes policy membership, userId, grantId or authenticatedAt, or rotates
1102
+ the managed client credential. Rejected responses and ordinary JWT renewal do
1103
+ not carry this marker. Lango Client uses it to update identical token scopes and
1104
+ notify other same-origin tabs to reload explicitly, preserving their visible
1105
+ inputs. The marker grants no permission and contains no token/credential data.
@@ -100,6 +100,9 @@ function postgresQuery(sql, parameters) {
100
100
  return { text: text + sql.slice(at), values };
101
101
  }
102
102
  export const DB = Object.freeze({ Active: "active", RollbackOnly: "rollback_only", Failed: "failed" });
103
+ const loggingStore = Symbol.for("lango.logging");
104
+ const logging = globalThis[loggingStore] ?? { verbose: false };
105
+ globalThis[loggingStore] = logging;
103
106
  const contextStore = Symbol.for("lango.contexts");
104
107
  const contexts = globalThis[contextStore] ?? new Map();
105
108
  globalThis[contextStore] = contexts;
@@ -114,6 +117,8 @@ export class RuntimeConfigurationError extends Error {
114
117
  export function configure(options = {}) {
115
118
  if (options === null || typeof options !== "object" || Array.isArray(options))
116
119
  throw new RuntimeConfigurationError("runtime configuration must be an object");
120
+ if (options.verbose !== undefined && typeof options.verbose !== "boolean")
121
+ throw new RuntimeConfigurationError("runtime verbose must be boolean");
117
122
  const nextCatalog = options.catalog ?? {};
118
123
  const nextOutput = options.output ?? null;
119
124
  const nextDatabase = options.database_adapter ?? null;
@@ -135,6 +140,7 @@ export function configure(options = {}) {
135
140
  } catch (error) {
136
141
  throw new RuntimeConfigurationError(error.message);
137
142
  }
143
+ if (options.verbose !== undefined) logging.verbose = options.verbose;
138
144
  defaultI18n = nextI18n;
139
145
  output = nextOutput;
140
146
  if (database !== null) failedTransactions.delete(database);
@@ -341,7 +347,8 @@ export function println(value) {
341
347
  }
342
348
 
343
349
  const defaultLog = Object.freeze({
344
- debug(value) { return writeLog(process.stdout, "DEBUG", value); },
350
+ get verbose() { return logging.verbose || process.env.LANGO_VERBOSE === "1"; },
351
+ debug(value) { if (!defaultLog.verbose) return null; return writeLog(process.stdout, "DEBUG", value); },
345
352
  info(value) { return writeLog(process.stdout, "INFO", value); },
346
353
  warn(value) { return writeLog(process.stderr, "WARN", value); },
347
354
  err(value) { return writeLog(process.stderr, "ERROR", value); },
@@ -675,6 +682,22 @@ export function withArity(callback, requiredPositions, name) {
675
682
  };
676
683
  }
677
684
 
685
+ // Capture the environment even when context use is hidden in a downstream call.
686
+ // Each invocation uses fresh stack arrays and restores the caller synchronously.
687
+ export function bindContexts(callback) {
688
+ const captured = new Map([...contexts].map(([name, stack]) => [name, stack.at(-1)]));
689
+ return function (...args) {
690
+ const previous = new Map(contexts);
691
+ for (const [name, value] of captured) contexts.set(name, [value]);
692
+ try {
693
+ return Reflect.apply(callback, this, args);
694
+ } finally {
695
+ contexts.clear();
696
+ for (const [name, stack] of previous) contexts.set(name, stack);
697
+ }
698
+ };
699
+ }
700
+
678
701
  export function contextGet(name) {
679
702
  const stack = contexts.get(name);
680
703
  if ((!stack || stack.length === 0) && name === "log") return defaultLog;
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  hostGlobal as __hostGlobal,
3
3
  hostGlobalCall as __hostGlobalCall,
4
+ bindContexts as __bindContexts,
4
5
  isNumber as __isNumber,
5
6
  isString as __isString,
6
7
  isBool as __isBool,
@@ -47,28 +48,28 @@ export class BodyReader {
47
48
  this.#size = 0;
48
49
  this.#done = false;
49
50
  this.#timer = null;
50
- let data = __withArity((chunk) => {
51
+ let data = __withArity(__bindContexts((chunk) => {
51
52
  chunk = __boundary(chunk);
52
53
  this.#accept(chunk);
53
54
  return null;
54
- }, [0], "closure");
55
- let ended = () => {
55
+ }), [0], "closure");
56
+ let ended = __bindContexts(() => {
56
57
  this.#finish();
57
58
  return null;
58
- };
59
- let failed = __withArity((error) => {
59
+ });
60
+ let failed = __withArity(__bindContexts((error) => {
60
61
  error = __boundary(error);
61
62
  this.#reject(400, "BadRequest");
62
63
  return null;
63
- }, [0], "closure");
64
- let aborted = () => {
64
+ }), [0], "closure");
65
+ let aborted = __bindContexts(() => {
65
66
  this.#abandon();
66
67
  return null;
67
- };
68
- let closed = () => {
68
+ });
69
+ let closed = __bindContexts(() => {
69
70
  this.#abandon();
70
71
  return null;
71
- };
72
+ });
72
73
  this.#data = data;
73
74
  this.#ended = ended;
74
75
  this.#failed = failed;
@@ -91,10 +92,10 @@ export class BodyReader {
91
92
  this.#reject(413, "RequestTooLarge");
92
93
  return null;
93
94
  }
94
- let expired = () => {
95
+ let expired = __bindContexts(() => {
95
96
  this.#reject(408, "RequestTimeout");
96
97
  return null;
97
- };
98
+ });
98
99
  this.#timer = __hostGlobalCall(["setTimeout"], expired, __normalize(options.bodyTimeoutMs));
99
100
  __normalize(req.on("data", __normalize(this.#data)));
100
101
  __normalize(req.on("end", __normalize(this.#ended)));
@@ -155,10 +156,10 @@ export class BodyReader {
155
156
  __normalize(req.pause());
156
157
  if (__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(res.writableEnded))) && __requireBoolean(!__requireBoolean(__normalize(res.destroyed))))) {
157
158
  __normalize(res.setHeader("Connection", "close"));
158
- __normalize(res.once("finish", () => {
159
+ __normalize(res.once("finish", __bindContexts(() => {
159
160
  __normalize(req.destroy());
160
161
  return null;
161
- }));
162
+ })));
162
163
  let callback = __normalize(this.#failure);
163
164
  __call(callback, status, error);
164
165
  }
@@ -1 +1 @@
1
- {"version":3,"file":"body_reader.mjs","sources":["body_reader.lango"],"sourcesContent":["import js global Buffer\nimport js global Number\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class BodyReader\n methods\n start()\n\nBodyReader(req, res, options, complete, failure)\n @req = req\n @res = res\n @options = options\n @complete = complete\n @failure = failure\n @chunks = []\n @size = 0\n @done = false\n @timer = null\n data = (chunk)\n accept(chunk)\n ended = ()\n finish()\n failed = (error)\n reject(400, \"BadRequest\")\n aborted = ()\n abandon()\n closed = ()\n abandon()\n @data = data\n @ended = ended\n @failed = failed\n @aborted = aborted\n @closed = closed\n\nBodyReader:start()\n req = @req\n res = @res\n if req.aborted or res.destroyed\n abandon()\n return null\n req.on(\"error\", @failed)\n req.on(\"aborted\", @aborted)\n res.on(\"close\", @closed)\n length = req.headers[\"content-length\"]\n options = @options\n if is_string(length) and Number/parseInt(length, 10) > options.bodyLimit\n reject(413, \"RequestTooLarge\")\n return null\n expired = ()\n reject(408, \"RequestTimeout\")\n @timer = setTimeout(expired, options.bodyTimeoutMs)\n req.on(\"data\", @data)\n req.on(\"end\", @ended)\n return null\n\nBodyReader:accept(chunk)\n if @done\n return null\n @size = @size + chunk.length\n options = @options\n if @size > options.bodyLimit\n reject(413, \"RequestTooLarge\")\n else\n @chunks.add(chunk)\n return null\n\nBodyReader:finish()\n if @done\n return null\n @done = true\n body = Buffer/concat(@chunks).toString(\"utf8\")\n cleanup()\n @chunks = []\n callback = @complete\n callback(body)\n return null\n\nBodyReader:abandon()\n if @done\n return null\n @done = true\n cleanup()\n @chunks = []\n return null\n\nBodyReader:reject(status, error)\n if @done\n return null\n @done = true\n cleanup()\n @chunks = []\n req = @req\n res = @res\n req.pause()\n if !res.writableEnded and !res.destroyed\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n callback = @failure\n callback(status, error)\n return null\n\nBodyReader:cleanup()\n clearTimeout(@timer)\n req = @req\n req.removeListener(\"data\", @data)\n req.removeListener(\"end\", @ended)\n req.removeListener(\"aborted\", @aborted)\n @res.removeListener(\"close\", @closed)\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"body_reader.mjs","sources":["body_reader.lango"],"sourcesContent":["import js global Buffer\nimport js global Number\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class BodyReader\n methods\n start()\n\nBodyReader(req, res, options, complete, failure)\n @req = req\n @res = res\n @options = options\n @complete = complete\n @failure = failure\n @chunks = []\n @size = 0\n @done = false\n @timer = null\n data = (chunk)\n accept(chunk)\n ended = ()\n finish()\n failed = (error)\n reject(400, \"BadRequest\")\n aborted = ()\n abandon()\n closed = ()\n abandon()\n @data = data\n @ended = ended\n @failed = failed\n @aborted = aborted\n @closed = closed\n\nBodyReader:start()\n req = @req\n res = @res\n if req.aborted or res.destroyed\n abandon()\n return null\n req.on(\"error\", @failed)\n req.on(\"aborted\", @aborted)\n res.on(\"close\", @closed)\n length = req.headers[\"content-length\"]\n options = @options\n if is_string(length) and Number/parseInt(length, 10) > options.bodyLimit\n reject(413, \"RequestTooLarge\")\n return null\n expired = ()\n reject(408, \"RequestTimeout\")\n @timer = setTimeout(expired, options.bodyTimeoutMs)\n req.on(\"data\", @data)\n req.on(\"end\", @ended)\n return null\n\nBodyReader:accept(chunk)\n if @done\n return null\n @size = @size + chunk.length\n options = @options\n if @size > options.bodyLimit\n reject(413, \"RequestTooLarge\")\n else\n @chunks.add(chunk)\n return null\n\nBodyReader:finish()\n if @done\n return null\n @done = true\n body = Buffer/concat(@chunks).toString(\"utf8\")\n cleanup()\n @chunks = []\n callback = @complete\n callback(body)\n return null\n\nBodyReader:abandon()\n if @done\n return null\n @done = true\n cleanup()\n @chunks = []\n return null\n\nBodyReader:reject(status, error)\n if @done\n return null\n @done = true\n cleanup()\n @chunks = []\n req = @req\n res = @res\n req.pause()\n if !res.writableEnded and !res.destroyed\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n callback = @failure\n callback(status, error)\n return null\n\nBodyReader:cleanup()\n clearTimeout(@timer)\n req = @req\n req.removeListener(\"data\", @data)\n req.removeListener(\"end\", @ended)\n req.removeListener(\"aborted\", @aborted)\n @res.removeListener(\"close\", @closed)\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -100,6 +100,9 @@ function postgresQuery(sql, parameters) {
100
100
  return { text: text + sql.slice(at), values };
101
101
  }
102
102
  export const DB = Object.freeze({ Active: "active", RollbackOnly: "rollback_only", Failed: "failed" });
103
+ const loggingStore = Symbol.for("lango.logging");
104
+ const logging = globalThis[loggingStore] ?? { verbose: false };
105
+ globalThis[loggingStore] = logging;
103
106
  const contextStore = Symbol.for("lango.contexts");
104
107
  const contexts = globalThis[contextStore] ?? new Map();
105
108
  globalThis[contextStore] = contexts;
@@ -114,6 +117,8 @@ export class RuntimeConfigurationError extends Error {
114
117
  export function configure(options = {}) {
115
118
  if (options === null || typeof options !== "object" || Array.isArray(options))
116
119
  throw new RuntimeConfigurationError("runtime configuration must be an object");
120
+ if (options.verbose !== undefined && typeof options.verbose !== "boolean")
121
+ throw new RuntimeConfigurationError("runtime verbose must be boolean");
117
122
  const nextCatalog = options.catalog ?? {};
118
123
  const nextOutput = options.output ?? null;
119
124
  const nextDatabase = options.database_adapter ?? null;
@@ -135,6 +140,7 @@ export function configure(options = {}) {
135
140
  } catch (error) {
136
141
  throw new RuntimeConfigurationError(error.message);
137
142
  }
143
+ if (options.verbose !== undefined) logging.verbose = options.verbose;
138
144
  defaultI18n = nextI18n;
139
145
  output = nextOutput;
140
146
  if (database !== null) failedTransactions.delete(database);
@@ -341,7 +347,8 @@ export function println(value) {
341
347
  }
342
348
 
343
349
  const defaultLog = Object.freeze({
344
- debug(value) { return writeLog(process.stdout, "DEBUG", value); },
350
+ get verbose() { return logging.verbose || process.env.LANGO_VERBOSE === "1"; },
351
+ debug(value) { if (!defaultLog.verbose) return null; return writeLog(process.stdout, "DEBUG", value); },
345
352
  info(value) { return writeLog(process.stdout, "INFO", value); },
346
353
  warn(value) { return writeLog(process.stderr, "WARN", value); },
347
354
  err(value) { return writeLog(process.stderr, "ERROR", value); },
@@ -675,6 +682,22 @@ export function withArity(callback, requiredPositions, name) {
675
682
  };
676
683
  }
677
684
 
685
+ // Capture the environment even when context use is hidden in a downstream call.
686
+ // Each invocation uses fresh stack arrays and restores the caller synchronously.
687
+ export function bindContexts(callback) {
688
+ const captured = new Map([...contexts].map(([name, stack]) => [name, stack.at(-1)]));
689
+ return function (...args) {
690
+ const previous = new Map(contexts);
691
+ for (const [name, value] of captured) contexts.set(name, [value]);
692
+ try {
693
+ return Reflect.apply(callback, this, args);
694
+ } finally {
695
+ contexts.clear();
696
+ for (const [name, stack] of previous) contexts.set(name, stack);
697
+ }
698
+ };
699
+ }
700
+
678
701
  export function contextGet(name) {
679
702
  const stack = contexts.get(name);
680
703
  if ((!stack || stack.length === 0) && name === "log") return defaultLog;