@lango-project/lango-server 0.2.2 → 0.2.4

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 (158) hide show
  1. package/README.md +252 -29
  2. package/dist/.lango/runtime.mjs +16 -0
  3. package/dist/body_reader.mjs +15 -14
  4. package/dist/body_reader.mjs.map +1 -1
  5. package/dist/builder.mjs +26 -2
  6. package/dist/builder.mjs.map +1 -1
  7. package/dist/cli/.lango/runtime.mjs +16 -0
  8. package/dist/cli/body_reader.mjs +15 -14
  9. package/dist/cli/body_reader.mjs.map +1 -1
  10. package/dist/cli/client_identity.mjs +250 -0
  11. package/dist/cli/client_identity.mjs.map +1 -0
  12. package/dist/cli/database.mjs +23 -8
  13. package/dist/cli/database.mjs.map +1 -1
  14. package/dist/cli/database_scope.mjs +11 -0
  15. package/dist/cli/database_scope.mjs.map +1 -1
  16. package/dist/cli/endpoint.mjs +11 -7
  17. package/dist/cli/endpoint.mjs.map +1 -1
  18. package/dist/cli/longpoll_broker.mjs +9 -8
  19. package/dist/cli/longpoll_broker.mjs.map +1 -1
  20. package/dist/cli/longpoll_options.mjs +8 -7
  21. package/dist/cli/longpoll_options.mjs.map +1 -1
  22. package/dist/cli/longpoll_session.mjs +11 -10
  23. package/dist/cli/longpoll_session.mjs.map +1 -1
  24. package/dist/cli/middleware.mjs +1 -1
  25. package/dist/cli/middleware.mjs.map +1 -1
  26. package/dist/cli/options.mjs +41 -4
  27. package/dist/cli/options.mjs.map +1 -1
  28. package/dist/cli/origin.mjs +87 -0
  29. package/dist/cli/origin.mjs.map +1 -0
  30. package/dist/cli/policy.mjs +121 -0
  31. package/dist/cli/policy.mjs.map +1 -0
  32. package/dist/cli/postgres_adapter.mjs +15 -3
  33. package/dist/cli/postgres_adapter.mjs.map +1 -1
  34. package/dist/cli/routes.mjs +69 -18
  35. package/dist/cli/routes.mjs.map +1 -1
  36. package/dist/cli/server.mjs +88 -81
  37. package/dist/cli/server.mjs.map +1 -1
  38. package/dist/cli/static_files.mjs +5 -4
  39. package/dist/cli/static_files.mjs.map +1 -1
  40. package/dist/client_identity.mjs +250 -0
  41. package/dist/client_identity.mjs.map +1 -0
  42. package/dist/database.mjs +23 -8
  43. package/dist/database.mjs.map +1 -1
  44. package/dist/database_action.mjs +71 -0
  45. package/dist/database_action.mjs.map +1 -0
  46. package/dist/database_scope.mjs +11 -0
  47. package/dist/database_scope.mjs.map +1 -1
  48. package/dist/endpoint.mjs +11 -7
  49. package/dist/endpoint.mjs.map +1 -1
  50. package/dist/execution_failure.mjs +30 -0
  51. package/dist/execution_failure.mjs.map +1 -0
  52. package/dist/execution_identity.mjs +103 -0
  53. package/dist/execution_identity.mjs.map +1 -0
  54. package/dist/execution_log.mjs +47 -0
  55. package/dist/execution_log.mjs.map +1 -0
  56. package/dist/execution_runtime.mjs +201 -0
  57. package/dist/execution_runtime.mjs.map +1 -0
  58. package/dist/execution_worker.mjs +41 -0
  59. package/dist/execution_worker.mjs.map +1 -0
  60. package/dist/executor.mjs +384 -0
  61. package/dist/executor.mjs.map +1 -0
  62. package/dist/group.mjs +49 -16
  63. package/dist/group.mjs.map +1 -1
  64. package/dist/http_failure.mjs +9 -2
  65. package/dist/http_failure.mjs.map +1 -1
  66. package/dist/job_configuration.mjs +37 -0
  67. package/dist/job_configuration.mjs.map +1 -0
  68. package/dist/job_context.mjs +61 -0
  69. package/dist/job_context.mjs.map +1 -0
  70. package/dist/library.mjs +31 -0
  71. package/dist/library.mjs.map +1 -1
  72. package/dist/longpoll_broker.mjs +9 -8
  73. package/dist/longpoll_broker.mjs.map +1 -1
  74. package/dist/longpoll_options.mjs +8 -7
  75. package/dist/longpoll_options.mjs.map +1 -1
  76. package/dist/longpoll_session.mjs +11 -10
  77. package/dist/longpoll_session.mjs.map +1 -1
  78. package/dist/middleware.mjs +1 -1
  79. package/dist/middleware.mjs.map +1 -1
  80. package/dist/module_loader.mjs +44 -0
  81. package/dist/module_loader.mjs.map +1 -0
  82. package/dist/options.mjs +41 -4
  83. package/dist/options.mjs.map +1 -1
  84. package/dist/origin.mjs +87 -0
  85. package/dist/origin.mjs.map +1 -0
  86. package/dist/policy.mjs +121 -0
  87. package/dist/policy.mjs.map +1 -0
  88. package/dist/postgres_adapter.mjs +15 -3
  89. package/dist/postgres_adapter.mjs.map +1 -1
  90. package/dist/postgres_worker.mjs +82 -19
  91. package/dist/postgres_worker.mjs.map +1 -1
  92. package/dist/queue_provider.mjs +52 -0
  93. package/dist/queue_provider.mjs.map +1 -0
  94. package/dist/response.mjs +1 -1
  95. package/dist/response.mjs.map +1 -1
  96. package/dist/route_info.mjs +1 -1
  97. package/dist/route_info.mjs.map +1 -1
  98. package/dist/routes.mjs +69 -18
  99. package/dist/routes.mjs.map +1 -1
  100. package/dist/runtime.mjs +287 -132
  101. package/dist/runtime.mjs.map +1 -1
  102. package/dist/server.mjs +88 -81
  103. package/dist/server.mjs.map +1 -1
  104. package/dist/server_context.mjs +21 -9
  105. package/dist/server_context.mjs.map +1 -1
  106. package/dist/static_files.mjs +5 -4
  107. package/dist/static_files.mjs.map +1 -1
  108. package/dist/token.mjs +34 -7
  109. package/dist/token.mjs.map +1 -1
  110. package/dist/tokens.mjs +11 -2
  111. package/dist/tokens.mjs.map +1 -1
  112. package/dist/worker.mjs +7 -6
  113. package/dist/worker.mjs.map +1 -1
  114. package/docs/jobs.md +123 -0
  115. package/docs/security.md +420 -0
  116. package/examples/security/README.md +160 -0
  117. package/examples/security/deploy.xml +12 -0
  118. package/examples/security/handlers.lango +610 -0
  119. package/examples/security/package.json +19 -0
  120. package/examples/security/passwords.lango +61 -0
  121. package/examples/security/routes.xml +14 -0
  122. package/examples/security/schema.lango +91 -0
  123. package/examples/security/setup.lango +30 -0
  124. package/package.json +14 -6
  125. package/src/builder.lango +22 -0
  126. package/src/client_identity.lango +184 -0
  127. package/src/database.lango +15 -4
  128. package/src/database_action.lango +30 -0
  129. package/src/database_scope.lango +7 -0
  130. package/src/endpoint.lango +12 -5
  131. package/src/execution_failure.lango +14 -0
  132. package/src/execution_identity.lango +71 -0
  133. package/src/execution_log.lango +28 -0
  134. package/src/execution_runtime.lango +135 -0
  135. package/src/execution_worker.lango +32 -0
  136. package/src/executor.lango +284 -0
  137. package/src/group.lango +36 -21
  138. package/src/http_failure.lango +9 -5
  139. package/src/job_configuration.lango +29 -0
  140. package/src/job_context.lango +44 -0
  141. package/src/library.lango +21 -0
  142. package/src/longpoll_options.lango +11 -5
  143. package/src/middleware.lango +1 -1
  144. package/src/module_loader.lango +25 -0
  145. package/src/options.lango +41 -2
  146. package/src/origin.lango +56 -0
  147. package/src/policy.lango +84 -0
  148. package/src/postgres_adapter.lango +12 -0
  149. package/src/postgres_worker.lango +54 -3
  150. package/src/queue_provider.lango +30 -0
  151. package/src/response.lango +1 -1
  152. package/src/route_info.lango +2 -0
  153. package/src/routes.lango +74 -15
  154. package/src/runtime.lango +173 -94
  155. package/src/server.lango +9 -2
  156. package/src/server_context.lango +10 -2
  157. package/src/token.lango +26 -5
  158. package/src/tokens.lango +10 -3
