@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
@@ -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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,250 @@
1
+ import * as crypto from "node:crypto";
2
+ import {
3
+ hostGlobal as __hostGlobal,
4
+ hostGlobalCall as __hostGlobalCall,
5
+ contextGet as __contextGet,
6
+ contextSet as __contextSet,
7
+ contextRestore as __contextRestore,
8
+ isNumber as __isNumber,
9
+ isString as __isString,
10
+ isBool as __isBool,
11
+ isObject as __isObject,
12
+ isArray as __isArray,
13
+ requireBoolean as __requireBoolean,
14
+ normalize as __normalize,
15
+ finite as __finite,
16
+ numericAdd as __numericAdd,
17
+ boundary as __boundary,
18
+ startTrans as __startTrans,
19
+ commitTrans as __commitTrans,
20
+ rollbackTrans as __rollbackTrans,
21
+ transState as __transState,
22
+ query as __query,
23
+ requireArity as __requireArity,
24
+ } from "./.lango/runtime.mjs";
25
+
26
+ export class ClientIdentity {
27
+ #settings;
28
+ #database;
29
+ constructor(settings, database) {
30
+ __requireArity(arguments.length, [0, 1], "constructor");
31
+ settings = __boundary(settings);
32
+ database = __boundary(database);
33
+ this.#settings = settings;
34
+ this.#database = database;
35
+ }
36
+ initialize() {
37
+ const __contextScope = [];
38
+ try {
39
+ __contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
40
+ try {
41
+ __startTrans();
42
+ if (__requireBoolean(__normalize(__contextGet("db").parameterStyle) === "postgresql")) {
43
+ let lock = __query("select pg_advisory_xact_lock(1818324591, 1)", []);
44
+ __normalize(lock.execute());
45
+ }
46
+ let row = __query("create table if not exists _lango_clients (\n client_id text primary key,\n secret_hash text not null unique,\n expires_at bigint not null\n)", []);
47
+ __normalize(row.execute());
48
+ __commitTrans();
49
+ } finally {
50
+ __normalize(__contextGet("db").finish());
51
+ }
52
+ return null;
53
+ return null;
54
+ } finally {
55
+ __contextRestore(__contextScope);
56
+ }
57
+ }
58
+ begin(claims, tokens) {
59
+ const __contextScope = [];
60
+ try {
61
+ __requireArity(arguments.length, [0, 1], "begin");
62
+ claims = __boundary(claims);
63
+ tokens = __boundary(tokens);
64
+ let value = readCookie();
65
+ if (__requireBoolean(__requireBoolean(value === null) && __requireBoolean(claims !== null))) {
66
+ __normalize(__contextGet("response").reject(401, "ClientProofRequired"));
67
+ }
68
+ let hash = null;
69
+ let row = null;
70
+ if (__requireBoolean(value === null)) {
71
+ value = clientSecret();
72
+ claims = __normalize(tokens.create());
73
+ hash = clientDigest(value);
74
+ claims.clientProof = hash;
75
+ return { claims: claims, value: value, hash: hash, fresh: true, restored: false, rotate: false, closed: false };
76
+ }
77
+ hash = clientDigest(value);
78
+ row = __query("select client_id from _lango_clients where secret_hash = :hash and expires_at > :now", ["hash","now"]);
79
+ row.hash = hash;
80
+ row.now = __normalize(__hostGlobal(["Date"]).now());
81
+ __normalize(row.execute());
82
+ if (__requireBoolean(!__requireBoolean(__normalize(row.next())))) {
83
+ __normalize(__contextGet("response").reject(401, "ClientCookieRejected"));
84
+ }
85
+ let restored = claims === null;
86
+ if (__requireBoolean(restored)) {
87
+ claims = __normalize(tokens.create(__normalize(row.client_id)));
88
+ claims.clientProof = hash;
89
+ }
90
+ if (__requireBoolean(__requireBoolean(__normalize(claims.clientId) !== __normalize(row.client_id)) || __requireBoolean(!__requireBoolean(sameProof(__normalize(claims.clientProof), hash))))) {
91
+ __normalize(__contextGet("response").reject(401, "ClientProofRequired"));
92
+ }
93
+ return { claims: claims, value: value, hash: hash, fresh: false, restored: restored, rotate: false, closed: false };
94
+ return null;
95
+ } finally {
96
+ __contextRestore(__contextScope);
97
+ }
98
+ }
99
+ publish(identity, claims, response, tokens) {
100
+ const __contextScope = [];
101
+ try {
102
+ __requireArity(arguments.length, [0, 1, 2, 3], "publish");
103
+ identity = __boundary(identity);
104
+ claims = __boundary(claims);
105
+ response = __boundary(response);
106
+ tokens = __boundary(tokens);
107
+ let value = __normalize(identity.value);
108
+ if (__requireBoolean(__normalize(identity.rotate))) {
109
+ value = clientSecret();
110
+ }
111
+ let hash = clientDigest(value);
112
+ claims.clientProof = hash;
113
+ let encoded = __normalize(tokens.sign(claims));
114
+ __contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
115
+ let row = null;
116
+ try {
117
+ if (__requireBoolean(__normalize(identity.fresh))) {
118
+ row = __query("insert into _lango_clients (client_id, secret_hash, expires_at)\nvalues (:id, :hash, :expires)", ["id","hash","expires"]);
119
+ row.id = __normalize(claims.clientId);
120
+ row.hash = hash;
121
+ row.expires = __numericAdd(__normalize(__hostGlobal(["Date"]).now()), __finite(__normalize(this.#settings.maxAgeSeconds) * 1000));
122
+ __normalize(row.execute());
123
+ } else {
124
+ row = __query("update _lango_clients set secret_hash = :replacement, expires_at = :expires\nwhere client_id = :id and secret_hash = :previous and expires_at > :now\nreturning client_id", ["replacement","expires","id","previous","now"]);
125
+ row.id = __normalize(claims.clientId);
126
+ row.previous = __normalize(identity.hash);
127
+ row.replacement = hash;
128
+ row.now = __normalize(__hostGlobal(["Date"]).now());
129
+ row.expires = __numericAdd(__normalize(__hostGlobal(["Date"]).now()), __finite(__normalize(this.#settings.maxAgeSeconds) * 1000));
130
+ __normalize(row.execute());
131
+ if (__requireBoolean(!__requireBoolean(__normalize(row.next())))) {
132
+ __normalize(response.reject(401, "ClientProofRequired"));
133
+ }
134
+ }
135
+ __normalize(response.header("Set-Cookie", `__Host-lango-client=${value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${__normalize(this.#settings.maxAgeSeconds)}`));
136
+ } finally {
137
+ __normalize(__contextGet("db").finish());
138
+ }
139
+ identity.closed = true;
140
+ return encoded;
141
+ return null;
142
+ } finally {
143
+ __contextRestore(__contextScope);
144
+ }
145
+ }
146
+ }
147
+ export function clientOptions(spec, database, origin) {
148
+ __requireArity(arguments.length, [0, 1, 2], "clientOptions");
149
+ spec = __boundary(spec);
150
+ database = __boundary(database);
151
+ origin = __boundary(origin);
152
+ if (__requireBoolean(spec === null)) {
153
+ return null;
154
+ }
155
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(spec))) || __requireBoolean(__isArray(spec)))) {
156
+ throw "Client configuration must be an object";
157
+ }
158
+ for (const name of __normalize(__hostGlobal(["Object"]).keys(spec))) {
159
+ if (__requireBoolean(name !== "maxAgeSeconds")) {
160
+ throw `Unknown client option: ${name}`;
161
+ }
162
+ }
163
+ if (__requireBoolean(database === null)) {
164
+ throw "Managed client identity requires a database";
165
+ }
166
+ if (__requireBoolean(__requireBoolean(__normalize(database.type) === "sqlite") && __requireBoolean(__normalize(database.file) === ":memory:"))) {
167
+ throw "Managed client identity requires persistent database storage";
168
+ }
169
+ if (__requireBoolean(__requireBoolean(__requireBoolean(origin === null) || __requireBoolean(!__requireBoolean(__normalize(origin.required)))) || __requireBoolean(!__requireBoolean(__normalize(origin.url.startsWith("https:")))))) {
170
+ throw "Managed client identity requires a required HTTPS origin";
171
+ }
172
+ let lifetime = __normalize(spec.maxAgeSeconds);
173
+ if (__requireBoolean(lifetime === null)) {
174
+ lifetime = 2592000;
175
+ }
176
+ if (__requireBoolean(__isString(lifetime))) {
177
+ lifetime = __hostGlobalCall(["Number"], lifetime);
178
+ }
179
+ if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(lifetime)))) || __requireBoolean(lifetime < 1)) || __requireBoolean(lifetime > 31536000))) {
180
+ throw "Client maxAgeSeconds must be between 1 and 31536000";
181
+ }
182
+ return { maxAgeSeconds: lifetime };
183
+ return null;
184
+ }
185
+
186
+ function readCookie() {
187
+ const __contextScope = [];
188
+ try {
189
+ let pattern;
190
+ let headers = __normalize(__contextGet("request").headers);
191
+ let header = __normalize(headers.cookie);
192
+ if (__requireBoolean(header === null)) {
193
+ return null;
194
+ }
195
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(header))) || __requireBoolean(__normalize(header.length) > 8192))) {
196
+ __normalize(__contextGet("response").reject(400, "InvalidCookie"));
197
+ }
198
+ let found = null;
199
+ for (const part of __normalize(header.split(";"))) {
200
+ let pair = __normalize(part.trim());
201
+ let index = __normalize(pair.indexOf("="));
202
+ if (__requireBoolean(__requireBoolean(index >= 0) && __requireBoolean(__normalize(pair.slice(0, index)) === "__Host-lango-client"))) {
203
+ if (__requireBoolean(found !== null)) {
204
+ __normalize(__contextGet("response").reject(400, "InvalidCookie"));
205
+ }
206
+ found = __normalize(pair.slice(__numericAdd(index, 1)));
207
+ }
208
+ }
209
+ if (__requireBoolean(found !== null)) {
210
+ pattern = new (__hostGlobal(["RegExp"]))("^[a-f0-9]{64}$");
211
+ if (__requireBoolean(!__requireBoolean(__normalize(pattern.test(found))))) {
212
+ __normalize(__contextGet("response").reject(400, "InvalidCookie"));
213
+ }
214
+ }
215
+ return found;
216
+ return null;
217
+ } finally {
218
+ __contextRestore(__contextScope);
219
+ }
220
+ }
221
+
222
+ function clientSecret() {
223
+ let bytes = __normalize(crypto.randomBytes(32));
224
+ return __normalize(bytes.toString("hex"));
225
+ return null;
226
+ }
227
+
228
+ function clientDigest(value) {
229
+ __requireArity(arguments.length, [0], "clientDigest");
230
+ value = __boundary(value);
231
+ let hash = __normalize(crypto.createHash("sha256"));
232
+ __normalize(hash.update(value));
233
+ return __normalize(hash.digest("hex"));
234
+ return null;
235
+ }
236
+
237
+ function sameProof(left, right) {
238
+ __requireArity(arguments.length, [0, 1], "sameProof");
239
+ left = __boundary(left);
240
+ right = __boundary(right);
241
+ let pattern = new (__hostGlobal(["RegExp"]))("^[a-f0-9]{64}$");
242
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(left))) || __requireBoolean(!__requireBoolean(__normalize(pattern.test(left)))))) {
243
+ return false;
244
+ }
245
+ let first = __normalize(__hostGlobal(["Buffer"]).from(left, "hex"));
246
+ let second = __normalize(__hostGlobal(["Buffer"]).from(right, "hex"));
247
+ return __normalize(crypto.timingSafeEqual(first, second));
248
+ return null;
249
+ }
250
+ //# sourceMappingURL=client_identity.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client_identity.mjs","sources":["client_identity.lango"],"sourcesContent":["import js \"node:crypto\" as crypto\nimport js global Date\nimport js global Object\nimport js global Number\nimport js global RegExp\nimport js global Buffer\n\nexport clientOptions(spec, database, origin)\nexport class ClientIdentity(settings, database)\n methods\n initialize()\n begin(claims, tokens)\n publish(identity, claims, response, tokens)\n\nclientOptions(spec, database, origin)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Client configuration must be an object\"\n for Object/keys(spec) as name\n if name != \"maxAgeSeconds\"\n throw \"Unknown client option: ${name}\"\n if database == null\n throw \"Managed client identity requires a database\"\n if database.type == \"sqlite\" and database.file == \":memory:\"\n throw \"Managed client identity requires persistent database storage\"\n if origin == null or !origin.required or !origin.url.startsWith(\"https:\")\n throw \"Managed client identity requires a required HTTPS origin\"\n lifetime = spec.maxAgeSeconds\n if lifetime == null\n lifetime = 2592000\n if is_string(lifetime)\n lifetime = Number(lifetime)\n if !Number/isSafeInteger(lifetime) or lifetime < 1 or lifetime > 31536000\n throw \"Client maxAgeSeconds must be between 1 and 31536000\"\n return {\n maxAgeSeconds: lifetime\n }\n\nClientIdentity(settings, database)\n @settings = settings\n @database = database\n\nClientIdentity:initialize()\n context db = @database.scope()\n try\n start_trans()\n if db.parameterStyle == \"postgresql\"\n lock = SQL\n select pg_advisory_xact_lock(1818324591, 1)\n lock.execute()\n row = SQL\n create table if not exists _lango_clients (\n client_id text primary key,\n secret_hash text not null unique,\n expires_at bigint not null\n )\n row.execute()\n commit_trans()\n finally\n db.finish()\n return null\n\nClientIdentity:begin(claims, tokens)\n context response\n value = readCookie()\n if value == null and claims != null\n response.reject(401, \"ClientProofRequired\")\n hash = null\n row = null\n if value == null\n value = clientSecret()\n claims = tokens.create()\n hash = clientDigest(value)\n claims.clientProof = hash\n return {\n claims: claims\n value: value\n hash: hash\n fresh: true\n restored: false\n rotate: false\n closed: false\n }\n hash = clientDigest(value)\n row = SQL\n select client_id from _lango_clients where secret_hash = :hash and expires_at > :now\n row.hash = hash\n row.now = Date/now()\n row.execute()\n if !row.next()\n response.reject(401, \"ClientCookieRejected\")\n restored = claims == null\n if restored\n claims = tokens.create(row.client_id)\n claims.clientProof = hash\n if claims.clientId != row.client_id or !sameProof(claims.clientProof, hash)\n response.reject(401, \"ClientProofRequired\")\n return {\n claims: claims\n value: value\n hash: hash\n fresh: false\n restored: restored\n rotate: false\n closed: false\n }\n\nClientIdentity:publish(identity, claims, response, tokens)\n value = identity.value\n if identity.rotate\n value = clientSecret()\n hash = clientDigest(value)\n claims.clientProof = hash\n encoded = tokens.sign(claims)\n context db = @database.scope()\n row = null\n try\n if identity.fresh\n row = SQL\n insert into _lango_clients (client_id, secret_hash, expires_at)\n values (:id, :hash, :expires)\n row.id = claims.clientId\n row.hash = hash\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n else\n row = SQL\n update _lango_clients set secret_hash = :replacement, expires_at = :expires\n where client_id = :id and secret_hash = :previous and expires_at > :now\n returning client_id\n row.id = claims.clientId\n row.previous = identity.hash\n row.replacement = hash\n row.now = Date/now()\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n if !row.next()\n response.reject(401, \"ClientProofRequired\")\n response.header(\"Set-Cookie\", \"__Host-lango-client=${value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${@settings.maxAgeSeconds}\")\n finally\n db.finish()\n identity.closed = true\n return encoded\n\nreadCookie()\n context request\n context response\n headers = request.headers\n header = headers.cookie\n if header == null\n return null\n if !is_string(header) or header.length > 8192\n response.reject(400, \"InvalidCookie\")\n found = null\n for header.split(\";\") as part\n pair = part.trim()\n index = pair.indexOf(\"=\")\n if index >= 0 and pair.slice(0, index) == \"__Host-lango-client\"\n if found != null\n response.reject(400, \"InvalidCookie\")\n found = pair.slice(index + 1)\n if found != null\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !pattern.test(found)\n response.reject(400, \"InvalidCookie\")\n return found\n\nclientSecret()\n bytes = crypto/randomBytes(32)\n return bytes.toString(\"hex\")\n\nclientDigest(value)\n hash = crypto/createHash(\"sha256\")\n hash.update(value)\n return hash.digest(\"hex\")\n\nsameProof(left, right)\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !is_string(left) or !pattern.test(left)\n return false\n first = Buffer/from(left, \"hex\")\n second = Buffer/from(right, \"hex\")\n return crypto/timingSafeEqual(first, second)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;AAIA;;;;;;;;;AAKA;;;;;;;;;;;;;;"}
@@ -1,3 +1,4 @@
1
+ import { ClientIdentity } from "./client_identity.mjs";
1
2
  import { DatabaseScope } from "./database_scope.mjs";
