@sixb/server 0.0.1

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 (216) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +123 -0
  3. package/dist/auth/access-token-boundary.d.ts +23 -0
  4. package/dist/auth/access-token-boundary.d.ts.map +1 -0
  5. package/dist/auth/application-access.d.ts +4 -0
  6. package/dist/auth/application-access.d.ts.map +1 -0
  7. package/dist/auth/browser-origin.d.ts +62 -0
  8. package/dist/auth/browser-origin.d.ts.map +1 -0
  9. package/dist/auth/csrf.d.ts +2 -0
  10. package/dist/auth/csrf.d.ts.map +1 -0
  11. package/dist/auth/guard.d.ts +35 -0
  12. package/dist/auth/guard.d.ts.map +1 -0
  13. package/dist/auth/public-routes.d.ts +8 -0
  14. package/dist/auth/public-routes.d.ts.map +1 -0
  15. package/dist/auth/responses.d.ts +11 -0
  16. package/dist/auth/responses.d.ts.map +1 -0
  17. package/dist/auth/return-to.d.ts +3 -0
  18. package/dist/auth/return-to.d.ts.map +1 -0
  19. package/dist/auth/scope.d.ts +43 -0
  20. package/dist/auth/scope.d.ts.map +1 -0
  21. package/dist/auth/session-activity.d.ts +4 -0
  22. package/dist/auth/session-activity.d.ts.map +1 -0
  23. package/dist/auth/session-cookies.d.ts +12 -0
  24. package/dist/auth/session-cookies.d.ts.map +1 -0
  25. package/dist/files/content.d.ts +141 -0
  26. package/dist/files/content.d.ts.map +1 -0
  27. package/dist/index.d.ts +3 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +11522 -0
  30. package/dist/index.js.map +78 -0
  31. package/dist/openapi/security.d.ts +26 -0
  32. package/dist/openapi/security.d.ts.map +1 -0
  33. package/dist/openapi/tags.d.ts +151 -0
  34. package/dist/openapi/tags.d.ts.map +1 -0
  35. package/dist/registerRoutes.d.ts +31 -0
  36. package/dist/registerRoutes.d.ts.map +1 -0
  37. package/dist/routes/action-runs.d.ts +244 -0
  38. package/dist/routes/action-runs.d.ts.map +1 -0
  39. package/dist/routes/actions.d.ts +183 -0
  40. package/dist/routes/actions.d.ts.map +1 -0
  41. package/dist/routes/agent-api-gateway.d.ts +4 -0
  42. package/dist/routes/agent-api-gateway.d.ts.map +1 -0
  43. package/dist/routes/agents.d.ts +1061 -0
  44. package/dist/routes/agents.d.ts.map +1 -0
  45. package/dist/routes/auth.d.ts +1366 -0
  46. package/dist/routes/auth.d.ts.map +1 -0
  47. package/dist/routes/connectors.d.ts +108 -0
  48. package/dist/routes/connectors.d.ts.map +1 -0
  49. package/dist/routes/datasets.d.ts +339 -0
  50. package/dist/routes/datasets.d.ts.map +1 -0
  51. package/dist/routes/events.d.ts +116 -0
  52. package/dist/routes/events.d.ts.map +1 -0
  53. package/dist/routes/files.d.ts +340 -0
  54. package/dist/routes/files.d.ts.map +1 -0
  55. package/dist/routes/links.d.ts +175 -0
  56. package/dist/routes/links.d.ts.map +1 -0
  57. package/dist/routes/logs.d.ts +88 -0
  58. package/dist/routes/logs.d.ts.map +1 -0
  59. package/dist/routes/objects.d.ts +450 -0
  60. package/dist/routes/objects.d.ts.map +1 -0
  61. package/dist/routes/ontology.d.ts +240 -0
  62. package/dist/routes/ontology.d.ts.map +1 -0
  63. package/dist/routes/pipelines.d.ts +399 -0
  64. package/dist/routes/pipelines.d.ts.map +1 -0
  65. package/dist/routes/project.d.ts +56 -0
  66. package/dist/routes/project.d.ts.map +1 -0
  67. package/dist/routes/projections.d.ts +916 -0
  68. package/dist/routes/projections.d.ts.map +1 -0
  69. package/dist/routes/rules.d.ts +165 -0
  70. package/dist/routes/rules.d.ts.map +1 -0
  71. package/dist/routes/status.d.ts +81 -0
  72. package/dist/routes/status.d.ts.map +1 -0
  73. package/dist/routes/syncs.d.ts +294 -0
  74. package/dist/routes/syncs.d.ts.map +1 -0
  75. package/dist/routes/telemetry.d.ts +241 -0
  76. package/dist/routes/telemetry.d.ts.map +1 -0
  77. package/dist/routes/webhook-runs.d.ts +89 -0
  78. package/dist/routes/webhook-runs.d.ts.map +1 -0
  79. package/dist/routes/webhooks.d.ts +60 -0
  80. package/dist/routes/webhooks.d.ts.map +1 -0
  81. package/dist/routes/workflows.d.ts +973 -0
  82. package/dist/routes/workflows.d.ts.map +1 -0
  83. package/dist/routes/ws/agents.d.ts +99 -0
  84. package/dist/routes/ws/agents.d.ts.map +1 -0
  85. package/dist/routes/ws/events.d.ts +89 -0
  86. package/dist/routes/ws/events.d.ts.map +1 -0
  87. package/dist/routes/ws/index.d.ts +31 -0
  88. package/dist/routes/ws/index.d.ts.map +1 -0
  89. package/dist/routes/ws/log-subscription-hub.d.ts +47 -0
  90. package/dist/routes/ws/log-subscription-hub.d.ts.map +1 -0
  91. package/dist/routes/ws/logs.d.ts +110 -0
  92. package/dist/routes/ws/logs.d.ts.map +1 -0
  93. package/dist/schemas/actions.d.ts +644 -0
  94. package/dist/schemas/actions.d.ts.map +1 -0
  95. package/dist/schemas/agents.d.ts +3157 -0
  96. package/dist/schemas/agents.d.ts.map +1 -0
  97. package/dist/schemas/auth.d.ts +2023 -0
  98. package/dist/schemas/auth.d.ts.map +1 -0
  99. package/dist/schemas/common.d.ts +30 -0
  100. package/dist/schemas/common.d.ts.map +1 -0
  101. package/dist/schemas/connectors.d.ts +82 -0
  102. package/dist/schemas/connectors.d.ts.map +1 -0
  103. package/dist/schemas/datasets.d.ts +744 -0
  104. package/dist/schemas/datasets.d.ts.map +1 -0
  105. package/dist/schemas/event-payloads.d.ts +477 -0
  106. package/dist/schemas/event-payloads.d.ts.map +1 -0
  107. package/dist/schemas/events.d.ts +665 -0
  108. package/dist/schemas/events.d.ts.map +1 -0
  109. package/dist/schemas/files.d.ts +241 -0
  110. package/dist/schemas/files.d.ts.map +1 -0
  111. package/dist/schemas/links.d.ts +90 -0
  112. package/dist/schemas/links.d.ts.map +1 -0
  113. package/dist/schemas/logs.d.ts +231 -0
  114. package/dist/schemas/logs.d.ts.map +1 -0
  115. package/dist/schemas/objects.d.ts +288 -0
  116. package/dist/schemas/objects.d.ts.map +1 -0
  117. package/dist/schemas/ontology.d.ts +778 -0
  118. package/dist/schemas/ontology.d.ts.map +1 -0
  119. package/dist/schemas/pipelines.d.ts +1373 -0
  120. package/dist/schemas/pipelines.d.ts.map +1 -0
  121. package/dist/schemas/project.d.ts +9 -0
  122. package/dist/schemas/project.d.ts.map +1 -0
  123. package/dist/schemas/projections.d.ts +6992 -0
  124. package/dist/schemas/projections.d.ts.map +1 -0
  125. package/dist/schemas/rules.d.ts +204 -0
  126. package/dist/schemas/rules.d.ts.map +1 -0
  127. package/dist/schemas/status.d.ts +189 -0
  128. package/dist/schemas/status.d.ts.map +1 -0
  129. package/dist/schemas/syncs.d.ts +538 -0
  130. package/dist/schemas/syncs.d.ts.map +1 -0
  131. package/dist/schemas/telemetry.d.ts +265 -0
  132. package/dist/schemas/telemetry.d.ts.map +1 -0
  133. package/dist/schemas/webhook-runs.d.ts +169 -0
  134. package/dist/schemas/webhook-runs.d.ts.map +1 -0
  135. package/dist/schemas/workflows.d.ts +1720 -0
  136. package/dist/schemas/workflows.d.ts.map +1 -0
  137. package/dist/server.d.ts +64 -0
  138. package/dist/server.d.ts.map +1 -0
  139. package/dist/tsconfig.json +5 -0
  140. package/dist/utils/http.d.ts +23 -0
  141. package/dist/utils/http.d.ts.map +1 -0
  142. package/dist/utils/request-body.d.ts +15 -0
  143. package/dist/utils/request-body.d.ts.map +1 -0
  144. package/dist/utils/ws.d.ts +10 -0
  145. package/dist/utils/ws.d.ts.map +1 -0
  146. package/package.json +68 -0
  147. package/src/auth/access-token-boundary.ts +68 -0
  148. package/src/auth/application-access.ts +16 -0
  149. package/src/auth/browser-origin.ts +367 -0
  150. package/src/auth/csrf.ts +1 -0
  151. package/src/auth/guard.ts +169 -0
  152. package/src/auth/public-routes.ts +87 -0
  153. package/src/auth/responses.ts +54 -0
  154. package/src/auth/return-to.ts +21 -0
  155. package/src/auth/scope.ts +64 -0
  156. package/src/auth/session-activity.ts +19 -0
  157. package/src/auth/session-cookies.ts +43 -0
  158. package/src/files/content.ts +419 -0
  159. package/src/index.ts +2 -0
  160. package/src/openapi/security.ts +37 -0
  161. package/src/openapi/tags.ts +151 -0
  162. package/src/registerRoutes.ts +49 -0
  163. package/src/routes/action-runs.ts +238 -0
  164. package/src/routes/actions.ts +126 -0
  165. package/src/routes/agent-api-gateway.ts +260 -0
  166. package/src/routes/agents.ts +943 -0
  167. package/src/routes/auth.ts +2233 -0
  168. package/src/routes/connectors.ts +69 -0
  169. package/src/routes/datasets.ts +402 -0
  170. package/src/routes/events.ts +55 -0
  171. package/src/routes/files.ts +675 -0
  172. package/src/routes/links.ts +143 -0
  173. package/src/routes/logs.ts +65 -0
  174. package/src/routes/objects.ts +838 -0
  175. package/src/routes/ontology.ts +138 -0
  176. package/src/routes/pipelines.ts +332 -0
  177. package/src/routes/project.ts +16 -0
  178. package/src/routes/projections.ts +251 -0
  179. package/src/routes/rules.ts +124 -0
  180. package/src/routes/status.ts +53 -0
  181. package/src/routes/syncs.ts +243 -0
  182. package/src/routes/telemetry.ts +207 -0
  183. package/src/routes/webhook-runs.ts +81 -0
  184. package/src/routes/webhooks.ts +508 -0
  185. package/src/routes/workflows.ts +1333 -0
  186. package/src/routes/ws/agents.ts +301 -0
  187. package/src/routes/ws/events.ts +278 -0
  188. package/src/routes/ws/index.ts +12 -0
  189. package/src/routes/ws/log-subscription-hub.ts +375 -0
  190. package/src/routes/ws/logs.ts +117 -0
  191. package/src/schemas/actions.ts +123 -0
  192. package/src/schemas/agents.ts +293 -0
  193. package/src/schemas/auth.ts +317 -0
  194. package/src/schemas/common.ts +60 -0
  195. package/src/schemas/connectors.ts +21 -0
  196. package/src/schemas/datasets.ts +107 -0
  197. package/src/schemas/event-payloads.ts +79 -0
  198. package/src/schemas/events.ts +117 -0
  199. package/src/schemas/files.ts +82 -0
  200. package/src/schemas/links.ts +38 -0
  201. package/src/schemas/logs.ts +76 -0
  202. package/src/schemas/objects.ts +759 -0
  203. package/src/schemas/ontology.ts +77 -0
  204. package/src/schemas/pipelines.ts +150 -0
  205. package/src/schemas/project.ts +5 -0
  206. package/src/schemas/projections.ts +144 -0
  207. package/src/schemas/rules.ts +98 -0
  208. package/src/schemas/status.ts +51 -0
  209. package/src/schemas/syncs.ts +83 -0
  210. package/src/schemas/telemetry.ts +59 -0
  211. package/src/schemas/webhook-runs.ts +40 -0
  212. package/src/schemas/workflows.ts +229 -0
  213. package/src/server.ts +383 -0
  214. package/src/utils/http.ts +108 -0
  215. package/src/utils/request-body.ts +62 -0
  216. package/src/utils/ws.ts +59 -0