@@ -0,0 +1,91 @@
1
+ import js "node:crypto" as crypto
2
+ import js global RegExp
3
+ import "./passwords"
4
+ hashPassword(password)
5
+
6
+ export initialize()
7
+ export createUser(username, password, admin = false)
8
+
9
+ initialize()
10
+ users = SQL
11
+ create table if not exists security_users (
12
+ id text primary key,
13
+ username text not null unique,
14
+ password_hash text not null,
15
+ auth_version integer not null default 1,
16
+ is_admin integer not null default 0,
17
+ banned integer not null default 0
18
+ )
19
+ users.execute()
20
+ clients = SQL
21
+ create table if not exists security_clients (
22
+ client_id text primary key,
23
+ current_grant text,
24
+ created_at bigint not null,
25
+ last_seen bigint not null,
26
+ registered_ip text,
27
+ registered_user_agent text,
28
+ last_ip text,
29
+ last_user_agent text,
30
+ guest_used integer not null default 0
31
+ )
32
+ clients.execute()
33
+ grants = SQL
34
+ create table if not exists security_grants (
35
+ id text primary key,
36
+ client_id text not null references security_clients(client_id),
37
+ user_id text not null references security_users(id),
38
+ user_version integer not null,
39
+ created_at bigint not null,
40
+ last_active bigint not null,
41
+ expires_at bigint not null,
42
+ authenticated_at bigint not null,
43
+ remember integer not null,
44
+ revoked integer not null default 0
45
+ )
46
+ grants.execute()
47
+ audit = SQL
48
+ create table if not exists security_audit (
49
+ id text primary key,
50
+ occurred_at bigint not null,
51
+ request_id text not null,
52
+ client_id text not null,
53
+ user_id text,
54
+ grant_hash text,
55
+ event text not null,
56
+ target_id text,
57
+ peer_ip text,
58
+ user_agent text
59
+ )
60
+ audit.execute()
61
+ attempts = SQL
62
+ create table if not exists security_limits (
63
+ bucket text primary key,
64
+ started_at bigint not null,
65
+ hits integer not null
66
+ )
67
+ attempts.execute()
68
+ index = SQL
69
+ create index if not exists security_grants_user on security_grants(user_id, client_id)
70
+ index.execute()
71
+ return null
72
+
73
+ createUser(username, password, admin = false)
74
+ pattern = new RegExp("^[a-z0-9_.@+-]{3,128}$")
75
+ name = null
76
+ if is_string(username)
77
+ name = username.trim().toLowerCase()
78
+ if name == null or !pattern.test(name)
79
+ throw "Username must contain 3 to 128 supported ASCII characters"
80
+ id = crypto/randomUUID()
81
+ record = SQL
82
+ insert into security_users (id, username, password_hash, is_admin)
83
+ values (:id, :username, :hash, :admin)
84
+ record.id = id
85
+ record.username = name
86
+ record.hash = hashPassword(password)
87
+ record.admin = 0
88
+ if admin
89
+ record.admin = 1
90
+ record.execute()
91
+ return id
@@ -0,0 +1,30 @@
1
+ import js "@lango-project/lango-js/database" as database
2
+ import js "node:fs" as fs
3
+ import js "node:path" as path
4
+ import js global process
5
+ import "./schema"
6
+ initialize()
7
+ createUser(username, password, admin = false)
8
+
9
+ export main(args)
10
+
11
+ main(args)
12
+ if args.length < 1 or args.length > 3
13
+ throw "Usage: setup <sqlite-file> [<username> [admin]] (password from SECURITY_SETUP_PASSWORD)"
14
+ if args.length == 3 and args[2] != "admin"
15
+ throw "Only the optional admin role is supported"
16
+ fs/mkdirSync(path/dirname(path/resolve(args[0])), {
17
+ recursive: true
18
+ })
19
+ adapter = database/createSqliteAdapter(args[0])
20
+ context db = adapter
21
+ try
22
+ initialize()
23
+ if args.length == 1
24
+ println("Initialized security schema")
25
+ else
26
+ id = createUser(args[1], process.env.SECURITY_SETUP_PASSWORD, args[2] == "admin")
27
+ println("Created user ${id}")
28
+ finally
29
+ adapter.close()
30
+ return null
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lango-project/lango-server",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "A small JSON HTTP server for Lango applications.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -22,16 +22,24 @@
22
22
  "src/*.lua",
