@lango-project/lango-server 0.2.0 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +290 -27
  2. package/dist/.lango/runtime.mjs +24 -1
  3. package/dist/body_reader.mjs +15 -14
  4. package/dist/body_reader.mjs.map +1 -1
  5. package/dist/cli/.lango/runtime.mjs +24 -1
  6. package/dist/cli/body_reader.mjs +15 -14
  7. package/dist/cli/body_reader.mjs.map +1 -1
  8. package/dist/cli/client_identity.mjs +250 -0
  9. package/dist/cli/client_identity.mjs.map +1 -0
  10. package/dist/cli/database.mjs +23 -8
  11. package/dist/cli/database.mjs.map +1 -1
  12. package/dist/cli/endpoint.mjs +11 -7
  13. package/dist/cli/endpoint.mjs.map +1 -1
  14. package/dist/cli/error_details.mjs +45 -0
  15. package/dist/cli/error_details.mjs.map +1 -0
  16. package/dist/cli/longpoll_broker.mjs +9 -8
  17. package/dist/cli/longpoll_broker.mjs.map +1 -1
  18. package/dist/cli/longpoll_options.mjs +8 -7
  19. package/dist/cli/longpoll_options.mjs.map +1 -1
  20. package/dist/cli/longpoll_session.mjs +11 -10
  21. package/dist/cli/longpoll_session.mjs.map +1 -1
  22. package/dist/cli/options.mjs +29 -3
  23. package/dist/cli/options.mjs.map +1 -1
  24. package/dist/cli/origin.mjs +87 -0
  25. package/dist/cli/origin.mjs.map +1 -0
  26. package/dist/cli/policy.mjs +121 -0
  27. package/dist/cli/policy.mjs.map +1 -0
  28. package/dist/cli/postgres_adapter.mjs +3 -2
  29. package/dist/cli/postgres_adapter.mjs.map +1 -1
  30. package/dist/cli/routes.mjs +33 -17
  31. package/dist/cli/routes.mjs.map +1 -1
  32. package/dist/cli/server.mjs +148 -101
  33. package/dist/cli/server.mjs.map +1 -1
  34. package/dist/cli/static_files.mjs +7 -4
  35. package/dist/cli/static_files.mjs.map +1 -1
  36. package/dist/cli/trace.mjs +53 -0
  37. package/dist/cli/trace.mjs.map +1 -0
  38. package/dist/client_identity.mjs +250 -0
  39. package/dist/client_identity.mjs.map +1 -0
  40. package/dist/database.mjs +23 -8
  41. package/dist/database.mjs.map +1 -1
  42. package/dist/endpoint.mjs +11 -7
  43. package/dist/endpoint.mjs.map +1 -1
  44. package/dist/error_details.mjs +45 -0
  45. package/dist/error_details.mjs.map +1 -0
  46. package/dist/group.mjs +34 -16
  47. package/dist/group.mjs.map +1 -1
  48. package/dist/http_failure.mjs +9 -2
  49. package/dist/http_failure.mjs.map +1 -1
  50. package/dist/longpoll_broker.mjs +9 -8
  51. package/dist/longpoll_broker.mjs.map +1 -1
  52. package/dist/longpoll_options.mjs +8 -7
  53. package/dist/longpoll_options.mjs.map +1 -1
  54. package/dist/longpoll_session.mjs +11 -10
  55. package/dist/longpoll_session.mjs.map +1 -1
  56. package/dist/options.mjs +29 -3
  57. package/dist/options.mjs.map +1 -1
  58. package/dist/origin.mjs +87 -0
  59. package/dist/origin.mjs.map +1 -0
  60. package/dist/policy.mjs +121 -0
  61. package/dist/policy.mjs.map +1 -0
  62. package/dist/postgres_adapter.mjs +3 -2
  63. package/dist/postgres_adapter.mjs.map +1 -1
  64. package/dist/postgres_worker.mjs +15 -14
  65. package/dist/postgres_worker.mjs.map +1 -1
  66. package/dist/request_identity.mjs +22 -0
  67. package/dist/request_identity.mjs.map +1 -0
  68. package/dist/response.mjs +1 -1
  69. package/dist/response.mjs.map +1 -1
  70. package/dist/route_info.mjs +1 -1
  71. package/dist/route_info.mjs.map +1 -1
  72. package/dist/routes.mjs +33 -17
  73. package/dist/routes.mjs.map +1 -1
  74. package/dist/runtime.mjs +241 -110
  75. package/dist/runtime.mjs.map +1 -1
  76. package/dist/server.mjs +148 -101
  77. package/dist/server.mjs.map +1 -1
  78. package/dist/server_context.mjs +21 -9
  79. package/dist/server_context.mjs.map +1 -1
  80. package/dist/static_files.mjs +7 -4
  81. package/dist/static_files.mjs.map +1 -1
  82. package/dist/token.mjs +34 -7
  83. package/dist/token.mjs.map +1 -1
  84. package/dist/tokens.mjs +11 -2
  85. package/dist/tokens.mjs.map +1 -1
  86. package/dist/trace.mjs +53 -0
  87. package/dist/trace.mjs.map +1 -0
  88. package/dist/worker.mjs +8 -6
  89. package/dist/worker.mjs.map +1 -1
  90. package/docs/security.md +420 -0
  91. package/examples/security/README.md +160 -0
  92. package/examples/security/deploy.xml +12 -0
  93. package/examples/security/handlers.lango +610 -0
  94. package/examples/security/package.json +19 -0
  95. package/examples/security/passwords.lango +61 -0
  96. package/examples/security/routes.xml +14 -0
  97. package/examples/security/schema.lango +91 -0
  98. package/examples/security/setup.lango +30 -0
  99. package/package.json +12 -6
  100. package/src/client_identity.lango +184 -0
  101. package/src/database.lango +15 -4
  102. package/src/endpoint.lango +12 -5
  103. package/src/error_details.lango +21 -0
  104. package/src/group.lango +25 -21
  105. package/src/http_failure.lango +9 -5
  106. package/src/longpoll_options.lango +11 -5
  107. package/src/options.lango +34 -1
  108. package/src/origin.lango +56 -0
  109. package/src/policy.lango +84 -0
  110. package/src/request_identity.lango +9 -0
  111. package/src/response.lango +1 -1
  112. package/src/route_info.lango +2 -0
  113. package/src/routes.lango +30 -15
  114. package/src/runtime.lango +149 -77
  115. package/src/server.lango +48 -7
  116. package/src/server_context.lango +10 -2
  117. package/src/static_files.lango +3 -0
  118. package/src/token.lango +26 -5
  119. package/src/tokens.lango +10 -3
  120. package/src/trace.lango +23 -0
  121. package/src/worker.lango +1 -0
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","sources":["server.lango"],"sourcesContent":["import \"./longpoll_broker\"\n class LongpollBroker\nimport \"./longpoll_session\"\n class LongpollSession\nimport \"./database\"\n prepareDatabase(settings)\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 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 @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 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)\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\")\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 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 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 if state.done\n return null\n state.done = true\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 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 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 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 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.id}] 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 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 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 if args.length != 1\n throw \"Usage: lango-server <application-directory>\"\n server = new Server(args[0])\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA;;;;;;;;AAoGA;;;;;;;;;;;;;;;;;AAgXA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA;;;;;;;;;;;;;;;;"}
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 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 @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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA;;;;;;;;AAqGA;;;;;;;;;;;;;;;;;AAiYA;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;AASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA;;;;;;;;;;;;;;;;"}
@@ -1,9 +1,11 @@
1
+ import { trace } from "./trace.mjs";
1
2
  import * as fs from "node:fs";
