@lango-project/lango-server 0.2.0 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +290 -27
  2. package/dist/.lango/runtime.mjs +24 -1
  3. package/dist/body_reader.mjs +15 -14
  4. package/dist/body_reader.mjs.map +1 -1
  5. package/dist/cli/.lango/runtime.mjs +24 -1
  6. package/dist/cli/body_reader.mjs +15 -14
  7. package/dist/cli/body_reader.mjs.map +1 -1
  8. package/dist/cli/client_identity.mjs +250 -0
  9. package/dist/cli/client_identity.mjs.map +1 -0
  10. package/dist/cli/database.mjs +23 -8
  11. package/dist/cli/database.mjs.map +1 -1
  12. package/dist/cli/endpoint.mjs +11 -7
  13. package/dist/cli/endpoint.mjs.map +1 -1
  14. package/dist/cli/error_details.mjs +45 -0
  15. package/dist/cli/error_details.mjs.map +1 -0
  16. package/dist/cli/longpoll_broker.mjs +9 -8
  17. package/dist/cli/longpoll_broker.mjs.map +1 -1
  18. package/dist/cli/longpoll_options.mjs +8 -7
  19. package/dist/cli/longpoll_options.mjs.map +1 -1
  20. package/dist/cli/longpoll_session.mjs +11 -10
  21. package/dist/cli/longpoll_session.mjs.map +1 -1
  22. package/dist/cli/options.mjs +29 -3
  23. package/dist/cli/options.mjs.map +1 -1
  24. package/dist/cli/origin.mjs +87 -0
  25. package/dist/cli/origin.mjs.map +1 -0
  26. package/dist/cli/policy.mjs +121 -0
  27. package/dist/cli/policy.mjs.map +1 -0
  28. package/dist/cli/postgres_adapter.mjs +3 -2
  29. package/dist/cli/postgres_adapter.mjs.map +1 -1
  30. package/dist/cli/routes.mjs +33 -17
  31. package/dist/cli/routes.mjs.map +1 -1
  32. package/dist/cli/server.mjs +148 -101
  33. package/dist/cli/server.mjs.map +1 -1
  34. package/dist/cli/static_files.mjs +7 -4
  35. package/dist/cli/static_files.mjs.map +1 -1
  36. package/dist/cli/trace.mjs +53 -0
  37. package/dist/cli/trace.mjs.map +1 -0
  38. package/dist/client_identity.mjs +250 -0
  39. package/dist/client_identity.mjs.map +1 -0
  40. package/dist/database.mjs +23 -8
  41. package/dist/database.mjs.map +1 -1
  42. package/dist/endpoint.mjs +11 -7
  43. package/dist/endpoint.mjs.map +1 -1
  44. package/dist/error_details.mjs +45 -0
  45. package/dist/error_details.mjs.map +1 -0
  46. package/dist/group.mjs +34 -16
  47. package/dist/group.mjs.map +1 -1
  48. package/dist/http_failure.mjs +9 -2
  49. package/dist/http_failure.mjs.map +1 -1
  50. package/dist/longpoll_broker.mjs +9 -8
  51. package/dist/longpoll_broker.mjs.map +1 -1
  52. package/dist/longpoll_options.mjs +8 -7
  53. package/dist/longpoll_options.mjs.map +1 -1
  54. package/dist/longpoll_session.mjs +11 -10
  55. package/dist/longpoll_session.mjs.map +1 -1
  56. package/dist/options.mjs +29 -3
  57. package/dist/options.mjs.map +1 -1
  58. package/dist/origin.mjs +87 -0
  59. package/dist/origin.mjs.map +1 -0
  60. package/dist/policy.mjs +121 -0
  61. package/dist/policy.mjs.map +1 -0
  62. package/dist/postgres_adapter.mjs +3 -2
  63. package/dist/postgres_adapter.mjs.map +1 -1
  64. package/dist/postgres_worker.mjs +15 -14
  65. package/dist/postgres_worker.mjs.map +1 -1
  66. package/dist/request_identity.mjs +22 -0
  67. package/dist/request_identity.mjs.map +1 -0
  68. package/dist/response.mjs +1 -1
  69. package/dist/response.mjs.map +1 -1
  70. package/dist/route_info.mjs +1 -1
  71. package/dist/route_info.mjs.map +1 -1
  72. package/dist/routes.mjs +33 -17
  73. package/dist/routes.mjs.map +1 -1
  74. package/dist/runtime.mjs +241 -110
  75. package/dist/runtime.mjs.map +1 -1
  76. package/dist/server.mjs +148 -101
  77. package/dist/server.mjs.map +1 -1
  78. package/dist/server_context.mjs +21 -9
  79. package/dist/server_context.mjs.map +1 -1
  80. package/dist/static_files.mjs +7 -4
  81. package/dist/static_files.mjs.map +1 -1
  82. package/dist/token.mjs +34 -7
  83. package/dist/token.mjs.map +1 -1
  84. package/dist/tokens.mjs +11 -2
  85. package/dist/tokens.mjs.map +1 -1
  86. package/dist/trace.mjs +53 -0
  87. package/dist/trace.mjs.map +1 -0
  88. package/dist/worker.mjs +8 -6
  89. package/dist/worker.mjs.map +1 -1
  90. package/docs/security.md +420 -0
  91. package/examples/security/README.md +160 -0
  92. package/examples/security/deploy.xml +12 -0
  93. package/examples/security/handlers.lango +610 -0
  94. package/examples/security/package.json +19 -0
  95. package/examples/security/passwords.lango +61 -0
  96. package/examples/security/routes.xml +14 -0
  97. package/examples/security/schema.lango +91 -0
  98. package/examples/security/setup.lango +30 -0
  99. package/package.json +12 -6
  100. package/src/client_identity.lango +184 -0
  101. package/src/database.lango +15 -4
  102. package/src/endpoint.lango +12 -5
  103. package/src/error_details.lango +21 -0
  104. package/src/group.lango +25 -21
  105. package/src/http_failure.lango +9 -5
  106. package/src/longpoll_options.lango +11 -5
  107. package/src/options.lango +34 -1
  108. package/src/origin.lango +56 -0
  109. package/src/policy.lango +84 -0
  110. package/src/request_identity.lango +9 -0
  111. package/src/response.lango +1 -1
  112. package/src/route_info.lango +2 -0
  113. package/src/routes.lango +30 -15
  114. package/src/runtime.lango +149 -77
  115. package/src/server.lango +48 -7
  116. package/src/server_context.lango +10 -2
  117. package/src/static_files.lango +3 -0
  118. package/src/token.lango +26 -5
  119. package/src/tokens.lango +10 -3
  120. package/src/trace.lango +23 -0
  121. package/src/worker.lango +1 -0