23
23
  "README.md",
24
24
  "LICENSE",
25
- "NOTICE"
25
+ "NOTICE",
26
+ "docs/**",
27
+ "examples/security/*.lango",
28
+ "examples/security/*.xml",
29
+ "examples/security/package.json",
30
+ "examples/security/README.md"
26
31
  ],
27
32
  "scripts": {
28
- "build": "lango run tools/clean.lango && lango build src/library.lango --out dist/library.mjs && lango build src/server.lango --out dist/cli/server.mjs --executable && lango build src/worker.lango --out dist/worker.mjs && lango build examples/application/handlers.lango --out examples/application/dist/handlers.mjs && lango build src/postgres_worker.lango --out dist/postgres_worker.mjs && lango build examples/database/handlers.lango --out examples/database/dist/handlers.mjs",
29
- "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 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",
33
+ "build": "lango run tools/clean.lango && lango build src/library.lango --out dist/library.mjs && lango build src/server.lango --out dist/cli/server.mjs --executable && lango build src/execution_worker.lango --out dist/execution_worker.mjs && lango build src/worker.lango --out dist/worker.mjs && lango build examples/application/handlers.lango --out examples/application/dist/handlers.mjs && lango build src/postgres_worker.lango --out dist/postgres_worker.mjs && lango build examples/database/handlers.lango --out examples/database/dist/handlers.mjs && lango build examples/security/handlers.lango --out examples/security/dist/handlers.mjs && lango build examples/security/setup.lango --out examples/security/dist/setup.mjs --executable",
34
+ "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",
30
35
  "start": "node dist/cli/server.mjs examples/application",
31
36
  "prepack": "npm run build",
32
37
  "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",
33
38
  "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",
34
- "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"
39
+ "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
+ "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
+ "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",
42
+ "test:executor": "npm run build && lango build src/test/execution_handlers.lango --out .test-output/execution_handlers.mjs && lango test src/test/executor.lango --build-dir .test-output/executor"
35
43
  },
