@lango-project/lango-server 0.2.2 → 0.2.4

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 (158) hide show
  1. package/README.md +252 -29
  2. package/dist/.lango/runtime.mjs +16 -0
  3. package/dist/body_reader.mjs +15 -14
  4. package/dist/body_reader.mjs.map +1 -1
  5. package/dist/builder.mjs +26 -2
  6. package/dist/builder.mjs.map +1 -1
  7. package/dist/cli/.lango/runtime.mjs +16 -0
  8. package/dist/cli/body_reader.mjs +15 -14
  9. package/dist/cli/body_reader.mjs.map +1 -1
  10. package/dist/cli/client_identity.mjs +250 -0
  11. package/dist/cli/client_identity.mjs.map +1 -0
  12. package/dist/cli/database.mjs +23 -8
  13. package/dist/cli/database.mjs.map +1 -1
  14. package/dist/cli/database_scope.mjs +11 -0
  15. package/dist/cli/database_scope.mjs.map +1 -1
  16. package/dist/cli/endpoint.mjs +11 -7
  17. package/dist/cli/endpoint.mjs.map +1 -1
  18. package/dist/cli/longpoll_broker.mjs +9 -8
  19. package/dist/cli/longpoll_broker.mjs.map +1 -1
  20. package/dist/cli/longpoll_options.mjs +8 -7
  21. package/dist/cli/longpoll_options.mjs.map +1 -1
  22. package/dist/cli/longpoll_session.mjs +11 -10
  23. package/dist/cli/longpoll_session.mjs.map +1 -1
  24. package/dist/cli/middleware.mjs +1 -1
  25. package/dist/cli/middleware.mjs.map +1 -1
  26. package/dist/cli/options.mjs +41 -4
  27. package/dist/cli/options.mjs.map +1 -1
  28. package/dist/cli/origin.mjs +87 -0
  29. package/dist/cli/origin.mjs.map +1 -0
  30. package/dist/cli/policy.mjs +121 -0
  31. package/dist/cli/policy.mjs.map +1 -0
  32. package/dist/cli/postgres_adapter.mjs +15 -3
  33. package/dist/cli/postgres_adapter.mjs.map +1 -1
  34. package/dist/cli/routes.mjs +69 -18
  35. package/dist/cli/routes.mjs.map +1 -1
  36. package/dist/cli/server.mjs +88 -81
  37. package/dist/cli/server.mjs.map +1 -1
  38. package/dist/cli/static_files.mjs +5 -4
  39. package/dist/cli/static_files.mjs.map +1 -1
  40. package/dist/client_identity.mjs +250 -0
  41. package/dist/client_identity.mjs.map +1 -0
  42. package/dist/database.mjs +23 -8
  43. package/dist/database.mjs.map +1 -1
  44. package/dist/database_action.mjs +71 -0
  45. package/dist/database_action.mjs.map +1 -0
  46. package/dist/database_scope.mjs +11 -0
  47. package/dist/database_scope.mjs.map +1 -1
  48. package/dist/endpoint.mjs +11 -7
  49. package/dist/endpoint.mjs.map +1 -1
  50. package/dist/execution_failure.mjs +30 -0
  51. package/dist/execution_failure.mjs.map +1 -0
  52. package/dist/execution_identity.mjs +103 -0
  53. package/dist/execution_identity.mjs.map +1 -0
  54. package/dist/execution_log.mjs +47 -0
  55. package/dist/execution_log.mjs.map +1 -0
  56. package/dist/execution_runtime.mjs +201 -0
  57. package/dist/execution_runtime.mjs.map +1 -0
  58. package/dist/execution_worker.mjs +41 -0
  59. package/dist/execution_worker.mjs.map +1 -0
  60. package/dist/executor.mjs +384 -0
  61. package/dist/executor.mjs.map +1 -0
  62. package/dist/group.mjs +49 -16
  63. package/dist/group.mjs.map +1 -1
  64. package/dist/http_failure.mjs +9 -2
  65. package/dist/http_failure.mjs.map +1 -1
  66. package/dist/job_configuration.mjs +37 -0
  67. package/dist/job_configuration.mjs.map +1 -0
  68. package/dist/job_context.mjs +61 -0
  69. package/dist/job_context.mjs.map +1 -0
  70. package/dist/library.mjs +31 -0
  71. package/dist/library.mjs.map +1 -1
  72. package/dist/longpoll_broker.mjs +9 -8
  73. package/dist/longpoll_broker.mjs.map +1 -1
  74. package/dist/longpoll_options.mjs +8 -7
  75. package/dist/longpoll_options.mjs.map +1 -1
  76. package/dist/longpoll_session.mjs +11 -10
  77. package/dist/longpoll_session.mjs.map +1 -1
  78. package/dist/middleware.mjs +1 -1
  79. package/dist/middleware.mjs.map +1 -1
  80. package/dist/module_loader.mjs +44 -0
  81. package/dist/module_loader.mjs.map +1 -0
  82. package/dist/options.mjs +41 -4
  83. package/dist/options.mjs.map +1 -1
  84. package/dist/origin.mjs +87 -0
  85. package/dist/origin.mjs.map +1 -0
  86. package/dist/policy.mjs +121 -0
  87. package/dist/policy.mjs.map +1 -0
  88. package/dist/postgres_adapter.mjs +15 -3
  89. package/dist/postgres_adapter.mjs.map +1 -1
  90. package/dist/postgres_worker.mjs +82 -19
  91. package/dist/postgres_worker.mjs.map +1 -1
  92. package/dist/queue_provider.mjs +52 -0
  93. package/dist/queue_provider.mjs.map +1 -0
  94. package/dist/response.mjs +1 -1
  95. package/dist/response.mjs.map +1 -1
  96. package/dist/route_info.mjs +1 -1
  97. package/dist/route_info.mjs.map +1 -1
  98. package/dist/routes.mjs +69 -18
  99. package/dist/routes.mjs.map +1 -1
  100. package/dist/runtime.mjs +287 -132
  101. package/dist/runtime.mjs.map +1 -1
  102. package/dist/server.mjs +88 -81
  103. package/dist/server.mjs.map +1 -1
  104. package/dist/server_context.mjs +21 -9
  105. package/dist/server_context.mjs.map +1 -1
  106. package/dist/static_files.mjs +5 -4
  107. package/dist/static_files.mjs.map +1 -1
  108. package/dist/token.mjs +34 -7
  109. package/dist/token.mjs.map +1 -1
  110. package/dist/tokens.mjs +11 -2
  111. package/dist/tokens.mjs.map +1 -1
  112. package/dist/worker.mjs +7 -6
  113. package/dist/worker.mjs.map +1 -1
  114. package/docs/jobs.md +123 -0
  115. package/docs/security.md +420 -0
  116. package/examples/security/README.md +160 -0
  117. package/examples/security/deploy.xml +12 -0
  118. package/examples/security/handlers.lango +610 -0
  119. package/examples/security/package.json +19 -0
  120. package/examples/security/passwords.lango +61 -0
  121. package/examples/security/routes.xml +14 -0
  122. package/examples/security/schema.lango +91 -0
  123. package/examples/security/setup.lango +30 -0
  124. package/package.json +14 -6
  125. package/src/builder.lango +22 -0
  126. package/src/client_identity.lango +184 -0
  127. package/src/database.lango +15 -4
  128. package/src/database_action.lango +30 -0
  129. package/src/database_scope.lango +7 -0
  130. package/src/endpoint.lango +12 -5
  131. package/src/execution_failure.lango +14 -0
  132. package/src/execution_identity.lango +71 -0
  133. package/src/execution_log.lango +28 -0
  134. package/src/execution_runtime.lango +135 -0
  135. package/src/execution_worker.lango +32 -0
  136. package/src/executor.lango +284 -0
  137. package/src/group.lango +36 -21
  138. package/src/http_failure.lango +9 -5
  139. package/src/job_configuration.lango +29 -0
  140. package/src/job_context.lango +44 -0
  141. package/src/library.lango +21 -0
  142. package/src/longpoll_options.lango +11 -5
  143. package/src/middleware.lango +1 -1
  144. package/src/module_loader.lango +25 -0
  145. package/src/options.lango +41 -2
  146. package/src/origin.lango +56 -0
  147. package/src/policy.lango +84 -0
  148. package/src/postgres_adapter.lango +12 -0
  149. package/src/postgres_worker.lango +54 -3
  150. package/src/queue_provider.lango +30 -0
  151. package/src/response.lango +1 -1
  152. package/src/route_info.lango +2 -0
  153. package/src/routes.lango +74 -15
  154. package/src/runtime.lango +173 -94
  155. package/src/server.lango +9 -2
  156. package/src/server_context.lango +10 -2
  157. package/src/token.lango +26 -5
  158. package/src/tokens.lango +10 -3
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, an HTTP-free `Executor`, and configuration readers for internal jobs. 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
@@ -272,12 +272,23 @@ createServer(root, signingKey)
272
272
  ```
273
273
 
274
274
  `Builder(root)` defaults to the current directory. `configure`, `addMiddleware`, `endpoint`,
275
- `include`, and `event` return the Builder. `group` returns a group supporting
276
- `endpoint`, nested `group`, and `include`; retain the Builder for `build()`.
275
+ `job`, `include`, and `event` return the Builder. `group` returns a group supporting
276
+ `endpoint`, `job`, nested `group`, and `include`; retain the Builder for `build()`.
277
277
  The built Server snapshots definitions; later Builder changes do not affect it.
278
+
279
+ `builder.loadDeployment()` explicitly reads `deploy.xml` from the Builder's root,
280
+ including its HTTP/database settings and signing credentials, and returns the
281
+ Builder. Call it before `configure(...)` when code should override file settings.
282
+ It does not load routes or events: those remain explicit Builder definitions.
283
+ Constructing a Builder alone does not read the deployment file. This method is
284
+ available from version 0.2.4.
278
285
  `new server/Server(directory)` is the XML equivalent. Routes, Endpoint, worker
279
286
  classes, and token implementation classes are internal package details.
280
287
 
288
+ Internal `<job>` targets are separate from HTTP endpoints and do not become
289
+ public routes. See [internal job configuration](docs/jobs.md) for XML, Builder
290
+ support, and the `readDatabaseConfiguration` / `readJobRoutes` library functions.
291
+
281
292
  ## Route middleware
282
293
 
283
294
  Middleware wraps an application handler inside its worker. Register an exported
@@ -334,7 +345,7 @@ a thrown/rejected error fails startup. Validators run without request contexts;
334
345
  they check configuration rather than handling requests.
335
346
 
336
347
  Inside request handlers and middleware, `context server` also provides
337
- `routes()`. It returns a fresh array of `{ path, kind, auth, middleware }` records,
348
+ `routes()`. It returns a fresh array of `{ path, kind, policy, reauthSeconds, auth, middleware }` records,
338
349
  where kind is `endpoint` or `longpoll`. Module paths and handler names are not
339
350
  exposed. Mutating a snapshot cannot change routing. Startup validators receive
340
351
  the same metadata shape, allowing libraries to discover their configured URLs
@@ -409,18 +420,56 @@ contain at least 32 characters and should be cryptographically random. Only
409
420
  HS256 is accepted; algorithm, key ID, issuer, audience, expiry, and server-owned
410
421
  timestamps are checked. Keys are never generated or stored by the server.
411
422
 
423
+ ## Origin policy
424
+
425
+ Origin checks are an optional server deployment policy, applied to JSON endpoint
426
+ requests before token processing, lifecycle events and handlers:
427
+
428
+ ```xml
429
+ <origin url="https://app.example.com" required="true"/>
430
+ ```
431
+
432
+ Use `urlEnv="LANGO_ORIGIN"` instead of `url` to read the external origin from an
433
+ environment variable. The two attributes are mutually exclusive. Builder accepts
434
+ `origin: { url: "https://app.example.com", required: true }` in its configuration.
435
+ The URL must be an exact HTTP/HTTPS origin without a trailing slash, credentials,
436
+ path, query or fragment. Configure the externally visible origin when behind a
437
+ proxy; the server never infers it from Host or forwarded headers.
438
+
439
+ `required` defaults to true: missing, literal-null and unrelated Origin headers
440
+ produce 403 `OriginRejected`. With `required=false`, requests without Origin are
441
+ allowed, but a supplied Origin must still match. When Sec-Fetch-Site is present,
442
+ only `same-origin` and `none` are accepted. This is a same-origin policy, not a
443
+ cross-origin/CORS allowlist. Origin is not an authentication credential.
444
+
445
+ Without an origin section, no Origin/Fetch Metadata policy is imposed. Static
446
+ GET/HEAD serving remains independent. The security example enables the policy;
447
+ its application code does not parse or validate these headers.
448
+
412
449
  ## Contexts and authorization
413
450
 
414
451
  Handlers and events can declare `context request`, `response`, `token`, and `log`.
415
452
  Request metadata is read-only: `id`, `method`, `path`, `headers`, `remoteAddress`.
416
- Response supports `status(code)`, `header(name, value)` and `reject(status, code)`;
417
- the handler return value supplies its JSON body. Transport/token headers remain
418
- server-owned. `reject` throws a controlled HTTP failure (400–599) with a short
419
- error code, for example `response.reject(400, "InvalidInput")`. Codes start with
420
- an ASCII letter and contain at most 64 letters, digits or underscores. Configured
421
- response headers are preserved. Rejections roll back open SQL transactions and
422
- send `{ error: code }` without a token; committed side effects are not undone.
423
- Unexpected exceptions still produce a generic 500.
453
+ Response supports `status(code)`, `header(name, value)` and `reject(status, code)`.
454
+ The handler's normal return value supplies its JSON body. To reject a request:
455
+
456
+ ```lango
457
+ restricted(input)
458
+ context response
459
+ response.reject(401, "InvalidCredentials")
460
+ ```
461
+
462
+ `reject` throws a controlled `HttpFailure` and stops the current execution path;
463
+ it does not return a response value. The server sends status 401 and
464
+ `{ "error": "InvalidCredentials" }` for this example. Status must be an integer
465
+ from 400 to 599. Codes start with an ASCII letter and contain at most 64 ASCII
466
+ letters, digits or underscores. Invalid arguments produce a generic 500.
467
+
468
+ Controlled rejections roll back open SQL transactions and publish no token or
469
+ token changes. Already committed side effects are not undone. Response headers
470
+ are preserved, and 401 includes `WWW-Authenticate: Bearer`. This behavior also
471
+ applies to middleware, synchronous helpers and Lango callbacks. Transport/token
472
+ headers remain server-owned. Unexpected exceptions still produce a generic 500.
424
473
 
425
474
  Tokens arrive in `Authorization: Bearer <jwt>` and successful replies contain
426
475
  `X-Lango-Token`. Missing tokens create an anonymous identity with a UUID
@@ -430,17 +479,18 @@ Unauthorized requests do not receive a newly created token.
430
479
 
431
480
  `context token` supports:
432
481
 
433
- * `clientId?`, `auth?`, `expiresAt?`: getter-only identity, comma-separated
434
- permissions and expiry. Direct assignment is rejected, including JavaScript
482
+ * `clientId?`, `auth?`, `policies?`, `expiresAt?`: getter-only identity, comma-separated
483
+ permissions, a copied policy array and expiry. Direct assignment is rejected, including JavaScript
435
484
  attempts to shadow these properties. Use the controlled methods below to update
436
485
  claims or permissions.
437
- * `AddAuth("login")`, `clearAuth()`, `hasAuth("admin")`: exact trimmed membership.
486
+ * `addPolicy("login")`, `clearPolicies()`, `hasPolicy("admin")`: exact trimmed membership.
487
+ `AddAuth`, `clearAuth` and `hasAuth` remain compatibility aliases.
438
488
  * `get(name)`, `set(name, value)`: JSON custom claims; server-owned JWT fields are
439
489
  protected. `get` returns a copy for structured values.
440
490
  * `renew()`: requests renewal after successful serialization and SQL cleanup on
441
491
  a reply with a status below 400. It does not immediately change `expiresAt?`.
442
492
 
443
- Default endpoint auth is `login`. `auth="anonymous"` permits anonymous callers;
493
+ Default endpoint policy is `login`. `policy="anonymous"` permits anonymous callers;
444
494
  other values require that exact permission. `admin` does not imply `login`.
445
495
  The application authenticates credentials and grants permissions. These methods
446
496
  do not authenticate anyone automatically.
@@ -460,17 +510,166 @@ before renewal and signing; an expired token cannot be revived. Failed or
460
510
  rejected requests publish no renewal. Previously issued tokens remain valid
461
511
  until their own expiry unless the application's Validate policy revokes them.
462
512
 
513
+ ## Built-in route policies
514
+
515
+ Policy checks are a built-in Server feature, applied on every request before
516
+ middleware and handlers. They do not require a security middleware registration:
517
+
518
+ ```xml
519
+ <endpoint path="/admin" module="@shop/admin" handler="home"
520
+ policy="admin" reauthSeconds="300"/>
521
+ ```
522
+
523
+ After verifying login credentials, trusted application code grants policies:
524
+
525
+ ```lango
526
+ import js global Date
527
+
528
+ context token
529
+ token.addPolicy("login")
530
+ token.addPolicy("admin")
531
+ token.set("authenticatedAt", Date/now())
532
+ ```
533
+
534
+ `authenticatedAt` must be the actual password-authentication time as epoch
535
+ milliseconds, recorded by trusted server code (for example `Date/now()` after
536
+ `import js global Date`). Never copy this value from client input. Token refresh does not change
537
+ this timestamp. `reauthSeconds` is the maximum permitted age; missing, invalid,
538
+ future or stale timestamps produce 403 `ReauthenticationRequired`. Zero disables
539
+ this extra condition. Membership and freshness checks are independent of the
540
+ Validate event's freshness interval.
541
+
542
+ `policy="anonymous"` explicitly permits anonymous requests. Otherwise one exact
543
+ policy membership is required; there is no implicit role hierarchy. Missing
544
+ `login` gives 401 `LoginRequired`; other missing policies give 403 `Forbidden`.
545
+ Without a policy/auth declaration, the default remains login. Policies and
546
+ reauthSeconds are inherited through groups/includes; an endpoint can override
547
+ them, including explicit `reauthSeconds="0"`.
548
+
549
+ Declare shared requirements in `deploy.xml` to avoid repeating durations:
550
+
551
+ ```xml
552
+ <policies reauthSeconds="43200">
553
+ <policy name="login"/>
554
+ <policy name="admin" reauthSeconds="300"/>
555
+ </policies>
556
+ ```
557
+
558
+ The declaration is a child of `<deploy>`. `anonymous` is built in and exempt from
559
+ freshness. Named policies inherit the section default unless they specify their
560
+ own duration. All protected route policies must be declared when this section is
561
+ present; undefined names fail startup. Without this section, existing route-level
562
+ configuration continues to work. Builder configuration uses `policies: {
563
+ reauthSeconds, items: [{ name, reauthSeconds }] }` with the same rules.
564
+
565
+ An omitted endpoint/group duration inherits the selected policy requirement.
566
+ An explicit duration may shorten it but cannot lengthen or disable a positive
567
+ policy requirement. The effective requirement is resolved before route validators
568
+ and worker startup. `0` at the policy level disables freshness for that policy.
569
+ There is one shared `authenticatedAt`, not a timestamp per policy: any successful
570
+ password verification refreshes the same time for all policy checks. Merely
571
+ visiting a protected endpoint never refreshes it.
572
+
573
+ Login/password-confirmation handlers must remain reachable while authentication
574
+ is stale, normally with `policy="anonymous"`. They must verify credentials and,
575
+ for reauthentication, the current account/grant themselves. Do not try to disable
576
+ a central policy requirement on the password-confirmation endpoint.
577
+
578
+ Only the built-in pre-handler gate returns `x-lango-need-login: 1` with a
579
+ `needLogin` response map (reason, path, policy, reauthSeconds, userId). Missing login
580
+ or stale authentication can then invoke the optional UI needLogin event. Missing
581
+ permissions on an already logged-in token, invalid tokens, bans and ordinary
582
+ handler failures do not carry this marker. The client may replay a challenged
583
+ form request once after login; it never retries network failures. Reauthentication
584
+ replays also send `X-Lango-Expected-User`, which Server compares with the signed
585
+ userId before invoking the handler; a mismatch returns 409 `IdentityChanged`.
586
+
587
+ Builder endpoint/group/longpoll maps accept `policy` and `reauthSeconds` too.
588
+ Handlers/middleware can read frozen `request.route` metadata containing the matched
589
+ path, kind, policy and reauthSeconds (without module/handler internals). The metadata
590
+ comes from server route configuration, independently of request input.
591
+
592
+ Token supports `addPolicy(name)`, `hasPolicy(name)`, `clearPolicies()` and the
593
+ readonly `policies?` snapshot. The existing auth XML/Builder field and
594
+ AddAuth/hasAuth/clearAuth methods remain compatibility aliases over the same signed
595
+ JWT auth claim; no separate permission store is introduced. Conflicting auth and
596
+ policy declarations fail configuration. Legacy auth retains its existing 401
597
+ denial behavior.
598
+
599
+ A signed policy membership is not proof that an account is still enabled or that
600
+ its live DB role is unchanged. Applications with immediate ban/revocation or
601
+ resource-ownership requirements retain those live checks in their guard. Server
602
+ does not assume an application user/grant schema. The security example keeps
603
+ those business checks and transactions in its guard, while route policy selection
604
+ and the generic policy/freshness gate belong to Server.
605
+
606
+ ## Managed client identity
607
+
608
+ Browser deployments can delegate client continuity and cookie binding to Server:
609
+
610
+ ```xml
611
+ <client maxAgeSeconds="2592000"/>
612
+ <origin urlEnv="LANGO_ORIGIN" required="true"/>
613
+ <database type="sqlite" file="data/application.sqlite"/>
614
+ ```
615
+
616
+ Builder accepts `client: { maxAgeSeconds: 2592000 }`. The lifetime defaults to
617
+ 30 days and is refreshed on successful replies. Enabling this feature requires
618
+ persistent database storage and a required HTTPS origin. Without a client section,
619
+ existing JWT-only applications retain their previous behavior.
620
+
621
+ Server generates a 256-bit opaque `__Host-lango-client` cookie with Secure,
622
+ HttpOnly, SameSite=Strict and Path=/ attributes, and no Domain. It stores only the
623
+ credential hash and expiry in its owned `_lango_clients` table. All workers/pods
624
+ must share that database. The table is initialized before workers start; application
625
+ code must not read or update it. The reserved JWT `clientProof` claim binds a
626
+ Bearer token to the matching live cookie record. Application token setters cannot
627
+ change that claim. Unknown, expired, malformed, duplicate or mismatched credentials
628
+ fail before application events/handlers.
629
+
630
+ A first tokenless request without a cookie creates a clientId and invokes Register.
631
+ A tokenless request with a valid cookie gets a clean token for the same clientId:
632
+ permissions and application claims are empty, Register is skipped, and Validate
633
+ runs without its normal freshness shortcut. Invalid/expired supplied JWTs still
634
+ fail; Server never silently falls back to the cookie. Requests are not retried.
635
+ There is no application identity-restoration event or cookie parser to implement.
636
+
637
+ After login or password confirmation, the application requests credential renewal:
638
+
639
+ ```lango
640
+ context server
641
+ server.rotateClient()
642
+ ```
643
+
644
+ Server performs the rotation when preparing a successful response, keeping the
645
+ same clientId. The old cookie and old JWT binding then fail. Failed requests do
646
+ not rotate credentials or publish a token. Pending requests authorized before a
647
+ rotation can have already committed side effects; rejected operations are not
648
+ implicitly retried. Other forms/tabs need an explicit reinitialization flow.
649
+ Rotation is available only within the active managed client request scope.
650
+
651
+ The security example uses this mechanism; its tables retain user/grant/quota/audit
652
+ policy, not cookie storage. Cookie theft remains credential theft: with a remembered
653
+ application grant it may restore a normal login. Cookie flags and identity binding
654
+ do not make active XSS harmless. See [OWASP session management](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html).
655
+
463
656
  ## Events
464
657
 
465
658
  Event modules and function names are strings, resolved during worker startup.
466
659
  Promise results are supported, and events run under the request's contexts.
467
660
 
468
- * **register(input)** runs for a tokenless request after assigning `clientId`,
469
- before endpoint authorization. It can initialize custom token claims. Failure
661
+ * **register(input)** runs for a new client after assigning `clientId`,
662
+ before endpoint authorization. Its input is a shallow copy of the decoded
663
+ request input (including path parameters), with server-observed `ip` and
664
+ `userAgent` fields overriding any same-named JSON/path fields. `ip` is the
665
+ socket peer address; forwarded headers are not trusted. `userAgent` is the
666
+ User-Agent header (null when absent), not an authenticated identity. These
667
+ additions do not change the endpoint's original input. It can initialize custom
668
+ token claims. Failure
470
669
  prevents the handler and publishes no token. Return values are ignored; throw
471
670
  or reject to fail registration. It is not an account-creation
472
- guarantee: callers can omit tokens, so application side effects need their own
473
- policy. No Register event is required.
671
+ guarantee: JWT-only callers can omit tokens, and callers can discard cookies,
672
+ so application side effects need their own policy. No Register event is required.
474
673
  * **validate(input)** receives null and runs after standard JWT verification
475
674
  when the signed `validatedAt` is at least one second old. It receives a read-only
476
675
  token. Only `true` continues; `false` produces 401. Exceptions, invalid return
@@ -491,7 +690,7 @@ Promise results are supported, and events run under the request's contexts.
491
690
  the successful response. Enabling this event exposes application input/output
492
691
  to its configured handler; redact credentials and other sensitive fields there.
493
692
 
494
- Each event has `eventTimeoutMs`. The request deadline covers queueing, Register,
693
+ Each event has `eventTimeoutMs`. The request deadline covers queueing, client verification, Register,
495
694
  Validate, and the handler; Request has its own event deadline after the result is
496
695
  prepared. A hard timeout terminates the worker and the pool replaces it. Tasks
497
696
  are never automatically retried: worker termination cannot roll back completed
@@ -571,7 +770,7 @@ builder.configure({
571
770
  ```