package/dist/runtime.mjs CHANGED
@@ -1,3 +1,7 @@
1
+ import { routeInfo } from "./route_info.mjs";
2
+ import { ClientIdentity } from "./client_identity.mjs";
3
+ import { originAllowed } from "./origin.mjs";
4
+ import { trace } from "./trace.mjs";
1
5
  import { routePattern, matchPath, moreSpecific } from "./route_pattern.mjs";
2
6
  import { ServerContext } from "./server_context.mjs";
3
7
  import { Database } from "./database.mjs";
@@ -5,6 +9,9 @@ import { Token } from "./token.mjs";
5
9
  import { Tokens } from "./tokens.mjs";
6
10
  import { Response } from "./response.mjs";
7
11
  import { HttpFailure } from "./http_failure.mjs";
12
+ import { requestIdentity } from "./request_identity.mjs";
13
+ import { errorDetails, errorMessage } from "./error_details.mjs";
14
+ import * as crypto from "node:crypto";
8
15
  import * as threads from "node:worker_threads";
9
16
  import {
10
17
  hostGlobal as __hostGlobal,
@@ -12,6 +19,9 @@ import {
12
19
  contextGet as __contextGet,
13
20
  contextSet as __contextSet,
14
21
  contextRestore as __contextRestore,
22
+ bindContexts as __bindContexts,
23
+ fromJson as __fromJson,
24
+ toJson as __toJson,
15
25
  getClass as __getClass,
16
26
  isKindof as __isKindof,
17
27
  isNumber as __isNumber,
@@ -40,15 +50,20 @@ export class Runtime {
40
50
  #modules;
41
51
  #middlewares;
42
52
  #database;
53
+ #clients;
43
54
  constructor(definition) {
44
55
  __requireArity(arguments.length, [0], "constructor");
45
56
  definition = __boundary(definition);
46
- let refresh = __withArity((tokens) => {
57
+ let refresh = __withArity(__bindContexts((tokens) => {
47
58
  tokens = __boundary(tokens);
48
59
  return this.refreshTokens(tokens);
49
60
  return null;
50
- }, [0], "closure");
51
- this.#serverContext = new ServerContext(__normalize(definition.routes), refresh);
61
+ }), [0], "closure");
62
+ let rotate = __bindContexts(() => {
63
+ return this.#rotateClient();
64
+ return null;
65
+ });
66
+ this.#serverContext = new ServerContext(__normalize(definition.routes), refresh, rotate);
52
67
  this.#definition = definition;
53
68
  this.#routes = [];
54
69
  this.#events = { };
@@ -56,8 +71,13 @@ export class Runtime {
56
71
  this.#modules = { };
57
72
  this.#middlewares = __normalize(__hostGlobal(["Object"]).create(null));
58
73
  this.#database = new Database(definition.settings.database, definition.settings.root);
74
+ this.#clients = null;
75
+ if (__requireBoolean(definition.settings.client !== null)) {
76
+ this.#clients = new ClientIdentity(definition.settings.client, __normalize(this.#database));
77
+ }
59
78
  }
60
79
  preload() {
80
+ trace(`Worker ${__normalize(threads.threadId)}: preparing database, middleware, routes and events`);
61
81
  let definitions = __normalize(this.#definition.routes);
62
82
  let pending = __normalize(this.#database.open());
63
83
  if (__requireBoolean(__normalize(this.#definition.middlewares) !== null)) {
@@ -72,12 +92,12 @@ export class Runtime {
72
92
  for (const [name, target] of __entries(events)) {
73
93
  pending = this.#prepareEvent(pending, name, target);
74
94
  }
75
- return pending.catch(__withArity((error) => {
95
+ return pending.catch(__withArity(__bindContexts((error) => {
76
96
  error = __boundary(error);
77
97
  this.close();
78
98
  throw error;
79
99
  return null;
80
- }, [0], "closure"));
100
+ }), [0], "closure"));
81
101
  return null;
82
102
  }
83
103
  close() {
@@ -90,11 +110,11 @@ export class Runtime {
90
110
  pending = __boundary(pending);
91
111
  name = __boundary(name);
92
112
  spec = __boundary(spec);
93
- return pending.then(__withArity((ignored) => {
113
+ return pending.then(__withArity(__bindContexts((ignored) => {
94
114
  ignored = __boundary(ignored);
95
115
  return this.#target(spec);
96
116
  return null;
97
- }, [0], "closure")).then(__withArity((handler) => {
117
+ }), [0], "closure")).then(__withArity(__bindContexts((handler) => {
98
118
  handler = __boundary(handler);
99
119
  this.#middlewares[name] = handler;
100
120
  if (__requireBoolean(__normalize(spec.validate) !== null)) {
@@ -102,14 +122,14 @@ export class Runtime {
102
122
  }
103
123
  return null;
104
124
  return null;
105
- }, [0], "closure")).then(__withArity((validator) => {
125
+ }), [0], "closure")).then(__withArity(__bindContexts((validator) => {
106
126
  validator = __boundary(validator);
107
127
  if (__requireBoolean(validator !== null)) {
108
128
  return __call(validator, __normalize(this.#serverContext.routes()));
109
129
  }
110
130
  return null;
111
131
  return null;
112
- }, [0], "closure"));
132
+ }), [0], "closure"));
113
133
  return null;
114
134
  }
115
135
  #prepareRoute(pending, route) {
@@ -122,11 +142,11 @@ export class Runtime {
122
142
  __add(this.#routes, prepared);
123
143
  return pending;
124
144
  }
125
- return pending.then(__withArity((ignored) => {
145
+ return pending.then(__withArity(__bindContexts((ignored) => {
126
146
  ignored = __boundary(ignored);
127
147
  return this.#target(route);
128
148
  return null;
129
- }, [0], "closure")).then(__withArity((handler) => {
149
+ }), [0], "closure")).then(__withArity(__bindContexts((handler) => {
130
150
  handler = __boundary(handler);
131
151
  let middleware = null;
132
152
  let name = __normalize(route.middleware);
@@ -136,10 +156,10 @@ export class Runtime {
136
156
  }
137
157
  middleware = __normalize(this.#middlewares[name]);
138
158
  }
139
- __add(this.#routes, { path: __normalize(route.path), pattern: routePattern(__normalize(route.path)), auth: __normalize(route.auth), handler: handler, middleware: middleware });
159
+ __add(this.#routes, { path: __normalize(route.path), pattern: routePattern(__normalize(route.path)), auth: __normalize(route.auth), policy: __normalize(route.policy), reauthSeconds: __normalize(route.reauthSeconds), legacyAuth: __normalize(route.legacyAuth), handler: handler, middleware: middleware });
140
160
  return null;
141
161
  return null;
142
- }, [0], "closure"));
162
+ }), [0], "closure"));
143
163
  return null;
144
164
  }
145
165
  #prepareEvent(pending, name, spec) {
@@ -147,31 +167,32 @@ export class Runtime {
147
167
  pending = __boundary(pending);
148
168
  name = __boundary(name);
149
169
  spec = __boundary(spec);
150
- return pending.then(__withArity((ignored) => {
170
+ return pending.then(__withArity(__bindContexts((ignored) => {
151
171
  ignored = __boundary(ignored);
152
172
  return this.#target(spec);
153
173
  return null;
154
- }, [0], "closure")).then(__withArity((handler) => {
174
+ }), [0], "closure")).then(__withArity(__bindContexts((handler) => {
155
175
  handler = __boundary(handler);
156
176
  this.#events[name] = handler;
157
177
  return null;
158
178
  return null;
159
- }, [0], "closure"));
179
+ }), [0], "closure"));
160
180
  return null;
161
181
  }
162
182
  #target(spec) {
163
183
  __requireArity(arguments.length, [0], "target");
164
184
  spec = __boundary(spec);
165
185
  let file = __normalize(spec.module);
186
+ trace(`Worker ${__normalize(threads.threadId)}: resolving ${file} export ${__normalize(spec.handler)}`);
166
187
  if (__requireBoolean(__includes(file, __normalize(this.#modules)))) {
167
188
  return __normalize(__hostGlobal(["Promise"]).resolve(exported(__normalize(this.#modules[file]), __normalize(spec.handler))));
168
189
  }
169
- return import(file).then(__withArity((mod) => {
190
+ return import(file).then(__withArity(__bindContexts((mod) => {
170
191
  mod = __boundary(mod);
171
192
  this.#modules[file] = mod;
172
193
  return exported(mod, __normalize(spec.handler));
173
194
  return null;
174
- }, [0], "closure"));
195
+ }), [0], "closure"));
175
196
  return null;
176
197
  }
177
198
  #match(path) {
@@ -203,22 +224,28 @@ export class Runtime {
203
224
  __contextScope.push(__contextSet("server", __normalize(this.#serverContext)));
204
225
  __contextScope.push(__contextSet("request", __normalize(__hostGlobal(["Object"]).freeze(__normalize(task.request)))));
205
226
  __contextScope.push(__contextSet("response", new Response()));
227
+ if (__requireBoolean(!__requireBoolean(originAllowed(__normalize(this.#definition.settings.origin), __contextGet("request"))))) {
228
+ return failure(403, "OriginRejected");
229
+ }
206
230
  let fresh = __normalize(__contextGet("request").headers.authorization) === null;
207
231
  let claims = null;
208
232
  try {
209
- if (__requireBoolean(fresh)) {
210
- claims = __normalize(this.#tokens.create());
211
- } else {
233
+ if (__requireBoolean(!__requireBoolean(fresh))) {
212
234
  claims = __normalize(this.#tokens.read(__normalize(__contextGet("request").headers.authorization)));
213
235
  }
214
236
  } catch (error) {
237
+ __normalize(__contextGet("log").warn(`[${__normalize(__contextGet("request").id)}] ${__normalize(__contextGet("request").method)} ${__normalize(__contextGet("request").path)} Authorization rejected before handler: ${errorMessage(error)}`));
215
238
  return failure(401, "Unauthorized");
216
239
  }
217
240
  let matched = this.#match(__normalize(__contextGet("request").path));
218
241
  if (__requireBoolean(matched === null)) {
242
+ trace(`[${__normalize(__contextGet("request").id)}] No route matched ${__normalize(__contextGet("request").path)}`);
219
243
  return failure(404, "RouteNotFound");
220
244
  }
221
245
  let route = __normalize(matched.route);
246
+ let metadata = routeInfo([route]);
247
+ let selected = __normalize(__hostGlobal(["Object"]).freeze(__normalize(metadata[0])));
248
+ __contextScope.push(__contextSet("request", __normalize(__hostGlobal(["Object"]).freeze(__normalize(__hostGlobal(["Object"]).assign({ }, __contextGet("request"), { route: selected }))))));
222
249
  let input = null;
223
250
  try {
224
251
  input = __normalize(__hostGlobal(["JSON"]).parse(__normalize(task.body)));
@@ -235,46 +262,123 @@ export class Runtime {
235
262
  } catch (error) {
236
263
  return failure(400, "InvalidPath");
237
264
  }
238
- __contextScope.push(__contextSet("token", new Token(claims)));
239
265
  __contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
240
- return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
266
+ __contextScope.push(__contextSet("clientIdentity", null));
267
+ let restored = false;
268
+ try {
269
+ if (__requireBoolean(__normalize(this.#clients) !== null)) {
270
+ __contextScope.push(__contextSet("clientIdentity", __normalize(this.#clients.begin(claims, __normalize(this.#tokens)))));
271
+ claims = __normalize(__contextGet("clientIdentity").claims);
272
+ fresh = __normalize(__contextGet("clientIdentity").fresh);
273
+ restored = __normalize(__contextGet("clientIdentity").restored);
274
+ }
275
+ if (__requireBoolean(claims === null)) {
276
+ claims = __normalize(this.#tokens.create());
277
+ }
278
+ } catch (error) {
279
+ closeScope(__contextGet("db"), false);
280
+ if (__requireBoolean(__isKindof(error, HttpFailure))) {
281
+ return __normalize(error.result());
282
+ }
283
+ __normalize(__contextGet("log").err(`[${__normalize(__contextGet("request").id)}] Client identity failed: ${errorDetails(error)}`));
284
+ return failure(500, "InternalServerError");
285
+ }
286
+ return this.#process(task, route, input, claims, fresh, restored);
287
+ return null;
288
+ } finally {
289
+ __contextRestore(__contextScope);
290
+ }
291
+ }
292
+ #rotateClient() {
293
+ const __contextScope = [];
294
+ try {
295
+ if (__requireBoolean(__requireBoolean(__normalize(this.#clients) === null) || __requireBoolean(__contextGet("clientIdentity") === null))) {
296
+ throw "Managed client identity is unavailable";
297
+ }
298
+ if (__requireBoolean(__normalize(__contextGet("clientIdentity").closed))) {
299
+ throw "Client identity scope is closed";
300
+ }
301
+ __contextGet("clientIdentity").rotate = true;
302
+ return null;
303
+ return null;
304
+ } finally {
305
+ __contextRestore(__contextScope);
306
+ }
307
+ }
308
+ #signResponse(claims) {
309
+ const __contextScope = [];
310
+ try {
311
+ __requireArity(arguments.length, [0], "signResponse");
312
+ claims = __boundary(claims);
313
+ if (__requireBoolean(__normalize(this.#clients) === null)) {
314
+ return __normalize(this.#tokens.sign(claims));
315
+ }
316
+ return __normalize(this.#clients.publish(__contextGet("clientIdentity"), claims, __contextGet("response"), __normalize(this.#tokens)));
317
+ return null;
318
+ } finally {
319
+ __contextRestore(__contextScope);
320
+ }
321
+ }
322
+ #process(task, route, input, claims, fresh, restored) {
323
+ const __contextScope = [];
324
+ try {
325
+ __requireArity(arguments.length, [0, 1, 2, 3, 4, 5], "process");
326
+ task = __boundary(task);
327
+ route = __boundary(route);
328
+ input = __boundary(input);
329
+ claims = __boundary(claims);
330
+ fresh = __boundary(fresh);
331
+ restored = __boundary(restored);
332
+ __contextScope.push(__contextSet("token", new Token(claims)));
333
+ trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Matched route ${__normalize(route.path)}; fresh=${fresh}`);
334
+ return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(__bindContexts((ignored) => {
241
335
  const __contextScope = [];
242
336
  try {
243
- __contextScope.push(__contextSet("server", __capturedContext0));
244
- __contextScope.push(__contextSet("request", __capturedContext1));
245
- __contextScope.push(__contextSet("response", __capturedContext2));
246
- __contextScope.push(__contextSet("token", __capturedContext3));
247
- __contextScope.push(__contextSet("log", __capturedContext4));
248
- __contextScope.push(__contextSet("db", __capturedContext5));
249
337
  ignored = __boundary(ignored);
250
338
  if (__requireBoolean(fresh)) {
251
- return this.#event("register", input);
339
+ let registration = __normalize(__hostGlobal(["Object"]).assign({ }, input, { ip: __normalize(__contextGet("request").remoteAddress), userAgent: __normalize(__contextGet("request").headers["user-agent"]) }));
340
+ return this.#event("register", registration);
252
341
  }
253
- return this.#validate();
342
+ return this.#validate(restored);
254
343
  return null;
255
344
  } finally {
256
345
  __contextRestore(__contextScope);
257
346
  }
258
- })(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (validatedAt) => {
347
+ }), [0], "closure")).then(__withArity(__bindContexts((validatedAt) => {
259
348
  const __contextScope = [];
260
349
  try {
261
- __contextScope.push(__contextSet("server", __capturedContext0));
262
- __contextScope.push(__contextSet("request", __capturedContext1));
263
- __contextScope.push(__contextSet("response", __capturedContext2));
264
- __contextScope.push(__contextSet("token", __capturedContext3));
265
- __contextScope.push(__contextSet("log", __capturedContext4));
266
- __contextScope.push(__contextSet("db", __capturedContext5));
267
350
  validatedAt = __boundary(validatedAt);
268
351
  if (__requireBoolean(__requireBoolean(!__requireBoolean(fresh)) && __requireBoolean(__isNumber(validatedAt)))) {
269
352
  stampValidation(claims, validatedAt);
270
353
  __normalize(__contextGet("token").renew());
271
354
  }
272
- if (__requireBoolean(__requireBoolean(__normalize(route.auth) !== "anonymous") && __requireBoolean(!__requireBoolean(__normalize(__contextGet("token").hasAuth(__normalize(route.auth))))))) {
273
- throw { status: 401, error: "Unauthorized" };
355
+ if (__requireBoolean(__requireBoolean(__normalize(route.policy) !== "anonymous") && __requireBoolean(!__requireBoolean(__normalize(__contextGet("token").hasPolicy(__normalize(route.policy))))))) {
356
+ if (__requireBoolean(__normalize(route.legacyAuth))) {
357
+ __normalize(__contextGet("response").reject(401, "Unauthorized"));
358
+ }
359
+ if (__requireBoolean(__requireBoolean(__normalize(route.policy) === "login") || __requireBoolean(!__requireBoolean(__normalize(__contextGet("token").hasPolicy("login")))))) {
360
+ needLogin(route, 401, "LoginRequired");
361
+ }
362
+ __normalize(__contextGet("response").reject(403, "Forbidden"));
363
+ }
364
+ if (__requireBoolean(__normalize(route.reauthSeconds) > 0)) {
365
+ let authenticatedAt = __normalize(__contextGet("token").get("authenticatedAt"));
366
+ let now = __normalize(__hostGlobal(["Date"]).now());
367
+ if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(authenticatedAt)))) || __requireBoolean(authenticatedAt < 0)) || __requireBoolean(authenticatedAt > now))) {
368
+ needLogin(route, 403, "ReauthenticationRequired");
369
+ }
370
+ if (__requireBoolean(__finite(now - authenticatedAt) >= __finite(__normalize(route.reauthSeconds) * 1000))) {
371
+ needLogin(route, 403, "ReauthenticationRequired");
372
+ }
373
+ }
374
+ let expected = __normalize(__contextGet("request").headers["x-lango-expected-user"]);
375
+ if (__requireBoolean(__requireBoolean(expected !== null) && __requireBoolean(expected !== __toJson(__normalize(__contextGet("token").get("userId")))))) {
376
+ __normalize(__contextGet("response").reject(409, "IdentityChanged"));
274
377
  }
275
378
  if (__requireBoolean(__normalize(route.kind) === "longpoll")) {
276
379
  return null;
277
380
  }
381
+ trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Invoking handler; middleware=${__normalize(route.middleware) !== null}`);
278
382
  let handler = __normalize(route.handler);
279
383
  let middleware = __normalize(route.middleware);
280
384
  if (__requireBoolean(middleware !== null)) {
@@ -285,20 +389,15 @@ export class Runtime {
285
389
  } finally {
286
390
  __contextRestore(__contextScope);
287
391
  }
288
- })(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (output) => {
392
+ }), [0], "closure")).then(__withArity(__bindContexts((output) => {
289
393
  const __contextScope = [];
290
394
  try {
291
- __contextScope.push(__contextSet("server", __capturedContext0));
292
- __contextScope.push(__contextSet("request", __capturedContext1));
293
- __contextScope.push(__contextSet("response", __capturedContext2));
294
- __contextScope.push(__contextSet("token", __capturedContext3));
295
- __contextScope.push(__contextSet("log", __capturedContext4));
296
- __contextScope.push(__contextSet("db", __capturedContext5));
297
395
  output = __boundary(output);
396
+ let encoded = null;
298
397
  if (__requireBoolean(__normalize(task.authorize) === true)) {
299
398
  closeScope(__contextGet("db"), true);
300
399
  let authorizedClaims = this.#tokenClaims(__contextGet("token"), claims, true);
301
- let encoded = __normalize(this.#tokens.sign(authorizedClaims));
400
+ encoded = this.#signResponse(authorizedClaims);
302
401
  if (__requireBoolean(__normalize(task.pollResult) === null)) {
303
402
  return { status: 200, authorization: encoded };
304
403
  }
@@ -313,6 +412,7 @@ export class Runtime {
313
412
  }
314
413
  return pollResponse;
315
414
  }
415
+ trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Handler completed; serializing response`);
316
416
  let body = __normalize(__hostGlobal(["JSON"]).stringify(output));
317
417
  if (__requireBoolean(!__requireBoolean(__isString(body)))) {
318
418
  throw "Handler result is not JSON serializable";
@@ -320,46 +420,51 @@ export class Runtime {
320
420
  closeScope(__contextGet("db"), true);
321
421
  let result = __normalize(__contextGet("response").result(body));
322
422
  let updated = this.#tokenClaims(__contextGet("token"), claims, __normalize(result.status) < 400);
323
- result.headers["x-lango-token"] = __normalize(this.#tokens.sign(updated));
423
+ encoded = this.#signResponse(updated);
424
+ result = __normalize(__contextGet("response").result(body));
425
+ result.headers["x-lango-token"] = encoded;
426
+ if (__requireBoolean(__requireBoolean(__normalize(result.status) < 400) && __requireBoolean(authenticationChanged(claims, updated)))) {
427
+ result.headers["x-lango-auth-change"] = `v1:${__normalize(crypto.randomUUID())}`;
428
+ }
324
429
  if (__requireBoolean(__requireBoolean(__requireBoolean(__normalize(task.internal) !== true) && __requireBoolean(__normalize(this.#definition.settings.requestEvent))) && __requireBoolean(__includes("request", __normalize(this.#events))))) {
325
430
  return this.#audit(__normalize(__contextGet("request").id), result, __normalize(task.body), body, updated);
326
431
  }
432
+ trace(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Request completed status=${__normalize(result.status)}`);
327
433
  return result;
328
434
  return null;
329
435
  } finally {
330
436
  __contextRestore(__contextScope);
331
437
  }
332
- })(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3) => (error) => {
438
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
333
439
  const __contextScope = [];
334
440
  try {
335
- __contextScope.push(__contextSet("server", __capturedContext0));
336
- __contextScope.push(__contextSet("request", __capturedContext1));
337
- __contextScope.push(__contextSet("log", __capturedContext2));
338
- __contextScope.push(__contextSet("db", __capturedContext3));
339
441
  error = __boundary(error);
340
442
  closeScope(__contextGet("db"), false);
341
443
  if (__requireBoolean(__isKindof(error, HttpFailure))) {
342
444
  return __normalize(error.result());
343
445
  }
344
446
  if (__requireBoolean(__requireBoolean(error === "TokenExpired") || __requireBoolean(__requireBoolean(__isObject(error)) && __requireBoolean(__normalize(error.status) === 401)))) {
447
+ __normalize(__contextGet("log").warn(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} ${__normalize(__contextGet("request").method)} ${__normalize(__contextGet("request").path)} Authorization or validation rejected: Unauthorized`));
345
448
  return failure(401, "Unauthorized");
346
449
  }
347
- __normalize(__contextGet("log").err(`[${__normalize(__contextGet("request").id)}] Request failed`));
450
+ __normalize(__contextGet("log").err(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Request failed: ${errorDetails(error)}`));
348
451
  return failure(500, "InternalServerError");
349
452
  return null;
350
453
  } finally {
351
454
  __contextRestore(__contextScope);
352
455
  }
353
- })(__contextGet("server"), __contextGet("request"), __contextGet("log"), __contextGet("db")), [0], "closure")).finally(((__capturedContext0) => () => {
456
+ }), [0], "closure")).finally(__bindContexts(() => {
354
457
  const __contextScope = [];
355
458
  try {
356
- __contextScope.push(__contextSet("db", __capturedContext0));
459
+ if (__requireBoolean(__contextGet("clientIdentity") !== null)) {
460
+ __contextGet("clientIdentity").closed = true;
461
+ }
357
462
  closeScope(__contextGet("db"), false);
358
463
  return null;
359
464
  } finally {
360
465
  __contextRestore(__contextScope);
361
466
  }
362
- })(__contextGet("db")));
467
+ }));
363
468
  return null;
364
469
  } finally {
365
470
  __contextRestore(__contextScope);
@@ -400,11 +505,16 @@ export class Runtime {
400
505
  let child = __normalize(__hostGlobal(["Object"]).assign({ }, __contextGet("request"), { headers: __normalize(__hostGlobal(["Object"]).assign({ }, __normalize(__contextGet("request").headers), { authorization: `Bearer ${encoded}` })) }));
401
506
  pending = this.#refreshOne(pending, results, encoded, owner, child);
402
507
  }
403
- return pending.then(__withArity((ignored) => {
404
- ignored = __boundary(ignored);
405
- return results;
406
- return null;
407
- }, [0], "closure"));
508
+ return pending.then(__withArity(__bindContexts((ignored) => {
509
+ const __contextScope = [];
510
+ try {
511
+ ignored = __boundary(ignored);
512
+ return results;
513
+ return null;
514
+ } finally {
515
+ __contextRestore(__contextScope);
516
+ }
517
+ }), [0], "closure"));
408
518
  return null;
409
519
  } finally {
410
520
  __contextRestore(__contextScope);
@@ -417,7 +527,7 @@ export class Runtime {
417
527
  encoded = __boundary(encoded);
418
528
  owner = __boundary(owner);
419
529
  child = __boundary(child);
420
- return pending.then(__withArity((ignored) => {
530
+ return pending.then(__withArity(__bindContexts((ignored) => {
421
531
  ignored = __boundary(ignored);
422
532
  let checked = null;
423
533
  try {
@@ -430,7 +540,7 @@ export class Runtime {
430
540
  }
431
541
  return this.handle({ request: child, body: "{}", internal: true });
432
542
  return null;
433
- }, [0], "closure")).then(__withArity((result) => {
543
+ }), [0], "closure")).then(__withArity(__bindContexts((result) => {
434
544
  result = __boundary(result);
435
545
  let updated = null;
436
546
  if (__requireBoolean(__normalize(result.status) < 400)) {
@@ -439,7 +549,7 @@ export class Runtime {
439
549
  __add(results, { previous: encoded, token: updated, status: __normalize(result.status) });
440
550
  return null;
441
551
  return null;
442
- }, [0], "closure"));
552
+ }), [0], "closure"));
443
553
  return null;
444
554
  }
445
555
  #event(name, input) {
@@ -451,44 +561,42 @@ export class Runtime {
451
561
  if (__requireBoolean(!__requireBoolean(__includes(name, __normalize(this.#events))))) {
452
562
  return null;
453
563
  }
564
+ let identity = `[${__normalize(__contextGet("request").id)}]`;
565
+ if (__requireBoolean(__contextGet("token") !== null)) {
566
+ identity = requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"));
567
+ }
568
+ trace(`${identity} Running event ${name}`);
454
569
  let handler = __normalize(this.#events[name]);
455
570
  __normalize(threads.parentPort.postMessage({ kind: "event", id: __normalize(__contextGet("request").id) }));
456
- return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
571
+ return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(__bindContexts((ignored) => {
457
572
  const __contextScope = [];
458
573
  try {
459
- __contextScope.push(__contextSet("server", __capturedContext0));
460
- __contextScope.push(__contextSet("request", __capturedContext1));
461
- __contextScope.push(__contextSet("response", __capturedContext2));
462
- __contextScope.push(__contextSet("token", __capturedContext3));
463
- __contextScope.push(__contextSet("log", __capturedContext4));
464
- __contextScope.push(__contextSet("db", __capturedContext5));
465
574
  ignored = __boundary(ignored);
466
575
  return __call(handler, input);
467
576
  return null;
468
577
  } finally {
469
578
  __contextRestore(__contextScope);
470
579
  }
471
- })(__contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("token"), __contextGet("log"), __contextGet("db")), [0], "closure")).finally(((__capturedContext0, __capturedContext1) => () => {
580
+ }), [0], "closure")).finally(__bindContexts(() => {
472
581
  const __contextScope = [];
473
582
  try {
474
- __contextScope.push(__contextSet("server", __capturedContext0));
475
- __contextScope.push(__contextSet("request", __capturedContext1));
476
583
  __normalize(threads.parentPort.postMessage({ kind: "handler", id: __normalize(__contextGet("request").id) }));
477
584
  return null;
478
585
  } finally {
479
586
  __contextRestore(__contextScope);
480
587
  }
481
- })(__contextGet("server"), __contextGet("request")));
588
+ }));
482
589
  return null;
483
590
  } finally {
484
591
  __contextRestore(__contextScope);
485
592
  }
486
593
  }
487
- #validate() {
594
+ #validate(force = false) {
488
595
  const __contextScope = [];
489
596
  try {
597
+ force = __boundary(force);
490
598
  let claims = __normalize(__contextGet("token").snapshot());
491
- if (__requireBoolean(__finite(__normalize(__hostGlobal(["Date"]).now()) - __normalize(claims.validatedAt)) < 1000)) {
599
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(force)) && __requireBoolean(__finite(__normalize(__hostGlobal(["Date"]).now()) - __normalize(claims.validatedAt)) < 1000))) {
492
600
  return null;
493
601
  }
494
602
  if (__requireBoolean(!__requireBoolean(__includes("validate", __normalize(this.#events))))) {
@@ -496,25 +604,18 @@ export class Runtime {
496
604
  }
497
605
  let original = __normalize(__hostGlobal(["JSON"]).stringify(claims));
498
606
  __contextScope.push(__contextSet("token", new Token(claims, true)));
499
- return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
607
+ return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(__bindContexts((ignored) => {
500
608
  const __contextScope = [];
501
609
  try {
502
- __contextScope.push(__contextSet("token", __capturedContext0));
503
- __contextScope.push(__contextSet("response", __capturedContext1));
504
- __contextScope.push(__contextSet("server", __capturedContext2));
505
- __contextScope.push(__contextSet("request", __capturedContext3));
506
- __contextScope.push(__contextSet("log", __capturedContext4));
507
- __contextScope.push(__contextSet("db", __capturedContext5));
508
610
  ignored = __boundary(ignored);
509
611
  return this.#event("validate", null);
510
612
  return null;
511
613
  } finally {
512
614
  __contextRestore(__contextScope);
513
615
  }
514
- })(__contextGet("token"), __contextGet("response"), __contextGet("server"), __contextGet("request"), __contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity(((__capturedContext0) => (valid) => {
616
+ }), [0], "closure")).then(__withArity(__bindContexts((valid) => {
515
617
  const __contextScope = [];
516
618
  try {
517
- __contextScope.push(__contextSet("token", __capturedContext0));
518
619
  valid = __boundary(valid);
519
620
  if (__requireBoolean(!__requireBoolean(__isBool(valid)))) {
520
621
  throw "Validate must return boolean";
@@ -531,7 +632,7 @@ export class Runtime {
531
632
  } finally {
532
633
  __contextRestore(__contextScope);
533
634
  }
534
- })(__contextGet("token")), [0], "closure"));
635
+ }), [0], "closure"));
535
636
  return null;
536
637
  } finally {
537
638
  __contextRestore(__contextScope);
@@ -550,26 +651,19 @@ export class Runtime {
550
651
  __contextScope.push(__contextSet("token", new Token(claims, true)));
551
652
  __contextScope.push(__contextSet("response", __normalize(__hostGlobal(["Object"]).freeze({ }))));
552
653
  let metadata = { input: input, output: output, status: __normalize(result.status) };
553
- __normalize(threads.parentPort.postMessage({ kind: "prepared", id: id, result: result }));
554
- return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(((__capturedContext0, __capturedContext1, __capturedContext2, __capturedContext3, __capturedContext4, __capturedContext5) => (ignored) => {
654
+ __normalize(threads.parentPort.postMessage({ kind: "prepared", logIdentity: requestIdentity(id, __contextGet("token")), id: id, result: result }));
655
+ return __normalize(__hostGlobal(["Promise"]).resolve(null)).then(__withArity(__bindContexts((ignored) => {
555
656
  const __contextScope = [];
556
657
  try {
557
- __contextScope.push(__contextSet("token", __capturedContext0));
558
- __contextScope.push(__contextSet("server", __capturedContext1));
559
- __contextScope.push(__contextSet("request", __capturedContext2));
560
- __contextScope.push(__contextSet("response", __capturedContext3));
561
- __contextScope.push(__contextSet("log", __capturedContext4));
562
- __contextScope.push(__contextSet("db", __capturedContext5));
563
658
  ignored = __boundary(ignored);
564
659
  return this.#event("request", __normalize(__hostGlobal(["Object"]).freeze(metadata)));
565
660
  return null;
566
661
  } finally {
567
662
  __contextRestore(__contextScope);
568
663
  }
569
- })(__contextGet("token"), __contextGet("server"), __contextGet("request"), __contextGet("response"), __contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity(((__capturedContext0) => (ignored) => {
664
+ }), [0], "closure")).then(__withArity(__bindContexts((ignored) => {
570
665
  const __contextScope = [];
571
666
  try {
572
- __contextScope.push(__contextSet("db", __capturedContext0));
573
667
  ignored = __boundary(ignored);
574
668
  closeScope(__contextGet("db"), true);
575
669
  return null;
@@ -577,33 +671,35 @@ export class Runtime {
577
671
  } finally {
578
672
  __contextRestore(__contextScope);
579
673
  }
580
- })(__contextGet("db")), [0], "closure")).catch(__withArity(((__capturedContext0, __capturedContext1) => (error) => {
674
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
581
675
  const __contextScope = [];
582
676
  try {
583
- __contextScope.push(__contextSet("log", __capturedContext0));
584
- __contextScope.push(__contextSet("db", __capturedContext1));
585
677
  error = __boundary(error);
586
678
  closeScope(__contextGet("db"), false);
587
- __normalize(__contextGet("log").err("Request event failed"));
679
+ __normalize(__contextGet("log").err(`${requestIdentity(__normalize(__contextGet("request").id), __contextGet("token"))} Request event failed: ${errorDetails(error)}`));
588
680
  return null;
589
681
  return null;
590
682
  } finally {
591
683
  __contextRestore(__contextScope);
592
684
  }
593
- })(__contextGet("log"), __contextGet("db")), [0], "closure")).then(__withArity((ignored) => {
594
- ignored = __boundary(ignored);
595
- return result;
596
- return null;
597
- }, [0], "closure")).finally(((__capturedContext0) => () => {
685
+ }), [0], "closure")).then(__withArity(__bindContexts((ignored) => {
686
+ const __contextScope = [];
687
+ try {
688
+ ignored = __boundary(ignored);
689
+ return result;
690
+ return null;
691
+ } finally {
692
+ __contextRestore(__contextScope);
693
+ }
694
+ }), [0], "closure")).finally(__bindContexts(() => {
598
695
  const __contextScope = [];
599
696
  try {
600
- __contextScope.push(__contextSet("db", __capturedContext0));
601
697
  closeScope(__contextGet("db"), false);
602
698
  return null;
603
699
  } finally {
604
700
  __contextRestore(__contextScope);
605
701
  }
606
- })(__contextGet("db")));
702
+ }));
607
703
  return null;
608
704
  } finally {
609
705
  __contextRestore(__contextScope);
@@ -656,4 +752,39 @@ function closeScope(db, strict) {
656
752
  return null;
657
753
  return null;
658
754
  }
755
+
756
+ function needLogin(route, status, reason) {
757
+ const __contextScope = [];
758
+ try {
759
+ __requireArity(arguments.length, [0, 1, 2], "needLogin");
760
+ route = __boundary(route);
761
+ status = __boundary(status);
762
+ reason = __boundary(reason);
763
+ throw new HttpFailure(status, reason, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", "x-lango-need-login": "1" }, { reason: reason, path: __normalize(__contextGet("request").path), policy: __normalize(route.policy), reauthSeconds: __normalize(route.reauthSeconds), userId: __normalize(__contextGet("token").get("userId")) });
764
+ return null;
765
+ } finally {
766
+ __contextRestore(__contextScope);
767
+ }
768
+ }
769
+
770
+ function authenticationChanged(previous, current) {
771
+ const __contextScope = [];
772
+ try {
773
+ __requireArity(arguments.length, [0, 1], "authenticationChanged");
774
+ previous = __boundary(previous);
775
+ current = __boundary(current);
776
+ if (__requireBoolean(__requireBoolean(__contextGet("clientIdentity") !== null) && __requireBoolean(__normalize(__contextGet("clientIdentity").rotate)))) {
777
+ return true;
778
+ }
779
+ for (const name of ["auth", "userId", "grantId", "authenticatedAt"]) {
780
+ if (__requireBoolean(__toJson(__normalize(previous[name])) !== __toJson(__normalize(current[name])))) {
781
+ return true;
782
+ }
783
+ }
784
+ return false;
785
+ return null;
786
+ } finally {
787
+ __contextRestore(__contextScope);
788
+ }
789
+ }
659
790
  //# sourceMappingURL=runtime.mjs.map