36
44
  "dependencies": {
37
45
  "jsonwebtoken": "^9.0.3",
@@ -41,6 +49,6 @@
41
49
  "serve-static": "^2.2.1"
42
50
  },
43
51
  "devDependencies": {
44
- "@lango-project/lango-js": "^0.1.17"
52
+ "@lango-project/lango-js": "^0.1.18"
45
53
  }
46
54
  }
package/src/builder.lango CHANGED
@@ -6,14 +6,20 @@ import "./group"
6
6
  class Group
7
7
  import "./options"
8
8
  options(root, supplied = null)
9
+ readDeployment(directory, credentials = true)
9
10
  import "./server"
10
11
  class Server
12
+ import "./queue_provider"
13
+ queueProvider(root, spec)
11
14
 
12
15
  export class Builder(root = null)
13
16
  methods
14
17
  configure(settings)
18
+ loadDeployment()
15
19
  addMiddleware(name, spec)
20
+ provideQueue(spec)
16
21
  endpoint(spec)
22
+ job(spec)
17
23
  longpoll(spec)
18
24
  group(spec)
19
25
  include(spec)
@@ -25,6 +31,7 @@ Builder(root = null)
25
31
  root = process.cwd()
26
32
  @root = path/resolve(root)
27
33
  @settings = {}
34
+ @queueProvider = null
28
35
  @routes = new Routes(@root)
29
36
 
30
37
  Builder:configure(settings)
@@ -32,14 +39,27 @@ Builder:configure(settings)
32
39
  @settings[key] = value
33
40
  return @this
34
41
 
42
+ Builder:loadDeployment()
43
+ return configure(readDeployment(@root))
44
+
35
45
  Builder:addMiddleware(name, spec)
36
46
  @routes.addMiddleware(name, spec)