@@ -0,0 +1,229 @@
1
+ import { z } from "zod"
2
+
3
+ export const WorkflowParamsSchema = z.object({
4
+ workflowId: z.string().min(1),
5
+ })
6
+
7
+ export const WorkflowRunParamsSchema = z.object({
8
+ runId: z.string().min(1),
9
+ })
10
+
11
+ export const WorkflowInterventionParamsSchema = z.object({
12
+ interventionId: z.string().min(1),
13
+ })
14
+
15
+ export const WorkflowRunStatusSchema = z.enum([
16
+ "queued",
17
+ "running",
18
+ "waiting",
19
+ "succeeded",
20
+ "failed",
21
+ "cancelled",
22
+ ])
23
+
24
+ export const WorkflowInterventionStatusSchema = z.enum([
25
+ "pending",
26
+ "submitted",
27
+ "cancelled",
28
+ "expired",
29
+ ])
30
+
31
+ export const WorkflowRunsQuerySchema = z.object({
32
+ workflowId: z.string().optional(),
33
+ status: WorkflowRunStatusSchema.optional(),
34
+ startedAfter: z.string().optional(),
35
+ startedBefore: z.string().optional(),
36
+ limit: z.string().optional(),
37
+ offset: z.string().optional(),
38
+ order: z.enum(["asc", "desc"]).optional(),
39
+ })
40
+
41
+ export const WorkflowInterventionsQuerySchema = z.object({
42
+ workflowId: z.string().optional(),
43
+ workflowRunId: z.string().optional(),
44
+ nodeRunId: z.string().optional(),
45
+ nodeId: z.string().optional(),
46
+ nodeKey: z.string().optional(),
47
+ interventionId: z.string().optional(),
48
+ status: WorkflowInterventionStatusSchema.optional(),
49
+ requestedAfter: z.string().optional(),
50
+ requestedBefore: z.string().optional(),
51
+ limit: z.string().optional(),
52
+ offset: z.string().optional(),
53
+ order: z.enum(["asc", "desc"]).optional(),
54
+ })
55
+
56
+ export const RequestWorkflowRunBodySchema = z
57
+ .object({
58
+ input: z.record(z.unknown()).optional(),
59
+ })
60
+ .default({})
61
+
62
+ export const WorkflowInterventionActorSchema = z.object({
63
+ principalType: z.enum(["user", "serviceAccount", "system"]),
64
+ principalId: z.string().min(1),
65
+ })
66
+
67
+ export const CancelWorkflowRunBodySchema = z.object({}).default({})
68
+
69
+ export const SubmitWorkflowInterventionBodySchema = z.object({
70
+ response: z.record(z.unknown()),
71
+ })
72
+
73
+ export const CancelWorkflowInterventionBodySchema = z.object({}).default({})
74
+
75
+ const WorkflowTriggerSchema = z.object({
76
+ type: z.literal("schedule"),
77
+ scheduleId: z.string(),
78
+ })
79
+
80
+ const WorkflowNodeSchema = z.union([
81
+ z.object({
82
+ type: z.literal("step"),
83
+ id: z.string(),
84
+ key: z.string(),
85
+ input: z.record(z.unknown()),
86
+ output: z.record(z.unknown()),
87
+ }),
88
+ z.object({
89
+ type: z.literal("action"),
90
+ id: z.string(),
91
+ key: z.string(),
92
+ objectTypeId: z.string().optional(),
93
+ params: z.record(z.unknown()),
94
+ }),
95
+ z.object({
96
+ type: z.literal("intervention"),
97
+ id: z.string(),
98
+ key: z.string(),
99
+ input: z.record(z.unknown()),
100
+ response: z.record(z.unknown()),
101
+ description: z.string().optional(),
102
+ }),
103
+ z.object({
104
+ type: z.literal("agent"),
105
+ id: z.string(),
106
+ key: z.string(),
107
+ agentId: z.string(),
108
+ input: z.record(z.unknown()),
109
+ output: z.record(z.unknown()),
110
+ }),
111
+ ])
112
+
113
+ export const WorkflowRunSchema = z.object({
114
+ id: z.string(),
115
+ projectId: z.string(),
116
+ workflowId: z.string(),
117
+ status: WorkflowRunStatusSchema,
118
+ input: z.record(z.unknown()),
119
+ queuedAt: z.string().optional(),
120
+ startedAt: z.string(),
121
+ finishedAt: z.string().optional(),
122
+ error: z.string().optional(),
123
+ requestedBy: WorkflowInterventionActorSchema,
124
+ })
125
+
126
+ export const WorkflowAgentNodeExecutionSummarySchema = z.object({
127
+ agentId: z.string(),
128
+ status: z.enum(["queued", "running", "succeeded", "failed", "cancelled"]),
129
+ attempt: z.number().int().nonnegative(),
130
+ modelId: z.string().optional(),
131
+ finishReason: z.string().optional(),
132
+ usage: z.record(z.unknown()).optional(),
133
+ startedAt: z.string().optional(),
134
+ completedAt: z.string().optional(),
135
+ })
136
+
137
+ export const WorkflowAgentNodeExecutionSchema = WorkflowAgentNodeExecutionSummarySchema.extend({
138
+ nodeRunId: z.string(),
139
+ prompt: z.string(),
140
+ executionPrincipal: WorkflowInterventionActorSchema.optional(),
141
+ trace: z.array(z.unknown()).optional(),
142
+ diagnostics: z.array(z.unknown()).optional(),
143
+ error: z.string().optional(),
144
+ createdAt: z.string(),
145
+ })
146
+
147
+ export const WorkflowNodeRunSchema = z.object({
148
+ id: z.string(),
149
+ projectId: z.string(),
150
+ workflowRunId: z.string(),
151
+ workflowId: z.string(),
152
+ nodeIndex: z.number(),
153
+ nodeType: z.enum(["step", "action", "intervention", "agent"]),
154
+ nodeId: z.string(),
155
+ nodeKey: z.string(),
156
+ status: z.enum(["running", "waiting", "succeeded", "failed", "cancelled"]),
157
+ input: z.record(z.unknown()),
158
+ startedAt: z.string(),
159
+ finishedAt: z.string().optional(),
160
+ output: z.record(z.unknown()).optional(),
161
+ error: z.string().optional(),
162
+ agentExecution: WorkflowAgentNodeExecutionSummarySchema.optional(),
163
+ })
164
+
165
+ export const WorkflowInterventionSchema = z.object({
166
+ id: z.string(),
167
+ projectId: z.string(),
168
+ workflowId: z.string(),
169
+ workflowRunId: z.string(),
170
+ nodeRunId: z.string(),
171
+ nodeIndex: z.number(),
172
+ nodeId: z.string(),
173
+ nodeKey: z.string(),
174
+ interventionId: z.string(),
175
+ input: z.record(z.unknown()),
176
+ defaultResponse: z.record(z.unknown()),
177
+ status: WorkflowInterventionStatusSchema,
178
+ requestedAt: z.string(),
179
+ expiresAt: z.string().optional(),
180
+ submittedAt: z.string().optional(),
181
+ submittedBy: WorkflowInterventionActorSchema.optional(),
182
+ response: z.record(z.unknown()).optional(),
183
+ cancelledAt: z.string().optional(),
184
+ cancelledBy: WorkflowInterventionActorSchema.optional(),
185
+ expiredAt: z.string().optional(),
186
+ })
187
+
188
+ export const WorkflowSchema = z.object({
189
+ id: z.string(),
190
+ input: z.record(z.unknown()),
191
+ triggers: z.array(WorkflowTriggerSchema),
192
+ nodes: z.array(WorkflowNodeSchema),
193
+ latestRun: WorkflowRunSchema.nullable(),
194
+ })
195
+
196
+ export const WorkflowRunListResponseSchema = z.object({
197
+ runs: z.array(WorkflowRunSchema),
198
+ hasMore: z.boolean(),
199
+ total: z.number(),
200
+ })
201
+
202
+ export const WorkflowRunDetailResponseSchema = z.object({
203
+ run: WorkflowRunSchema,
204
+ nodes: z.array(WorkflowNodeRunSchema),
205
+ })
206
+
207
+ export const CancelWorkflowRunResponseSchema = WorkflowRunDetailResponseSchema
208
+
209
+ export const WorkflowInterventionListResponseSchema = z.object({
210
+ interventions: z.array(WorkflowInterventionSchema),
211
+ hasMore: z.boolean(),
212
+ total: z.number(),
213
+ })
214
+
215
+ export const SubmitWorkflowInterventionResponseSchema = z.object({
216
+ intervention: WorkflowInterventionSchema,
217
+ jobId: z.string(),
218
+ })
219
+
220
+ export const CancelWorkflowInterventionResponseSchema = z.object({
221
+ intervention: WorkflowInterventionSchema,
222
+ })
223
+
224
+ export const RequestWorkflowRunResponseSchema = z.object({
225
+ runId: z.string(),
226
+ jobId: z.string(),
227
+ workflowId: z.string(),
228
+ queuedAt: z.string(),
229
+ })
package/src/server.ts ADDED
@@ -0,0 +1,383 @@
1
+ import { cors } from "@elysiajs/cors"
2
+ import { openapi } from "@elysiajs/openapi"
3
+ import type { OntologyMaintenanceHandle, OntologySource, Sixb } from "@sixb/core"
4
+ import { CSRF_HEADER_NAME } from "@sixb/core/internal/auth"
5
+ import { Elysia } from "elysia"
6
+ import { websocket as elysiaWebSocket } from "elysia/ws"
7
+ import { zodToJsonSchema } from "zod-to-json-schema"
8
+ import {
9
+ type AuthInvitationDestinationOptions,
10
+ type AuthInvitationRedirectContext,
11
+ type AuthInvitationRedirectInput,
12
+ BrowserOriginError,
13
+ createApiBrowserAuthContextResolver,
14
+ createApiBrowserAuthRedirectContextResolver,
15
+ getApiBrowserInvitationDestinationOptions,
16
+ isAllowedApiBrowserOrigin,
17
+ type RequestAuthContext,
18
+ type ResolveAuthRedirectContext,
19
+ type ResolvedSixbApiBrowserPolicy,
20
+ type ResolveRequestAuthContext,
21
+ resolveApiBrowserInvitationRedirectContext,
22
+ resolveApiBrowserPolicy,
23
+ resolveApiBrowserPublicOrigin,
24
+ type SixbApiBrowserPolicy,
25
+ } from "./auth/browser-origin"
26
+ import { CSRF_TOKEN_RESPONSE_HEADER_NAME } from "./auth/csrf"
27
+ import { ServerAuthGuard } from "./auth/guard"
28
+ import { consumeInternalRequestAuthState } from "./auth/scope"
29
+ import { SESSION_ACTIVITY_HEADER_NAME } from "./auth/session-activity"
30
+ import { createSessionRenewalCookieHeaders } from "./auth/session-cookies"
31
+ import {
32
+ SIXB_BEARER_SECURITY_SCHEME,
33
+ SIXB_BEARER_SECURITY_SCHEME_ID,
34
+ SIXB_CSRF_SECURITY_SCHEME,
35
+ SIXB_CSRF_SECURITY_SCHEME_ID,
36
+ } from "./openapi/security"
37
+ import { OPENAPI_TAG_METADATA } from "./openapi/tags"
38
+ import { registerHttpRoutes } from "./registerRoutes"
39
+ import { registerAuthRoutes } from "./routes/auth"
40
+ import { registerWebhookRoutes } from "./routes/webhooks"
41
+ import { registerWebSocketRoutes } from "./routes/ws"
42
+ import { jsonValueOpenApiOverride } from "./schemas/common"
43
+ import { ObjectQueryOpenApiSchemas } from "./schemas/objects"
44
+
45
+ export interface SixbServerOptions {
46
+ sixb: Sixb<readonly OntologySource[]>
47
+ port?: number
48
+ host?: string
49
+ quiet?: boolean
50
+ browser: SixbApiBrowserPolicy
51
+ }
52
+
53
+ export function createSixbServer(options: SixbServerOptions): SixbServer {
54
+ return new SixbServer(options)
55
+ }
56
+
57
+ export class SixbServer {
58
+ private readonly sixb: Sixb<readonly OntologySource[]>
59
+ private readonly port: number
60
+ private readonly host: string
61
+ private readonly quiet: boolean
62
+ private readonly apiBrowserPolicy: ResolvedSixbApiBrowserPolicy
63
+ private readonly authContextResolver: ResolveRequestAuthContext
64
+ private readonly authRedirectContextResolver: ResolveAuthRedirectContext
65
+ private app: SixbApp | null = null
66
+ private bunServer: ReturnType<typeof Bun.serve> | null = null
67
+ private maintenance: OntologyMaintenanceHandle | null = null
68
+
69
+ constructor(options: SixbServerOptions) {
70
+ this.sixb = options.sixb
71
+ this.port = options.port ?? 3000
72
+ this.host = options.host ?? "0.0.0.0"
73
+ this.quiet = options.quiet ?? false
74
+ this.apiBrowserPolicy = resolveApiBrowserPolicy(options.browser)
75
+ this.authContextResolver = createApiBrowserAuthContextResolver(this.apiBrowserPolicy)
76
+ this.authRedirectContextResolver = createApiBrowserAuthRedirectContextResolver(
77
+ this.apiBrowserPolicy
78
+ )
79
+ }
80
+
81
+ getSixb(): Sixb<readonly OntologySource[]> {
82
+ return this.sixb
83
+ }
84
+
85
+ getPort(): number {
86
+ return this.port
87
+ }
88
+
89
+ resolveAuthContext(request: Request): RequestAuthContext {
90
+ return this.authContextResolver(request)
91
+ }
92
+
93
+ resolveAuthRedirectContext(
94
+ request: Parameters<ResolveAuthRedirectContext>[0],
95
+ input: Parameters<ResolveAuthRedirectContext>[1]
96
+ ): ReturnType<ResolveAuthRedirectContext> {
97
+ return this.authRedirectContextResolver(request, input)
98
+ }
99
+
100
+ resolveAuthRequestOrigin(request: Request): string {
101
+ return resolveApiBrowserPublicOrigin(this.apiBrowserPolicy, request)
102
+ }
103
+
104
+ getInvitationDestinationOptions(_request: Request): AuthInvitationDestinationOptions {
105
+ return getApiBrowserInvitationDestinationOptions(this.apiBrowserPolicy)
106
+ }
107
+
108
+ resolveInvitationRedirectContext(
109
+ request: Request,
110
+ input: AuthInvitationRedirectInput
111
+ ): AuthInvitationRedirectContext {
112
+ return resolveApiBrowserInvitationRedirectContext(this.apiBrowserPolicy, request, input)
113
+ }
114
+
115
+ getApiBrowserPolicy(): ResolvedSixbApiBrowserPolicy {
116
+ return this.apiBrowserPolicy
117
+ }
118
+
119
+ async start(): Promise<void> {
120
+ if (this.app !== null || this.bunServer !== null || this.maintenance !== null) {
121
+ throw new Error("[SixbServer] Server is already running.")
122
+ }
123
+
124
+ const maintenance = await this.sixb.startOntologyMaintenance()
125
+ this.maintenance = maintenance
126
+
127
+ try {
128
+ this.app = createSixbApi(this)
129
+ this.bunServer = startApiServer(this.app, {
130
+ host: this.host,
131
+ port: this.port,
132
+ })
133
+ } catch (error) {
134
+ this.app = null
135
+ this.bunServer = null
136
+ this.maintenance = null
137
+ await maintenance.stop()
138
+ const message = error instanceof Error ? error.message : String(error)
139
+ throw new Error(`[SixbServer] Failed to listen on ${this.host}:${this.port}: ${message}`)
140
+ }
141
+
142
+ if (!this.quiet) {
143
+ const base = `http://${this.host}:${this.port}`
144
+ console.log(`Sixb server running at ${base}`)
145
+ console.log(`OpenAPI docs at ${base}/docs`)
146
+ }
147
+ }
148
+
149
+ async stop(): Promise<void> {
150
+ if (this.bunServer) {
151
+ this.bunServer.stop(true)
152
+ this.bunServer = null
153
+ }
154
+
155
+ if (this.app) {
156
+ await this.app.stop()
157
+ this.app = null
158
+ }
159
+
160
+ const maintenance = this.maintenance
161
+ this.maintenance = null
162
+ await maintenance?.stop()
163
+ }
164
+ }
165
+
166
+ export function createSixbApi(server: SixbServer) {
167
+ const sixb = server.getSixb()
168
+ const guard = new ServerAuthGuard({
169
+ sixb,
170
+ resolveAuthContext: (request) => server.resolveAuthContext(request),
171
+ })
172
+ guard.assertCanServeHttp({ production: process.env.NODE_ENV === "production" })
173
+ const apiBrowserPolicy = server.getApiBrowserPolicy()
174
+
175
+ const app = new Elysia()
176
+
177
+ app.onRequest(({ request }) => {
178
+ const response = rejectDisallowedBrowserOrigin(request, apiBrowserPolicy)
179
+ if (response) {
180
+ return response
181
+ }
182
+ })
183
+ app.use(
184
+ cors({
185
+ origin: (request) => isAllowedApiBrowserOrigin(apiBrowserPolicy, request),
186
+ credentials: true,
187
+ methods: ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
188
+ allowedHeaders: [
189
+ "authorization",
190
+ "content-type",
191
+ CSRF_HEADER_NAME,
192
+ SESSION_ACTIVITY_HEADER_NAME,
193
+ ],
194
+ exposeHeaders: [CSRF_TOKEN_RESPONSE_HEADER_NAME],
195
+ maxAge: 600,
196
+ })
197
+ )
198
+
199
+ // Resolve the session once per request and attach the principal's scoped SDK.
200
+ // The beforeHandle enforces the auth decision before any route runs; `scoped`
201
+ // and `authz` stay null for public routes and disabled auth (privileged mode).
202
+ app
203
+ .derive(async ({ request }) => {
204
+ const internalAuthState = consumeInternalRequestAuthState(request)
205
+ if (internalAuthState) {
206
+ return { auth: { kind: "allow" as const, session: null }, ...internalAuthState }
207
+ }
208
+
209
+ const auth = await guard.resolve(request)
210
+ if (auth.kind === "deny" || !auth.session?.authenticated) {
211
+ return { auth, authz: null, scoped: null }
212
+ }
213
+
214
+ const authz = sixb.auth.contextFromSession(auth.session)
215
+ return { auth, authz, scoped: sixb.as(authz) }
216
+ })
217
+ .onBeforeHandle(({ auth }) => (auth.kind === "deny" ? auth.response : undefined))
218
+ .mapResponse(({ auth, request, set }) => {
219
+ if (
220
+ !auth ||
221
+ auth.kind !== "allow" ||
222
+ auth.session?.credentialSource !== "session" ||
223
+ auth.session.sessionRenewed !== true
224
+ ) {
225
+ return
226
+ }
227
+
228
+ const renewal = createSessionRenewalCookieHeaders({
229
+ sixb,
230
+ request,
231
+ session: auth.session,
232
+ })
233
+ if (!renewal) {
234
+ return
235
+ }
236
+
237
+ appendSetCookieHeaders(set, renewal.headers)
238
+ setResponseHeader(set, CSRF_TOKEN_RESPONSE_HEADER_NAME, renewal.csrfToken)
239
+ })
240
+
241
+ app.use(
242
+ openapi({
243
+ path: "/docs",
244
+ provider: "swagger-ui",
245
+ documentation: {
246
+ info: {
247
+ title: "Sixb API",
248
+ version: "0.0.1",
249
+ description: "Ontology-first digital twins runtime API",
250
+ },
251
+ components: {
252
+ securitySchemes: {
253
+ [SIXB_CSRF_SECURITY_SCHEME_ID]: SIXB_CSRF_SECURITY_SCHEME,
254
+ [SIXB_BEARER_SECURITY_SCHEME_ID]: SIXB_BEARER_SECURITY_SCHEME,
255
+ },
256
+ schemas: ObjectQueryOpenApiSchemas,
257
+ },
258
+ tags: OPENAPI_TAG_METADATA,
259
+ },
260
+ swagger: {
261
+ withCredentials: true,
262
+ },
263
+ mapJsonSchema: {
264
+ zod: (schema: Parameters<typeof zodToJsonSchema>[0]) =>
265
+ zodToJsonSchema(schema, {
266
+ $refStrategy: "none",
267
+ target: "openApi3",
268
+ override: jsonValueOpenApiOverride,
269
+ }),
270
+ },
271
+ })
272
+ )
273
+
274
+ registerAuthRoutes(app, sixb, {
275
+ resolveAuthContext: (request) => server.resolveAuthContext(request),
276
+ resolveAuthRedirectContext: (request, input) =>
277
+ server.resolveAuthRedirectContext(request, input),
278
+ getInvitationDestinationOptions: (request) => server.getInvitationDestinationOptions(request),
279
+ resolveAuthRequestOrigin: (request) => server.resolveAuthRequestOrigin(request),
280
+ resolveInvitationRedirectContext: (request, input) =>
281
+ server.resolveInvitationRedirectContext(request, input),
282
+ })
283
+ registerHttpRoutes(app, sixb)
284
+ registerWebhookRoutes(app, sixb)
285
+ registerWebSocketRoutes(app, server)
286
+
287
+ return app
288
+ }
289
+
290
+ interface ElysiaSet {
291
+ headers?: unknown
292
+ }
293
+
294
+ function appendSetCookieHeaders(set: ElysiaSet, values: readonly string[]): void {
295
+ if (set.headers instanceof Headers) {
296
+ for (const value of values) set.headers.append("set-cookie", value)
297
+ return
298
+ }
299
+
300
+ if (!set.headers || typeof set.headers !== "object" || Array.isArray(set.headers)) {
301
+ set.headers = {}
302
+ }
303
+
304
+ const headers = set.headers as Record<string, string | number | string[] | undefined>
305
+ const existing = headers["set-cookie"]
306
+ headers["set-cookie"] = [
307
+ ...(existing === undefined ? [] : Array.isArray(existing) ? existing : [String(existing)]),
308
+ ...values,
309
+ ]
310
+ }
311
+
312
+ function setResponseHeader(set: ElysiaSet, name: string, value: string): void {
313
+ if (set.headers instanceof Headers) {
314
+ set.headers.set(name, value)
315
+ return
316
+ }
317
+
318
+ if (!set.headers || typeof set.headers !== "object" || Array.isArray(set.headers)) {
319
+ set.headers = {}
320
+ }
321
+
322
+ const headers = set.headers as Record<string, string | number | string[] | undefined>
323
+ headers[name] = value
324
+ }
325
+
326
+ function rejectDisallowedBrowserOrigin(
327
+ request: Request,
328
+ policy: ResolvedSixbApiBrowserPolicy
329
+ ): Response | undefined {
330
+ if (!request.headers.has("origin")) {
331
+ return undefined
332
+ }
333
+
334
+ try {
335
+ if (isAllowedApiBrowserOrigin(policy, request)) {
336
+ return undefined
337
+ }
338
+ } catch (error) {
339
+ if (!(error instanceof BrowserOriginError)) {
340
+ throw error
341
+ }
342
+ }
343
+
344
+ return new Response(JSON.stringify({ error: "Browser origin is not allowed" }), {
345
+ status: 403,
346
+ headers: {
347
+ "content-type": "application/json; charset=utf-8",
348
+ "cache-control": "no-store",
349
+ },
350
+ })
351
+ }
352
+
353
+ export type SixbApp = ReturnType<typeof createSixbApi>
354
+
355
+ function startApiServer(
356
+ app: SixbApp,
357
+ options: {
358
+ readonly host: string
359
+ readonly port: number
360
+ }
361
+ ) {
362
+ const bunServer = Bun.serve({
363
+ port: options.port,
364
+ hostname: options.host,
365
+ fetch: (request) => app.fetch(request),
366
+ websocket: getElysiaWsHandler(app),
367
+ } as Parameters<typeof Bun.serve>[0])
368
+
369
+ attachBunServer(app, bunServer)
370
+ return bunServer
371
+ }
372
+
373
+ function getElysiaWsHandler(app: SixbApp) {
374
+ const cfg = (app as unknown as { config?: { websocket?: Record<string, unknown> } }).config
375
+ return {
376
+ ...elysiaWebSocket,
377
+ ...(cfg?.websocket ?? {}),
378
+ } as Parameters<typeof Bun.serve>[0]["websocket"]
379
+ }
380
+
381
+ function attachBunServer(app: SixbApp, bunServer: ReturnType<typeof Bun.serve>) {
382
+ ;(app as unknown as { server: typeof bunServer }).server = bunServer
383
+ }
@@ -0,0 +1,108 @@
1
+ import { AuthorizationError, OntologyNotFoundError, OntologyValidationError } from "@sixb/core"
2
+ import {
3
+ FileUploadSessionError,
4
+ type FileUploadSessionErrorReason,
5
+ ObjectNotFoundError,
6
+ } from "@sixb/core/storage"
7
+ import { RequestBodyTooLargeError } from "./request-body"
8
+
9
+ export function toIsoString(value: Date): string {
10
+ return value.toISOString()
11
+ }
12
+
13
+ export function parseDate(value: string | undefined): Date | undefined {
14
+ if (!value) {
15
+ return undefined
16
+ }
17
+
18
+ const parsed = new Date(value)
19
+ if (Number.isNaN(parsed.getTime())) {
20
+ throw new Error(`Invalid date: ${value}`)
21
+ }
22
+
23
+ return parsed
24
+ }
25
+
26
+ export function parseOptionalInt(value: string | undefined): number | undefined {
27
+ if (value === undefined) {
28
+ return undefined
29
+ }
30
+
31
+ const parsed = Number.parseInt(value, 10)
32
+ if (!Number.isFinite(parsed)) {
33
+ throw new Error(`Invalid integer: ${value}`)
34
+ }
35
+
36
+ return parsed
37
+ }
38
+
39
+ /**
40
+ * A storage role the runtime was not configured with.
41
+ *
42
+ * 501 and not 400: the request was well-formed and the caller can do nothing
43
+ * about it. It is not 404 either — that would claim the resource is absent when
44
+ * what is absent is the store that would have recorded it. Callers that treat
45
+ * "no rows" and "not recorded" the same way silently report an empty history as
46
+ * a healthy one.
47
+ */
48
+ export function unconfiguredStorageResponse(
49
+ set: { status?: number | string },
50
+ role: string
51
+ ): { error: string } {
52
+ set.status = 501
53
+ return { error: `[SixbServer] ${role} is not configured on this runtime.` }
54
+ }
55
+
56
+ export function handleRouteError(
57
+ error: unknown,
58
+ set: { status?: number | string }
59
+ ): {
60
+ error: string
61
+ } {
62
+ if (error instanceof AuthorizationError) {
63
+ set.status = 403
64
+ return { error: error.message }
65
+ }
66
+
67
+ if (error instanceof FileUploadSessionError) {
68
+ set.status = fileUploadSessionErrorStatus(error.reason)
69
+ return { error: error.message }
70
+ }
71
+
72
+ if (error instanceof RequestBodyTooLargeError) {
73
+ set.status = 413
74
+ return { error: error.message }
75
+ }
76
+
77
+ // Before the OntologyValidationError branch: it is a subclass, and it is the half that is a
78
+ // missing resource rather than bad input.
79
+ if (error instanceof OntologyNotFoundError || error instanceof ObjectNotFoundError) {
80
+ set.status = 404
81
+ return { error: error.message }
82
+ }
83
+
84
+ if (error instanceof OntologyValidationError) {
85
+ set.status = 400
86
+ return { error: error.message }
87
+ }
88
+
89
+ // The tail. Core still throws a bare `Error` for "Unknown sync 'x'" and its siblings, so the
90
+ // message is all a route has to go on; reading it is a guess that misfires whenever a validation
91
+ // message happens to contain one of these words. Every error that gains a class moves above this
92
+ // line and the guess covers less.
93
+ const message = error instanceof Error ? error.message : String(error)
94
+ set.status = message.includes("not found") || message.includes("Unknown") ? 404 : 400
95
+ return { error: message }
96
+ }
97
+
98
+ function fileUploadSessionErrorStatus(reason: FileUploadSessionErrorReason): number {
99
+ switch (reason) {
100
+ case "not_found":
101
+ return 404
102
+ case "expired":
103
+ return 410
104
+ case "already_completed":
105
+ case "already_aborted":
106
+ return 409
107
+ }
108
+ }