572
771
 
573
772
  Each request worker owns one persistent connection. The server creates a fresh
574
- DB scope before Register/Validate and keeps it available to the handler. Request
773
+ DB scope before client verification/Register/Validate and keeps it available to the handler. Request
575
774
  gets a separate clean scope after the handler result is serialized. Scopes cannot
576
775
  be reused after completion. Physical connections are released on shutdown; worker
577
776
  replacement discards the old connection and creates a new one. If DB configuration
@@ -582,7 +781,6 @@ Application code uses Lango SQL rather than a driver API:
582
781
 
583
782
  ```lango
584
783
  findCustomer(input)
585
- context db
586
784
  row = SQL
587
785
  select id, name from customer where id = :id
588
786
  row.id = input.id
@@ -597,8 +795,11 @@ findCustomer(input)
597
795
 
598
796
  **Build all SQL application modules with lango-js 0.1.13 or newer.** SQL and
599
797
  `start_trans()`, `commit_trans()`, `rollback_trans()`, `trans_state()` use the active
600
- db context across separately compiled runtime copies. Promise callbacks that use
601
- SQL should declare/capture db using the normal context capture rules.
798
+ database context across separately compiled runtime copies. SQL functions do not
799
+ need a `context db` declaration. Declare it only when directly accessing the scope
800
+ object. All active contexts propagate to Lango callbacks automatically, including
801
+ when SQL is used only by a downstream function. No `capture db` is needed.
802
+ A callback cannot reuse a database scope after that scope has closed.
602
803
 
603
804
  Transactions are explicit. The server never implicitly commits a transaction.
604
805
  An open transaction at successful scope completion is rolled back and reported as
@@ -891,3 +1092,25 @@ invoked; raw JWTs and unverified claims are not logged as client identity.
891
1092
  Expired or invalid tokens can occur during ordinary session lifetimes, but a
892
1093
  failed startup is still a logged rejection. Detailed internal failures retain
893
1094
  their existing exception and identity logs.
1095
+
1096
+
1097
+ ## Security policy example
1098
+
1099
+ The [security guide](docs/security.md) and [runnable Lango example](examples/security/README.md)
1100
+ cover anonymous browser quotas, client/login attribution, remembered login,
1101
+ password reauthentication, shared login/admin password freshness, global account bans and
1102
+ selected-client revocation. JWTs are bound to a separate HttpOnly browser cookie
1103
+ and live database state; a copied JWT alone is insufficient. The guide explicitly
1104
+ covers cookie theft, XSS and the remaining UI integration boundaries.
1105
+
1106
+ Run `npm run test:security` for the isolated two-worker HTTP regression suite.
1107
+ This is opt-in application policy, not a change to every server application's
1108
+ existing authentication behavior.
1109
+
1110
+
1111
+ Successful JSON responses carry `x-lango-auth-change: v1:<opaque-id>` when the
1112
+ request changes policy membership, userId, grantId or authenticatedAt, or rotates
1113
+ the managed client credential. Rejected responses and ordinary JWT renewal do
1114
+ not carry this marker. Lango Client uses it to update identical token scopes and
1115
+ notify other same-origin tabs to reload explicitly, preserving their visible
1116
+ inputs. The marker grants no permission and contains no token/credential data.
@@ -682,6 +682,22 @@ export function withArity(callback, requiredPositions, name) {
682
682
  };
683
683
  }
684
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
+
685
701
  export function contextGet(name) {
686
702
  const stack = contexts.get(name);
687
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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/builder.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { Routes } from "./routes.mjs";
2
2
  import { Group } from "./group.mjs";
3
- import { options } from "./options.mjs";
3
+ import { options, readDeployment } from "./options.mjs";
4
4
  import { Server } from "./server.mjs";
5
+ import { queueProvider } from "./queue_provider.mjs";
5
6
  import * as path from "node:path";
6
7
  import {
7
8
  hostGlobal as __hostGlobal,
@@ -15,6 +16,7 @@ import {
15
16
  export class Builder {
16
17
  #root;
17
18
  #settings;
19
+ #queueProvider;
18
20
  #routes;
19
21
  constructor(root = null) {
20
22
  root = __boundary(root);
@@ -23,6 +25,7 @@ export class Builder {
23
25
  }
24
26
  this.#root = __normalize(path.resolve(root));
25
27
  this.#settings = { };
28
+ this.#queueProvider = null;
26
29
  this.#routes = new Routes(__normalize(this.#root));
27
30
  }
28
31
  configure(settings) {
@@ -34,6 +37,10 @@ export class Builder {
34
37
  return this;
35
38
  return null;
36
39
  }
40
+ loadDeployment() {
41
+ return this.configure(readDeployment(__normalize(this.#root)));
42
+ return null;
43
+ }
37
44
  addMiddleware(name, spec) {
38
45
  __requireArity(arguments.length, [0, 1], "addMiddleware");
39
46
  name = __boundary(name);
@@ -42,6 +49,16 @@ export class Builder {
42
49
  return this;
43
50
  return null;
44
51
  }
52
+ provideQueue(spec) {
53
+ __requireArity(arguments.length, [0], "provideQueue");
54
+ spec = __boundary(spec);
55
+ if (__requireBoolean(__normalize(this.#queueProvider) !== null)) {
56
+ throw "Queue provider is already configured";
57
+ }
58
+ this.#queueProvider = queueProvider(__normalize(this.#root), spec);
59
+ return this;
60
+ return null;
61
+ }
45
62
  endpoint(spec) {
46
63
  __requireArity(arguments.length, [0], "endpoint");
47
64
  spec = __boundary(spec);
@@ -49,6 +66,13 @@ export class Builder {
49
66
  return this;
50
67
  return null;
51
68
  }
69
+ job(spec) {
70
+ __requireArity(arguments.length, [0], "job");
71
+ spec = __boundary(spec);
72
+ __normalize(this.#routes.job(spec));
73
+ return this;
74
+ return null;
75
+ }
52
76
  longpoll(spec) {
53
77
  __requireArity(arguments.length, [0], "longpoll");
54
78
  spec = __boundary(spec);
@@ -77,7 +101,7 @@ export class Builder {
77
101
  return null;
78
102
  }
79
103
  build() {
80
- return new Server(null, { settings: options(__normalize(this.#root), __normalize(this.#settings)), routes: __normalize(this.#routes.definitions()), events: __normalize(this.#routes.events()), middlewares: __normalize(this.#routes.middlewares()) });
104
+ return new Server(null, { settings: options(__normalize(this.#root), __normalize(this.#settings)), routes: __normalize(this.#routes.definitions()), jobs: __normalize(this.#routes.jobs()), events: __normalize(this.#routes.events()), middlewares: __normalize(this.#routes.middlewares()), queueProvider: __normalize(this.#queueProvider) });
81
105
  return null;
82
106
  }
83
107
  }
@@ -1 +1 @@
1
- {"version":3,"file":"builder.mjs","sources":["builder.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global process\nimport \"./routes\"\n class Routes\nimport \"./group\"\n class Group\nimport \"./options\"\n options(root, supplied = null)\nimport \"./server\"\n class Server\n\nexport class Builder(root = null)\n methods\n configure(settings)\n addMiddleware(name, spec)\n endpoint(spec)\n longpoll(spec)\n group(spec)\n include(spec)\n event(spec)\n build()\n\nBuilder(root = null)\n if root == null\n root = process.cwd()\n @root = path/resolve(root)\n @settings = {}\n @routes = new Routes(@root)\n\nBuilder:configure(settings)\n for settings as key: value\n @settings[key] = value\n return @this\n\nBuilder:addMiddleware(name, spec)\n @routes.addMiddleware(name, spec)\n return @this\n\nBuilder:endpoint(spec)\n @routes.endpoint(spec)\n return @this\n\nBuilder:longpoll(spec)\n @routes.longpoll(spec)\n return @this\n\nBuilder:group(spec)\n return new Group(@routes, spec)\n\nBuilder:include(spec)\n @routes.include(spec)\n return @this\n\nBuilder:event(spec)\n @routes.event(spec)\n return @this\n\nBuilder:build()\n return new Server(null, {\n settings: options(@root, @settings)\n routes: @routes.definitions()\n events: @routes.events()\n middlewares: @routes.middlewares()\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"builder.mjs","sources":["builder.lango"],"sourcesContent":["import js \"node:path\" as path\nimport js global process\nimport \"./routes\"\n class Routes\nimport \"./group\"\n class Group\nimport \"./options\"\n options(root, supplied = null)\n readDeployment(directory, credentials = true)\nimport \"./server\"\n class Server\nimport \"./queue_provider\"\n queueProvider(root, spec)\n\nexport class Builder(root = null)\n methods\n configure(settings)\n loadDeployment()\n addMiddleware(name, spec)\n provideQueue(spec)\n endpoint(spec)\n job(spec)\n longpoll(spec)\n group(spec)\n include(spec)\n event(spec)\n build()\n\nBuilder(root = null)\n if root == null\n root = process.cwd()\n @root = path/resolve(root)\n @settings = {}\n @queueProvider = null\n @routes = new Routes(@root)\n\nBuilder:configure(settings)\n for settings as key: value\n @settings[key] = value\n return @this\n\nBuilder:loadDeployment()\n return configure(readDeployment(@root))\n\nBuilder:addMiddleware(name, spec)\n @routes.addMiddleware(name, spec)\n return @this\n\nBuilder:provideQueue(spec)\n if @queueProvider != null\n throw \"Queue provider is already configured\"\n @queueProvider = queueProvider(@root, spec)\n return @this\n\nBuilder:endpoint(spec)\n @routes.endpoint(spec)\n return @this\n\nBuilder:job(spec)\n @routes.job(spec)\n return @this\n\nBuilder:longpoll(spec)\n @routes.longpoll(spec)\n return @this\n\nBuilder:group(spec)\n return new Group(@routes, spec)\n\nBuilder:include(spec)\n @routes.include(spec)\n return @this\n\nBuilder:event(spec)\n @routes.event(spec)\n return @this\n\nBuilder:build()\n return new Server(null, {\n settings: options(@root, @settings)\n routes: @routes.definitions()\n jobs: @routes.jobs()\n events: @routes.events()\n middlewares: @routes.middlewares()\n queueProvider: @queueProvider\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -682,6 +682,22 @@ export function withArity(callback, requiredPositions, name) {
682
682
  };
683
683
  }
684
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
+
685
701
  export function contextGet(name) {
686
702
  const stack = contexts.get(name);
687
703
  if ((!stack || stack.length === 0) && name === "log") return defaultLog;