@lango-project/lango-server 0.2.4 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -5
- package/dist/body_reader.mjs.map +1 -1
- package/dist/builder.mjs.map +1 -1
- package/dist/cli/server.mjs +3 -838
- package/dist/cli/server.mjs.map +1 -1
- package/dist/client_identity.mjs.map +1 -1
- package/dist/database.mjs.map +1 -1
- package/dist/database_action.mjs.map +1 -1
- package/dist/database_options.mjs.map +1 -1
- package/dist/database_scope.mjs.map +1 -1
- package/dist/endpoint.mjs.map +1 -1
- package/dist/error_details.mjs.map +1 -1
- package/dist/execution_failure.mjs.map +1 -1
- package/dist/execution_identity.mjs.map +1 -1
- package/dist/execution_log.mjs.map +1 -1
- package/dist/execution_runtime.mjs.map +1 -1
- package/dist/execution_worker.mjs.map +1 -1
- package/dist/executor.mjs.map +1 -1
- package/dist/group.mjs.map +1 -1
- package/dist/http_failure.mjs.map +1 -1
- package/dist/job_configuration.mjs.map +1 -1
- package/dist/job_context.mjs.map +1 -1
- package/dist/library.mjs.map +1 -1
- package/dist/longpoll_broker.mjs.map +1 -1
- package/dist/longpoll_options.mjs.map +1 -1
- package/dist/longpoll_session.mjs.map +1 -1
- package/dist/middleware.mjs.map +1 -1
- package/dist/module_loader.mjs.map +1 -1
- package/dist/options.mjs.map +1 -1
- package/dist/origin.mjs.map +1 -1
- package/dist/policy.mjs.map +1 -1
- package/dist/postgres_adapter.mjs.map +1 -1
- package/dist/postgres_worker.mjs.map +1 -1
- package/dist/queue_provider.mjs.map +1 -1
- package/dist/request_identity.mjs.map +1 -1
- package/dist/response.mjs +1 -1
- package/dist/response.mjs.map +1 -1
- package/dist/route_info.mjs +5 -1
- package/dist/route_info.mjs.map +1 -1
- package/dist/route_pattern.mjs.map +1 -1
- package/dist/routes.mjs +27 -4
- package/dist/routes.mjs.map +1 -1
- package/dist/runtime.mjs +66 -11
- package/dist/runtime.mjs.map +1 -1
- package/dist/server.mjs +2 -1
- package/dist/server.mjs.map +1 -1
- package/dist/server_context.mjs.map +1 -1
- package/dist/sqlite_adapter.mjs.map +1 -1
- package/dist/static_files.mjs.map +1 -1
- package/dist/token.mjs.map +1 -1
- package/dist/tokens.mjs +4 -1
- package/dist/tokens.mjs.map +1 -1
- package/dist/trace.mjs +6 -1
- package/dist/trace.mjs.map +1 -1
- package/dist/worker.mjs.map +1 -1
- package/docs/browser-sessions.md +96 -0
- package/examples/security/package.json +1 -1
- package/package.json +8 -5
- package/src/response.lango +1 -1
- package/src/route_info.lango +5 -2
- package/src/routes.lango +20 -3
- package/src/runtime.lango +56 -11
- package/src/server.lango +3 -2
- package/src/tokens.lango +4 -0
- package/src/trace.lango +5 -2
- package/dist/cli/.lango/bignumber.mjs +0 -3119
- package/dist/cli/.lango/localization.mjs +0 -108
- package/dist/cli/.lango/runtime.mjs +0 -725
- package/dist/cli/.lango/vendor/i18next.LICENSE +0 -21
- package/dist/cli/.lango/vendor/i18next.mjs +0 -2434
- package/dist/cli/.lango/xmldom/conventions.js +0 -429
- package/dist/cli/.lango/xmldom/dom-parser.js +0 -591
- package/dist/cli/.lango/xmldom/dom.js +0 -3759
- package/dist/cli/.lango/xmldom/entities.js +0 -2171
- package/dist/cli/.lango/xmldom/errors.js +0 -205
- package/dist/cli/.lango/xmldom/grammar.js +0 -559
- package/dist/cli/.lango/xmldom/index.js +0 -41
- package/dist/cli/.lango/xmldom/package.json +0 -1
- package/dist/cli/.lango/xmldom/sax.js +0 -983
- package/dist/cli/.lango/xmldom.LICENSE.md +0 -8
- package/dist/cli/body_reader.mjs +0 -180
- package/dist/cli/body_reader.mjs.map +0 -1
- package/dist/cli/client_identity.mjs +0 -250
- package/dist/cli/client_identity.mjs.map +0 -1
- package/dist/cli/database.mjs +0 -116
- package/dist/cli/database.mjs.map +0 -1
- package/dist/cli/database_options.mjs +0 -83
- package/dist/cli/database_options.mjs.map +0 -1
- package/dist/cli/database_scope.mjs +0 -93
- package/dist/cli/database_scope.mjs.map +0 -1
- package/dist/cli/endpoint.mjs +0 -50
- package/dist/cli/endpoint.mjs.map +0 -1
- package/dist/cli/error_details.mjs +0 -45
- package/dist/cli/error_details.mjs.map +0 -1
- package/dist/cli/longpoll_broker.mjs +0 -215
- package/dist/cli/longpoll_broker.mjs.map +0 -1
- package/dist/cli/longpoll_options.mjs +0 -103
- package/dist/cli/longpoll_options.mjs.map +0 -1
- package/dist/cli/longpoll_session.mjs +0 -136
- package/dist/cli/longpoll_session.mjs.map +0 -1
- package/dist/cli/middleware.mjs +0 -25
- package/dist/cli/middleware.mjs.map +0 -1
- package/dist/cli/options.mjs +0 -214
- package/dist/cli/options.mjs.map +0 -1
- package/dist/cli/origin.mjs +0 -87
- package/dist/cli/origin.mjs.map +0 -1
- package/dist/cli/policy.mjs +0 -121
- package/dist/cli/policy.mjs.map +0 -1
- package/dist/cli/postgres_adapter.mjs +0 -178
- package/dist/cli/postgres_adapter.mjs.map +0 -1
- package/dist/cli/route_pattern.mjs +0 -129
- package/dist/cli/route_pattern.mjs.map +0 -1
- package/dist/cli/routes.mjs +0 -360
- package/dist/cli/routes.mjs.map +0 -1
- package/dist/cli/sqlite_adapter.mjs +0 -163
- package/dist/cli/sqlite_adapter.mjs.map +0 -1
- package/dist/cli/static_files.mjs +0 -224
- package/dist/cli/static_files.mjs.map +0 -1
- package/dist/cli/trace.mjs +0 -53
- package/dist/cli/trace.mjs.map +0 -1
package/dist/server.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./policy\"\n resolvePolicies(routes, registry)\nimport \"./trace\"\n trace(message)\n responseLog(id, method, path, status)\nimport \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings, root = null, client = null)\nimport \"./error_details\"\n errorDetails(error)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\nimport \"./static_files\"\n class StaticFiles\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n publish(path, key, data)\n cursor(path, key)\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n jobs: routes.jobs()\n events: routes.events()\n middlewares: routes.middlewares()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n settings = @definition.settings\n resolvePolicies(@definition.routes, settings.policies)\n if @definition.jobs != null\n resolvePolicies(@definition.jobs, settings.policies)\n @broker = new LongpollBroker(@definition.settings, @definition.routes)\n @polls = Object/create(null)\n @state = \"new\"\n @connections = []\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n @static = null\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:publish(path, key, data)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.publish(path, key, data)\n\nServer:cursor(path, key)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.cursor(path, key)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n trace(\"Server starting: ${settings.root}; workers=${settings.workers}\")\n if settings.static != null\n try\n @static = new StaticFiles(settings.static)\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n return chain @broker.open()\n then(ignored)\n capture settings\n return prepareDatabase(settings.database, settings.root, settings.client)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error: ${errorDetails(error)}\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.on(\"connection\", (socket)\n connected(socket)\n )\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @broker.close()\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"longpoll\"\n brokerMessage(message)\n return null\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n record.logIdentity = message.logIdentity\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:connected(socket)\n record = {\n socket: socket\n active: 0\n }\n @connections.add(record)\n socket.once(\"close\", ()\n capture record\n index = @connections.indexOf(record)\n if index >= 0\n @connections.splice(index, 1)\n )\n return null\n\nServer:trackResponse(req, res)\n target = req.url.split(\"?\")[0]\n for @connections as record\n if record.socket == req.socket\n record.active = record.active + 1\n state = {\n done: false\n }\n complete = ()\n capture record\n capture state\n capture req\n capture res\n capture target\n if state.done\n return null\n state.done = true\n if res.writableFinished\n responseLog(res.langoRequestId, req.method, target, res.statusCode)\n else\n trace(\"HTTP ${req.method} ${target} connection closed before response completed\")\n record.active = record.active - 1\n if @state == \"closing\" and record.active == 0\n record.socket.end()\n return null\n res.once(\"finish\", complete)\n res.once(\"close\", complete)\n return null\n return null\n\nServer:receive(req, res)\n trackResponse(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n trace(\"HTTP ${req.method} ${req.url.split('?')[0]}\")\n if @static != null and (req.method == \"GET\" or req.method == \"HEAD\")\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n return @static.receive(req, res, failed)\n if req.method != \"POST\"\n allowed = \"POST\"\n if @static != null\n allowed = \"GET, HEAD, POST\"\n res.setHeader(\"Allow\", allowed)\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n pending = null\n route = @broker.route(req.url)\n if route == null\n pending = dispatch(req, res, body)\n else\n pending = longpoll(req, res, body, route)\n return chain pending\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n capture req\n context log\n log.err(\"HTTP ${req.method} ${req.url.split('?')[0]} request failed: ${errorDetails(error)}\")\n send(res, failure(500, \"InternalServerError\"))\n return null\n\nServer:longpoll(req, res, body, route)\n if Object/keys(@polls).length >= @definition.settings.redis.maxPendingPolls\n return Promise/resolve(failure(503, \"PollLimit\"))\n authorize = (token, result)\n capture req\n capture res\n capture body\n return dispatch(req, res, body, true, token, result)\n session = new LongpollSession(@broker, route, authorize, body)\n id = crypto/randomUUID()\n @polls[id] = session\n disconnected = ()\n capture session\n session.cancel()\n res.once(\"close\", disconnected)\n return chain session.run()\n finally\n capture res\n capture disconnected\n capture id\n res.removeListener(\"close\", disconnected)\n Reflect/deleteProperty(@polls, id)\n\nServer:brokerMessage(message)\n port = message.port\n pending = null\n try\n switch message.operation\n case \"publish\"\n pending = publish(message.path, message.key, message.data)\n case \"cursor\"\n pending = cursor(message.path, message.key)\n else\n pending = Promise/reject(\"Unknown longpoll operation\")\n catch error\n pending = Promise/reject(error)\n return chain pending\n then(value)\n capture port\n brokerReply(port, {\n ok: true\n value: value\n })\n catch(error)\n capture port\n brokerReply(port, {\n ok: false\n })\n finally\n capture port\n port.close()\n\nServer:dispatch(req, res, body, authorize = false, token = null, pollResult = null)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return Promise/resolve(failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n res.langoRequestId = id\n trace(\"[${id}] Queued request ${req.method} ${req.url}\")\n record = {\n id: id\n task: {\n authorize: authorize\n pollResult: pollResult\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: Object/assign({}, req.headers)\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n if token != null\n record.task.request.headers.authorization = \"Bearer ${token}\"\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n disconnected = ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n res.once(\"close\", disconnected)\n pump()\n return chain record.completed.promise\n catch(error)\n capture record\n if record.expired\n return failure(504, \"RequestTimeout\")\n return failure(500, \"InternalServerError\")\n finally\n capture res\n capture disconnected\n res.removeListener(\"close\", disconnected)\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n trace(\"[${record.id}] Dispatching to worker\")\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"${record.logIdentity} Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n for @connections as record\n if record.active == 0\n record.socket.destroy()\n for @polls as id: session\n session.cancel()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @broker.close()\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n trace(\"HTTP response status=${result.status}\")\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n context log\n log.err(\"[${res.langoRequestId}] Response write failed: ${errorDetails(error)}\")\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n directory = null\n verbose = false\n for args as arg\n if arg == \"--verbose\"\n verbose = true\n else\n if arg.startsWith(\"--\") or directory != null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n directory = arg\n if directory == null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n if verbose\n process.env.LANGO_VERBOSE = \"1\"\n trace(\"Loading server configuration: ${directory}\")\n server = new Server(directory)\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n\nbrokerReply(port, message)\n try\n port.postMessage(message)\n catch error\n return null\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA;;;;;;;;AAqGA;;;;;;;;;;;;;;;;;AAiYA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./policy\"\n resolvePolicies(routes, registry)\nimport \"./trace\"\n trace(message)\n responseLog(id, method, path, status, session = null)\nimport \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings, root = null, client = null)\nimport \"./error_details\"\n errorDetails(error)\nimport js \"node:http\" as http\nimport js \"node:path\" as path\nimport js \"node:module\" as modules\nimport js \"node:crypto\" as crypto\nimport js \"piscina\" as piscina\nimport js global process\nimport js global Promise\nimport js global Date\nimport js global Math\nimport js global Object\nimport js global Reflect\nimport js global AbortController\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./options\"\n deployment(directory)\nimport \"./routes\"\n class Routes\nimport \"./body_reader\"\n class BodyReader\nimport \"./static_files\"\n class StaticFiles\n\nexport main(args)\n\nexport class Server(path, definition = null)\n methods\n start()\n close()\n publish(path, key, data)\n cursor(path, key)\n\nServer(path, definition = null)\n if path != null\n directory = path\n routes = new Routes(directory)\n routes.xml(pathJoin(directory, \"routes.xml\"))\n definition = {\n settings: deployment(directory)\n routes: routes.definitions()\n jobs: routes.jobs()\n events: routes.events()\n middlewares: routes.middlewares()\n }\n if definition == null\n throw \"Use Server(directory) or Builder.build()\"\n @definition = from_json(to_json(definition))\n settings = @definition.settings\n resolvePolicies(@definition.routes, settings.policies)\n if @definition.jobs != null\n resolvePolicies(@definition.jobs, settings.policies)\n @broker = new LongpollBroker(@definition.settings, @definition.routes)\n @polls = Object/create(null)\n @state = \"new\"\n @connections = []\n @server = null\n @pool = null\n @starting = null\n @closing = null\n @waiting = []\n @active = 0\n @tasks = Object/create(null)\n @ready = Promise/withResolvers()\n @readyIds = []\n @destroying = false\n @static = null\n\npathJoin(directory, file)\n return path/join(directory, file)\n\nServer:publish(path, key, data)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.publish(path, key, data)\n\nServer:cursor(path, key)\n if @state != \"running\"\n return Promise/reject(\"Server is not running\")\n return @broker.cursor(path, key)\n\nServer:start()\n if @state != \"new\"\n return Promise/reject(\"Server can only be started once\")\n @state = \"starting\"\n @starting = launch()\n return @starting\n\nServer:launch()\n settings = @definition.settings\n trace(\"Server starting: ${settings.root}; workers=${settings.workers}\")\n if settings.static != null\n try\n @static = new StaticFiles(settings.static)\n catch error\n @state = \"closed\"\n return Promise/reject(error)\n return chain @broker.open()\n then(ignored)\n capture settings\n return prepareDatabase(settings.database, settings.root, settings.client)\n then(ignored)\n capture path\n capture modules\n capture settings\n resolver = modules/createRequire(path/join(settings.root, \"package.json\"))\n entry = resolver.resolve(\"@lango-project/lango-server\")\n @pool = new piscina/Piscina({\n filename: path/join(path/dirname(entry), \"worker.mjs\")\n name: \"execute\"\n minThreads: settings.workers\n maxThreads: settings.workers\n maxQueue: settings.maxQueue\n concurrentTasksPerWorker: 1\n closeTimeout: settings.shutdownTimeoutMs\n workerData: @definition\n })\n pool = @pool\n pool.on(\"message\", (message)\n messageReceived(message)\n )\n pool.on(\"error\", (error)\n @ready.reject(error)\n context log\n log.err(\"Worker pool error: ${errorDetails(error)}\")\n )\n return startupDeadline(@ready.promise, settings.startupTimeoutMs)\n then(ignored)\n capture settings\n if @state != \"starting\"\n throw \"Server closed during startup\"\n server = new http/Server((req, res)\n receive(req, res)\n )\n @server = server\n server.on(\"connection\", (socket)\n connected(socket)\n )\n server.headersTimeout = settings.bodyTimeoutMs\n server.requestTimeout = settings.bodyTimeoutMs\n listening = new Promise((resolve, reject)\n capture server\n capture settings\n server.once(\"error\", reject)\n server.listen(settings.port, settings.host, ()\n capture server\n capture resolve\n capture reject\n server.removeListener(\"error\", reject)\n if @state != \"starting\"\n reject(\"Server closed during startup\")\n return null\n @state = \"running\"\n address = server.address()\n resolve({\n host: address.address\n port: address.port\n })\n )\n )\n return listening\n catch(error)\n @broker.close()\n @state = \"closed\"\n return chain destroyPool()\n then(ignored)\n capture error\n throw error\n\nstartupDeadline(pending, timeout)\n expired = Promise/withResolvers()\n expire = ()\n capture expired\n expired.reject(\"Worker startup timed out\")\n timer = setTimeout(expire, timeout)\n return chain Promise/race([pending, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n\nServer:messageReceived(message)\n if message.kind == \"longpoll\"\n brokerMessage(message)\n return null\n if message.kind == \"ready\"\n if !@readyIds.includes(message.threadId)\n @readyIds.add(message.threadId)\n if @readyIds.length >= @definition.settings.workers\n @ready.resolve(null)\n return null\n if !(message.id in @tasks)\n return null\n record = @tasks[message.id]\n if message.kind == \"prepared\"\n record.result = message.result\n record.logIdentity = message.logIdentity\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"event\"\n resetDeadline(record, @definition.settings.eventTimeoutMs)\n if message.kind == \"handler\" and record.result == null\n resetDeadline(record, record.deadline - Date/now())\n return null\n\nServer:resetDeadline(record, duration)\n clearTimeout(record.timer)\n if record.result == null\n duration = Math/min(duration, record.deadline - Date/now())\n expired = ()\n capture record\n expire(record)\n record.timer = setTimeout(expired, Math/max(1, duration))\n return null\n\nServer:connected(socket)\n record = {\n socket: socket\n active: 0\n }\n @connections.add(record)\n socket.once(\"close\", ()\n capture record\n index = @connections.indexOf(record)\n if index >= 0\n @connections.splice(index, 1)\n )\n return null\n\nServer:trackResponse(req, res)\n target = req.url.split(\"?\")[0]\n for @connections as record\n if record.socket == req.socket\n record.active = record.active + 1\n state = {\n done: false\n }\n complete = ()\n capture record\n capture state\n capture req\n capture res\n capture target\n if state.done\n return null\n state.done = true\n if res.writableFinished\n responseLog(res.langoRequestId, req.method, target, res.statusCode, res.langoSession)\n else\n trace(\"HTTP ${req.method} ${target} connection closed before response completed\")\n record.active = record.active - 1\n if @state == \"closing\" and record.active == 0\n record.socket.end()\n return null\n res.once(\"finish\", complete)\n res.once(\"close\", complete)\n return null\n return null\n\nServer:receive(req, res)\n trackResponse(req, res)\n req.on(\"error\", (error)\n return null\n )\n if @state != \"running\"\n return rejectHttp(req, res, 503, \"Unavailable\")\n trace(\"HTTP ${req.method} ${req.url.split('?')[0]}\")\n if @static != null and (req.method == \"GET\" or req.method == \"HEAD\")\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n return @static.receive(req, res, failed)\n if req.method != \"POST\"\n allowed = \"POST\"\n if @static != null\n allowed = \"GET, HEAD, POST\"\n res.setHeader(\"Allow\", allowed)\n return rejectHttp(req, res, 405, \"MethodNotAllowed\")\n if req.url.includes(\"?\") or req.url.includes(\"#\") or req.url.includes(\"\\\\\")\n return rejectHttp(req, res, 400, \"InvalidPath\")\n type = req.headers[\"content-type\"]\n media = \"\"\n if is_string(type)\n parts = type.split(\";\")\n media = parts[0].trim()\n if media.toLowerCase() != \"application/json\"\n return rejectHttp(req, res, 415, \"JsonRequired\")\n settings = @definition.settings\n if @active >= settings.workers and @waiting.length >= settings.maxQueue\n return rejectHttp(req, res, 503, \"QueueFull\")\n complete = (body)\n capture req\n capture res\n submit(req, res, body)\n failed = (status, code)\n capture res\n send(res, failure(status, code))\n reader = new BodyReader(req, res, settings, complete, failed)\n reader.start()\n return null\n\nServer:submit(req, res, body)\n pending = null\n route = @broker.route(req.url)\n if route == null\n pending = dispatch(req, res, body)\n else\n pending = longpoll(req, res, body, route)\n return chain pending\n then(result)\n capture res\n send(res, result)\n return null\n catch(error)\n capture res\n capture req\n context log\n log.err(\"HTTP ${req.method} ${req.url.split('?')[0]} request failed: ${errorDetails(error)}\")\n send(res, failure(500, \"InternalServerError\"))\n return null\n\nServer:longpoll(req, res, body, route)\n if Object/keys(@polls).length >= @definition.settings.redis.maxPendingPolls\n return Promise/resolve(failure(503, \"PollLimit\"))\n authorize = (token, result)\n capture req\n capture res\n capture body\n return dispatch(req, res, body, true, token, result)\n session = new LongpollSession(@broker, route, authorize, body)\n id = crypto/randomUUID()\n @polls[id] = session\n disconnected = ()\n capture session\n session.cancel()\n res.once(\"close\", disconnected)\n return chain session.run()\n finally\n capture res\n capture disconnected\n capture id\n res.removeListener(\"close\", disconnected)\n Reflect/deleteProperty(@polls, id)\n\nServer:brokerMessage(message)\n port = message.port\n pending = null\n try\n switch message.operation\n case \"publish\"\n pending = publish(message.path, message.key, message.data)\n case \"cursor\"\n pending = cursor(message.path, message.key)\n else\n pending = Promise/reject(\"Unknown longpoll operation\")\n catch error\n pending = Promise/reject(error)\n return chain pending\n then(value)\n capture port\n brokerReply(port, {\n ok: true\n value: value\n })\n catch(error)\n capture port\n brokerReply(port, {\n ok: false\n })\n finally\n capture port\n port.close()\n\nServer:dispatch(req, res, body, authorize = false, token = null, pollResult = null)\n settings = @definition.settings\n if @state != \"running\" or (@active >= settings.workers and @waiting.length >= settings.maxQueue)\n return Promise/resolve(failure(503, \"Unavailable\"))\n id = crypto/randomUUID()\n res.langoRequestId = id\n trace(\"[${id}] Queued request ${req.method} ${req.url}\")\n record = {\n id: id\n task: {\n authorize: authorize\n pollResult: pollResult\n body: body\n request: {\n id: id\n method: req.method\n path: req.url\n headers: Object/assign({}, req.headers)\n remoteAddress: req.socket.remoteAddress\n }\n }\n completed: Promise/withResolvers()\n controller: new AbortController()\n started: false\n result: null\n expired: false\n deadline: Date/now() + settings.requestTimeoutMs\n timer: null\n }\n if token != null\n record.task.request.headers.authorization = \"Bearer ${token}\"\n @tasks[id] = record\n resetDeadline(record, settings.requestTimeoutMs)\n @waiting.add(record)\n disconnected = ()\n capture res\n capture record\n if !res.writableEnded\n cancel(record)\n res.once(\"close\", disconnected)\n pump()\n return chain record.completed.promise\n catch(error)\n capture record\n if record.expired\n return failure(504, \"RequestTimeout\")\n return failure(500, \"InternalServerError\")\n finally\n capture res\n capture disconnected\n res.removeListener(\"close\", disconnected)\n\nServer:expire(record)\n record.expired = true\n cancel(record)\n return null\n\nServer:cancel(record)\n if !(record.id in @tasks)\n return null\n if record.started\n record.controller.abort()\n else\n index = @waiting.indexOf(record)\n if index >= 0\n @waiting.splice(index, 1)\n finish(record, null, \"Request cancelled\")\n return null\n\nServer:pump()\n loop while !@destroying and @waiting.length > 0 and @active < @definition.settings.workers\n record = @waiting.shift()\n record.started = true\n @active = @active + 1\n trace(\"[${record.id}] Dispatching to worker\")\n pending = @pool.run(record.task, {\n signal: record.controller.signal\n })\n settle(record, pending)\n return null\n\nServer:settle(record, pending)\n return chain pending\n then(result)\n capture record\n finish(record, result, null)\n return null\n catch(error)\n capture record\n if record.result != null\n context log\n log.err(\"${record.logIdentity} Request event interrupted; preserving prepared result\")\n finish(record, record.result, error)\n return null\n finally\n @active = @active - 1\n pump()\n\nServer:finish(record, result, error)\n clearTimeout(record.timer)\n Reflect/deleteProperty(@tasks, record.id)\n if result != null\n record.completed.resolve(result)\n else\n record.completed.reject(error)\n return null\n\nServer:close()\n if @closing != null\n return @closing\n previous = @state\n @state = \"closing\"\n @shutdownDeadline = Date/now() + @definition.settings.shutdownTimeoutMs\n if previous == \"new\" or previous == \"closed\"\n @state = \"closed\"\n @closing = Promise/resolve(null)\n return @closing\n @ready.reject(\"Server closed during startup\")\n @closing = stop()\n return @closing\n\nServer:stop()\n for @connections as record\n if record.active == 0\n record.socket.destroy()\n for @polls as id: session\n session.cancel()\n drained = new Promise((resolve)\n server = @server\n if server == null or !server.listening\n resolve(null)\n else\n server.close(()\n capture resolve\n resolve(null)\n )\n )\n expired = Promise/withResolvers()\n force = ()\n capture expired\n @destroying = true\n for @waiting as record\n finish(record, null, \"Server closed\")\n @waiting = []\n if @server != null\n @server.closeAllConnections()\n expired.reject(\"Server shutdown timed out\")\n timer = setTimeout(force, @definition.settings.shutdownTimeoutMs)\n return chain Promise/race([drained, expired.promise])\n finally\n capture timer\n clearTimeout(timer)\n return destroyPool()\n finally\n @broker.close()\n @state = \"closed\"\n\nServer:destroyPool()\n @destroying = true\n if @pool == null\n return Promise/resolve(null)\n pool = @pool\n pending = Promise/resolve(null)\n if @definition.settings.database != null and @state == \"closing\" and @active == 0\n remaining = @shutdownDeadline - Date/now()\n if remaining > 0\n tasks = []\n for range(@definition.settings.workers) as index\n tasks.add(pool.run({\n close: true\n }))\n pending = startupDeadline(Promise/all(tasks), remaining)\n return chain pending\n finally\n capture pool\n return pool.destroy()\n\nServer:send(res, result)\n trace(\"HTTP response status=${result.status}\")\n if @state == \"closing\"\n result.headers.connection = \"close\"\n return write(res, result)\n\nfailure(status, code)\n return {\n status: status\n headers: {\n \"content-type\": \"application/json; charset=utf-8\"\n \"cache-control\": \"no-store\"\n }\n body: to_json({\n error: code\n })\n }\n\nwrite(res, result)\n if res.destroyed or res.writableEnded\n return null\n try\n res.langoSession = result.headers[\"x-lango-session\"]\n res.writeHead(result.status, result.headers)\n res.end(result.body)\n catch error\n context log\n log.err(\"[${res.langoRequestId}] Response write failed: ${errorDetails(error)}\")\n res.destroy()\n return null\n\nrejectHttp(req, res, status, code)\n res.setHeader(\"Connection\", \"close\")\n res.once(\"finish\", ()\n capture req\n req.destroy()\n )\n req.resume()\n return write(res, failure(status, code))\n\nmain(args)\n directory = null\n verbose = false\n for args as arg\n if arg == \"--verbose\"\n verbose = true\n else\n if arg.startsWith(\"--\") or directory != null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n directory = arg\n if directory == null\n throw \"Usage: lango-server <application-directory> [--verbose]\"\n if verbose\n process.env.LANGO_VERBOSE = \"1\"\n trace(\"Loading server configuration: ${directory}\")\n server = new Server(directory)\n stop = ()\n capture server\n return chain server.close()\n catch(error)\n context log\n log.err(\"Server shutdown failed\")\n process.exitCode = 1\n process.once(\"SIGTERM\", stop)\n process.once(\"SIGINT\", stop)\n return chain server.start()\n then(address)\n context log\n log.info(\"Listening on ${address.host}:${address.port}\")\n return null\n catch(error)\n capture stop\n process.removeListener(\"SIGTERM\", stop)\n process.removeListener(\"SIGINT\", stop)\n throw error\n\nbrokerReply(port, message)\n try\n port.postMessage(message)\n catch error\n return null\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA;;;;;;;;AAqGA;;;;;;;;;;;;;;;;;AAiYA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;;AAaA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"e20a0daef7a2f4cdd0ac752ad037212141a860885c9f13b335bb36412afcfac5","outputHash":"b49d571fb4a564bc3228ebdf9d3dc47821a5816a3fadaa60a9b77d386084605b","mapHash":"2eba7b1a8cac39ff3fb981f063194c16c628556b9dd41256669dc0751e9db1e1"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server_context.mjs","sources":["server_context.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./route_info\"\n routeInfo(definitions)\n\nexport class ServerContext(definitions = null, refresh = null, rotate = null)\n methods\n publish(path, key, data)\n cursor(path, key)\n routes()\n refreshTokens(tokens)\n rotateClient()\n\nServerContext(definitions = null, refresh = null, rotate = null)\n if definitions == null\n definitions = []\n @routes = routeInfo(definitions)\n @refresh = refresh\n @rotate = rotate\n\nServerContext:rotateClient()\n if @rotate == null\n throw \"Managed client identity is unavailable\"\n rotate = @rotate\n return rotate()\n\nServerContext:refreshTokens(tokens)\n if @refresh == null\n throw \"Token refresh is unavailable\"\n refresh = @refresh\n return refresh(tokens)\n\nServerContext:routes()\n return from_json(to_json(@routes))\n\nServerContext:publish(path, key, data)\n return invoke(\"publish\", path, key, data)\n\nServerContext:cursor(path, key)\n return invoke(\"cursor\", path, key, null)\n\ninvoke(operation, path, key, data)\n channel = new threads/MessageChannel()\n port = channel.port1\n remote = channel.port2\n pending = new Promise((resolve, reject)\n capture port\n port.once(\"message\", (message)\n capture resolve\n capture reject\n if message.ok\n resolve(message.value)\n else\n reject(\"Longpoll operation failed\")\n )\n )\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"Longpoll operation timed out\")\n timer = setTimeout(fail, 4000)\n try\n threads/parentPort/postMessage({\n kind: \"longpoll\"\n operation: operation\n path: path\n key: key\n data: from_json(to_json(data))\n port: remote\n }, [remote])\n catch error\n port.close()\n clearTimeout(timer)\n throw error\n return chain Promise/race([pending, expired.promise])\n finally\n capture port\n capture timer\n clearTimeout(timer)\n port.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"server_context.mjs","sources":["server_context.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global setTimeout\nimport js global clearTimeout\nimport \"./route_info\"\n routeInfo(definitions)\n\nexport class ServerContext(definitions = null, refresh = null, rotate = null)\n methods\n publish(path, key, data)\n cursor(path, key)\n routes()\n refreshTokens(tokens)\n rotateClient()\n\nServerContext(definitions = null, refresh = null, rotate = null)\n if definitions == null\n definitions = []\n @routes = routeInfo(definitions)\n @refresh = refresh\n @rotate = rotate\n\nServerContext:rotateClient()\n if @rotate == null\n throw \"Managed client identity is unavailable\"\n rotate = @rotate\n return rotate()\n\nServerContext:refreshTokens(tokens)\n if @refresh == null\n throw \"Token refresh is unavailable\"\n refresh = @refresh\n return refresh(tokens)\n\nServerContext:routes()\n return from_json(to_json(@routes))\n\nServerContext:publish(path, key, data)\n return invoke(\"publish\", path, key, data)\n\nServerContext:cursor(path, key)\n return invoke(\"cursor\", path, key, null)\n\ninvoke(operation, path, key, data)\n channel = new threads/MessageChannel()\n port = channel.port1\n remote = channel.port2\n pending = new Promise((resolve, reject)\n capture port\n port.once(\"message\", (message)\n capture resolve\n capture reject\n if message.ok\n resolve(message.value)\n else\n reject(\"Longpoll operation failed\")\n )\n )\n expired = Promise/withResolvers()\n fail = ()\n capture expired\n expired.reject(\"Longpoll operation timed out\")\n timer = setTimeout(fail, 4000)\n try\n threads/parentPort/postMessage({\n kind: \"longpoll\"\n operation: operation\n path: path\n key: key\n data: from_json(to_json(data))\n port: remote\n }, [remote])\n catch error\n port.close()\n clearTimeout(timer)\n throw error\n return chain Promise/race([pending, expired.promise])\n finally\n capture port\n capture timer\n clearTimeout(timer)\n port.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"6369c91817d567ad11ffe3db0a83bb0d4ee75f2ae91ac0ad62b3af99f85a70ee","outputHash":"c50f1fccbeb8cf6646823e56238b28fd2be96f3be9cb06636336803cba42f517","mapHash":"4844c9ee96c27a0e796570f49be4e62cd1d4bf333a4ed51bf24cd7640849981b"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sqlite_adapter.mjs","sources":["sqlite_adapter.lango"],"sourcesContent":["import js global Error\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Reflect\nimport js global Object\nimport js global Number\n\nexport class SqliteAdapter(mod, settings)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n begin()\n commit()\n rollback()\n transactionState()\n close()\n\nSqliteAdapter(mod, settings)\n if settings.file != \":memory:\"\n fs/mkdirSync(path/dirname(settings.file), {\n recursive: true\n })\n @connection = Reflect/construct(mod.DatabaseSync, [settings.file])\n @depth = 0\n @state = null\n @parameterStyle = \"named\"\n try\n @connection.exec(\"PRAGMA busy_timeout=${settings.busyTimeoutMs}\")\n @connection.exec(\"PRAGMA foreign_keys=ON\")\n modeQuery = @connection.prepare(\"PRAGMA journal_mode\")\n mode = modeQuery.get()\n if settings.file != \":memory:\" and mode.journal_mode != \"wal\"\n @connection.exec(\"PRAGMA journal_mode=WAL\")\n catch error\n @connection.close()\n throw \"SQLite initialization failed\"\n\nSqliteAdapter:execute(sql, parameters)\n bound = {}\n for parameters as name: value\n if is_bool(value)\n bound[name] = Number(value)\n else\n bound[name] = value\n statement = @connection.prepare(sql)\n statement.setReadBigInts(true)\n columns = statement.columns()\n if columns.length > 0\n records = statement.all(bound)\n for records as row\n for row as name: value\n row[name] = normalizeInteger(value)\n return {\n rows: records\n changes: null\n lastInsertRowid: null\n }\n result = statement.run(bound)\n changes = null\n generated = null\n operation = sql.trim()\n operation = operation.toLowerCase()\n if operation.startsWith(\"insert\") or operation.startsWith(\"update\") or operation.startsWith(\"delete\") or operation.startsWith(\"with\")\n changes = normalizeInteger(result.changes)\n if operation.startsWith(\"insert\") and changes == 1\n generated = normalizeInteger(result.lastInsertRowid)\n return {\n rows: []\n changes: changes\n lastInsertRowid: generated\n }\n\nSqliteAdapter:begin()\n if @depth == 0 and !@connection.isTransaction\n @connection.exec(\"BEGIN\")\n @depth = @depth + 1\n if @state == null\n @state = \"active\"\n return null\n\nSqliteAdapter:commit()\n if @depth == 0\n throw new Error(\"NoActiveTransaction\")\n if @depth > 1\n @depth = @depth - 1\n return null\n if @state == \"rollback_only\"\n rollback()\n throw new Error(\"TransactionRolledBack\")\n @connection.exec(\"COMMIT\")\n @depth = 0\n @state = null\n return null\n\nSqliteAdapter:rollback()\n if @depth > 1\n @depth = @depth - 1\n @state = \"rollback_only\"\n return null\n if @connection.isTransaction\n @connection.exec(\"ROLLBACK\")\n @depth = 0\n @state = null\n return null\n\nSqliteAdapter:transactionState()\n if !@connection.isTransaction\n @depth = 0\n @state = null\n if @connection.isTransaction and @state == null\n return \"active\"\n return @state\n\nSqliteAdapter:close()\n loop while transactionState() != null\n rollback()\n @connection.close()\n return null\n\nnormalizeInteger(value)\n if Object/prototype/toString/call(value) != \"[object BigInt]\"\n return value\n number = Number(value)\n if Number/isSafeInteger(number)\n return number\n return \"${value}\"\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"sqlite_adapter.mjs","sources":["sqlite_adapter.lango"],"sourcesContent":["import js global Error\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js global Reflect\nimport js global Object\nimport js global Number\n\nexport class SqliteAdapter(mod, settings)\n properties\n parameterStyle\n methods\n execute(sql, parameters)\n begin()\n commit()\n rollback()\n transactionState()\n close()\n\nSqliteAdapter(mod, settings)\n if settings.file != \":memory:\"\n fs/mkdirSync(path/dirname(settings.file), {\n recursive: true\n })\n @connection = Reflect/construct(mod.DatabaseSync, [settings.file])\n @depth = 0\n @state = null\n @parameterStyle = \"named\"\n try\n @connection.exec(\"PRAGMA busy_timeout=${settings.busyTimeoutMs}\")\n @connection.exec(\"PRAGMA foreign_keys=ON\")\n modeQuery = @connection.prepare(\"PRAGMA journal_mode\")\n mode = modeQuery.get()\n if settings.file != \":memory:\" and mode.journal_mode != \"wal\"\n @connection.exec(\"PRAGMA journal_mode=WAL\")\n catch error\n @connection.close()\n throw \"SQLite initialization failed\"\n\nSqliteAdapter:execute(sql, parameters)\n bound = {}\n for parameters as name: value\n if is_bool(value)\n bound[name] = Number(value)\n else\n bound[name] = value\n statement = @connection.prepare(sql)\n statement.setReadBigInts(true)\n columns = statement.columns()\n if columns.length > 0\n records = statement.all(bound)\n for records as row\n for row as name: value\n row[name] = normalizeInteger(value)\n return {\n rows: records\n changes: null\n lastInsertRowid: null\n }\n result = statement.run(bound)\n changes = null\n generated = null\n operation = sql.trim()\n operation = operation.toLowerCase()\n if operation.startsWith(\"insert\") or operation.startsWith(\"update\") or operation.startsWith(\"delete\") or operation.startsWith(\"with\")\n changes = normalizeInteger(result.changes)\n if operation.startsWith(\"insert\") and changes == 1\n generated = normalizeInteger(result.lastInsertRowid)\n return {\n rows: []\n changes: changes\n lastInsertRowid: generated\n }\n\nSqliteAdapter:begin()\n if @depth == 0 and !@connection.isTransaction\n @connection.exec(\"BEGIN\")\n @depth = @depth + 1\n if @state == null\n @state = \"active\"\n return null\n\nSqliteAdapter:commit()\n if @depth == 0\n throw new Error(\"NoActiveTransaction\")\n if @depth > 1\n @depth = @depth - 1\n return null\n if @state == \"rollback_only\"\n rollback()\n throw new Error(\"TransactionRolledBack\")\n @connection.exec(\"COMMIT\")\n @depth = 0\n @state = null\n return null\n\nSqliteAdapter:rollback()\n if @depth > 1\n @depth = @depth - 1\n @state = \"rollback_only\"\n return null\n if @connection.isTransaction\n @connection.exec(\"ROLLBACK\")\n @depth = 0\n @state = null\n return null\n\nSqliteAdapter:transactionState()\n if !@connection.isTransaction\n @depth = 0\n @state = null\n if @connection.isTransaction and @state == null\n return \"active\"\n return @state\n\nSqliteAdapter:close()\n loop while transactionState() != null\n rollback()\n @connection.close()\n return null\n\nnormalizeInteger(value)\n if Object/prototype/toString/call(value) != \"[object BigInt]\"\n return value\n number = Number(value)\n if Number/isSafeInteger(number)\n return number\n return \"${value}\"\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiHA;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"ac20d44a8157ea5bd2d5228cc472c6f5fc227296001e65b95a5fecb32624102c","outputHash":"b07ae05a0e735953161ff738dfbb38f662d8f65f01dd085ab5dac42651d80f1d","mapHash":"8387f3b46bc8578feb05081bc9a346a7663531c89546c3a303fb4d9a0ad702c4"}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\nimport js global decodeURIComponent\nimport js global String\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n fallback = spec.fallback\n if fallback != null and (!is_string(fallback) or fallback == \"\" or fallback.startsWith(\".\") or fallback.includes(\"/\") or fallback.includes(\"\\\\\"))\n throw \"Static fallback must be a file name\"\n runtime = spec.runtime\n if runtime == null or runtime == \"false\"\n runtime = false\n if runtime == \"true\"\n runtime = true\n if !is_bool(runtime)\n throw \"Static runtime must be boolean\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n fallback: fallback\n runtime: runtime\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n if settings.fallback != null and !fs/statSync(path/join(settings.directory, settings.fallback)).isFile()\n throw \"Static fallback must be a file\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n @runtime = files/default(settings.directory, {\n index: false\n dotfiles: \"allow\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n local = req.url.split(\"?\")[0]\n decoded = null\n try\n decoded = decodeURIComponent(local)\n catch error\n failed(400, \"InvalidPath\")\n return null\n if decoded.includes(\"\\\\\") or decoded.includes(String/fromCharCode(0))\n failed(400, \"InvalidPath\")\n return null\n segments = decoded.split(\"/\")\n runtime = false\n for segments as index: segment\n if segment.startsWith(\".\")\n if index == 1 and segment == \".lango\" and @settings.runtime\n runtime = true\n else\n failed(403, \"Forbidden\")\n return null\n done = (error)\n capture req\n capture res\n capture failed\n capture decoded\n failure(req, res, failed, error, decoded)\n serve = @serve\n if runtime\n serve = @runtime\n trace(\"Static ${req.method} ${pathname}: directory=${@settings.directory}; index=${@settings.index}; runtime=${runtime}\")\n serve(req, res, done)\n return null\n\nStaticFiles:failure(req, res, failed, error, pathname = null)\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n if status == 404 and pathname != null and @settings.fallback != null and !pathname.startsWith(\"/.lango\") and path/posix/extname(pathname) == \"\" and acceptsHTML(req.headers.accept)\n req.url = \"/${@settings.fallback}\"\n done = (error)\n capture req\n capture res\n capture failed\n failure(req, res, failed, error)\n serve = @serve\n serve(req, res, done)\n return null\n failed(status, code)\n return null\n\nacceptsHTML(value)\n if !is_string(value)\n return false\n zero = new RegExp(\"^q\\\\s*=\\\\s*0(?:\\\\.0*)?$\", \"i\")\n for value.split(\",\") as range\n parts = range.split(\";\")\n media = parts[0]\n type = media.trim().toLowerCase()\n if type == \"text/html\" or type == \"application/xhtml+xml\"\n allowed = true\n for parts.slice(1) as parameter\n if zero.test(parameter.trim())\n allowed = false\n if allowed\n return true\n return false\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2IA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import \"./trace\"\n trace(message)\nimport js \"node:fs\" as fs\nimport js \"node:path\" as path\nimport js \"serve-static\" as files\nimport js global RegExp\nimport js global decodeURIComponent\nimport js global String\n\nexport staticOptions(root, spec)\nexport class StaticFiles(settings)\n methods\n receive(req, res, failed)\n\nstaticOptions(root, spec)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"static must be a map\"\n allowed = [\"path\", \"directory\", \"index\", \"fallback\", \"runtime\"]\n for spec as key: value\n if !allowed.includes(key)\n throw \"Unknown static option: ${key}\"\n mount = spec.path\n if mount == null\n mount = \"/\"\n pattern = new RegExp(\"^/(?:[A-Za-z0-9_-]+/)*[A-Za-z0-9_-]*$\")\n if !is_string(mount) or !pattern.test(mount)\n throw \"Static path must be an absolute URL prefix\"\n if mount != \"/\" and mount.endsWith(\"/\")\n mount = mount.slice(0, -1)\n if !is_string(spec.directory) or spec.directory.trim() == \"\"\n throw \"Static directory is required\"\n index = spec.index\n if index == null\n index = \"index.html\"\n if !is_string(index) or index == \"\" or index.startsWith(\".\") or index.includes(\"/\") or index.includes(\"\\\\\")\n throw \"Static index must be a file name\"\n fallback = spec.fallback\n if fallback != null and (!is_string(fallback) or fallback == \"\" or fallback.startsWith(\".\") or fallback.includes(\"/\") or fallback.includes(\"\\\\\"))\n throw \"Static fallback must be a file name\"\n runtime = spec.runtime\n if runtime == null or runtime == \"false\"\n runtime = false\n if runtime == \"true\"\n runtime = true\n if !is_bool(runtime)\n throw \"Static runtime must be boolean\"\n return {\n path: mount\n directory: path/resolve(root, spec.directory)\n index: index\n fallback: fallback\n runtime: runtime\n }\n\nStaticFiles(settings)\n @settings = settings\n if !fs/statSync(settings.directory).isDirectory()\n throw \"Static directory must be a directory\"\n if settings.fallback != null and !fs/statSync(path/join(settings.directory, settings.fallback)).isFile()\n throw \"Static fallback must be a file\"\n @serve = files/default(settings.directory, {\n index: settings.index\n dotfiles: \"deny\"\n fallthrough: false\n redirect: false\n })\n @runtime = files/default(settings.directory, {\n index: false\n dotfiles: \"allow\"\n fallthrough: false\n redirect: false\n })\n\nStaticFiles:receive(req, res, failed)\n mount = @settings.path\n url = req.url\n pathname = url.split(\"?\")[0]\n if mount != \"/\" and pathname != mount and !pathname.startsWith(\"${mount}/\")\n failed(404, \"NotFound\")\n return null\n if mount != \"/\"\n req.url = url.slice(mount.length)\n if req.url == \"\" or req.url.startsWith(\"?\")\n req.url = \"/${req.url}\"\n local = req.url.split(\"?\")[0]\n decoded = null\n try\n decoded = decodeURIComponent(local)\n catch error\n failed(400, \"InvalidPath\")\n return null\n if decoded.includes(\"\\\\\") or decoded.includes(String/fromCharCode(0))\n failed(400, \"InvalidPath\")\n return null\n segments = decoded.split(\"/\")\n runtime = false\n for segments as index: segment\n if segment.startsWith(\".\")\n if index == 1 and segment == \".lango\" and @settings.runtime\n runtime = true\n else\n failed(403, \"Forbidden\")\n return null\n done = (error)\n capture req\n capture res\n capture failed\n capture decoded\n failure(req, res, failed, error, decoded)\n serve = @serve\n if runtime\n serve = @runtime\n trace(\"Static ${req.method} ${pathname}: directory=${@settings.directory}; index=${@settings.index}; runtime=${runtime}\")\n serve(req, res, done)\n return null\n\nStaticFiles:failure(req, res, failed, error, pathname = null)\n if res.headersSent\n res.destroy()\n return null\n status = 404\n code = \"NotFound\"\n if error != null\n switch error.status\n case 400\n status = 400\n code = \"InvalidPath\"\n case 403\n status = 403\n code = \"Forbidden\"\n case 416\n status = 416\n code = \"RangeNotSatisfiable\"\n case 404\n status = 404\n else\n status = 500\n code = \"InternalServerError\"\n if status == 404 and pathname != null and @settings.fallback != null and !pathname.startsWith(\"/.lango\") and path/posix/extname(pathname) == \"\" and acceptsHTML(req.headers.accept)\n req.url = \"/${@settings.fallback}\"\n done = (error)\n capture req\n capture res\n capture failed\n failure(req, res, failed, error)\n serve = @serve\n serve(req, res, done)\n return null\n failed(status, code)\n return null\n\nacceptsHTML(value)\n if !is_string(value)\n return false\n zero = new RegExp(\"^q\\\\s*=\\\\s*0(?:\\\\.0*)?$\", \"i\")\n for value.split(\",\") as range\n parts = range.split(\";\")\n media = parts[0]\n type = media.trim().toLowerCase()\n if type == \"text/html\" or type == \"application/xhtml+xml\"\n allowed = true\n for parts.slice(1) as parameter\n if zero.test(parameter.trim())\n allowed = false\n if allowed\n return true\n return false\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2IA;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"5a2f9c8067185c4228bc613444196d9ff6758307463b44f729d3ca64a9c0508a","outputHash":"73406289acc908165b0396946d6146fc528ed41ba14de3c5d74dd7c9c617085c","mapHash":"646b8c409be99a80565319bd944dfa49f42fcfef09eb2647c857052d3b71d254"}}
|
package/dist/token.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token.mjs","sources":["token.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js global Object\n\nexport class Token(claims, readonly = false)\n properties\n clientId?\n auth?\n policies?\n expiresAt?\n methods\n addPolicy(permission)\n hasPolicy(permission)\n clearPolicies()\n AddAuth(permission)\n clearAuth()\n hasAuth(permission)\n get(name)\n set(name, value)\n snapshot()\n renew()\n renewalRequested()\n\nToken(claims, readonly = false)\n @claims = from_json(to_json(claims))\n @readonly = readonly\n @renew = false\n @clientId = claims.clientId\n @auth = claims.auth\n @expiresAt = claims.exp\n Object/freeze(@this)\n\nToken:clientId?\n return @clientId\n\nToken:auth?\n return @auth\n\nToken:expiresAt?\n return @expiresAt\n\nToken:addPolicy(permission)\n writable()\n if !is_string(permission) or permission.trim() == \"\" or permission.includes(\",\")\n throw \"Permission must be a nonempty name without commas\"\n permission = permission.trim()\n if !hasPolicy(permission)\n if @auth == \"\"\n @auth = permission\n else\n @auth = \"${@auth}, ${permission}\"\n return @this\n\nToken:clearPolicies()\n writable()\n @auth = \"\"\n return @this\n\nToken:hasPolicy(permission)\n for @auth.split(\",\") as name\n if name.trim() == permission\n return true\n return false\n\nToken:policies?\n result = []\n for @auth.split(\",\") as name\n value = name.trim()\n if value != \"\"\n result.add(value)\n return result\n\nToken:AddAuth(permission)\n return addPolicy(permission)\n\nToken:hasAuth(permission)\n return hasPolicy(permission)\n\nToken:clearAuth()\n return clearPolicies()\n\nToken:get(name)\n if !Object/hasOwn(@claims, name)\n return null\n return from_json(to_json(@claims[name]))\n\nToken:set(name, value)\n writable()\n if contains([\"clientProof\", \"clientId\", \"auth\", \"iat\", \"exp\", \"iss\", \"aud\", \"validatedAt\", \"nbf\", \"__proto__\", \"constructor\", \"prototype\"], name)\n throw \"Reserved token field: ${name}\"\n @claims[name] = from_json(to_json(value))\n return @this\n\nToken:snapshot()\n claims = from_json(to_json(@claims))\n if @clientId != claims.clientId or @expiresAt != claims.exp or !is_string(@auth)\n throw \"Token identity and expiry cannot be changed\"\n claims.auth = @auth\n return claims\n\nToken:renew()\n writable()\n @renew = true\n return @this\n\nToken:renewalRequested()\n return @renew\n\nToken:writable()\n if @readonly\n throw \"Token is read-only during this event\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"token.mjs","sources":["token.lango"],"sourcesContent":["import \"./options\"\n contains(items, value)\nimport js global Object\n\nexport class Token(claims, readonly = false)\n properties\n clientId?\n auth?\n policies?\n expiresAt?\n methods\n addPolicy(permission)\n hasPolicy(permission)\n clearPolicies()\n AddAuth(permission)\n clearAuth()\n hasAuth(permission)\n get(name)\n set(name, value)\n snapshot()\n renew()\n renewalRequested()\n\nToken(claims, readonly = false)\n @claims = from_json(to_json(claims))\n @readonly = readonly\n @renew = false\n @clientId = claims.clientId\n @auth = claims.auth\n @expiresAt = claims.exp\n Object/freeze(@this)\n\nToken:clientId?\n return @clientId\n\nToken:auth?\n return @auth\n\nToken:expiresAt?\n return @expiresAt\n\nToken:addPolicy(permission)\n writable()\n if !is_string(permission) or permission.trim() == \"\" or permission.includes(\",\")\n throw \"Permission must be a nonempty name without commas\"\n permission = permission.trim()\n if !hasPolicy(permission)\n if @auth == \"\"\n @auth = permission\n else\n @auth = \"${@auth}, ${permission}\"\n return @this\n\nToken:clearPolicies()\n writable()\n @auth = \"\"\n return @this\n\nToken:hasPolicy(permission)\n for @auth.split(\",\") as name\n if name.trim() == permission\n return true\n return false\n\nToken:policies?\n result = []\n for @auth.split(\",\") as name\n value = name.trim()\n if value != \"\"\n result.add(value)\n return result\n\nToken:AddAuth(permission)\n return addPolicy(permission)\n\nToken:hasAuth(permission)\n return hasPolicy(permission)\n\nToken:clearAuth()\n return clearPolicies()\n\nToken:get(name)\n if !Object/hasOwn(@claims, name)\n return null\n return from_json(to_json(@claims[name]))\n\nToken:set(name, value)\n writable()\n if contains([\"clientProof\", \"clientId\", \"auth\", \"iat\", \"exp\", \"iss\", \"aud\", \"validatedAt\", \"nbf\", \"__proto__\", \"constructor\", \"prototype\"], name)\n throw \"Reserved token field: ${name}\"\n @claims[name] = from_json(to_json(value))\n return @this\n\nToken:snapshot()\n claims = from_json(to_json(@claims))\n if @clientId != claims.clientId or @expiresAt != claims.exp or !is_string(@auth)\n throw \"Token identity and expiry cannot be changed\"\n claims.auth = @auth\n return claims\n\nToken:renew()\n writable()\n @renew = true\n return @this\n\nToken:renewalRequested()\n return @renew\n\nToken:writable()\n if @readonly\n throw \"Token is read-only during this event\"\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"be158421d032f826f0b84b92caa6898c85c76dfb429a6568da757fd17b8966fd","outputHash":"6e81066ea78b36df62d03ad445fb6c53f895747be11eb9033b56a92a68ea1c6c","mapHash":"e749dfb14650bfa8b5f324370c99afd46f50ac1bf99e8b93f2032a205e5c43d3"}}
|
package/dist/tokens.mjs
CHANGED
|
@@ -59,7 +59,7 @@ export class Tokens {
|
|
|
59
59
|
if (__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Object"]).hasOwn(keys, __normalize(head.kid)))))) {
|
|
60
60
|
throw "InvalidToken";
|
|
61
61
|
}
|
|
62
|
-
let claims = __normalize(jwt.default.verify(encoded, __normalize(keys[__normalize(head.kid)]), { algorithms: ["HS256"], issuer: __normalize(settings.issuer), audience: __normalize(settings.audience) }));
|
|
62
|
+
let claims = __normalize(jwt.default.verify(encoded, __normalize(keys[__normalize(head.kid)]), { algorithms: ["HS256"], issuer: __normalize(settings.issuer), audience: __normalize(settings.audience), ignoreExpiration: true }));
|
|
63
63
|
if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(claims))) || __requireBoolean(!__requireBoolean(__isString(__normalize(claims.clientId))))) || __requireBoolean(__normalize(claims.clientId) === "")) || __requireBoolean(!__requireBoolean(__isString(__normalize(claims.auth)))))) {
|
|
64
64
|
throw "InvalidToken";
|
|
65
65
|
}
|
|
@@ -69,6 +69,9 @@ export class Tokens {
|
|
|
69
69
|
if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(__normalize(claims.validatedAt))))) || __requireBoolean(__normalize(claims.validatedAt) < 0)) || __requireBoolean(__normalize(claims.validatedAt) > __normalize(__hostGlobal(["Date"]).now())))) {
|
|
70
70
|
throw "InvalidToken";
|
|
71
71
|
}
|
|
72
|
+
if (__requireBoolean(__finite(__normalize(claims.exp) * 1000) <= __normalize(__hostGlobal(["Date"]).now()))) {
|
|
73
|
+
throw "TokenExpired";
|
|
74
|
+
}
|
|
72
75
|
return claims;
|
|
73
76
|
return null;
|
|
74
77
|
}
|
package/dist/tokens.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\nimport js global RegExp\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create(clientId = null)\n renew(claims)\n\nTokens(settings)\n @settings = settings\n\nTokens:create(clientId = null)\n if clientId == null\n clientId = crypto/randomUUID()\n else\n pattern = new RegExp(\"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$\")\n if !is_string(clientId) or !pattern.test(clientId)\n throw \"Invalid server clientId\"\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId: clientId\n auth: \"\"\n iat: now\n exp: now + settings.ttlSeconds\n iss: settings.issuer\n aud: settings.audience\n validatedAt: Date/now()\n }\n\nTokens:read(header)\n settings = @settings\n if !is_string(header) or header.length > 16384 or header.slice(0, 7).toLowerCase() != \"bearer \" or header.length == 7\n throw \"InvalidToken\"\n encoded = header.slice(7)\n decoded = jwt/default/decode(encoded, {\n complete: true\n })\n if !is_object(decoded) or !is_object(decoded.header)\n throw \"InvalidToken\"\n head = decoded.header\n if head.alg != \"HS256\" or head.typ != \"JWT\" or !is_string(head.kid) or head.crit != null or head.b64 != null\n throw \"InvalidToken\"\n keys = settings.keys\n if !Object/hasOwn(keys, head.kid)\n throw \"InvalidToken\"\n claims = jwt/default/verify(encoded, keys[head.kid], {\n algorithms: [\"HS256\"]\n issuer: settings.issuer\n audience: settings.audience\n })\n if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == \"\" or !is_string(claims.auth)\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt < 0 or claims.validatedAt > Date/now()\n throw \"InvalidToken\"\n return claims\n\nTokens:renew(claims)\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n updated = from_json(to_json(claims))\n now = Math/floor(Date/now() / 1000)\n updated.iat = now\n updated.exp = now + @settings.ttlSeconds\n return updated\n\nTokens:sign(claims)\n settings = @settings\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n keys = settings.keys\n return jwt/default/sign(claims, keys[settings.activeKeyId], {\n algorithm: \"HS256\"\n header: {\n typ: \"JWT\"\n kid: settings.activeKeyId\n }\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAQA
|
|
1
|
+
{"version":3,"file":"tokens.mjs","sources":["tokens.lango"],"sourcesContent":["import js \"jsonwebtoken\" as jwt\nimport js \"node:crypto\" as crypto\nimport js global Object\nimport js global Date\nimport js global Math\nimport js global Number\nimport js global RegExp\n\nexport class Tokens(settings)\n methods\n read(header)\n sign(claims)\n create(clientId = null)\n renew(claims)\n\nTokens(settings)\n @settings = settings\n\nTokens:create(clientId = null)\n if clientId == null\n clientId = crypto/randomUUID()\n else\n pattern = new RegExp(\"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$\")\n if !is_string(clientId) or !pattern.test(clientId)\n throw \"Invalid server clientId\"\n settings = @settings\n now = Math/floor(Date/now() / 1000)\n return {\n clientId: clientId\n auth: \"\"\n iat: now\n exp: now + settings.ttlSeconds\n iss: settings.issuer\n aud: settings.audience\n validatedAt: Date/now()\n }\n\nTokens:read(header)\n settings = @settings\n if !is_string(header) or header.length > 16384 or header.slice(0, 7).toLowerCase() != \"bearer \" or header.length == 7\n throw \"InvalidToken\"\n encoded = header.slice(7)\n decoded = jwt/default/decode(encoded, {\n complete: true\n })\n if !is_object(decoded) or !is_object(decoded.header)\n throw \"InvalidToken\"\n head = decoded.header\n if head.alg != \"HS256\" or head.typ != \"JWT\" or !is_string(head.kid) or head.crit != null or head.b64 != null\n throw \"InvalidToken\"\n keys = settings.keys\n if !Object/hasOwn(keys, head.kid)\n throw \"InvalidToken\"\n # Classify expiration only after verifying the signature, issuer and audience.\n claims = jwt/default/verify(encoded, keys[head.kid], {\n algorithms: [\"HS256\"]\n issuer: settings.issuer\n audience: settings.audience\n ignoreExpiration: true\n })\n if !is_object(claims) or !is_string(claims.clientId) or claims.clientId == \"\" or !is_string(claims.auth)\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.iat) or !Number/isSafeInteger(claims.exp) or claims.exp <= claims.iat or claims.exp - claims.iat > settings.ttlSeconds or claims.iat * 1000 > Date/now()\n throw \"InvalidToken\"\n if !Number/isSafeInteger(claims.validatedAt) or claims.validatedAt < 0 or claims.validatedAt > Date/now()\n throw \"InvalidToken\"\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n return claims\n\nTokens:renew(claims)\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n updated = from_json(to_json(claims))\n now = Math/floor(Date/now() / 1000)\n updated.iat = now\n updated.exp = now + @settings.ttlSeconds\n return updated\n\nTokens:sign(claims)\n settings = @settings\n if claims.exp * 1000 <= Date/now()\n throw \"TokenExpired\"\n keys = settings.keys\n return jwt/default/sign(claims, keys[settings.activeKeyId], {\n algorithm: \"HS256\"\n header: {\n typ: \"JWT\"\n kid: settings.activeKeyId\n }\n })\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"ba0c522f4b07dd352d54f30fd69902bf33078058e7cb5707849a0a81361f99ad","outputHash":"8b74513f80160f57542d3db0e28ecf960dc6c0cb9f7ff540c9aec2f608a0f55f","mapHash":"88d9e9a849da613c3ac12082b23a7f67a104f3eac6107273c6624c066c1e6666"}}
|
package/dist/trace.mjs
CHANGED
|
@@ -23,7 +23,7 @@ export function trace(message) {
|
|
|
23
23
|
}
|
|
24
24
|
}
|
|
25
25
|
|
|
26
|
-
export function responseLog(id, method, path, status) {
|
|
26
|
+
export function responseLog(id, method, path, status, session = null) {
|
|
27
27
|
const __contextScope = [];
|
|
28
28
|
try {
|
|
29
29
|
__requireArity(arguments.length, [0, 1, 2, 3], "responseLog");
|
|
@@ -31,10 +31,15 @@ export function responseLog(id, method, path, status) {
|
|
|
31
31
|
method = __boundary(method);
|
|
32
32
|
path = __boundary(path);
|
|
33
33
|
status = __boundary(status);
|
|
34
|
+
session = __boundary(session);
|
|
34
35
|
let message = `HTTP ${method} ${path} completed status=${status}`;
|
|
35
36
|
if (__requireBoolean(id !== null)) {
|
|
36
37
|
message = `[${id}] ${message}`;
|
|
37
38
|
}
|
|
39
|
+
if (__requireBoolean(__requireBoolean(status === 401) && __requireBoolean(session === "expired"))) {
|
|
40
|
+
__normalize(__contextGet("log").info(`${message} reason=SessionExpired`));
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
38
43
|
if (__requireBoolean(status >= 500)) {
|
|
39
44
|
__normalize(__contextGet("log").err(message));
|
|
40
45
|
} else {
|
package/dist/trace.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trace.mjs","sources":["trace.lango"],"sourcesContent":["export trace(message)\nexport responseLog(id, method, path, status)\n\ntrace(message)\n context log\n if log.verbose? == true\n log.debug(message)\n return null\n\n\nresponseLog(id, method, path, status)\n context log\n message = \"HTTP ${method} ${path} completed status=${status}\"\n if id != null\n message = \"[${id}] ${message}\"\n if status >= 500\n log.err(message)\n else\n if status >= 400\n log.warn(message)\n else\n trace(message)\n return null\n"],"names":[],"mappings":";;;;;;;;;;AAGA;;;;;;;;;;;;;;;AAOA
|
|
1
|
+
{"version":3,"file":"trace.mjs","sources":["trace.lango"],"sourcesContent":["export trace(message)\nexport responseLog(id, method, path, status, session = null)\n\ntrace(message)\n context log\n if log.verbose? == true\n log.debug(message)\n return null\n\n\nresponseLog(id, method, path, status, session = null)\n context log\n message = \"HTTP ${method} ${path} completed status=${status}\"\n if id != null\n message = \"[${id}] ${message}\"\n if status == 401 and session == \"expired\"\n log.info(\"${message} reason=SessionExpired\")\n return null\n if status >= 500\n log.err(message)\n else\n if status >= 400\n log.warn(message)\n else\n trace(message)\n return null\n"],"names":[],"mappings":";;;;;;;;;;AAGA;;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;","x_lango_build":{"fingerprint":"c614e51be712e1094596d00440a1004aed9b06f192e2853c8f8782cfb9f75585","outputHash":"031defb50ef64d500585c234c2cf8b46b5d458c7d37d7042d17bb40051848527","mapHash":"0ccb668e4e12429874c944fe49c50ab42480302360a87300c300f23af9d2bf88"}}
|
package/dist/worker.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker.mjs","sources":["worker.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global process\nimport js global setTimeout\nimport \"./runtime\"\n class Runtime\n\nexport global execute\n\nglobal runtime = new Runtime(threads.workerData)\nglobal execute = initialize()\n\ninitialize()\n global runtime\n process.setSourceMapsEnabled(true)\n return chain runtime.preload()\n then(ignored)\n capture threads\n threads/parentPort/postMessage({\n kind: \"ready\"\n threadId: threads.threadId\n })\n registerCleanup()\n return workerHandler()\n\nrun(task)\n global runtime\n if task.close == true\n runtime.close()\n pending = new Promise((resolve)\n setTimeout(resolve, 10)\n )\n return pending\n return runtime.handle(task)\n\nworkerHandler()\n return run\n\nregisterCleanup()\n process.once(\"exit\", ()\n global runtime\n runtime.close()\n )\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;AASA;;AACA;AAEA;;;;;;;;;;;;AAaA;;;;;;;;;;;;;;;;;AAUA;;;;;AAGA;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"worker.mjs","sources":["worker.lango"],"sourcesContent":["import js \"node:worker_threads\" as threads\nimport js global Promise\nimport js global process\nimport js global setTimeout\nimport \"./runtime\"\n class Runtime\n\nexport global execute\n\nglobal runtime = new Runtime(threads.workerData)\nglobal execute = initialize()\n\ninitialize()\n global runtime\n process.setSourceMapsEnabled(true)\n return chain runtime.preload()\n then(ignored)\n capture threads\n threads/parentPort/postMessage({\n kind: \"ready\"\n threadId: threads.threadId\n })\n registerCleanup()\n return workerHandler()\n\nrun(task)\n global runtime\n if task.close == true\n runtime.close()\n pending = new Promise((resolve)\n setTimeout(resolve, 10)\n )\n return pending\n return runtime.handle(task)\n\nworkerHandler()\n return run\n\nregisterCleanup()\n process.once(\"exit\", ()\n global runtime\n runtime.close()\n )\n return null\n"],"names":[],"mappings":";;;;;;;;;;;;;AASA;;AACA;AAEA;;;;;;;;;;;;AAaA;;;;;;;;;;;;;;;;;AAUA;;;;;AAGA;;;;;;;;;","x_lango_build":{"fingerprint":"af736cdf033104c1d8d4bd2d1aadfd70bf6f7bcce2f79fcdc2dad929435988f7","outputHash":"0e2765f348052ac87d7acd9681e3e254163c741de65202de820fa4facd8d97f6","mapHash":"7af5b795e336e3807c1973586c739df195bc66b2a9dbc8e3c0a9705cf4aad2aa"}}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# Browser startup and session expiration
|
|
2
|
+
|
|
3
|
+
Managed browser identity requires persistent SQL storage, a required HTTPS
|
|
4
|
+
origin and the existing `client` setting. A short-lived access JWT and the
|
|
5
|
+
server-owned HttpOnly cookie have different lifetimes. An expired access JWT
|
|
6
|
+
never authorizes a request or becomes valid again.
|
|
7
|
+
|
|
8
|
+
## Bootstrap middleware
|
|
9
|
+
|
|
10
|
+
Mark a startup middleware explicitly:
|
|
11
|
+
|
|
12
|
+
```lango
|
|
13
|
+
builder.addMiddleware("application-start", {
|
|
14
|
+
module: "@app/startup"
|
|
15
|
+
handler: "start"
|
|
16
|
+
bootstrap: true
|
|
17
|
+
})
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
XML middleware declarations accept `bootstrap="true"`. A bootstrap middleware
|
|
21
|
+
can serve only exact anonymous endpoints without password freshness requirements.
|
|
22
|
+
Server enforces this before listening. It does not recognize UI names or assume
|
|
23
|
+
a particular URL. Lango UI's `configure()` registers this flag automatically;
|
|
24
|
+
handwritten `ui-start` declarations must include it.
|
|
25
|
+
|
|
26
|
+
The browser framework sends its cached opaque token as `X-Lango-Startup-Token`
|
|
27
|
+
on bootstrap, instead of using it as Authorization. Application client code does
|
|
28
|
+
not inspect JWT claims, manage cookies or choose a recovery mode.
|
|
29
|
+
|
|
30
|
+
* With managed identity, Server ignores this optional hint and uses the live
|
|
31
|
+
cookie record. A valid cookie produces clean claims for the same clientId and
|
|
32
|
+
forces Validate, even if a previous JWT was recently validated. Old permissions,
|
|
33
|
+
user identity, form claims and password timestamps are not copied from the hint.
|
|
34
|
+
* Without managed identity, Server verifies the hint as an ordinary JWT. This
|
|
35
|
+
preserves existing JWT-only deployments and local HTTP development. Expired,
|
|
36
|
+
malformed and incorrectly signed hints are rejected.
|
|
37
|
+
* A supplied Authorization header is always verified, including on bootstrap.
|
|
38
|
+
Cookie binding must match. An expired Authorization token is not replaced by a
|
|
39
|
+
cookie fallback; updated clients avoid sending it at startup.
|
|
40
|
+
* A missing cookie creates a new anonymous client. Unknown, expired, malformed
|
|
41
|
+
and mismatched cookies are rejected. A JWT hint cannot recover somebody else's
|
|
42
|
+
clientId or replace a rejected cookie. Hints on non-bootstrap endpoints are
|
|
43
|
+
rejected with `400 InvalidStartupRequest`.
|
|
44
|
+
|
|
45
|
+
Cookie continuity does not automatically restore application login. Validate is
|
|
46
|
+
still readonly; the application's existing guard can restore a remembered grant
|
|
47
|
+
from its authoritative database records before invoking the Start handler.
|
|
48
|
+
Revocation, account bans and selected-client logout must be checked there.
|
|
49
|
+
`authenticatedAt` must remain the original password-authentication timestamp;
|
|
50
|
+
token issuance, cookie continuity and renewal do not refresh it. UI creates a new
|
|
51
|
+
sessionId for each successful startup.
|
|
52
|
+
|
|
53
|
+
## Expiration during use
|
|
54
|
+
|
|
55
|
+
After signature, issuer, audience and claim-shape checks, an expired token yields
|
|
56
|
+
`401` with `{ "error": "SessionExpired" }` and the reserved response header
|
|
57
|
+
`X-Lango-Session: expired`. Invalid signatures and other credential failures do
|
|
58
|
+
not receive this marker. Expiration detected while completing a request uses the
|
|
59
|
+
same result. Never infer that a failed response proves no side effect committed.
|
|
60
|
+
|
|
61
|
+
Lango Client freezes forms sharing that exact token, cancels their activities
|
|
62
|
+
and queued sends, and keeps their existing values visible. Unrelated tokens keep
|
|
63
|
+
working. Late responses and Ping renewals cannot revive frozen forms. The user
|
|
64
|
+
gets an explicit Reload page action; the original business request is not
|
|
65
|
+
automatically repeated. Reload starts a new bootstrap; it does not replay the old
|
|
66
|
+
form submission or promise to preserve the draft after navigation.
|
|
67
|
+
Fetch-level HTTP redirects are rejected, including same-origin redirects: they
|
|
68
|
+
cannot forward the startup hint or implicitly replay a POST. UI navigation uses
|
|
69
|
+
the explicit server commands instead.
|
|
70
|
+
|
|
71
|
+
The client removes only stored values equal to the expired token. A newer token
|
|
72
|
+
from another form or authentication generation is retained. Ping results can also
|
|
73
|
+
carry `reason: "SessionExpired"` for an individual expired token.
|
|
74
|
+
|
|
75
|
+
Expected expiration produces one informational HTTP completion record containing
|
|
76
|
+
the request ID and `reason=SessionExpired`. Signature, cookie, origin, validation
|
|
77
|
+
and authorization failures retain their warning/error handling. JWTs and cookie
|
|
78
|
+
secrets are not logged.
|
|
79
|
+
|
|
80
|
+
## Replicas and deployment
|
|
81
|
+
|
|
82
|
+
All replicas share the existing `_lango_clients` SQL table, application grant
|
|
83
|
+
tables, and consistent JWT signing/verification configuration. Every bootstrap
|
|
84
|
+
reads the live cookie record and current application authorization. No additional
|
|
85
|
+
process-local session authority, sticky routing, Redis, or replica messaging is
|
|
86
|
+
introduced. The same cookie can bootstrap on another replica; revocation and
|
|
87
|
+
cookie rotation are observed through the shared database.
|
|
88
|
+
|
|
89
|
+
Deploy the matching Server, UI and browser Client versions together, publishing
|
|
90
|
+
Server first, then UI and Client. Refresh copied browser assets and update any
|
|
91
|
+
handwritten startup middleware declarations. Keep the HTTPS origin and persistent
|
|
92
|
+
client configuration enabled behind the TLS ingress.
|
|
93
|
+
|
|
94
|
+
HTTP/JWT-only development still rejects expired tokens and requires an explicit
|
|
95
|
+
reload. Without a valid persistent cookie it cannot securely recover the previous
|
|
96
|
+
anonymous clientId or remembered login from an expired JWT or a localStorage ID.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lango-project/lango-server",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
4
4
|
"description": "A small JSON HTTP server for Lango applications.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -30,12 +30,15 @@
|
|
|
30
30
|
"examples/security/README.md"
|
|
31
31
|
],
|
|
32
32
|
"scripts": {
|
|
33
|
-
"
|
|
34
|
-
"
|
|
33
|
+
"clean": "lango run tools/clean.lango",
|
|
34
|
+
"build:clean": "npm run clean && npm run build",
|
|
35
|
+
"build": "lango build --project",
|
|
36
|
+
"test": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango build src/test/execution_handlers.lango --out .test-output/execution_handlers.mjs && lango test src/test/executor.lango --build-dir .test-output/executor && lango test src/test/jobs.lango --build-dir .test-output/jobs && lango test src/test/database.lango --build-dir .test-output/database && lango test src/test/unit.lango --build-dir .test-output/unit && lango test src/test/route_parameters.lango --build-dir .test-output/route-parameters && lango test src/test/http.lango --build-dir .test-output/http && lango test src/test/middleware.lango --build-dir .test-output/middleware && lango test src/test/static.lango --build-dir .test-output/static && lango test src/test/standalone.lango --build-dir .test-output/standalone && npm run test:security && npm run test:bootstrap",
|
|
35
37
|
"start": "node dist/cli/server.mjs examples/application",
|
|
36
|
-
"prepack": "npm run build",
|
|
38
|
+
"prepack": "npm run build:clean",
|
|
37
39
|
"test:postgres": "lango build src/test/sql_handlers.lango --out .test-output/sql_handlers.mjs && lango test src/test/database.lango --build-dir .test-output/database-postgres",
|
|
38
40
|
"test:longpoll": "lango build src/test/longpoll_handlers.lango --out .test-output/longpoll_handlers.mjs && lango test src/test/longpoll.lango --build-dir .test-output/longpoll && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/standalone.lango --build-dir .test-output/standalone-longpoll",
|
|
41
|
+
"test:bootstrap": "lango build src/test/bootstrap_handlers.lango --out .test-output/bootstrap_handlers.mjs && lango test src/test/bootstrap.lango --build-dir .test-output/bootstrap",
|
|
39
42
|
"test:middleware": "lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango build src/test/middleware_handlers.lango --out .test-output/middleware_handlers.mjs && lango test src/test/middleware.lango --build-dir .test-output/middleware",
|
|
40
43
|
"test:security": "lango build examples/security/handlers.lango --out .test-output/security-handlers.mjs && lango build examples/security/setup.lango --out examples/security/dist/setup.mjs --executable && lango test src/test/security.lango --build-dir .test-output/security",
|
|
41
44
|
"test:jobs": "npm run build && lango build src/test/handlers.lango --out .test-output/handlers.mjs && lango test src/test/jobs.lango --build-dir .test-output/jobs",
|
|
@@ -49,6 +52,6 @@
|
|
|
49
52
|
"serve-static": "^2.2.1"
|
|
50
53
|
},
|
|
51
54
|
"devDependencies": {
|
|
52
|
-
"@lango-project/lango-js": "^0.
|
|
55
|
+
"@lango-project/lango-js": "^0.2.0"
|
|
53
56
|
}
|
|
54
57
|
}
|
package/src/response.lango
CHANGED
|
@@ -28,7 +28,7 @@ Response:header(name, value)
|
|
|
28
28
|
if !is_string(name) or !is_string(value)
|
|
29
29
|
throw "Header name and value must be strings"
|
|
30
30
|
name = name.toLowerCase()
|
|
31
|
-
if contains(["x-lango-auth-change", "x-lango-need-login", "x-lango-token", "content-length", "transfer-encoding", "connection", "content-type"], name)
|
|
31
|
+
if contains(["x-lango-auth-change", "x-lango-need-login", "x-lango-token", "x-lango-session", "content-length", "transfer-encoding", "connection", "content-type"], name)
|
|
32
32
|
throw "Reserved response header: ${name}"
|
|
33
33
|
if name.includes("\r") or name.includes("\n") or value.includes("\r") or value.includes("\n")
|
|
34
34
|
throw "Invalid response header"
|
package/src/route_info.lango
CHANGED
|
@@ -6,12 +6,15 @@ routeInfo(definitions)
|
|
|
6
6
|
kind = route.kind
|
|
7
7
|
if kind == null
|
|
8
8
|
kind = "endpoint"
|
|
9
|
-
|
|
9
|
+
info = {
|
|
10
10
|
path: route.path
|
|
11
11
|
kind: kind
|
|
12
12
|
auth: route.auth
|
|
13
13
|
policy: route.policy
|
|
14
14
|
reauthSeconds: route.reauthSeconds
|
|
15
15
|
middleware: route.middleware
|
|
16
|
-
}
|
|
16
|
+
}
|
|
17
|
+
if route.bootstrap == true
|
|
18
|
+
info.bootstrap = true
|
|
19
|
+
result.add(info)
|
|
17
20
|
return result
|
package/src/routes.lango
CHANGED
|
@@ -99,17 +99,27 @@ Routes:addMiddleware(name, spec)
|
|
|
99
99
|
if !is_object(spec) or is_array(spec)
|
|
100
100
|
throw "Middleware requires a module and exported handler"
|
|
101
101
|
for spec as key: value
|
|
102
|
-
if key != "module" and key != "handler" and key != "validate"
|
|
102
|
+
if key != "module" and key != "handler" and key != "validate" and key != "bootstrap"
|
|
103
103
|
throw "Unknown middleware option: ${key}"
|
|
104
104
|
if !is_string(spec.handler) or spec.handler == ""
|
|
105
105
|
throw "Middleware handler is required"
|
|
106
106
|
if spec.validate != null and (!is_string(spec.validate) or spec.validate == "")
|
|
107
107
|
throw "Middleware validate must name an exported function"
|
|
108
|
+
bootstrap = spec.bootstrap
|
|
109
|
+
if bootstrap == "true"
|
|
110
|
+
bootstrap = true
|
|
111
|
+
if bootstrap == "false"
|
|
112
|
+
bootstrap = false
|
|
113
|
+
if bootstrap != null and !is_bool(bootstrap)
|
|
114
|
+
throw "Middleware bootstrap must be boolean"
|
|
108
115
|
@middlewares[name] = {
|
|
109
116
|
module: resolveModule(spec.module, @root)
|
|
110
117
|
handler: spec.handler
|
|
111
118
|
validate: spec.validate
|
|
112
119
|
}
|
|
120
|
+
if bootstrap == true
|
|
121
|
+
middleware = @middlewares[name]
|
|
122
|
+
middleware.bootstrap = true
|
|
113
123
|
return @this
|
|
114
124
|
|
|
115
125
|
Routes:middlewares()
|
|
@@ -143,7 +153,13 @@ Routes:xml(file)
|
|
|
143
153
|
return @this
|
|
144
154
|
|
|
145
155
|
Routes:definitions()
|
|
146
|
-
|
|
156
|
+
definitions = from_json(to_json(@items))
|
|
157
|
+
for definitions as route
|
|
158
|
+
if route.middleware != null and Object/hasOwn(@middlewares, route.middleware)
|
|
159
|
+
spec = @middlewares[route.middleware]
|
|
160
|
+
if spec.bootstrap == true
|
|
161
|
+
route.bootstrap = true
|
|
162
|
+
return definitions
|
|
147
163
|
|
|
148
164
|
Routes:events()
|
|
149
165
|
return from_json(to_json(@events))
|
|
@@ -256,7 +272,7 @@ Routes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack,
|
|
|
256
272
|
leaf(tag)
|
|
257
273
|
includeAt(spec, directory, prefix, stack, auth, policy, reauthSeconds)
|
|
258
274
|
case "middleware"
|
|
259
|
-
attributes(tag, ["name", "module", "handler", "validate"])
|
|
275
|
+
attributes(tag, ["name", "module", "handler", "validate", "bootstrap"])
|
|
260
276
|
leaf(tag)
|
|
261
277
|
if !allowEvents
|
|
262
278
|
throw "Middleware declarations are only allowed in the application's root routes.xml"
|
|
@@ -264,6 +280,7 @@ Routes:collect(parent, prefix, inheritedModule, inheritedAuth, directory, stack,
|
|
|
264
280
|
module: resolveModule(spec.module, directory)
|
|
265
281
|
handler: spec.handler
|
|
266
282
|
validate: spec.validate
|
|
283
|
+
bootstrap: spec.bootstrap
|
|
267
284
|
})
|
|
268
285
|
case "event"
|
|
269
286
|
attributes(tag, ["name", "module", "handler"])
|