@lango-project/lango-server 0.2.2 → 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 (106) hide show
  1. package/README.md +239 -27
  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/cli/.lango/runtime.mjs +16 -0
  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/longpoll_broker.mjs +9 -8
  15. package/dist/cli/longpoll_broker.mjs.map +1 -1
  16. package/dist/cli/longpoll_options.mjs +8 -7
  17. package/dist/cli/longpoll_options.mjs.map +1 -1
  18. package/dist/cli/longpoll_session.mjs +11 -10
  19. package/dist/cli/longpoll_session.mjs.map +1 -1
  20. package/dist/cli/options.mjs +29 -3
  21. package/dist/cli/options.mjs.map +1 -1
  22. package/dist/cli/origin.mjs +87 -0
  23. package/dist/cli/origin.mjs.map +1 -0
  24. package/dist/cli/policy.mjs +121 -0
  25. package/dist/cli/policy.mjs.map +1 -0
  26. package/dist/cli/postgres_adapter.mjs +3 -2
  27. package/dist/cli/postgres_adapter.mjs.map +1 -1
  28. package/dist/cli/routes.mjs +33 -17
  29. package/dist/cli/routes.mjs.map +1 -1
  30. package/dist/cli/server.mjs +84 -80
  31. package/dist/cli/server.mjs.map +1 -1
  32. package/dist/cli/static_files.mjs +5 -4
  33. package/dist/cli/static_files.mjs.map +1 -1
  34. package/dist/client_identity.mjs +250 -0
  35. package/dist/client_identity.mjs.map +1 -0
  36. package/dist/database.mjs +23 -8
  37. package/dist/database.mjs.map +1 -1
  38. package/dist/endpoint.mjs +11 -7
  39. package/dist/endpoint.mjs.map +1 -1
  40. package/dist/group.mjs +34 -16
  41. package/dist/group.mjs.map +1 -1
  42. package/dist/http_failure.mjs +9 -2
  43. package/dist/http_failure.mjs.map +1 -1
  44. package/dist/longpoll_broker.mjs +9 -8
  45. package/dist/longpoll_broker.mjs.map +1 -1
  46. package/dist/longpoll_options.mjs +8 -7
  47. package/dist/longpoll_options.mjs.map +1 -1
  48. package/dist/longpoll_session.mjs +11 -10
  49. package/dist/longpoll_session.mjs.map +1 -1
  50. package/dist/options.mjs +29 -3
  51. package/dist/options.mjs.map +1 -1
  52. package/dist/origin.mjs +87 -0
  53. package/dist/origin.mjs.map +1 -0
  54. package/dist/policy.mjs +121 -0
  55. package/dist/policy.mjs.map +1 -0
  56. package/dist/postgres_adapter.mjs +3 -2
  57. package/dist/postgres_adapter.mjs.map +1 -1
  58. package/dist/postgres_worker.mjs +15 -14
  59. package/dist/postgres_worker.mjs.map +1 -1
  60. package/dist/response.mjs +1 -1
  61. package/dist/response.mjs.map +1 -1
  62. package/dist/route_info.mjs +1 -1
  63. package/dist/route_info.mjs.map +1 -1
  64. package/dist/routes.mjs +33 -17
  65. package/dist/routes.mjs.map +1 -1
  66. package/dist/runtime.mjs +227 -112
  67. package/dist/runtime.mjs.map +1 -1
  68. package/dist/server.mjs +84 -80
  69. package/dist/server.mjs.map +1 -1
  70. package/dist/server_context.mjs +21 -9
  71. package/dist/server_context.mjs.map +1 -1
  72. package/dist/static_files.mjs +5 -4
  73. package/dist/static_files.mjs.map +1 -1
  74. package/dist/token.mjs +34 -7
  75. package/dist/token.mjs.map +1 -1
  76. package/dist/tokens.mjs +11 -2
  77. package/dist/tokens.mjs.map +1 -1
  78. package/dist/worker.mjs +7 -6
  79. package/dist/worker.mjs.map +1 -1
  80. package/docs/security.md +420 -0
  81. package/examples/security/README.md +160 -0
  82. package/examples/security/deploy.xml +12 -0
  83. package/examples/security/handlers.lango +610 -0
  84. package/examples/security/package.json +19 -0
  85. package/examples/security/passwords.lango +61 -0
  86. package/examples/security/routes.xml +14 -0
  87. package/examples/security/schema.lango +91 -0
  88. package/examples/security/setup.lango +30 -0
  89. package/package.json +12 -6
  90. package/src/client_identity.lango +184 -0
  91. package/src/database.lango +15 -4
  92. package/src/endpoint.lango +12 -5
  93. package/src/group.lango +25 -21
  94. package/src/http_failure.lango +9 -5
  95. package/src/longpoll_options.lango +11 -5
  96. package/src/options.lango +34 -1
  97. package/src/origin.lango +56 -0
  98. package/src/policy.lango +84 -0
  99. package/src/response.lango +1 -1
  100. package/src/route_info.lango +2 -0
  101. package/src/routes.lango +30 -15
  102. package/src/runtime.lango +131 -80
  103. package/src/server.lango +6 -2
  104. package/src/server_context.lango +10 -2
  105. package/src/token.lango +26 -5
  106. 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. 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