37
47
  return @this
38
48
 
49
+ Builder:provideQueue(spec)
50
+ if @queueProvider != null
51
+ throw "Queue provider is already configured"
52
+ @queueProvider = queueProvider(@root, spec)
53
+ return @this
54
+
39
55
  Builder:endpoint(spec)
40
56
  @routes.endpoint(spec)
41
57
  return @this
42
58
 
59
+ Builder:job(spec)
60
+ @routes.job(spec)
61
+ return @this
62
+
43
63
  Builder:longpoll(spec)
44
64
  @routes.longpoll(spec)
45
65
  return @this
@@ -59,6 +79,8 @@ Builder:build()
59
79
  return new Server(null, {
60
80
  settings: options(@root, @settings)
61
81
  routes: @routes.definitions()
82
+ jobs: @routes.jobs()
62
83
  events: @routes.events()
63
84
  middlewares: @routes.middlewares()
85
+ queueProvider: @queueProvider
64
86
  })
@@ -0,0 +1,184 @@
1
+ import js "node:crypto" as crypto
2
+ import js global Date
3
+ import js global Object
4
+ import js global Number
5
+ import js global RegExp
6
+ import js global Buffer
7
+
8
+ export clientOptions(spec, database, origin)
9
+ export class ClientIdentity(settings, database)
10
+ methods
11
+ initialize()
12
+ begin(claims, tokens)
13
+ publish(identity, claims, response, tokens)
14
+
15
+ clientOptions(spec, database, origin)
16
+ if spec == null
17
+ return null
18
+ if !is_object(spec) or is_array(spec)
19
+ throw "Client configuration must be an object"
20
+ for Object/keys(spec) as name
21
+ if name != "maxAgeSeconds"
22
+ throw "Unknown client option: ${name}"
23
+ if database == null
24
+ throw "Managed client identity requires a database"
25
+ if database.type == "sqlite" and database.file == ":memory:"
26
+ throw "Managed client identity requires persistent database storage"
27
+ if origin == null or !origin.required or !origin.url.startsWith("https:")
28
+ throw "Managed client identity requires a required HTTPS origin"
29
+ lifetime = spec.maxAgeSeconds
30
+ if lifetime == null
31
+ lifetime = 2592000
32
+ if is_string(lifetime)
33
+ lifetime = Number(lifetime)
34
+ if !Number/isSafeInteger(lifetime) or lifetime < 1 or lifetime > 31536000
35
+ throw "Client maxAgeSeconds must be between 1 and 31536000"
36
+ return {
37
+ maxAgeSeconds: lifetime
38
+ }
39
+
40
+ ClientIdentity(settings, database)
41
+ @settings = settings
42
+ @database = database
43
+
44
+ ClientIdentity:initialize()
45
+ context db = @database.scope()
46
+ try
47
+ start_trans()
48
+ if db.parameterStyle == "postgresql"
49
+ lock = SQL
50
+ select pg_advisory_xact_lock(1818324591, 1)
51
+ lock.execute()
52
+ row = SQL
53
+ create table if not exists _lango_clients (
54
+ client_id text primary key,
55
+ secret_hash text not null unique,
56
+ expires_at bigint not null
57
+ )
58
+ row.execute()
59
+ commit_trans()
60
+ finally
61
+ db.finish()
62
+ return null
63
+
64
+ ClientIdentity:begin(claims, tokens)
65
+ context response
66
+ value = readCookie()
67
+ if value == null and claims != null
68
+ response.reject(401, "ClientProofRequired")
69
+ hash = null
70
+ row = null
71
+ if value == null
72
+ value = clientSecret()
73
+ claims = tokens.create()
74
+ hash = clientDigest(value)
75
+ claims.clientProof = hash
76
+ return {
77
+ claims: claims
78
+ value: value
79
+ hash: hash
80
+ fresh: true
81
+ restored: false
82
+ rotate: false
83
+ closed: false
84
+ }
85
+ hash = clientDigest(value)
86
+ row = SQL
87
+ select client_id from _lango_clients where secret_hash = :hash and expires_at > :now
88
+ row.hash = hash
89
+ row.now = Date/now()
90
+ row.execute()
91
+ if !row.next()
92
+ response.reject(401, "ClientCookieRejected")
93
+ restored = claims == null
94
+ if restored
95
+ claims = tokens.create(row.client_id)
96
+ claims.clientProof = hash
97
+ if claims.clientId != row.client_id or !sameProof(claims.clientProof, hash)
98
+ response.reject(401, "ClientProofRequired")
99
+ return {
100
+ claims: claims
101
+ value: value
102
+ hash: hash
103
+ fresh: false
104
+ restored: restored
105
+ rotate: false
106
+ closed: false
107
+ }
108
+
109
+ ClientIdentity:publish(identity, claims, response, tokens)
110
+ value = identity.value
111
+ if identity.rotate
112
+ value = clientSecret()
113
+ hash = clientDigest(value)
114
+ claims.clientProof = hash
115
+ encoded = tokens.sign(claims)
116
+ context db = @database.scope()
117
+ row = null
118
+ try
119
+ if identity.fresh
120
+ row = SQL
121
+ insert into _lango_clients (client_id, secret_hash, expires_at)
122
+ values (:id, :hash, :expires)
123
+ row.id = claims.clientId
124
+ row.hash = hash
125
+ row.expires = Date/now() + @settings.maxAgeSeconds * 1000
126
+ row.execute()
127
+ else
128
+ row = SQL
129
+ update _lango_clients set secret_hash = :replacement, expires_at = :expires
130
+ where client_id = :id and secret_hash = :previous and expires_at > :now
131
+ returning client_id
132
+ row.id = claims.clientId
133
+ row.previous = identity.hash
134
+ row.replacement = hash
135
+ row.now = Date/now()
136
+ row.expires = Date/now() + @settings.maxAgeSeconds * 1000
137
+ row.execute()
138
+ if !row.next()
139
+ response.reject(401, "ClientProofRequired")
140
+ response.header("Set-Cookie", "__Host-lango-client=${value}; Path=/; Secure; HttpOnly; SameSite=Strict; Max-Age=${@settings.maxAgeSeconds}")
141
+ finally
142
+ db.finish()
143
+ identity.closed = true
144
+ return encoded
145
+
146
+ readCookie()
147
+ context request
148
+ context response
149
+ headers = request.headers
150
+ header = headers.cookie
151
+ if header == null
152
+ return null
153
+ if !is_string(header) or header.length > 8192
154
+ response.reject(400, "InvalidCookie")
155
+ found = null
156
+ for header.split(";") as part
157
+ pair = part.trim()
158
+ index = pair.indexOf("=")
159
+ if index >= 0 and pair.slice(0, index) == "__Host-lango-client"
160
+ if found != null
161
+ response.reject(400, "InvalidCookie")
162
+ found = pair.slice(index + 1)
163
+ if found != null
164
+ pattern = new RegExp("^[a-f0-9]{64}$")
165
+ if !pattern.test(found)
166
+ response.reject(400, "InvalidCookie")
167
+ return found
168
+
169
+ clientSecret()
170
+ bytes = crypto/randomBytes(32)
171
+ return bytes.toString("hex")
172
+
173
+ clientDigest(value)
174
+ hash = crypto/createHash("sha256")
175
+ hash.update(value)
176
+ return hash.digest("hex")
177
+
178
+ sameProof(left, right)
179
+ pattern = new RegExp("^[a-f0-9]{64}$")
180
+ if !is_string(left) or !pattern.test(left)
181
+ return false
182
+ first = Buffer/from(left, "hex")
183
+ second = Buffer/from(right, "hex")
184
+ return crypto/timingSafeEqual(first, second)
@@ -1,3 +1,5 @@
1
+ import "./client_identity"
2
+ class ClientIdentity
1
3
  import js global Promise
