@lango-project/lango-server 0.2.0 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +290 -27
- package/dist/.lango/runtime.mjs +24 -1
- package/dist/body_reader.mjs +15 -14
- package/dist/body_reader.mjs.map +1 -1
- package/dist/cli/.lango/runtime.mjs +24 -1
- package/dist/cli/body_reader.mjs +15 -14
- package/dist/cli/body_reader.mjs.map +1 -1
- package/dist/cli/client_identity.mjs +250 -0
- package/dist/cli/client_identity.mjs.map +1 -0
- package/dist/cli/database.mjs +23 -8
- package/dist/cli/database.mjs.map +1 -1
- package/dist/cli/endpoint.mjs +11 -7
- package/dist/cli/endpoint.mjs.map +1 -1
- package/dist/cli/error_details.mjs +45 -0
- package/dist/cli/error_details.mjs.map +1 -0
- package/dist/cli/longpoll_broker.mjs +9 -8
- package/dist/cli/longpoll_broker.mjs.map +1 -1
- package/dist/cli/longpoll_options.mjs +8 -7
- package/dist/cli/longpoll_options.mjs.map +1 -1
- package/dist/cli/longpoll_session.mjs +11 -10
- package/dist/cli/longpoll_session.mjs.map +1 -1
- package/dist/cli/options.mjs +29 -3
- package/dist/cli/options.mjs.map +1 -1
- package/dist/cli/origin.mjs +87 -0
- package/dist/cli/origin.mjs.map +1 -0
- package/dist/cli/policy.mjs +121 -0
- package/dist/cli/policy.mjs.map +1 -0
- package/dist/cli/postgres_adapter.mjs +3 -2
- package/dist/cli/postgres_adapter.mjs.map +1 -1
- package/dist/cli/routes.mjs +33 -17
- package/dist/cli/routes.mjs.map +1 -1
- package/dist/cli/server.mjs +148 -101
- package/dist/cli/server.mjs.map +1 -1
- package/dist/cli/static_files.mjs +7 -4
- package/dist/cli/static_files.mjs.map +1 -1
- package/dist/cli/trace.mjs +53 -0
- package/dist/cli/trace.mjs.map +1 -0
- package/dist/client_identity.mjs +250 -0
- package/dist/client_identity.mjs.map +1 -0
- package/dist/database.mjs +23 -8
- package/dist/database.mjs.map +1 -1
- package/dist/endpoint.mjs +11 -7
- package/dist/endpoint.mjs.map +1 -1
- package/dist/error_details.mjs +45 -0
- package/dist/error_details.mjs.map +1 -0
- package/dist/group.mjs +34 -16
- package/dist/group.mjs.map +1 -1
- package/dist/http_failure.mjs +9 -2
- package/dist/http_failure.mjs.map +1 -1
- package/dist/longpoll_broker.mjs +9 -8
- package/dist/longpoll_broker.mjs.map +1 -1
- package/dist/longpoll_options.mjs +8 -7
- package/dist/longpoll_options.mjs.map +1 -1
- package/dist/longpoll_session.mjs +11 -10
- package/dist/longpoll_session.mjs.map +1 -1
- package/dist/options.mjs +29 -3
- package/dist/options.mjs.map +1 -1
- package/dist/origin.mjs +87 -0
- package/dist/origin.mjs.map +1 -0
- package/dist/policy.mjs +121 -0
- package/dist/policy.mjs.map +1 -0
- package/dist/postgres_adapter.mjs +3 -2
- package/dist/postgres_adapter.mjs.map +1 -1
- package/dist/postgres_worker.mjs +15 -14
- package/dist/postgres_worker.mjs.map +1 -1
- package/dist/request_identity.mjs +22 -0
- package/dist/request_identity.mjs.map +1 -0
- package/dist/response.mjs +1 -1
- package/dist/response.mjs.map +1 -1
- package/dist/route_info.mjs +1 -1
- package/dist/route_info.mjs.map +1 -1
- package/dist/routes.mjs +33 -17
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +241 -110
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs +148 -101
- package/dist/server.mjs.map +1 -1
- package/dist/server_context.mjs +21 -9
- package/dist/server_context.mjs.map +1 -1
- package/dist/static_files.mjs +7 -4
- package/dist/static_files.mjs.map +1 -1
- package/dist/token.mjs +34 -7
- package/dist/token.mjs.map +1 -1
- package/dist/tokens.mjs +11 -2
- package/dist/tokens.mjs.map +1 -1
- package/dist/trace.mjs +53 -0
- package/dist/trace.mjs.map +1 -0
- package/dist/worker.mjs +8 -6
- package/dist/worker.mjs.map +1 -1
- package/docs/security.md +420 -0
- package/examples/security/README.md +160 -0
- package/examples/security/deploy.xml +12 -0
- package/examples/security/handlers.lango +610 -0
- package/examples/security/package.json +19 -0
- package/examples/security/passwords.lango +61 -0
- package/examples/security/routes.xml +14 -0
- package/examples/security/schema.lango +91 -0
- package/examples/security/setup.lango +30 -0
- package/package.json +12 -6
- package/src/client_identity.lango +184 -0
- package/src/database.lango +15 -4
- package/src/endpoint.lango +12 -5
- package/src/error_details.lango +21 -0
- package/src/group.lango +25 -21
- package/src/http_failure.lango +9 -5
- package/src/longpoll_options.lango +11 -5
- package/src/options.lango +34 -1
- package/src/origin.lango +56 -0
- package/src/policy.lango +84 -0
- package/src/request_identity.lango +9 -0
- package/src/response.lango +1 -1
- package/src/route_info.lango +2 -0
- package/src/routes.lango +30 -15
- package/src/runtime.lango +149 -77
- package/src/server.lango +48 -7
- package/src/server_context.lango +10 -2
- package/src/static_files.lango +3 -0
- package/src/token.lango +26 -5
- package/src/tokens.lango +10 -3
- package/src/trace.lango +23 -0
- package/src/worker.lango +1 -0
package/docs/security.md
ADDED
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
# Browser identity, authentication and revocation
|
|
2
|
+
|
|
3
|
+
This guide accompanies the runnable [security example](../examples/security/README.md).
|
|
4
|
+
It implements an application security policy on top of Lango Server; it does not
|
|
5
|
+
change Server's token API or silently install policy in unrelated applications.
|
|
6
|
+
The example uses Lango SQL and SQLite. SQL and transaction statements use the
|
|
7
|
+
server-provided database scope without a `context db` declaration. It is a reference implementation for a
|
|
8
|
+
same-origin HTTPS browser application, not an identity provider or a complete
|
|
9
|
+
account-management product.
|
|
10
|
+
|
|
11
|
+
## 1. Security contract
|
|
12
|
+
|
|
13
|
+
| Requirement | Mechanism |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| Anonymous clients can do limited work | One server-issued clientId, a protected cookie and an atomic anonymous quota. |
|
|
16
|
+
| Client/login history is attributable | Client records, durable login grants, and bounded audit events. |
|
|
17
|
+
| Login can survive reloads | An explicitly remembered, revocable server-side grant restored by the protected browser cookie. |
|
|
18
|
+
| Authentication can require renewal | A password-authentication timestamp independent of JWT renewal and activity. |
|
|
19
|
+
| Admin access requires recent authentication | Current DB admin role plus a five-minute limit on the shared password-verification time. |
|
|
20
|
+
| Banning affects every login | A live user status/version check on every protected request and revocation of every user grant. |
|
|
21
|
+
| Users can log out selected clients | An ownership-checked client lookup revokes that user's grants for that client. |
|
|
22
|
+
| A copied JWT has limited value | The JWT must match a separate HttpOnly browser cookie and live DB binding. |
|
|
23
|
+
|
|
24
|
+
Authorization must be checked for every request and deny unknown actions. Here,
|
|
25
|
+
declarative route policy attributes and a startup validator prevent unguarded
|
|
26
|
+
endpoints from being added to the example. Server checks membership and signed
|
|
27
|
+
password freshness first; the application guard checks current DB state. This follows the [OWASP authorization guidance](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html).
|
|
28
|
+
|
|
29
|
+
## 2. Identify what was stolen
|
|
30
|
+
|
|
31
|
+
A bearer JWT alone is replayable by whoever possesses it. A signature proves
|
|
32
|
+
issuance and integrity; it does not prove that the caller is the original browser.
|
|
33
|
+
The JWT design guidance discusses a separately hardened browser cookie as an
|
|
34
|
+
additional binding against token sidejacking. [OWASP JWT guidance](https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_Cheat_Sheet.html)
|
|
35
|
+
|
|
36
|
+
Lango Server creates and manages a 256-bit random cookie:
|
|
37
|
+
|
|
38
|
+
```text
|
|
39
|
+
__Host-lango-client=<random-secret>; Path=/; Secure; HttpOnly; SameSite=Strict
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
There is no Domain attribute. Only its SHA-256 hash is stored in the database
|
|
43
|
+
and JWT. Server verifies the binding before application middleware; the application then
|
|
44
|
+
checks its live user/grant policy:
|
|
45
|
+
|
|
46
|
+
1. The JWT passed Server's signature, issuer, audience and expiry checks.
|
|
47
|
+
2. The raw cookie hashes to a live record in Server's owned client store.
|
|
48
|
+
3. JWT clientId and the server-reserved clientProof match that record.
|
|
49
|
+
4. For protected actions, the grant, account version, current role and time limits
|
|
50
|
+
are still valid in the DB.
|
|
51
|
+
|
|
52
|
+
Login and password confirmation rotate the cookie binding. Other tokens from
|
|
53
|
+
before that rotation no longer match it. Remembered restoration retains the original
|
|
54
|
+
password-verification time; it does not reset it. This is session binding, **not**
|
|
55
|
+
an independent second factor.
|
|
56
|
+
|
|
57
|
+
| Compromise | Consequence in this example |
|
|
58
|
+
| --- | --- |
|
|
59
|
+
| JWT alone | Cannot use bound browser endpoints, including admin; cannot bootstrap that identity without its cookie. |
|
|
60
|
+
| JWT plus an unrelated browser's cookie | Rejected because identities/proofs do not match. |
|
|
61
|
+
| Browser cookie alone with an active remembered grant | Can restore remembered login through bootstrap, including admin access if the current role and original password-verification time still satisfy policy. The cookie is a valuable refresh credential. |
|
|
62
|
+
| JWT and matching cookie | Can act within live DB policy and the shared password-freshness limits. |
|
|
63
|
+
| Active same-origin XSS | May send credentialed requests even though JavaScript cannot read the HttpOnly cookie. HttpOnly does not make an XSS-compromised browser safe. |
|
|
64
|
+
| Revoked grant or banned user | Old JWTs do not restore the revoked authorization. |
|
|
65
|
+
| Stolen DB read access | Exposes identity/audit metadata and password hashes, but not raw cookie secrets; this is still a serious breach. |
|
|
66
|
+
|
|
67
|
+
Do not claim that all token theft is harmless. For stronger resistance to copied
|
|
68
|
+
credentials, extend the client and server with a reviewed device-key proof or
|
|
69
|
+
WebAuthn flow, and require phishing-resistant MFA for administrators. That is
|
|
70
|
+
outside this example. A non-exportable key can limit secret extraction, but
|
|
71
|
+
active XSS may still invoke available browser operations.
|
|
72
|
+
|
|
73
|
+
The current Lango Client stores a JWT in localStorage. This example does not
|
|
74
|
+
remove that behavior; it reduces what a copied JWT alone can do. Never place the
|
|
75
|
+
raw browser secret or a refresh credential in JavaScript-visible storage.
|
|
76
|
+
|
|
77
|
+
## 3. Minimum identity model
|
|
78
|
+
|
|
79
|
+
| Identifier | Purpose |
|
|
80
|
+
| --- | --- |
|
|
81
|
+
| `clientId` | Immutable server-issued identity for this browser profile (the device in this model). |
|
|
82
|
+
| `grantId` | Revocable authenticated login associating a client with a user. |
|
|
83
|
+
| `userId` | Account identity obtained from the server-side grant. |
|
|
84
|
+
| `auth_version` | Account generation used to invalidate older grants. |
|
|
85
|
+
|
|
86
|
+
There is no separate deviceId, browserId, client-alias table or authentication
|
|
87
|
+
sessionId. A client can exist without an account. Login creates a grant linking
|
|
88
|
+
that same clientId to a user; logout keeps the client and its anonymous quota.
|
|
89
|
+
Only one grant is current per client. Logging into another account revokes the
|
|
90
|
+
previous grant, while its audit history remains attributable to the earlier user.
|
|
91
|
+
|
|
92
|
+
This client is a browser profile, not proof of a physical device or person. Cookie
|
|
93
|
+
deletion, private browsing or another profile creates a new client. Several people
|
|
94
|
+
can share one client. A later login does not prove who performed earlier anonymous
|
|
95
|
+
operations. Anonymous quotas require additional abuse controls for determined
|
|
96
|
+
callers who repeatedly create new profiles.
|
|
97
|
+
|
|
98
|
+
## 4. Database model and client lifecycle
|
|
99
|
+
|
|
100
|
+
The [schema](../examples/security/schema.lango) contains five tables:
|
|
101
|
+
|
|
102
|
+
- `security_clients`: clientId, current grant, anonymous usage,
|
|
103
|
+
registration/last-seen times and initial/latest IP and User-Agent.
|
|
104
|
+
- `security_users`: username, password hash, current role, ban flag and auth version.
|
|
105
|
+
- `security_grants`: client/user association, expiry, activity, password verification,
|
|
106
|
+
revocation and one shared password-verification timestamp.
|
|
107
|
+
- `security_limits`: atomic rate-limit buckets keyed by an application HMAC.
|
|
108
|
+
- `security_audit`: request/client/user association, hashed grant reference, event,
|
|
109
|
+
bounded target, peer IP and User-Agent.
|
|
110
|
+
|
|
111
|
+
Server's `<client maxAgeSeconds="2592000"/>` configuration owns identity creation,
|
|
112
|
+
credential hashing, storage, verification, cookie issuance and rotation. It needs
|
|
113
|
+
persistent database storage and the required HTTPS Origin policy. Server initializes
|
|
114
|
+
its internal `_lango_clients` table before starting workers; all pods must share
|
|
115
|
+
that authoritative store. Application code never reads or updates the internal
|
|
116
|
+
credential table and does not parse or emit the managed cookie.
|
|
117
|
+
|
|
118
|
+
Register receives `token.clientId?` after Server creates the client, and saves that
|
|
119
|
+
identifier with registration metadata. It does not generate a clientId/sessionId.
|
|
120
|
+
A later rejected request can leave a registration without a published token/cookie;
|
|
121
|
+
registration itself is not evidence of a successful operation.
|
|
122
|
+
|
|
123
|
+
For a tokenless request, a valid managed cookie restores the same clientId in a
|
|
124
|
+
clean token. Register is skipped; Server verifies the client proof and manages
|
|
125
|
+
token renewal without an application Validate event.
|
|
126
|
+
No application identity-restoration event is involved. App permissions and user/
|
|
127
|
+
grant/admin claims are empty until application logic explicitly supplies them.
|
|
128
|
+
Bootstrap restores only an eligible remembered grant and its original password-verification time.
|
|
129
|
+
A cookie-free tokenless request instead creates a new client; a supplied invalid
|
|
130
|
+
or expired JWT is rejected without cookie fallback or request retry.
|
|
131
|
+
|
|
132
|
+
Login/password confirmation request `server.rotateClient()`. Server rotates its
|
|
133
|
+
credential only while preparing a successful reply, invalidating the old cookie
|
|
134
|
+
and token proof. Failed replies discard the request. ClientId remains unchanged.
|
|
135
|
+
The application decides authentication and authorization; Server owns the transport
|
|
136
|
+
credential lifecycle. The reserved clientProof token field cannot be changed by
|
|
137
|
+
application token setters.
|
|
138
|
+
|
|
139
|
+
Initial metadata stays unchanged; successful bound requests update latest metadata
|
|
140
|
+
and last-seen time. User-Agent is limited to 512 characters and control characters
|
|
141
|
+
are removed. IP is the socket's `request.remoteAddress`, not client-controlled
|
|
142
|
+
Forwarded/X-Forwarded-For. Behind a proxy it identifies that peer until a reviewed
|
|
143
|
+
trusted-proxy policy is implemented. IP and User-Agent are observations, not
|
|
144
|
+
credentials: changes do not change clientId or revoke authentication. Limit access
|
|
145
|
+
and retention of this potentially personal audit data.
|
|
146
|
+
|
|
147
|
+
This is a fresh-database example. No old-schema migration or backfill is provided.
|
|
148
|
+
For multiple pods, use one authoritative transactional user/grant store; separate
|
|
149
|
+
SQLite files cannot provide global revocation. The runnable example is verified
|
|
150
|
+
with SQLite, not a multi-pod PostgreSQL deployment.
|
|
151
|
+
|
|
152
|
+
## 5. Login and remembered authentication
|
|
153
|
+
|
|
154
|
+
The example accepts only JSON POST endpoints. Server establishes client identity automatically. Call `/bootstrap` to restore
|
|
155
|
+
an eligible remembered login; it also returns the current identity. Then call `/auth/login` with username, password and a boolean remember.
|
|
156
|
+
|
|
157
|
+
Passwords are verified outside the write transaction. Before issuing a grant,
|
|
158
|
+
the transaction locks/rechecks the account's ban state, auth version and password
|
|
159
|
+
record so a concurrent change cannot reuse the earlier verification result.
|
|
160
|
+
Login revokes the previous grant, creates a new one and rotates the browser secret.
|
|
161
|
+
|
|
162
|
+
A remembered grant can be resumed after bootstrap, but only while its DB lifetime
|
|
163
|
+
and idle policy remain valid. A non-remembered grant is **not restored by
|
|
164
|
+
bootstrap**, including a page reload. This explicit behavior avoids pretending
|
|
165
|
+
that browser-close detection is reliable when the stock client persists JWTs.
|
|
166
|
+
A still-open page can keep using the non-remembered grant until its limits apply.
|
|
167
|
+
|
|
168
|
+
If an expired saved JWT is rejected by Lango Server before application code runs,
|
|
169
|
+
clear only that JWT and let the user explicitly reload/bootstrap without it.
|
|
170
|
+
The browser cookie may then resume a remembered grant. Do not automatically
|
|
171
|
+
repeat a business operation that received an error. The current stock client
|
|
172
|
+
already stops after clearing a rejected startup JWT; it does not retry for you.
|
|
173
|
+
|
|
174
|
+
JWT refresh, UI Ping and last activity are not password verification. They must
|
|
175
|
+
not reset authenticated_at. Server-side idle, absolute and reauthentication
|
|
176
|
+
limits serve different purposes. [OWASP session guidance](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html)
|
|
177
|
+
|
|
178
|
+
### Example policy values
|
|
179
|
+
|
|
180
|
+
These are application choices, not universal compliance requirements:
|
|
181
|
+
|
|
182
|
+
| Setting | Example value | Extended by ordinary JWT/Ping renewal? |
|
|
183
|
+
| --- | --- | --- |
|
|
184
|
+
| JWT expiry | 15 minutes | Server may renew it; this never replaces DB checks. |
|
|
185
|
+
| Browser cookie | 30 days | It identifies a browser, not an unlimited login. |
|
|
186
|
+
| Non-remembered grant absolute lifetime | 8 hours | No |
|
|
187
|
+
| Remembered grant absolute lifetime | 14 days | No |
|
|
188
|
+
| Grant idle lifetime | 3 days | Only real authenticated action updates activity; whoami/bootstrap do not. |
|
|
189
|
+
| Password reauthentication interval | 12 hours | No |
|
|
190
|
+
| Sensitive account action freshness | 15 minutes | No |
|
|
191
|
+
| Admin password freshness | 5 minutes since the same password verification | No |
|
|
192
|
+
|
|
193
|
+
Grant lifetimes are in `configuration()` in [handlers.lango](../examples/security/handlers.lango).
|
|
194
|
+
Password-freshness defaults and admin requirements are in `deploy.xml` under
|
|
195
|
+
`policies`; `routes.xml` tightens client revocation to 15 minutes.
|
|
196
|
+
Choose shorter periods for higher-risk accounts. A short JWT lifetime alone
|
|
197
|
+
does not bound a remembered login. Do not let heartbeat traffic keep a human
|
|
198
|
+
session indefinitely active.
|
|
199
|
+
|
|
200
|
+
## 6. Admin freshness uses the shared login time
|
|
201
|
+
|
|
202
|
+
All protected `/admin` operations require the **current DB** admin role and
|
|
203
|
+
password verification within the past five minutes. There is one password time:
|
|
204
|
+
`security_grants.authenticated_at` is its authoritative DB value and the signed
|
|
205
|
+
`authenticatedAt` claim carries that same value. There is no admin proof, nonce,
|
|
206
|
+
separate admin clock or elevation endpoint.
|
|
207
|
+
|
|
208
|
+
A normal admin login already satisfies the admin freshness rule. When admin
|
|
209
|
+
freshness expires, `POST /auth/reauth` verifies the current account's password,
|
|
210
|
+
updates the shared timestamp, refreshes policies from the current DB role and
|
|
211
|
+
rotates the client credential. That confirmation satisfies both login and admin
|
|
212
|
+
freshness. Ordinary requests, Ping and JWT renewal never reset password time.
|
|
213
|
+
A remembered bootstrap retains the previous time rather than treating restoration
|
|
214
|
+
as a fresh password verification.
|
|
215
|
+
|
|
216
|
+
Central policy configuration gives login a 12-hour limit and admin a five-minute
|
|
217
|
+
limit. `/auth/reauth` uses `policy="anonymous"` so expired freshness cannot block
|
|
218
|
+
the confirmation operation itself. The application still requires a live current
|
|
219
|
+
grant, matching user identity and a verified password inside its transaction.
|
|
220
|
+
Anonymous access to this route never means anonymous password confirmation.
|
|
221
|
+
|
|
222
|
+
Every admin action rechecks role, ban and grant status. Protect admin actions,
|
|
223
|
+
not just the route that draws an admin page. Serving a static HTML shell at
|
|
224
|
+
GET `/admin` is not a permission decision; protected data is fetched by POST.
|
|
225
|
+
Only the built-in pre-handler login challenge may use the optional UI needLogin
|
|
226
|
+
flow and one automatic replay. Live DB rejections remain ordinary failures; they
|
|
227
|
+
must not be blindly retried. Password confirmation is not MFA.
|
|
228
|
+
|
|
229
|
+
## 7. Ban, logout and selected-client revocation
|
|
230
|
+
|
|
231
|
+
Ban updates the user flag, increments auth_version and revokes **all** grants
|
|
232
|
+
in one transaction. Guard checks current DB state on every request. This example does not register
|
|
233
|
+
a Validate event and does not rely on its freshness interval. Role demotion is
|
|
234
|
+
also read live. An already completed side effect cannot be undone; an operation
|
|
235
|
+
that serialized before the ban may finish before the ban commits. The guarantee
|
|
236
|
+
is rejection at the next authorization check after the committed change.
|
|
237
|
+
Unbanning does not revive revoked grants; require a new login.
|
|
238
|
+
|
|
239
|
+
`/account/clients` lists the authenticated user's active grants and associated
|
|
240
|
+
clientId and initial/latest connection metadata. `/account/revoke-client` checks
|
|
241
|
+
ownership and revokes that user's grants directly for the selected client. A caller
|
|
242
|
+
cannot revoke another account's clients by supplying a guessed ID. This operation
|
|
243
|
+
requires recent password authentication. Revocation keeps anonymous browser
|
|
244
|
+
identity/quota; it does not reset guest usage.
|
|
245
|
+
|
|
246
|
+
`/auth/logout` revokes the browser's current grant and clears identity and policy
|
|
247
|
+
claims. It remains usable for the bound browser even if its old grant was revoked
|
|
248
|
+
or the account was banned. Logout does not mean the physical user is known or
|
|
249
|
+
that anonymous use can be prevented after deleting cookies.
|
|
250
|
+
|
|
251
|
+
No endpoint accepts userId from input as the actor. The ban target and selected
|
|
252
|
+
client are untrusted resource identifiers checked against the authenticated actor.
|
|
253
|
+
Password reset/change should similarly increment auth_version, revoke grants and
|
|
254
|
+
clear authentication claims; this example provisions users but does not implement recovery.
|
|
255
|
+
|
|
256
|
+
## 8. Passwords, requests and transport
|
|
257
|
+
|
|
258
|
+
The example uses Node's built-in scrypt (`N=131072, r=8, p=1`, maxmem 256 MiB),
|
|
259
|
+
a random salt and timing-safe comparison. Unknown users still perform a dummy
|
|
260
|
+
verification. Passwords are not trimmed. Provisioning requires at least 15
|
|
261
|
+
Unicode code points and at most 512 UTF-8 bytes. Add breached-password
|
|
262
|
+
screening and deliberate Unicode policy before offering public registration.
|
|
263
|
+
Argon2id is OWASP's preferred choice; scrypt is a supported alternative, chosen
|
|
264
|
+
here to avoid introducing another native dependency.
|
|
265
|
+
[OWASP password storage guidance](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html),
|
|
266
|
+
[Node crypto API](https://nodejs.org/docs/latest-v24.x/api/crypto.html).
|
|
267
|
+
|
|
268
|
+
Rate limits are reserved atomically **before** password hashing and survive failed
|
|
269
|
+
requests. Register also limits new-client creation before inserting registration records.
|
|
270
|
+
They cover request source and account; browser-cookie checks alone are
|
|
271
|
+
not abuse protection. Tune expensive hashing to available worker memory. Global
|
|
272
|
+
account throttling can also be abused to inconvenience an account; production
|
|
273
|
+
risk controls should handle that deliberately rather than silently removing limits.
|
|
274
|
+
|
|
275
|
+
The server's `<origin urlEnv="LANGO_ORIGIN" required="true"/>` policy requires
|
|
276
|
+
an exact external origin. Missing/null/foreign Origin and disallowed Fetch
|
|
277
|
+
Metadata fail with 403 before lifecycle events or application middleware.
|
|
278
|
+
There is no application `checkOrigin()` function. SameSite is an additional layer,
|
|
279
|
+
not a substitute. Origin is a browser CSRF defense, not proof against a non-browser
|
|
280
|
+
attacker; cookie/JWT/DB checks remain necessary.
|
|
281
|
+
The external origin comes from configuration, never arbitrary forwarded headers.
|
|
282
|
+
[OWASP CSRF guidance](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html).
|
|
283
|
+
|
|
284
|
+
Deploy behind HTTPS, with the server bound to loopback/private networking. Do not
|
|
285
|
+
strip Secure for a convenient production demo. Restrict direct access, configure
|
|
286
|
+
TLS/HSTS and a restrictive CSP for the UI, and keep dependencies patched. No
|
|
287
|
+
cross-origin credentialed CORS behavior is provided. With a reverse proxy,
|
|
288
|
+
remoteAddress identifies that proxy; configure trusted source-IP handling at a
|
|
289
|
+
reviewed boundary and rate-limit real client IPs at the edge. Do not simply
|
|
290
|
+
trust client-supplied X-Forwarded-For.
|
|
291
|
+
|
|
292
|
+
## 9. Audit without leaking credentials
|
|
293
|
+
|
|
294
|
+
Routine attribution should happen server-side without extra prompts, not through
|
|
295
|
+
covert fingerprinting or cross-site tracking. Keep a clear application privacy
|
|
296
|
+
notice and retention policy. Browser association is evidence of a client profile,
|
|
297
|
+
not proof of the human at the keyboard.
|
|
298
|
+
|
|
299
|
+
The example records login/logout, password confirmation, client revocation, ban,
|
|
300
|
+
successful guarded actions and denied actions. Grant references are hashed.
|
|
301
|
+
Passwords, JWTs, raw cookies, raw request bodies and arbitrary response contents
|
|
302
|
+
are excluded. This follows the exclusions in [OWASP logging guidance](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html).
|
|
303
|
+
|
|
304
|
+
Successful business and audit writes commit together here. Request-denial and
|
|
305
|
+
credential-failure records are written after/outside a rolled-back business
|
|
306
|
+
transaction. Do not replace this with a Request event that logs every raw input:
|
|
307
|
+
login inputs contain passwords. Protect audit access, export critical records to
|
|
308
|
+
an append-only destination, and alert on suspicious patterns. The local audit
|
|
309
|
+
table is not tamper-proof against a database administrator or compromised writer.
|
|
310
|
+
|
|
311
|
+
Schedule retention cleanup for expired grants, inactive clients and rate-limit
|
|
312
|
+
buckets; never delete active revocation state merely to save space. Expired rate
|
|
313
|
+
buckets can be removed after all configured windows have elapsed. Back up and
|
|
314
|
+
protect the DB and signing/HMAC keys separately.
|
|
315
|
+
|
|
316
|
+
### Application rate-limit counters
|
|
317
|
+
|
|
318
|
+
`checkRateLimit(key, maximum, window)` counts calls in an application-selected
|
|
319
|
+
fixed window. Keys distinguish operations and subjects, such as
|
|
320
|
+
`register:<ip>` and `password-account:<account>`. The application chooses keys,
|
|
321
|
+
thresholds and timing; this policy is not applied automatically by Lango Server.
|
|
322
|
+
The window duration is expressed in milliseconds.
|
|
323
|
+
|
|
324
|
+
The helper computes HMAC-SHA256 of the key using `SECURITY_AUDIT_KEY` and uses
|
|
325
|
+
that stable digest as the `security_limits.bucket` primary key. This avoids raw
|
|
326
|
+
identifiers in the counter table; it is not necessary for the counting algorithm
|
|
327
|
+
and does not anonymize the separate audit records. `started_at` records the first
|
|
328
|
+
call in the current window, and `hits` records its call count.
|
|
329
|
+
|
|
330
|
+
One SQL INSERT ... ON CONFLICT ... RETURNING statement either creates the counter,
|
|
331
|
+
resets an expired window, or increments a live one. Updating and reading the count
|
|
332
|
+
in one statement avoids a separate SELECT/update race between workers. A count
|
|
333
|
+
above the maximum causes a 429 `RateLimited` rejection with Retry-After. Successful
|
|
334
|
+
and unsuccessful attempts both count. Call this helper before the business
|
|
335
|
+
transaction: rolling its writes back would also undo the attempt counter.
|
|
336
|
+
|
|
337
|
+
## 10. Integrating with Lango UI/Client
|
|
338
|
+
|
|
339
|
+
This example deliberately returns JSON so the authentication policy can be tested
|
|
340
|
+
independently of UI presentation. It does not automatically install a login dialog,
|
|
341
|
+
admin prompt or account/device screen in the current client.
|
|
342
|
+
|
|
343
|
+
To integrate it:
|
|
344
|
+
|
|
345
|
+
1. Put the security gate around **all** application UI handlers and lifecycle
|
|
346
|
+
endpoints; compose with UI's processHandlers/processStart wrappers inside it.
|
|
347
|
+
Do not register a bypassing raw ui endpoint beside secured ones.
|
|
348
|
+
2. Adapt the XML policy/freshness declarations and route validator deliberately. The current
|
|
349
|
+
JSON example refuses unrelated UI/template/longpoll routes at startup.
|
|
350
|
+
3. Keep standard POST `/` for UI startup; run browser binding/restoration in its
|
|
351
|
+
secured Start path. The sample's `/bootstrap` is not a replacement stock UI
|
|
352
|
+
startup endpoint.
|
|
353
|
+
4. Configure the optional UI `needLogin` handler for missing login or stale
|
|
354
|
+
authentication. After verified credentials, update the shared timestamp and
|
|
355
|
+
emit `loginSatisfied()`. Only a marked pre-handler challenge can replay once.
|
|
356
|
+
5. Cookie rotation makes other open forms/tabs' old JWT proofs stale. Forms sharing
|
|
357
|
+
an identical token update together; distinct scopes require an explicit reload.
|
|
358
|
+
Lango Client now notifies other same-origin tabs and keeps their inputs visible
|
|
359
|
+
behind an explicit reload notice; it never merges distinct token claims.
|
|
360
|
+
6. A guarded response must remain serializable before transaction commit. Do not
|
|
361
|
+
wrap arbitrary async work or live UI Control objects with the sample's synchronous
|
|
362
|
+
JSON transaction helper unchanged; convert the UI result inside its proper wrapper.
|
|
363
|
+
7. Check live DB policy before longpoll delivery and sensitive business mutations,
|
|
364
|
+
not only once when a connection opens. The example currently forbids longpoll.
|
|
365
|
+
|
|
366
|
+
For multiple pods use a shared transactional store and test locking/revocation
|
|
367
|
+
there. The sample serializes SQLite transactions with an initial write before
|
|
368
|
+
security reads, and locks the user record before decisions. It prioritizes a clear
|
|
369
|
+
reference over high read throughput. No unmeasured production-scale claim is made.
|
|
370
|
+
|
|
371
|
+
## 11. Verification and remaining scope
|
|
372
|
+
|
|
373
|
+
Run `npm run test:security` in the server checkout. It tests real HTTP with two
|
|
374
|
+
workers, including Register-before-bootstrap persistence, initial/latest metadata, unchanged clientId on tokenless restoration, anonymous quotas, authenticated/admin JWT theft without the
|
|
375
|
+
cookie, wrong browser binding, remembered restore, selective logout, foreign-client
|
|
376
|
+
revocation rejection, normal reauthentication, shared admin freshness/demotion, absolute
|
|
377
|
+
expiry, ban across two active logins, preserved guest quota and rejected origins.
|
|
378
|
+
|
|
379
|
+
The example does not implement MFA/WebAuthn, enrollment, password recovery,
|
|
380
|
+
email verification, automatic UI auth transitions, trusted-proxy parsing,
|
|
381
|
+
distributed risk scoring or durable external audit export. Those are explicit
|
|
382
|
+
integration decisions, not guarantees implied by a working login handler.
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
## Declarative policy requirements
|
|
386
|
+
|
|
387
|
+
`deploy.xml` declares the login/admin policies and their freshness limits.
|
|
388
|
+
`routes.xml` selects policy="anonymous", policy="login" or policy="admin" and
|
|
389
|
+
may tighten reauthSeconds for a specific operation. These are native Server endpoint/longpoll features, not
|
|
390
|
+
application middleware options. The example no longer has routePolicy(path).
|
|
391
|
+
The application guard reads the server-selected request.route metadata when it
|
|
392
|
+
needs to compare the same freshness requirement against authoritative DB state.
|
|
393
|
+
|
|
394
|
+
Login and remembered bootstrap attach exact login/admin policy memberships from
|
|
395
|
+
current user records and set authenticatedAt from the password verification time.
|
|
396
|
+
Password confirmation refreshes both memberships and that timestamp; logout clears
|
|
397
|
+
them. Server token renewal never pretends that a password was re-entered. Server
|
|
398
|
+
checks policy and freshness on every request regardless of Validate caching.
|
|
399
|
+
A missing admin membership produces Forbidden; a stale DB role still produces
|
|
400
|
+
AdminRequired in the guard even if the signed policy membership has not expired.
|
|
401
|
+
Login and password confirmation update the same timestamp; no admin-specific
|
|
402
|
+
verification state remains. A recent normal admin login satisfies admin freshness.
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
## Complete UI reference
|
|
406
|
+
|
|
407
|
+
The `lango-ui` repository now includes `examples/security`, a runnable Secure notes
|
|
408
|
+
application using this same security source and an actual needLogin screen.
|
|
409
|
+
Its middleware supplies an optional synchronous `represent(output)` callback to
|
|
410
|
+
`guard(handler, path, input, represent)`. Controls and commands become a plain
|
|
411
|
+
response inside the transaction; representation errors roll back writes. The JSON
|
|
412
|
+
example keeps the original three-argument guard behavior.
|
|
413
|
+
|
|
414
|
+
The `lango-client` command `npm run test:security` builds and installs the example
|
|
415
|
+
from local package archives, provisions real scrypt-backed users, removes the
|
|
416
|
+
compiler, and exercises it over HTTPS with Chromium. It verifies anonymous work,
|
|
417
|
+
wrong passwords, one-time replay of a DB write after login, remembered restoration,
|
|
418
|
+
shared password confirmation, logout, client/user attribution, UI representation
|
|
419
|
+
rollback, and ban across two independent clients. This adds real browser/TLS
|
|
420
|
+
verification; a distributed PostgreSQL deployment and MFA remain outside scope.
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# Security example
|
|
2
|
+
|
|
3
|
+
A runnable **JSON API** security example in Lango, using Lango Server and SQLite.
|
|
4
|
+
Read the [security guide](../../docs/security.md) for its threat model, identity
|
|
5
|
+
mapping and integration boundaries. The example does not modify the stock UI
|
|
6
|
+
client or implement login/admin dialogs automatically.
|
|
7
|
+
|
|
8
|
+
## Build
|
|
9
|
+
|
|
10
|
+
From the lango-server checkout:
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install
|
|
14
|
+
npm run build
|
|
15
|
+
npm install --prefix examples/security --ignore-scripts
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
The example package refers to the adjacent server checkout. Use matching local
|
|
19
|
+
compiler packages when testing unreleased Lango features.
|
|
20
|
+
|
|
21
|
+
## Provision accounts
|
|
22
|
+
|
|
23
|
+
From `examples/security`, create accounts before starting the server:
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
npm run build
|
|
27
|
+
npm run setup -- data/security.sqlite alice
|
|
28
|
+
npm run setup -- data/security.sqlite administrator admin
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Each setup invocation requires a different `SECURITY_SETUP_PASSWORD` environment
|
|
32
|
+
value, supplied through your local secret tooling. There are no built-in accounts
|
|
33
|
+
or default passwords. Passwords are read from the environment, not command-line
|
|
34
|
+
arguments, and are not printed. Clear the variable after provisioning. Usernames
|
|
35
|
+
are trimmed/lowercased; use 3–128 ASCII username characters matching
|
|
36
|
+
`[a-z0-9_.@+-]`. Passwords require at least 15 Unicode code points and at most 512
|
|
37
|
+
UTF-8 bytes. Running setup again for the same username fails rather than silently
|
|
38
|
+
resetting an account. The first account is a regular user; the second is an admin.
|
|
39
|
+
|
|
40
|
+
The example uses a fresh database; no old-schema migration is included.
|
|
41
|
+
|
|
42
|
+
## Run behind local HTTPS
|
|
43
|
+
|
|
44
|
+
Set these separately generated secrets/settings in the example process:
|
|
45
|
+
|
|
46
|
+
| Variable | Purpose |
|
|
47
|
+
| --- | --- |
|
|
48
|
+
| `LANGO_JWT_KEY` | JWT signing secret, at least 32 random characters. |
|
|
49
|
+
| `SECURITY_AUDIT_KEY` | Separate HMAC key for rate-limit identifiers, at least 32 random characters. |
|
|
50
|
+
| `LANGO_ORIGIN` | Exact externally visible HTTPS origin, e.g. `https://localhost:3443`, without trailing slash. |
|
|
51
|
+
|
|
52
|
+
Start `npm start` in `examples/security`. Terminate TLS at a reverse proxy listening
|
|
53
|
+
on that origin and forward only to `127.0.0.1:3000`. The default deploy configuration
|
|
54
|
+
has two workers, a 15-minute JWT TTL and `data/security.sqlite`.
|
|
55
|
+
Do not expose the cleartext listener publicly. A browser will not send this
|
|
56
|
+
example's Secure cookie over an ordinary non-HTTPS deployment.
|
|
57
|
+
|
|
58
|
+
## Register and bootstrap
|
|
59
|
+
|
|
60
|
+
The server owns clientId creation, cookie parsing, verification and continuity.
|
|
61
|
+
The `<client>` section in deploy.xml enables this with 30-day credential storage;
|
|
62
|
+
`<origin>` enforces the external HTTPS origin. The application does not define an
|
|
63
|
+
identity-restoration event or cookie helper.
|
|
64
|
+
|
|
65
|
+
Register receives the server-issued ID and observed `input.ip`/`input.userAgent`,
|
|
66
|
+
then stores application metadata and anonymous quota state. A later tokenless
|
|
67
|
+
request with a valid server-managed cookie keeps the same clientId without
|
|
68
|
+
invoking Register again. An invalid or expired supplied JWT is still rejected.
|
|
69
|
+
Bootstrap restores an eligible remembered login; anonymous client creation does
|
|
70
|
+
not require a separate bootstrap call.
|
|
71
|
+
|
|
72
|
+
Login and password confirmation call `server.rotateClient()`. Server rotates the
|
|
73
|
+
credential on a successful response; the application never handles its raw value
|
|
74
|
+
or hash. The server owns `_lango_clients`; the five security_* tables implement
|
|
75
|
+
application policy. Failed initial requests can leave an application registration
|
|
76
|
+
without publishing a token/cookie. Forwarded headers and User-Agent are not identity
|
|
77
|
+
credentials.
|
|
78
|
+
|
|
79
|
+
## Request sequence
|
|
80
|
+
|
|
81
|
+
All endpoints use JSON POST. The server enforces the exact Origin header through
|
|
82
|
+
the origin section in deploy.xml before invoking application code. A browser
|
|
83
|
+
same-origin fetch sends cookies normally; use `credentials: "same-origin"`
|
|
84
|
+
explicitly in a custom caller if desired. Keep returned `x-lango-token` as the
|
|
85
|
+
next Bearer token. The browser handles Set-Cookie; never expose its secret in JS.
|
|
86
|
+
|
|
87
|
+
| Endpoint | Input | Result/requirement |
|
|
88
|
+
| --- | --- | --- |
|
|
89
|
+
| `/bootstrap` | `{}` | Establish client binding; restore an active remembered grant. |
|
|
90
|
+
| `/whoami` | `{}` | Current clientId/userId and shared authenticatedAt timestamp. |
|
|
91
|
+
| `/guest/action` | `{}` | Three anonymous actions per browser, independent of logout/login. |
|
|
92
|
+
| `/auth/login` | `{ username, password, remember }` | Verify password, issue grant, rotate cookie. |
|
|
93
|
+
| `/auth/logout` | `{}` | Revoke current browser login; keep anonymous identity/quota. |
|
|
94
|
+
| `/auth/reauth` | `{ password }` | Refresh password timestamp and rotate cookie. |
|
|
95
|
+
| `/account/clients` | `{}` | Own active client logins with initial/latest IP and User-Agent. |
|
|
96
|
+
| `/account/revoke-client` | `{ clientId }` | Revoke own selected client's logins; recent password required. |
|
|
97
|
+
| `/admin` | `{}` | Requires current admin role and password verification within five minutes. |
|
|
98
|
+
| `/admin/ban` | `{ userId }` | Recently authenticated admin bans the target and revokes all target grants. |
|
|
99
|
+
|
|
100
|
+
Routes declare policy and password-freshness requirements directly in XML.
|
|
101
|
+
Server enforces policy membership and reauthSeconds on every request before the
|
|
102
|
+
application guard. Login/bootstrap grant login/admin memberships from trusted DB
|
|
103
|
+
state; password confirmation refreshes authenticatedAt. The application does not
|
|
104
|
+
maintain a URL-to-policy table.
|
|
105
|
+
|
|
106
|
+
Every route also selects the closed security middleware for the application's
|
|
107
|
+
live DB checks, quotas, credential verification and transactions. Its startup
|
|
108
|
+
validator rejects bypasses and unknown example policy names. This middleware does
|
|
109
|
+
not implement Server's built-in policy gate. The example does not register a
|
|
110
|
+
Validate event. Each route names its own exported handler, including bootstrap.
|
|
111
|
+
|
|
112
|
+
Expected challenges include 401 `LoginRequired`/`SessionRevoked`, 403 `Forbidden`, 403
|
|
113
|
+
`ReauthenticationRequired`, 403 `AdminRequired`, and
|
|
114
|
+
403 `AccountDisabled`. They are distinct states for the application to present.
|
|
115
|
+
Do not automatically resubmit an operation after a challenge.
|
|
116
|
+
|
|
117
|
+
Remembered authentication uses the HttpOnly cookie as a refresh credential.
|
|
118
|
+
A stolen JWT alone cannot pass the binding, but a stolen remembered cookie can
|
|
119
|
+
restore a normal login. Admin restoration still requires password confirmation.
|
|
120
|
+
Non-remembered login is not restored by bootstrap, even on reload. Ban blocks
|
|
121
|
+
known authenticated grants, not an unidentifiable person who creates a new
|
|
122
|
+
anonymous browser profile.
|
|
123
|
+
|
|
124
|
+
Cookie rotation invalidates proofs in other tabs/forms. The JSON caller should
|
|
125
|
+
keep the latest token after each response. A full UI integration needs explicit
|
|
126
|
+
reinitialization after login/reauth; it is not provided by this demo.
|
|
127
|
+
|
|
128
|
+
## Tests
|
|
129
|
+
|
|
130
|
+
From the server checkout:
|
|
131
|
+
|
|
132
|
+
```sh
|
|
133
|
+
npm run test:security
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
The automated test creates temporary accounts/DB state, sends real HTTP requests
|
|
137
|
+
to an ephemeral loopback listener, and deletes the database afterward. Its
|
|
138
|
+
manually managed cookie headers model an HTTPS-terminating proxy; they do not
|
|
139
|
+
prove real browser Secure-cookie or TLS behavior. Run a browser/proxy integration
|
|
140
|
+
check before deployment. Test passwords/signing keys are fixtures only.
|
|
141
|
+
|
|
142
|
+
All request handlers in this example are synchronous. Their JSON output is
|
|
143
|
+
validated before transaction commit; business/audit writes share the transaction.
|
|
144
|
+
It does not support streaming, longpoll or arbitrary Promise handlers.
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
Login and admin policy durations are declared once in `deploy.xml`. A normal
|
|
148
|
+
admin login satisfies both requirements using the same password-verification
|
|
149
|
+
time. `/auth/reauth` is the only password-confirmation endpoint; it refreshes that
|
|
150
|
+
shared time for every policy. There is no separate admin proof or elevation state.
|
|
151
|
+
The confirmation route is anonymous at the Server gate so stale authentication
|
|
152
|
+
cannot block it; the application still verifies the current grant and password.
|
|
153
|
+
`/account/revoke-client` tightens login freshness to 15 minutes in `routes.xml`.
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
For the complete browser application, see `examples/security` in the lango-ui
|
|
157
|
+
repository. It reuses these security sources at build time and adds a needLogin
|
|
158
|
+
screen, guarded notes and an administrator ban screen. Its HTTPS/Chromium test is
|
|
159
|
+
`npm run test:security` in lango-client. This directory remains the independent
|
|
160
|
+
JSON reference and its tests remain `npm run test:security` in lango-server.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<deploy>
|
|
2
|
+
<policies reauthSeconds="43200">
|
|
3
|
+
<policy name="login"/>
|
|
4
|
+
<policy name="admin" reauthSeconds="300"/>
|
|
5
|
+
</policies>
|
|
6
|
+
<client maxAgeSeconds="2592000"/>
|
|
7
|
+
<origin urlEnv="LANGO_ORIGIN" required="true"/>
|
|
8
|
+
<http host="127.0.0.1" port="3000" bodyLimit="16384"/>
|
|
9
|
+
<workers workers="2" maxQueue="16" requestTimeoutMs="15000"/>
|
|
10
|
+
<jwt keyEnv="LANGO_JWT_KEY" ttlSeconds="900"/>
|
|
11
|
+
<database type="sqlite" file="data/security.sqlite"/>
|
|
12
|
+
</deploy>
|