@@ -409,18 +409,56 @@ contain at least 32 characters and should be cryptographically random. Only
409
409
  HS256 is accepted; algorithm, key ID, issuer, audience, expiry, and server-owned
410
410
  timestamps are checked. Keys are never generated or stored by the server.
411
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
+
412
438
  ## Contexts and authorization
413
439
 
414
440
  Handlers and events can declare `context request`, `response`, `token`, and `log`.
415
441
  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.
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.
424
462
 
425
463
  Tokens arrive in `Authorization: Bearer <jwt>` and successful replies contain
426
464
  `X-Lango-Token`. Missing tokens create an anonymous identity with a UUID
@@ -430,17 +468,18 @@ Unauthorized requests do not receive a newly created token.
430
468
 
431
469
  `context token` supports:
432
470
 
433
- * `clientId?`, `auth?`, `expiresAt?`: getter-only identity, comma-separated
434
- 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
435
473
  attempts to shadow these properties. Use the controlled methods below to update
436
474
  claims or permissions.
437
- * `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.
438
477
  * `get(name)`, `set(name, value)`: JSON custom claims; server-owned JWT fields are
439
478
  protected. `get` returns a copy for structured values.
440
479
  * `renew()`: requests renewal after successful serialization and SQL cleanup on
441
480
  a reply with a status below 400. It does not immediately change `expiresAt?`.
442
481
 
443
- Default endpoint auth is `login`. `auth="anonymous"` permits anonymous callers;
482
+ Default endpoint policy is `login`. `policy="anonymous"` permits anonymous callers;
444
483
  other values require that exact permission. `admin` does not imply `login`.
445
484
  The application authenticates credentials and grants permissions. These methods
446
485
  do not authenticate anyone automatically.
@@ -460,17 +499,166 @@ before renewal and signing; an expired token cannot be revived. Failed or
460
499
  rejected requests publish no renewal. Previously issued tokens remain valid
461
500
  until their own expiry unless the application's Validate policy revokes them.
462
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
+
463
645
  ## Events
464
646
 
465
647
  Event modules and function names are strings, resolved during worker startup.
466
648
  Promise results are supported, and events run under the request's contexts.
467
649
 
468
- * **register(input)** runs for a tokenless request after assigning `clientId`,
469
- 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
470
658
  prevents the handler and publishes no token. Return values are ignored; throw
471
659
  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.
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.
474
662
  * **validate(input)** receives null and runs after standard JWT verification
475
663
  when the signed `validatedAt` is at least one second old. It receives a read-only
476
664
  token. Only `true` continues; `false` produces 401. Exceptions, invalid return
@@ -491,7 +679,7 @@ Promise results are supported, and events run under the request's contexts.
491
679
  the successful response. Enabling this event exposes application input/output
492
680
  to its configured handler; redact credentials and other sensitive fields there.
493
681
 
494
- Each event has `eventTimeoutMs`. The request deadline covers queueing, Register,
682
+ Each event has `eventTimeoutMs`. The request deadline covers queueing, client verification, Register,
495
683
  Validate, and the handler; Request has its own event deadline after the result is
496
684
  prepared. A hard timeout terminates the worker and the pool replaces it. Tasks
497
685
  are never automatically retried: worker termination cannot roll back completed
@@ -571,7 +759,7 @@ builder.configure({
571
759
  ```
572
760
 
573
761
  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
762
+ DB scope before client verification/Register/Validate and keeps it available to the handler. Request
575
763
  gets a separate clean scope after the handler result is serialized. Scopes cannot
576
764
  be reused after completion. Physical connections are released on shutdown; worker
577
765
  replacement discards the old connection and creates a new one. If DB configuration
@@ -582,7 +770,6 @@ Application code uses Lango SQL rather than a driver API:
582
770
 
583
771
  ```lango
584
772
  findCustomer(input)
585
- context db
586
773
  row = SQL
587
774
  select id, name from customer where id = :id
588
775
  row.id = input.id
@@ -597,8 +784,11 @@ findCustomer(input)
597
784
 
598
785
  **Build all SQL application modules with lango-js 0.1.13 or newer.** SQL and
599
786
  `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.
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.
602
792
 
603
793
  Transactions are explicit. The server never implicitly commits a transaction.
604
794
  An open transaction at successful scope completion is rolled back and reported as
@@ -891,3 +1081,25 @@ invoked; raw JWTs and unverified claims are not logged as client identity.
891
1081
  Expired or invalid tokens can occur during ordinary session lifetimes, but a
892
1082
  failed startup is still a logged rejection. Detailed internal failures retain
893
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.
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}