2
4
  import "./database_scope"
3
5
  class DatabaseScope
@@ -6,7 +8,7 @@ import "./sqlite_adapter"
6
8
  import "./postgres_adapter"
7
9
  class PostgresAdapter
8
10
 
9
- export prepareDatabase(settings)
11
+ export prepareDatabase(settings, root = null, client = null)
10
12
 
11
13
  export class Database(settings, root = null)
12
14
  methods
@@ -56,11 +58,20 @@ Database:close()
56
58
  @adapter = null
57
59
  return null
58
60
 
59
- prepareDatabase(settings)
60
- if settings == null or settings.type != "sqlite" or settings.file == ":memory:"
61
+ prepareDatabase(settings, root = null, client = null)
62
+ if settings == null
61
63
  return Promise/resolve(null)
62
- database = new Database(settings)
64
+ if client == null and (settings.type != "sqlite" or settings.file == ":memory:")
65
+ return Promise/resolve(null)
66
+ database = new Database(settings, root)
63
67
  return chain database.open()
68
+ then(ignored)
69
+ capture database
70
+ capture client
71
+ if client != null
72
+ identity = new ClientIdentity(client, database)
73
+ identity.initialize()
74
+ return null
64
75
  finally
65
76
  capture database
66
77
  database.close()
@@ -0,0 +1,30 @@
1
+ import "./database"
2
+ class Database
3
+ import "./job_configuration"
4
+ readDatabaseConfiguration(directory)
5
+ import js "node:path" as path
6
+ import js global Promise
7
+
8
+ export withDatabase(directory, action)
9
+
10
+ withDatabase(directory, action)
11
+ root = path/resolve(directory)
12
+ database = new Database(readDatabaseConfiguration(root), root)
13
+ return chain database.open()
14
+ then(ignored)
15
+ capture database
16
+ context db = database.scope()
17
+ return chain Promise/resolve(null)
18
+ then(ignored)
19
+ capture action
20
+ return action()
21
+ then(result)
22
+ if db != null and db.finish()
23
+ throw "UnclosedTransaction"
24
+ return result
25
+ finally
26
+ if db != null
27
+ db.finish()
28
+ finally
29
+ capture database
30
+ database.close()
@@ -7,6 +7,7 @@ export class DatabaseScope(adapter)
7
7
  parameterStyle