2
3
  import * as path from "node:path";
3
4
  import * as files from "serve-static";
4
5
  import {
5
6
  hostGlobal as __hostGlobal,
6
7
  hostGlobalCall as __hostGlobalCall,
8
+ bindContexts as __bindContexts,
7
9
  isNumber as __isNumber,
8
10
  isString as __isString,
9
11
  isBool as __isBool,
@@ -78,15 +80,16 @@ export class StaticFiles {
78
80
  }
79
81
  }
80
82
  }
81
- let done = __withArity((error) => {
83
+ let done = __withArity(__bindContexts((error) => {
82
84
  error = __boundary(error);
83
85
  this.#failure(req, res, failed, error, decoded);
84
86
  return null;
85
- }, [0], "closure");
87
+ }), [0], "closure");
86
88
  let serve = __normalize(this.#serve);
87
89
  if (__requireBoolean(runtime)) {
88
90
  serve = __normalize(this.#runtime);
89
91
  }
92
+ trace(`Static ${__normalize(req.method)} ${pathname}: directory=${__normalize(this.#settings.directory)}; index=${__normalize(this.#settings.index)}; runtime=${runtime}`);
90
93
  __call(serve, req, res, done);
91
94
  return null;
92
95
  return null;
@@ -123,11 +126,11 @@ export class StaticFiles {
123
126
  }
124
127
  if (__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(__requireBoolean(status === 404) && __requireBoolean(pathname !== null)) && __requireBoolean(__normalize(this.#settings.fallback) !== null)) && __requireBoolean(!__requireBoolean(__normalize(pathname.startsWith("/.lango"))))) && __requireBoolean(__normalize(path.posix.extname(pathname)) === "")) && __requireBoolean(acceptsHTML(req.headers.accept)))) {
125
128
  req.url = `/${__normalize(this.#settings.fallback)}`;
126
- let done = __withArity((error) => {
129
+ let done = __withArity(__bindContexts((error) => {
127
130
  error = __boundary(error);
128
131
  this.#failure(req, res, failed, error);
129
132
  return null;
130
- }, [0], "closure");
133
+ }), [0], "closure");
131
134
  let serve = __normalize(this.#serve);
132
135
  __call(serve, req, res, done);
133
136
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"static_files.mjs","sources":["static_files.lango"],"sourcesContent":["import 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 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":";;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0IA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
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;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,53 @@
1
+ import {
2
+ contextGet as __contextGet,
3
+ contextSet as __contextSet,
4
+ contextRestore as __contextRestore,
5
+ requireBoolean as __requireBoolean,
6
+ normalize as __normalize,
7
+ boundary as __boundary,
8
+ requireArity as __requireArity,
9
+ } from "./.lango/runtime.mjs";
10
+
11
+ export function trace(message) {
12
+ const __contextScope = [];
13
+ try {
14
+ __requireArity(arguments.length, [0], "trace");
15
+ message = __boundary(message);
16
+ if (__requireBoolean(__normalize(__contextGet("log").verbose) === true)) {
17
+ __normalize(__contextGet("log").debug(message));
18
+ }
19
+ return null;
20
+ return null;
21
+ } finally {
22
+ __contextRestore(__contextScope);
23
+ }
24
+ }
25
+
26
+ export function responseLog(id, method, path, status) {
27
+ const __contextScope = [];
28
+ try {
29
+ __requireArity(arguments.length, [0, 1, 2, 3], "responseLog");
30
+ id = __boundary(id);
31
+ method = __boundary(method);
32
+ path = __boundary(path);
33
+ status = __boundary(status);
34
+ let message = `HTTP ${method} ${path} completed status=${status}`;
35
+ if (__requireBoolean(id !== null)) {
36
+ message = `[${id}] ${message}`;
37
+ }
38
+ if (__requireBoolean(status >= 500)) {
39
+ __normalize(__contextGet("log").err(message));
40
+ } else {
41
+ if (__requireBoolean(status >= 400)) {
42
+ __normalize(__contextGet("log").warn(message));
43
+ } else {
44
+ trace(message);
45
+ }
46
+ }
47
+ return null;
48
+ return null;
49
+ } finally {
50
+ __contextRestore(__contextScope);
51
+ }
52
+ }
53
+ //# sourceMappingURL=trace.mjs.map
@@ -0,0 +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;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,250 @@
1
+ import * as crypto from "node:crypto";
2
+ import {
3
+ hostGlobal as __hostGlobal,
4
+ hostGlobalCall as __hostGlobalCall,
5
+ contextGet as __contextGet,
6
+ contextSet as __contextSet,
7
+ contextRestore as __contextRestore,
8
+ isNumber as __isNumber,
9
+ isString as __isString,
10
+ isBool as __isBool,
11
+ isObject as __isObject,
12
+ isArray as __isArray,
13
+ requireBoolean as __requireBoolean,
14
+ normalize as __normalize,
15
+ finite as __finite,
16
+ numericAdd as __numericAdd,
17
+ boundary as __boundary,
18
+ startTrans as __startTrans,
19
+ commitTrans as __commitTrans,
20
+ rollbackTrans as __rollbackTrans,
21
+ transState as __transState,
22
+ query as __query,
23
+ requireArity as __requireArity,
24
+ } from "./.lango/runtime.mjs";
25
+
26
+ export class ClientIdentity {
27
+ #settings;
28
+ #database;
29
+ constructor(settings, database) {
30
+ __requireArity(arguments.length, [0, 1], "constructor");
31
+ settings = __boundary(settings);
32
+ database = __boundary(database);
33
+ this.#settings = settings;
34
+ this.#database = database;
35
+ }
36
+ initialize() {
37
+ const __contextScope = [];
38
+ try {
39
+ __contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
40
+ try {
41
+ __startTrans();
42
+ if (__requireBoolean(__normalize(__contextGet("db").parameterStyle) === "postgresql")) {
43
+ let lock = __query("select pg_advisory_xact_lock(1818324591, 1)", []);
44
+ __normalize(lock.execute());
45
+ }
46
+ let row = __query("create table if not exists _lango_clients (\n client_id text primary key,\n secret_hash text not null unique,\n expires_at bigint not null\n)", []);
47
+ __normalize(row.execute());
48
+ __commitTrans();
49
+ } finally {
50
+ __normalize(__contextGet("db").finish());
51
+ }
52
+ return null;
53
+ return null;
54
+ } finally {
55
+ __contextRestore(__contextScope);
56
+ }
57
+ }
58
+ begin(claims, tokens) {
59
+ const __contextScope = [];
60
+ try {
61
+ __requireArity(arguments.length, [0, 1], "begin");
62
+ claims = __boundary(claims);
63
+ tokens = __boundary(tokens);
64
+ let value = readCookie();
65
+ if (__requireBoolean(__requireBoolean(value === null) && __requireBoolean(claims !== null))) {
66
+ __normalize(__contextGet("response").reject(401, "ClientProofRequired"));
67
+ }
68
+ let hash = null;
69
+ let row = null;
70
+ if (__requireBoolean(value === null)) {
71
+ value = clientSecret();
72
+ claims = __normalize(tokens.create());
73
+ hash = clientDigest(value);
74
+ claims.clientProof = hash;
75
+ return { claims: claims, value: value, hash: hash, fresh: true, restored: false, rotate: false, closed: false };
76
+ }
77
+ hash = clientDigest(value);
78
+ row = __query("select client_id from _lango_clients where secret_hash = :hash and expires_at > :now", ["hash","now"]);
79
+ row.hash = hash;
80
+ row.now = __normalize(__hostGlobal(["Date"]).now());
81
+ __normalize(row.execute());
82
+ if (__requireBoolean(!__requireBoolean(__normalize(row.next())))) {
83
+ __normalize(__contextGet("response").reject(401, "ClientCookieRejected"));
84
+ }
85
+ let restored = claims === null;
86
+ if (__requireBoolean(restored)) {
87
+ claims = __normalize(tokens.create(__normalize(row.client_id)));
88
+ claims.clientProof = hash;
89
+ }
90
+ if (__requireBoolean(__requireBoolean(__normalize(claims.clientId) !== __normalize(row.client_id)) || __requireBoolean(!__requireBoolean(sameProof(__normalize(claims.clientProof), hash))))) {
91
+ __normalize(__contextGet("response").reject(401, "ClientProofRequired"));
92
+ }
93
+ return { claims: claims, value: value, hash: hash, fresh: false, restored: restored, rotate: false, closed: false };
94
+ return null;
95
+ } finally {
96
+ __contextRestore(__contextScope);
97
+ }
98
+ }
99
+ publish(identity, claims, response, tokens) {
100
+ const __contextScope = [];
101
+ try {
102
+ __requireArity(arguments.length, [0, 1, 2, 3], "publish");
103
+ identity = __boundary(identity);
104
+ claims = __boundary(claims);
105
+ response = __boundary(response);
106
+ tokens = __boundary(tokens);
107
+ let value = __normalize(identity.value);
108
+ if (__requireBoolean(__normalize(identity.rotate))) {
109
+ value = clientSecret();
110
+ }
111
+ let hash = clientDigest(value);
112
+ claims.clientProof = hash;
113
+ let encoded = __normalize(tokens.sign(claims));
114
+ __contextScope.push(__contextSet("db", __normalize(this.#database.scope())));
115
+ let row = null;
116
+ try {
117
+ if (__requireBoolean(__normalize(identity.fresh))) {
118
+ row = __query("insert into _lango_clients (client_id, secret_hash, expires_at)\nvalues (:id, :hash, :expires)", ["id","hash","expires"]);
119
+ row.id = __normalize(claims.clientId);
120
+ row.hash = hash;
121
+ row.expires = __numericAdd(__normalize(__hostGlobal(["Date"]).now()), __finite(__normalize(this.#settings.maxAgeSeconds) * 1000));
122
+ __normalize(row.execute());
123
+ } else {
124
+ row = __query("update _lango_clients set secret_hash = :replacement, expires_at = :expires\nwhere client_id = :id and secret_hash = :previous and expires_at > :now\nreturning client_id", ["replacement","expires","id","previous","now"]);
125
+ row.id = __normalize(claims.clientId);
126
+ row.previous = __normalize(identity.hash);
127
+ row.replacement = hash;
128
+ row.now = __normalize(__hostGlobal(["Date"]).now());
129
+ row.expires = __numericAdd(__normalize(__hostGlobal(["Date"]).now()), __finite(__normalize(this.#settings.maxAgeSeconds) * 1000));
130
+ __normalize(row.execute());
131
+ if (__requireBoolean(!__requireBoolean(__normalize(row.next())))) {
132
+ __normalize(response.reject(401, "ClientProofRequired"));
133
+ }
134
+ }
135
+ __normalize(response.header("Set-Cookie", `__Host-lango-client=${value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${__normalize(this.#settings.maxAgeSeconds)}`));
136
+ } finally {
137
+ __normalize(__contextGet("db").finish());
138
+ }
139
+ identity.closed = true;
140
+ return encoded;
141
+ return null;
142
+ } finally {
143
+ __contextRestore(__contextScope);
144
+ }
145
+ }
146
+ }
147
+ export function clientOptions(spec, database, origin) {
148
+ __requireArity(arguments.length, [0, 1, 2], "clientOptions");
149
+ spec = __boundary(spec);
150
+ database = __boundary(database);
151
+ origin = __boundary(origin);
152
+ if (__requireBoolean(spec === null)) {
153
+ return null;
154
+ }
155
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isObject(spec))) || __requireBoolean(__isArray(spec)))) {
156
+ throw "Client configuration must be an object";
157
+ }
158
+ for (const name of __normalize(__hostGlobal(["Object"]).keys(spec))) {
159
+ if (__requireBoolean(name !== "maxAgeSeconds")) {
160
+ throw `Unknown client option: ${name}`;
161
+ }
162
+ }
163
+ if (__requireBoolean(database === null)) {
164
+ throw "Managed client identity requires a database";
165
+ }
166
+ if (__requireBoolean(__requireBoolean(__normalize(database.type) === "sqlite") && __requireBoolean(__normalize(database.file) === ":memory:"))) {
167
+ throw "Managed client identity requires persistent database storage";
168
+ }
169
+ if (__requireBoolean(__requireBoolean(__requireBoolean(origin === null) || __requireBoolean(!__requireBoolean(__normalize(origin.required)))) || __requireBoolean(!__requireBoolean(__normalize(origin.url.startsWith("https:")))))) {
170
+ throw "Managed client identity requires a required HTTPS origin";
171
+ }
172
+ let lifetime = __normalize(spec.maxAgeSeconds);
173
+ if (__requireBoolean(lifetime === null)) {
174
+ lifetime = 2592000;
175
+ }
176
+ if (__requireBoolean(__isString(lifetime))) {
177
+ lifetime = __hostGlobalCall(["Number"], lifetime);
178
+ }
179
+ if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__normalize(__hostGlobal(["Number"]).isSafeInteger(lifetime)))) || __requireBoolean(lifetime < 1)) || __requireBoolean(lifetime > 31536000))) {
180
+ throw "Client maxAgeSeconds must be between 1 and 31536000";
181
+ }
182
+ return { maxAgeSeconds: lifetime };
183
+ return null;
184
+ }
185
+
186
+ function readCookie() {
187
+ const __contextScope = [];
188
+ try {
189
+ let pattern;
190
+ let headers = __normalize(__contextGet("request").headers);
191
+ let header = __normalize(headers.cookie);
192
+ if (__requireBoolean(header === null)) {
193
+ return null;
194
+ }
195
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(header))) || __requireBoolean(__normalize(header.length) > 8192))) {
196
+ __normalize(__contextGet("response").reject(400, "InvalidCookie"));
197
+ }
198
+ let found = null;
199
+ for (const part of __normalize(header.split(";"))) {
200
+ let pair = __normalize(part.trim());
201
+ let index = __normalize(pair.indexOf("="));
202
+ if (__requireBoolean(__requireBoolean(index >= 0) && __requireBoolean(__normalize(pair.slice(0, index)) === "__Host-lango-client"))) {
203
+ if (__requireBoolean(found !== null)) {
204
+ __normalize(__contextGet("response").reject(400, "InvalidCookie"));
205
+ }
206
+ found = __normalize(pair.slice(__numericAdd(index, 1)));
207
+ }
208
+ }
209
+ if (__requireBoolean(found !== null)) {
210
+ pattern = new (__hostGlobal(["RegExp"]))("^[a-f0-9]{64}$");
211
+ if (__requireBoolean(!__requireBoolean(__normalize(pattern.test(found))))) {
212
+ __normalize(__contextGet("response").reject(400, "InvalidCookie"));
213
+ }
214
+ }
215
+ return found;
216
+ return null;
217
+ } finally {
218
+ __contextRestore(__contextScope);
219
+ }
220
+ }
221
+
222
+ function clientSecret() {
223
+ let bytes = __normalize(crypto.randomBytes(32));
224
+ return __normalize(bytes.toString("hex"));
225
+ return null;
226
+ }
227
+
228
+ function clientDigest(value) {
229
+ __requireArity(arguments.length, [0], "clientDigest");
230
+ value = __boundary(value);
231
+ let hash = __normalize(crypto.createHash("sha256"));
232
+ __normalize(hash.update(value));
233
+ return __normalize(hash.digest("hex"));
234
+ return null;
235
+ }
236
+
237
+ function sameProof(left, right) {
238
+ __requireArity(arguments.length, [0, 1], "sameProof");
239
+ left = __boundary(left);
240
+ right = __boundary(right);
241
+ let pattern = new (__hostGlobal(["RegExp"]))("^[a-f0-9]{64}$");
242
+ if (__requireBoolean(__requireBoolean(!__requireBoolean(__isString(left))) || __requireBoolean(!__requireBoolean(__normalize(pattern.test(left)))))) {
243
+ return false;
244
+ }
245
+ let first = __normalize(__hostGlobal(["Buffer"]).from(left, "hex"));
246
+ let second = __normalize(__hostGlobal(["Buffer"]).from(right, "hex"));
247
+ return __normalize(crypto.timingSafeEqual(first, second));
248
+ return null;
249
+ }
250
+ //# sourceMappingURL=client_identity.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client_identity.mjs","sources":["client_identity.lango"],"sourcesContent":["import js \"node:crypto\" as crypto\nimport js global Date\nimport js global Object\nimport js global Number\nimport js global RegExp\nimport js global Buffer\n\nexport clientOptions(spec, database, origin)\nexport class ClientIdentity(settings, database)\n methods\n initialize()\n begin(claims, tokens)\n publish(identity, claims, response, tokens)\n\nclientOptions(spec, database, origin)\n if spec == null\n return null\n if !is_object(spec) or is_array(spec)\n throw \"Client configuration must be an object\"\n for Object/keys(spec) as name\n if name != \"maxAgeSeconds\"\n throw \"Unknown client option: ${name}\"\n if database == null\n throw \"Managed client identity requires a database\"\n if database.type == \"sqlite\" and database.file == \":memory:\"\n throw \"Managed client identity requires persistent database storage\"\n if origin == null or !origin.required or !origin.url.startsWith(\"https:\")\n throw \"Managed client identity requires a required HTTPS origin\"\n lifetime = spec.maxAgeSeconds\n if lifetime == null\n lifetime = 2592000\n if is_string(lifetime)\n lifetime = Number(lifetime)\n if !Number/isSafeInteger(lifetime) or lifetime < 1 or lifetime > 31536000\n throw \"Client maxAgeSeconds must be between 1 and 31536000\"\n return {\n maxAgeSeconds: lifetime\n }\n\nClientIdentity(settings, database)\n @settings = settings\n @database = database\n\nClientIdentity:initialize()\n context db = @database.scope()\n try\n start_trans()\n if db.parameterStyle == \"postgresql\"\n lock = SQL\n select pg_advisory_xact_lock(1818324591, 1)\n lock.execute()\n row = SQL\n create table if not exists _lango_clients (\n client_id text primary key,\n secret_hash text not null unique,\n expires_at bigint not null\n )\n row.execute()\n commit_trans()\n finally\n db.finish()\n return null\n\nClientIdentity:begin(claims, tokens)\n context response\n value = readCookie()\n if value == null and claims != null\n response.reject(401, \"ClientProofRequired\")\n hash = null\n row = null\n if value == null\n value = clientSecret()\n claims = tokens.create()\n hash = clientDigest(value)\n claims.clientProof = hash\n return {\n claims: claims\n value: value\n hash: hash\n fresh: true\n restored: false\n rotate: false\n closed: false\n }\n hash = clientDigest(value)\n row = SQL\n select client_id from _lango_clients where secret_hash = :hash and expires_at > :now\n row.hash = hash\n row.now = Date/now()\n row.execute()\n if !row.next()\n response.reject(401, \"ClientCookieRejected\")\n restored = claims == null\n if restored\n claims = tokens.create(row.client_id)\n claims.clientProof = hash\n if claims.clientId != row.client_id or !sameProof(claims.clientProof, hash)\n response.reject(401, \"ClientProofRequired\")\n return {\n claims: claims\n value: value\n hash: hash\n fresh: false\n restored: restored\n rotate: false\n closed: false\n }\n\nClientIdentity:publish(identity, claims, response, tokens)\n value = identity.value\n if identity.rotate\n value = clientSecret()\n hash = clientDigest(value)\n claims.clientProof = hash\n encoded = tokens.sign(claims)\n context db = @database.scope()\n row = null\n try\n if identity.fresh\n row = SQL\n insert into _lango_clients (client_id, secret_hash, expires_at)\n values (:id, :hash, :expires)\n row.id = claims.clientId\n row.hash = hash\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n else\n row = SQL\n update _lango_clients set secret_hash = :replacement, expires_at = :expires\n where client_id = :id and secret_hash = :previous and expires_at > :now\n returning client_id\n row.id = claims.clientId\n row.previous = identity.hash\n row.replacement = hash\n row.now = Date/now()\n row.expires = Date/now() + @settings.maxAgeSeconds * 1000\n row.execute()\n if !row.next()\n response.reject(401, \"ClientProofRequired\")\n response.header(\"Set-Cookie\", \"__Host-lango-client=${value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${@settings.maxAgeSeconds}\")\n finally\n db.finish()\n identity.closed = true\n return encoded\n\nreadCookie()\n context request\n context response\n headers = request.headers\n header = headers.cookie\n if header == null\n return null\n if !is_string(header) or header.length > 8192\n response.reject(400, \"InvalidCookie\")\n found = null\n for header.split(\";\") as part\n pair = part.trim()\n index = pair.indexOf(\"=\")\n if index >= 0 and pair.slice(0, index) == \"__Host-lango-client\"\n if found != null\n response.reject(400, \"InvalidCookie\")\n found = pair.slice(index + 1)\n if found != null\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !pattern.test(found)\n response.reject(400, \"InvalidCookie\")\n return found\n\nclientSecret()\n bytes = crypto/randomBytes(32)\n return bytes.toString(\"hex\")\n\nclientDigest(value)\n hash = crypto/createHash(\"sha256\")\n hash.update(value)\n return hash.digest(\"hex\")\n\nsameProof(left, right)\n pattern = new RegExp(\"^[a-f0-9]{64}$\")\n if !is_string(left) or !pattern.test(left)\n return false\n first = Buffer/from(left, \"hex\")\n second = Buffer/from(right, \"hex\")\n return crypto/timingSafeEqual(first, second)\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmIA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA;;;;;;AAIA;;;;;;;;;AAKA;;;;;;;;;;;;;;"}
package/dist/database.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { ClientIdentity } from "./client_identity.mjs";
1
2
  import { DatabaseScope } from "./database_scope.mjs";
2
3
  import { SqliteAdapter } from "./sqlite_adapter.mjs";
3
4
  import { PostgresAdapter } from "./postgres_adapter.mjs";
@@ -6,6 +7,7 @@ import {
6
7
  contextGet as __contextGet,
7
8
  contextSet as __contextSet,
8
9
  contextRestore as __contextRestore,
10
+ bindContexts as __bindContexts,
9
11
  requireBoolean as __requireBoolean,
10
12
  normalize as __normalize,
11
13
  boundary as __boundary,
@@ -34,7 +36,7 @@ export class Database {
34
36
  if (__requireBoolean(__normalize(this.#settings.type) === "postgresql")) {
35
37
  name = "node:worker_threads";
36
38
  }
37
- return import(name).then(__withArity((mod) => {
39
+ return import(name).then(__withArity(__bindContexts((mod) => {
38
40
  const __contextScope = [];
39
41
  try {
40
42
  mod = __boundary(mod);
@@ -55,7 +57,7 @@ export class Database {
55
57
  } finally {
56
58
  __contextRestore(__contextScope);
57
59
  }
58
- }, [0], "closure")).catch(__withArity((error) => {
60
+ }), [0], "closure")).catch(__withArity(__bindContexts((error) => {
59
61
  const __contextScope = [];
60
62
  try {
61
63
  error = __boundary(error);
@@ -66,7 +68,7 @@ export class Database {
66
68
  } finally {
67
69
  __contextRestore(__contextScope);
68
70
  }
69
- }, [0], "closure"));
71
+ }), [0], "closure"));
70
72
  return null;
71
73
  }
72
74
  scope() {
@@ -85,17 +87,30 @@ export class Database {
85
87
  return null;
86
88
  }
87
89
  }
88
- export function prepareDatabase(settings) {
90
+ export function prepareDatabase(settings, root = null, client = null) {
89
91
  __requireArity(arguments.length, [0], "prepareDatabase");
90
92
  settings = __boundary(settings);
91
- if (__requireBoolean(__requireBoolean(__requireBoolean(settings === null) || __requireBoolean(__normalize(settings.type) !== "sqlite")) || __requireBoolean(__normalize(settings.file) === ":memory:"))) {
93
+ root = __boundary(root);
94
+ client = __boundary(client);
95
+ if (__requireBoolean(settings === null)) {
92
96
  return __normalize(__hostGlobal(["Promise"]).resolve(null));
93
97
  }
94
- let database = new Database(settings);
95
- return __normalize(database.open()).finally(() => {
98
+ if (__requireBoolean(__requireBoolean(client === null) && __requireBoolean(__requireBoolean(__normalize(settings.type) !== "sqlite") || __requireBoolean(__normalize(settings.file) === ":memory:")))) {
99
+ return __normalize(__hostGlobal(["Promise"]).resolve(null));
100
+ }
101
+ let database = new Database(settings, root);
102
+ return __normalize(database.open()).then(__withArity(__bindContexts((ignored) => {
103
+ ignored = __boundary(ignored);
104
+ if (__requireBoolean(client !== null)) {
105
+ let identity = new ClientIdentity(client, database);
106
+ __normalize(identity.initialize());
107
+ }
108
+ return null;
109
+ return null;
110
+ }), [0], "closure")).finally(__bindContexts(() => {
96
111
  __normalize(database.close());
97
112
  return null;
98
- });
113
+ }));
99
114
  return null;
100
115
  }
101
116
  //# sourceMappingURL=database.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"database.mjs","sources":["database.lango"],"sourcesContent":["import js global Promise\nimport \"./database_scope\"\n class DatabaseScope\nimport \"./sqlite_adapter\"\n class SqliteAdapter\nimport \"./postgres_adapter\"\n class PostgresAdapter\n\nexport prepareDatabase(settings)\n\nexport class Database(settings, root = null)\n methods\n open()\n scope()\n close()\n\nDatabase(settings, root = null)\n @root = root\n @settings = settings\n @adapter = null\n\nDatabase:open()\n if @settings == null\n return Promise/resolve(null)\n name = \"node:sqlite\"\n if @settings.type == \"postgresql\"\n name = \"node:worker_threads\"\n return chain import_module(name)\n then(mod)\n if @settings.type == \"sqlite\"\n @adapter = new SqliteAdapter(mod, @settings)\n else\n @adapter = new PostgresAdapter(mod, @settings, @root)\n context db = scope()\n try\n query = SQL\n select 1\n query.execute()\n finally\n db.finish()\n return null\n catch(error)\n context log\n log.err(\"Database startup failed: ${error}\")\n close()\n throw \"Database startup failed; check configuration, compiler version and driver installation\"\n\nDatabase:scope()\n if @adapter == null\n return null\n return new DatabaseScope(@adapter)\n\nDatabase:close()\n if @adapter != null\n @adapter.close()\n @adapter = null\n return null\n\nprepareDatabase(settings)\n if settings == null or settings.type != \"sqlite\" or settings.file == \":memory:\"\n return Promise/resolve(null)\n database = new Database(settings)\n return chain database.open()\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAUA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"database.mjs","sources":["database.lango"],"sourcesContent":["import \"./client_identity\"\n class ClientIdentity\nimport js global Promise\nimport \"./database_scope\"\n class DatabaseScope\nimport \"./sqlite_adapter\"\n class SqliteAdapter\nimport \"./postgres_adapter\"\n class PostgresAdapter\n\nexport prepareDatabase(settings, root = null, client = null)\n\nexport class Database(settings, root = null)\n methods\n open()\n scope()\n close()\n\nDatabase(settings, root = null)\n @root = root\n @settings = settings\n @adapter = null\n\nDatabase:open()\n if @settings == null\n return Promise/resolve(null)\n name = \"node:sqlite\"\n if @settings.type == \"postgresql\"\n name = \"node:worker_threads\"\n return chain import_module(name)\n then(mod)\n if @settings.type == \"sqlite\"\n @adapter = new SqliteAdapter(mod, @settings)\n else\n @adapter = new PostgresAdapter(mod, @settings, @root)\n context db = scope()\n try\n query = SQL\n select 1\n query.execute()\n finally\n db.finish()\n return null\n catch(error)\n context log\n log.err(\"Database startup failed: ${error}\")\n close()\n throw \"Database startup failed; check configuration, compiler version and driver installation\"\n\nDatabase:scope()\n if @adapter == null\n return null\n return new DatabaseScope(@adapter)\n\nDatabase:close()\n if @adapter != null\n @adapter.close()\n @adapter = null\n return null\n\nprepareDatabase(settings, root = null, client = null)\n if settings == null\n return Promise/resolve(null)\n if client == null and (settings.type != \"sqlite\" or settings.file == \":memory:\")\n return Promise/resolve(null)\n database = new Database(settings, root)\n return chain database.open()\n then(ignored)\n capture database\n capture client\n if client != null\n identity = new ClientIdentity(client, database)\n identity.initialize()\n return null\n finally\n capture database\n database.close()\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;AAYA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/endpoint.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { policyOptions } from "./policy.mjs";
1
2
  import { routePattern } from "./route_pattern.mjs";
2
3
  import { middlewareName } from "./middleware.mjs";
3
4
  import {
@@ -17,6 +18,10 @@ export class Endpoint {
17
18
  module;
18
19
  handler;
19
20
  auth;
21
+ policy;
22
+ reauthSeconds;
23
+ reauthExplicit;
24
+ legacyAuth;
20
25
  middleware;
21
26
  constructor(spec) {
22
27
  __requireArity(arguments.length, [0], "constructor");
@@ -34,13 +39,12 @@ export class Endpoint {
34
39
  if (__requireBoolean(__normalize(this.middleware) !== null)) {
35
40
  middlewareName(__normalize(this.middleware));
36
41
  }
37
- this.auth = __normalize(spec.auth);
38
- if (__requireBoolean(__normalize(this.auth) === null)) {
39
- this.auth = "login";
40
- }
41
- if (__requireBoolean(__requireBoolean(__requireBoolean(!__requireBoolean(__isString(__normalize(this.auth)))) || __requireBoolean(__normalize(this.auth) === "")) || __requireBoolean(__normalize(this.auth.includes(","))))) {
42
- throw "Endpoint auth must name one permission";
43
- }
42
+ let selected = policyOptions(spec);
43
+ this.policy = __normalize(selected.name);
44
+ this.auth = __normalize(selected.name);
45
+ this.reauthSeconds = __normalize(selected.reauthSeconds);
46
+ this.reauthExplicit = __normalize(selected.explicit);
47
+ this.legacyAuth = __normalize(selected.legacy);
44
48
  }
45
49
  }
46
50
  //# sourceMappingURL=endpoint.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./route_pattern\"\n routePattern(path)\nimport \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n middleware\n\nEndpoint(spec)\n routePattern(spec.path)\n for [\"module\", \"handler\"] as key\n if !is_string(spec[key]) or spec[key] == \"\"\n throw \"Endpoint requires ${key}\"\n @path = spec.path\n @module = spec.module\n @handler = spec.handler\n @middleware = spec.middleware\n if @middleware != null\n middlewareName(@middleware)\n @auth = spec.auth\n if @auth == null\n @auth = \"login\"\n if !is_string(@auth) or @auth == \"\" or @auth.includes(\",\")\n throw \"Endpoint auth must name one permission\"\n"],"names":[],"mappings":";;;;;;;;;;;;;;AAKA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"endpoint.mjs","sources":["endpoint.lango"],"sourcesContent":["import \"./policy\"\n policyOptions(spec)\nimport \"./route_pattern\"\n routePattern(path)\nimport \"./middleware\"\n middlewareName(name)\n\nexport class Endpoint(spec)\n properties\n path\n module\n handler\n auth\n policy\n reauthSeconds\n reauthExplicit\n legacyAuth\n middleware\n\nEndpoint(spec)\n routePattern(spec.path)\n for [\"module\", \"handler\"] as key\n if !is_string(spec[key]) or spec[key] == \"\"\n throw \"Endpoint requires ${key}\"\n @path = spec.path\n @module = spec.module\n @handler = spec.handler\n @middleware = spec.middleware\n if @middleware != null\n middlewareName(@middleware)\n selected = policyOptions(spec)\n @policy = selected.name\n @auth = selected.name\n @reauthSeconds = selected.reauthSeconds\n @reauthExplicit = selected.explicit\n @legacyAuth = selected.legacy\n"],"names":[],"mappings":";;;;;;;;;;;;;;;AAOA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}