2
3
  import { SqliteAdapter } from "./sqlite_adapter.mjs";
3
4
  import { PostgresAdapter } from "./postgres_adapter.mjs";
@@ -6,6 +7,7 @@ import {
6
7
  contextGet as __contextGet,
7
8
  contextSet as __contextSet,
8
9
  contextRestore as __contextRestore,
10
+ bindContexts as __bindContexts,
9
11
  requireBoolean as __requireBoolean,
10
12
  normalize as __normalize,
11
13
  boundary as __boundary,
@@ -34,7 +36,7 @@ export class Database {
34
36
  if (__requireBoolean(__normalize(this.#settings.type) === "postgresql")) {
35
37
  name = "node:worker_threads";
36
38
  }
37
- return import(name).then(__withArity((mod) => {
39
+ return import(name).then(__withArity(__bindContexts((mod) => {
38
40
  const __contextScope = [];
39
41
  try {
40
42
  mod = __boundary(mod);
@@ -55,7 +57,7 @@ export class Database {
55
57
  } finally {
56
58
  __contextRestore(__contextScope);
57
59
  }
58
- }, [0], "closure")).catch(__withArity((error) => {
60
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
59
61
  const __contextScope = [];
60
62
  try {
61
63
  error = __boundary(error);
@@ -66,7 +68,7 @@ export class Database {
66
68
  } finally {
67
69
  __contextRestore(__contextScope);
68
70
  }
69
- }, [0], "closure"));
71
+ }), [0], "closure"));
70
72
  return null;
71
73
  }
72
74
  scope() {
@@ -85,17 +87,30 @@ export class Database {
85
87
  return null;
86
88
  }
87
89
  }
88
- export function prepareDatabase(settings) {
90
+ export function prepareDatabase(settings, root = null, client = null) {
89
91
  __requireArity(arguments.length, [0], "prepareDatabase");
90
92
  settings = __boundary(settings);
91
- if (__requireBoolean(__requireBoolean(__requireBoolean(settings === null) || __requireBoolean(__normalize(settings.type) !== "sqlite")) || __requireBoolean(__normalize(settings.file) === ":memory:"))) {
93
+ root = __boundary(root);
94
+ client = __boundary(client);
95
+ if (__requireBoolean(settings === null)) {
92
96
  return __normalize(__hostGlobal(["Promise"]).resolve(null));
93
97
  }
94
- let database = new Database(settings);
95
- return __normalize(database.open()).finally(() => {
98
+ if (__requireBoolean(__requireBoolean(client === null) && __requireBoolean(__requireBoolean(__normalize(settings.type) !== "sqlite") || __requireBoolean(__normalize(settings.file) === ":memory:")))) {
99
+ return __normalize(__hostGlobal(["Promise"]).resolve(null));
100
+ }
101
+ let database = new Database(settings, root);
102
+ return __normalize(database.open()).then(__withArity(__bindContexts((ignored) => {
103
+ ignored = __boundary(ignored);
104
+ if (__requireBoolean(client !== null)) {
105
+ let identity = new ClientIdentity(client, database);
106
+ __normalize(identity.initialize());
107
+ }
108
+ return null;
109
+ return null;
110
+ }), [0], "closure")).finally(__bindContexts(() => {
96
111
  __normalize(database.close());
97
112
  return null;
98
- });
113
+ }));
99
114
  return null;
100
115
  }
101
116
  //# sourceMappingURL=database.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"database.mjs","sources":["database.lango"],"sourcesContent":["import js global Promise\nimport \"./database_scope\"\n class DatabaseScope\nimport \"./sqlite_adapter\"\n class SqliteAdapter\nimport \"./postgres_adapter\"\n class PostgresAdapter\n\nexport prepareDatabase(settings)\n\nexport class Database(settings, root = null)\n methods\n open()\n scope()\n close()\n\nDatabase(settings, root = null)\n @root = root\n @settings = settings\n @adapter = null\n\nDatabase:open()\n if @settings == null\n return Promise/resolve(null)\n name = \"node:sqlite\"\n if @settings.type == \"postgresql\"\n name = \"node:worker_threads\"\n return chain import_module(name)\n then(mod)\n if @settings.type == \"sqlite\"\n @adapter = new SqliteAdapter(mod, @settings)\n else\n @adapter = new PostgresAdapter(mod, @settings, @root)\n context db = scope()\n try\n query = SQL\n select 1\n query.execute()\n finally\n db.finish()\n return null\n catch(error)\n context log\n log.err(\"Database startup failed: ${error}\")\n close()\n throw \"Database startup failed; check configuration, compiler version and driver installation\"\n\nDatabase:scope()\n if @adapter == null\n return null\n return new DatabaseScope(@adapter)\n\nDatabase:close()\n if @adapter != null\n @adapter.close()\n @adapter = null\n return null\n\nprepareDatabase(settings)\n if settings == null or settings.type != \"sqlite\" or settings.file == \":memory:\"\n return Promise/resolve(null)\n database = new Database(settings)\n return chain database.open()\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"database.mjs","sources":["database.lango"],"sourcesContent":["import \"./client_identity\"\n class ClientIdentity\nimport js global Promise\nimport \"./database_scope\"\n class DatabaseScope\nimport \"./sqlite_adapter\"\n class SqliteAdapter\nimport \"./postgres_adapter\"\n class PostgresAdapter\n\nexport prepareDatabase(settings, root = null, client = null)\n\nexport class Database(settings, root = null)\n methods\n open()\n scope()\n close()\n\nDatabase(settings, root = null)\n @root = root\n @settings = settings\n @adapter = null\n\nDatabase:open()\n if @settings == null\n return Promise/resolve(null)\n name = \"node:sqlite\"\n if @settings.type == \"postgresql\"\n name = \"node:worker_threads\"\n return chain import_module(name)\n then(mod)\n if @settings.type == \"sqlite\"\n @adapter = new SqliteAdapter(mod, @settings)\n else\n @adapter = new PostgresAdapter(mod, @settings, @root)\n context db = scope()\n try\n query = SQL\n select 1\n query.execute()\n finally\n db.finish()\n return null\n catch(error)\n context log\n log.err(\"Database startup failed: ${error}\")\n close()\n throw \"Database startup failed; check configuration, compiler version and driver installation\"\n\nDatabase:scope()\n if @adapter == null\n return null\n return new DatabaseScope(@adapter)\n\nDatabase:close()\n if @adapter != null\n @adapter.close()\n @adapter = null\n return null\n\nprepareDatabase(settings, root = null, client = null)\n if settings == null\n return Promise/resolve(null)\n if client == null and (settings.type != \"sqlite\" or settings.file == \":memory:\")\n return Promise/resolve(null)\n database = new Database(settings, root)\n return chain database.open()\n then(ignored)\n capture database\n capture client\n if client != null\n identity = new ClientIdentity(client, database)\n identity.initialize()\n return null\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -1,3 +1,4 @@
1
+ import { policyOptions } from "./policy.mjs";
1
2
  import { routePattern } from "./route_pattern.mjs";
2
3
  import { middlewareName } from "./middleware.mjs";
3
4
  import {
@@ -17,6 +18,10 @@ export class Endpoint {
17
18
  module;
18
19
  handler;
19
20
  auth;
21
+ policy;
22
+ reauthSeconds;
23
+ reauthExplicit;
24
+ legacyAuth;
20
25
  middleware;
21
26
  constructor(spec) {
22
27
  __requireArity(arguments.length, [0], "constructor");
@@ -34,13 +39,12 @@ export class Endpoint {
34
39
  if (__requireBoolean(__normalize(this.middleware) !== null)) {
35
40
  middlewareName(__normalize(this.middleware));
36
41
  }
37
- this.auth = __normalize(spec.auth);
38
- if (__requireBoolean(__normalize(this.auth) === null)) {
39
- this.auth = "login";
40
- }
41
- if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(this.auth)))) || __requireBoolean(__normalize(this.auth) === "")) || __requireBoolean(__normalize(this.auth.includes(","))))) {
42
- throw "Endpoint auth must name one permission";
43
- }
42
+ let selected = policyOptions(spec);
43
+ this.policy = __normalize(selected.name);
44
+ this.auth = __normalize(selected.name);
45
+ this.reauthSeconds = __normalize(selected.reauthSeconds);
46
+ this.reauthExplicit = __normalize(selected.explicit);
47
+ this.legacyAuth = __normalize(selected.legacy);
44
48
  }
45
49
  }
46
50
  //# sourceMappingURL=endpoint.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\nimport \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n middleware\n\nEndpoint(spec)\n routePattern(spec.path)\n for [\"module\", \"handler\"] as key\n if !is_string(spec[key]) or spec[key] == \"\"\n throw \"Endpoint requires ${key}\"\n @path = spec.path\n @module = spec.module\n @handler = spec.handler\n @middleware = spec.middleware\n if @middleware != null\n middlewareName(@middleware)\n @auth = spec.auth\n if @auth == null\n @auth = \"login\"\n if !is_string(@auth) or @auth == \"\" or @auth.includes(\",\")\n throw \"Endpoint auth must name one permission\"\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./policy\"\n policyOptions(spec)\nimport \"./route_pattern\"\n routePattern(path)\nimport \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n policy\n reauthSeconds\n reauthExplicit\n legacyAuth\n middleware\n\nEndpoint(spec)\n routePattern(spec.path)\n for [\"module\", \"handler\"] as key\n if !is_string(spec[key]) or spec[key] == \"\"\n throw \"Endpoint requires ${key}\"\n @path = spec.path\n @module = spec.module\n @handler = spec.handler\n @middleware = spec.middleware\n if @middleware != null\n middlewareName(@middleware)\n selected = policyOptions(spec)\n @policy = selected.name\n @auth = selected.name\n @reauthSeconds = selected.reauthSeconds\n @reauthExplicit = selected.explicit\n @legacyAuth = selected.legacy\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,45 @@
1
+ import {
2
+ isNumber as __isNumber,
3
+ isString as __isString,
4
+ isBool as __isBool,
5
+ isObject as __isObject,
6
+ isArray as __isArray,
7
+ requireBoolean as __requireBoolean,
8
+ normalize as __normalize,
9
+ boundary as __boundary,
10
+ requireArity as __requireArity,
11
+ } from "./.lango/runtime.mjs";
12
+
13
+ export function errorDetails(error) {
14
+ __requireArity(arguments.length, [0], "errorDetails");
15
+ error = __boundary(error);
16
+ if (__requireBoolean(__isObject(error))) {
17
+ if (__requireBoolean(__requireBoolean(__isString(__normalize(error.stack))) && __requireBoolean(__normalize(error.stack) !== ""))) {
18
+ return __normalize(error.stack);
19
+ }
20
+ if (__requireBoolean(__requireBoolean(__isString(__normalize(error.message))) && __requireBoolean(__normalize(error.message) !== ""))) {
21
+ return __normalize(error.message);
22
+ }
23
+ if (__requireBoolean(__isString(__normalize(error.code)))) {
24
+ return __normalize(error.code);
25
+ }
26
+ }
27
+ return `${error}`;
28
+ return null;
29
+ }
30
+
31
+ export function errorMessage(error) {
32
+ __requireArity(arguments.length, [0], "errorMessage");
33
+ error = __boundary(error);
34
+ if (__requireBoolean(__isObject(error))) {
35
+ if (__requireBoolean(__requireBoolean(__isString(__normalize(error.message))) && __requireBoolean(__normalize(error.message) !== ""))) {
36
+ return __normalize(error.message);
37
+ }
38
+ if (__requireBoolean(__isString(__normalize(error.code)))) {
39
+ return __normalize(error.code);
40
+ }
41
+ }
42
+ return `${error}`;
43
+ return null;
44
+ }
45
+ //# sourceMappingURL=error_details.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error_details.mjs","sources":["error_details.lango"],"sourcesContent":["export errorDetails(error)\nexport errorMessage(error)\n\nerrorDetails(error)\n if is_object(error)\n if is_string(error.stack) and error.stack != \"\"\n return error.stack\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n\n\nerrorMessage(error)\n if is_object(error)\n if is_string(error.message) and error.message != \"\"\n return error.message\n if is_string(error.code)\n return error.code\n return \"${error}\"\n"],"names":[],"mappings":";;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;AAWA;;;;;;;;;;;;;;;"}
@@ -6,6 +6,7 @@ import * as modules from "node:module";
6
6
  import {
7
7
  hostGlobal as __hostGlobal,
8
8
  hostGlobalCall as __hostGlobalCall,
9
+ bindContexts as __bindContexts,
9
10
  fromJson as __fromJson,
10
11
  toJson as __toJson,
11
12
  isNumber as __isNumber,
@@ -65,11 +66,11 @@ export class LongpollBroker {
65
66
  let name = __normalize(config.connectionEnv);
66
67
  this.#client = __normalize(redis.createClient({ url: __normalize(__hostGlobal(["process"]).env[name]), disableOfflineQueue: true, commandsQueueMaxLength: 2048, socket: { connectTimeout: 2000, reconnectStrategy: 500 } }));
67
68
  let client = __normalize(this.#client);
68
- __normalize(client.on("error", __withArity((error) => {
69
+ __normalize(client.on("error", __withArity(__bindContexts((error) => {
69
70
  error = __boundary(error);
70
71
  return null;
71
72
  return null;
72
- }, [0], "closure")));
73
+ }), [0], "closure")));
73
74
  return bounded(__normalize(client.connect()), 3000);
74
75
  return null;
75
76
  }
@@ -136,7 +137,7 @@ export class LongpollBroker {
136
137
  }
137
138
  }
138
139
  let pending = __normalize(this.#client.eval(__normalize(this.#script), { keys: [`${prefix}:stream`, `${prefix}:meta`], arguments: [operation, __normalize(crypto.randomUUID()), `${__normalize(item.retentionMs)}`, `${__normalize(item.maxMessages)}`, __normalize(position.generation), __normalize(position.id), body] }));
139
- return bounded(pending, 3000).then(__withArity((raw) => {
140
+ return bounded(pending, 3000).then(__withArity(__bindContexts((raw) => {
140
141
  raw = __boundary(raw);
141
142
  let result = __normalize(__hostGlobal(["JSON"]).parse(raw));
142
143
  if (__requireBoolean(__normalize(result.resyncRequired) === true)) {
@@ -154,7 +155,7 @@ export class LongpollBroker {
154
155
  }
155
156
  return { messages: messages, cursor: __normalize(result.cursor), resyncRequired: false };
156
157
  return null;
157
- }, [0], "closure"));
158
+ }), [0], "closure"));
158
159
  return null;
159
160
  }
160
161
  }
@@ -200,15 +201,15 @@ function bounded(pending, ms) {
200
201
  pending = __boundary(pending);
201
202
  ms = __boundary(ms);
202
203
  let expired = __normalize(__hostGlobal(["Promise"]).withResolvers());
203
- let fail = () => {
204
+ let fail = __bindContexts(() => {
204
205
  __normalize(expired.reject("RedisUnavailable"));
205
206
  return null;
206
- };
207
+ });
207
208
  let timer = __hostGlobalCall(["setTimeout"], fail, ms);
208
- return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(() => {
209
+ return __normalize(__hostGlobal(["Promise"]).race([pending, __normalize(expired.promise)])).finally(__bindContexts(() => {
209
210
  __hostGlobalCall(["clearTimeout"], timer);
210
211
  return null;
211
- });
212
+ }));
212
213
  return null;
213
214
  }
214
215
  //# sourceMappingURL=longpoll_broker.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"longpoll_broker.mjs","sources":["longpoll_broker.lango"],"sourcesContent":["import js \"redis\" as redis\nimport js \"node:crypto\" as crypto\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js global Buffer\nimport js global Promise\nimport js global process\nimport js global JSON\nimport js global RegExp\nimport js global Object\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class LongpollBroker(settings, routes)\n methods\n open()\n close()\n route(path)\n publish(path, key, data)\n cursor(path, key)\n read(path, key, cursor)\n\nLongpollBroker(settings, routes)\n @routes = Object/create(null)\n for routes as item\n if item.kind == \"longpoll\"\n @routes[item.path] = item\n @settings = settings.redis\n @client = null\n @script = null\n if Object/keys(@routes).length > 0 and @settings == null\n throw \"Longpoll routes require Redis configuration\"\n @root = settings.root\n\nLongpollBroker:route(path)\n if Object/hasOwn(@routes, path)\n return @routes[path]\n return null\n\nLongpollBroker:open()\n if Object/keys(@routes).length == 0\n return Promise/resolve(null)\n resolver = modules/createRequire(path/join(@root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @script = fs/readFileSync(path/join(path/dirname(entry), \"../src/longpoll.lua\"), \"utf8\")\n config = @settings\n name = config.connectionEnv\n @client = redis/createClient({\n url: process.env[name]\n disableOfflineQueue: true\n commandsQueueMaxLength: 2048\n socket: {\n connectTimeout: 2000\n reconnectStrategy: 500\n }\n })\n client = @client\n client.on(\"error\", (error)\n return null\n )\n return bounded(client.connect(), 3000)\n\nLongpollBroker:close()\n if @client != null and @client.isOpen\n @client.destroy()\n return null\n\nLongpollBroker:publish(path, key, data)\n body = JSON/stringify(data)\n if !is_string(body) or Buffer/byteLength(body) > 262144\n return Promise/reject(\"Longpoll message must be JSON within 262144 bytes\")\n return execute(\"publish\", path, key, null, body)\n\nLongpollBroker:cursor(path, key)\n return execute(\"cursor\", path, key, null, \"\")\n\nLongpollBroker:read(path, key, cursor)\n return execute(\"read\", path, key, cursor, \"\")\n\nLongpollBroker:execute(operation, path, key, cursor, body)\n item = route(path)\n if item == null\n return Promise/reject(\"Unknown longpoll path\")\n if !is_string(key) or key == \"\" or Buffer/byteLength(key) > 1024\n return Promise/reject(\"Longpoll key must contain 1 to 1024 bytes\")\n if @client == null or !@client.isReady\n return Promise/reject(\"RedisUnavailable\")\n hash = crypto/createHash(\"sha256\")\n hash.update(to_json([@settings.namespace, path, key]))\n channel = hash.digest(\"hex\")\n prefix = \"lango:longpoll:{${channel}}\"\n position = {\n generation: \"\"\n id: \"0-0\"\n }\n if cursor != null\n position = decode(cursor, channel)\n if position == null\n return Promise/resolve({\n resyncRequired: true\n })\n pending = @client.eval(@script, {\n keys: [\"${prefix}:stream\", \"${prefix}:meta\"]\n arguments: [operation, crypto/randomUUID(), \"${item.retentionMs}\", \"${item.maxMessages}\", position.generation, position.id, body]\n })\n return chain bounded(pending, 3000)\n then(raw)\n capture channel\n capture operation\n result = JSON/parse(raw)\n if result.resyncRequired == true\n return result\n result.cursor = encode(channel, result.generation, result.id)\n if operation != \"read\"\n return result.cursor\n messages = []\n if is_array(result.messages)\n for result.messages as message\n messages.add({\n id: encode(channel, result.generation, message.id)\n data: JSON/parse(message.data)\n })\n return {\n messages: messages\n cursor: result.cursor\n resyncRequired: false\n }\n\nencode(channel, generation, id)\n buffer = Buffer/from(to_json([channel, generation, id]))\n return buffer.toString(\"base64url\")\n\ndecode(cursor, channel)\n if !is_string(cursor) or cursor.length > 512\n return null\n try\n buffer = Buffer/from(cursor, \"base64url\")\n parts = from_json(buffer.toString(\"utf8\"))\n if !is_array(parts) or parts.length != 3 or parts[0] != channel or !is_string(parts[1]) or !is_string(parts[2])\n return null\n pattern = new RegExp(\"^(0|[1-9][0-9]{0,18})-(0|[1-9][0-9]{0,18})$\")\n if !pattern.test(parts[2]) or parts[2].length > 40\n return null\n return {\n generation: parts[1]\n id: parts[2]\n }\n catch error\n return null\n\nbounded(pending, ms)\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"RedisUnavailable\")\n timer = setTimeout(fail, ms)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmHA;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"longpoll_broker.mjs","sources":["longpoll_broker.lango"],"sourcesContent":["import js \"redis\" as redis\nimport js \"node:crypto\" as crypto\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js global Buffer\nimport js global Promise\nimport js global process\nimport js global JSON\nimport js global RegExp\nimport js global Object\nimport js global setTimeout\nimport js global clearTimeout\n\nexport class LongpollBroker(settings, routes)\n methods\n open()\n close()\n route(path)\n publish(path, key, data)\n cursor(path, key)\n read(path, key, cursor)\n\nLongpollBroker(settings, routes)\n @routes = Object/create(null)\n for routes as item\n if item.kind == \"longpoll\"\n @routes[item.path] = item\n @settings = settings.redis\n @client = null\n @script = null\n if Object/keys(@routes).length > 0 and @settings == null\n throw \"Longpoll routes require Redis configuration\"\n @root = settings.root\n\nLongpollBroker:route(path)\n if Object/hasOwn(@routes, path)\n return @routes[path]\n return null\n\nLongpollBroker:open()\n if Object/keys(@routes).length == 0\n return Promise/resolve(null)\n resolver = modules/createRequire(path/join(@root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @script = fs/readFileSync(path/join(path/dirname(entry), \"../src/longpoll.lua\"), \"utf8\")\n config = @settings\n name = config.connectionEnv\n @client = redis/createClient({\n url: process.env[name]\n disableOfflineQueue: true\n commandsQueueMaxLength: 2048\n socket: {\n connectTimeout: 2000\n reconnectStrategy: 500\n }\n })\n client = @client\n client.on(\"error\", (error)\n return null\n )\n return bounded(client.connect(), 3000)\n\nLongpollBroker:close()\n if @client != null and @client.isOpen\n @client.destroy()\n return null\n\nLongpollBroker:publish(path, key, data)\n body = JSON/stringify(data)\n if !is_string(body) or Buffer/byteLength(body) > 262144\n return Promise/reject(\"Longpoll message must be JSON within 262144 bytes\")\n return execute(\"publish\", path, key, null, body)\n\nLongpollBroker:cursor(path, key)\n return execute(\"cursor\", path, key, null, \"\")\n\nLongpollBroker:read(path, key, cursor)\n return execute(\"read\", path, key, cursor, \"\")\n\nLongpollBroker:execute(operation, path, key, cursor, body)\n item = route(path)\n if item == null\n return Promise/reject(\"Unknown longpoll path\")\n if !is_string(key) or key == \"\" or Buffer/byteLength(key) > 1024\n return Promise/reject(\"Longpoll key must contain 1 to 1024 bytes\")\n if @client == null or !@client.isReady\n return Promise/reject(\"RedisUnavailable\")\n hash = crypto/createHash(\"sha256\")\n hash.update(to_json([@settings.namespace, path, key]))\n channel = hash.digest(\"hex\")\n prefix = \"lango:longpoll:{${channel}}\"\n position = {\n generation: \"\"\n id: \"0-0\"\n }\n if cursor != null\n position = decode(cursor, channel)\n if position == null\n return Promise/resolve({\n resyncRequired: true\n })\n pending = @client.eval(@script, {\n keys: [\"${prefix}:stream\", \"${prefix}:meta\"]\n arguments: [operation, crypto/randomUUID(), \"${item.retentionMs}\", \"${item.maxMessages}\", position.generation, position.id, body]\n })\n return chain bounded(pending, 3000)\n then(raw)\n capture channel\n capture operation\n result = JSON/parse(raw)\n if result.resyncRequired == true\n return result\n result.cursor = encode(channel, result.generation, result.id)\n if operation != \"read\"\n return result.cursor\n messages = []\n if is_array(result.messages)\n for result.messages as message\n messages.add({\n id: encode(channel, result.generation, message.id)\n data: JSON/parse(message.data)\n })\n return {\n messages: messages\n cursor: result.cursor\n resyncRequired: false\n }\n\nencode(channel, generation, id)\n buffer = Buffer/from(to_json([channel, generation, id]))\n return buffer.toString(\"base64url\")\n\ndecode(cursor, channel)\n if !is_string(cursor) or cursor.length > 512\n return null\n try\n buffer = Buffer/from(cursor, \"base64url\")\n parts = from_json(buffer.toString(\"utf8\"))\n if !is_array(parts) or parts.length != 3 or parts[0] != channel or !is_string(parts[1]) or !is_string(parts[2])\n return null\n pattern = new RegExp(\"^(0|[1-9][0-9]{0,18})-(0|[1-9][0-9]{0,18})$\")\n if !pattern.test(parts[2]) or parts[2].length > 40\n return null\n return {\n generation: parts[1]\n id: parts[2]\n }\n catch error\n return null\n\nbounded(pending, ms)\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"RedisUnavailable\")\n timer = setTimeout(fail, ms)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAcA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmHA;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA;;;;;;;;;;;;;;;;;"}