8
8
  methods
9
9
  execute(sql, parameters)
10
+ invoke(spec, input)
10
11
  begin()
11
12
  commit()
12
13
  rollback()
@@ -22,6 +23,12 @@ DatabaseScope:execute(sql, parameters)
22
23
  requireOpen()
23
24
  return @adapter.execute(sql, parameters)
24
25
 
26
+ DatabaseScope:invoke(spec, input)
27
+ requireOpen()
28
+ if @parameterStyle != "postgresql"
29
+ throw "Database extensions require PostgreSQL"
30
+ return @adapter.invoke(spec, input)
31
+
25
32
  DatabaseScope:begin()
26
33
  requireOpen()
27
34
  return @adapter.begin()
@@ -1,3 +1,5 @@
1
+ import "./policy"
2
+ policyOptions(spec)
1
3
  import "./route_pattern"
2
4
  routePattern(path)
3
5
  import "./middleware"
@@ -9,6 +11,10 @@ export class Endpoint(spec)
9
11
  module
10
12
  handler
11
13
  auth
14
+ policy
15
+ reauthSeconds
16
+ reauthExplicit
17
+ legacyAuth
12
18
  middleware
13
19
 
14
20
  Endpoint(spec)
@@ -22,8 +28,9 @@ Endpoint(spec)
22
28
  @middleware = spec.middleware
23
29
  if @middleware != null
24
30
  middlewareName(@middleware)
25
- @auth = spec.auth
26
- if @auth == null
27
- @auth = "login"
28
- if !is_string(@auth) or @auth == "" or @auth.includes(",")
29
- throw "Endpoint auth must name one permission"
31
+ selected = policyOptions(spec)
32
+ @policy = selected.name
33
+ @auth = selected.name
34
+ @reauthSeconds = selected.reauthSeconds
35
+ @reauthExplicit = selected.explicit
36
+ @legacyAuth = selected.legacy
@@ -0,0 +1,14 @@
1
+ import js global RegExp
2
+
3
+ export class ExecutionFailure(code)
4
+ properties
5
+ code?
6
+
7
+ ExecutionFailure(code)
8
+ pattern = new RegExp("^[A-Za-z][A-Za-z0-9_]{0,63}$")
9
+ if !is_string(code) or !pattern.test(code)
10
+ throw "Execution rejection requires an error code"
11
+ @code = code
12
+
13
+ ExecutionFailure:code?
14
+ return @code
@@ -0,0 +1,71 @@
1
+ import "./execution_failure"
2
+ class ExecutionFailure
3
+ import "./token"
4
+ class Token
5
+ import js global Object
6
+ import js global Date
7
+ import js global Number
8
+
9
+ export executionSource(source)
10
+ export executionToken(identity, source, route)
11
+
12
+ executionSource(source)
13
+ if source == null or !is_object(source) or is_array(source)
14
+ throw "Execution source must be a map"
15
+ allowed = ["kind", "clientId", "userId", "grantId", "identity"]
16
+ for source as key: value
17
+ if !allowed.includes(key)
18
+ throw "Unknown execution source field: ${key}"
19
+ if key != "kind" and (!is_string(value) or value.trim() == "")
20
+ throw "Execution source references must be nonempty strings"
21
+ switch source.kind
22
+ case "user"
23
+ if source.clientId == null or source.identity != null
24
+ throw "User execution source requires clientId and cannot select a system identity"
25
+ case "system"
26
+ if source.identity == null or source.clientId != null or source.userId != null or source.grantId != null
27
+ throw "System execution source requires only a configured identity"
28
+ else
29
+ throw "Execution source kind must be user or system"
30
+ return from_json(to_json(source))
31
+
32
+ executionToken(identity, source, route)
33
+ if identity == null or identity == false
34
+ throw new ExecutionFailure("IdentityRejected")
35
+ if !is_object(identity) or is_array(identity)
36
+ throw "Identity provider must return a map or null"
37
+ allowed = ["clientId", "userId", "grantId", "identity", "policies", "authenticatedAt"]
38
+ for identity as key: value
39
+ if !allowed.includes(key)
40
+ throw "Unknown execution identity field: ${key}"
41
+ if !is_array(identity.policies)
42
+ throw "Execution identity requires a policies array"
43
+ if source.kind == "user"
44
+ for ["clientId", "userId", "grantId"] as key
45
+ if identity[key] != source[key]
46
+ throw new ExecutionFailure("IdentityChanged")
47
+ if identity.identity != null
48
+ throw new ExecutionFailure("IdentityChanged")
49
+ else
50
+ if identity.identity != source.identity or identity.clientId != null or identity.userId != null or identity.grantId != null
51
+ throw new ExecutionFailure("IdentityChanged")
52
+ now = Date/now()
53
+ stamp = identity.authenticatedAt
54
+ if stamp != null and (!Number/isSafeInteger(stamp) or stamp < 0 or stamp > now)
55
+ throw "Execution identity authenticatedAt must be a real past timestamp"
56
+ claims = {
57
+ clientId: identity.clientId
58
+ userId: identity.userId
59
+ grantId: identity.grantId
60
+ identity: identity.identity
61
+ auth: ""
62
+ authenticatedAt: stamp
63
+ }
64
+ token = new Token(claims)
65
+ for identity.policies as policy
66
+ token.addPolicy(policy)
67
+ if route.policy != "anonymous" and !token.hasPolicy(route.policy)
68
+ throw new ExecutionFailure("Forbidden")
69
+ if route.reauthSeconds > 0 and (stamp == null or now - stamp >= route.reauthSeconds * 1000)
70
+ throw new ExecutionFailure("ReauthenticationRequired")
71
+ return new Token(token.snapshot(), true)
@@ -0,0 +1,28 @@
1
+ export class ExecutionLog(sink, job)
2
+ properties
3
+ verbose?
4
+ methods
5
+ debug(message)
6
+ info(message)
7
+ warn(message)
8
+ err(message)
9
+
10
+ ExecutionLog(sink, job)
11
+ @sink = sink
12
+ source = job.source?
13
+ @prefix = "[jobId=${job.id?}] path=${job.path?} queue=${job.queue?} attempt=${job.attempt?} clientId=${source.clientId} userId=${source.userId} grantId=${source.grantId} identity=${source.identity}"
14
+
15
+ ExecutionLog:verbose?
16
+ return @sink.verbose?
17
+
18
+ ExecutionLog:debug(message)
19
+ return @sink.debug("${@prefix} ${message}")
20
+
21
+ ExecutionLog:info(message)
22
+ return @sink.info("${@prefix} ${message}")
23
+
24
+ ExecutionLog:warn(message)
25
+ return @sink.warn("${@prefix} ${message}")
26
+
27
+ ExecutionLog:err(message)
28
+ return @sink.err("${@prefix} ${message}")