@sixb/server 0.1.6 → 0.1.8

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 (120) hide show
  1. package/dist/auth/access-token-boundary.d.ts +3 -0
  2. package/dist/auth/access-token-boundary.d.ts.map +1 -1
  3. package/dist/auth/public-routes.d.ts.map +1 -1
  4. package/dist/auth/scope.d.ts +6 -2
  5. package/dist/auth/scope.d.ts.map +1 -1
  6. package/dist/auth/shared-access.d.ts +66 -0
  7. package/dist/auth/shared-access.d.ts.map +1 -0
  8. package/dist/files/content.d.ts +8 -0
  9. package/dist/files/content.d.ts.map +1 -1
  10. package/dist/index.d.ts +1 -0
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3402 -1693
  13. package/dist/index.js.map +35 -28
  14. package/dist/models/display.d.ts +22 -0
  15. package/dist/models/display.d.ts.map +1 -0
  16. package/dist/openapi/security.d.ts +15 -1
  17. package/dist/openapi/security.d.ts.map +1 -1
  18. package/dist/openapi/tags.d.ts +6 -2
  19. package/dist/openapi/tags.d.ts.map +1 -1
  20. package/dist/registerRoutes.d.ts +2 -0
  21. package/dist/registerRoutes.d.ts.map +1 -1
  22. package/dist/routes/action-runs.d.ts +2 -0
  23. package/dist/routes/action-runs.d.ts.map +1 -1
  24. package/dist/routes/actions.d.ts +1 -0
  25. package/dist/routes/actions.d.ts.map +1 -1
  26. package/dist/routes/agent-api-gateway.d.ts.map +1 -1
  27. package/dist/routes/agents.d.ts +100 -90
  28. package/dist/routes/agents.d.ts.map +1 -1
  29. package/dist/routes/ai-accounting.d.ts.map +1 -1
  30. package/dist/routes/auth.d.ts +143 -24
  31. package/dist/routes/auth.d.ts.map +1 -1
  32. package/dist/routes/connector-connection-runs.d.ts +8 -8
  33. package/dist/routes/connector-connections.d.ts +4 -4
  34. package/dist/routes/datasets.d.ts +5 -3
  35. package/dist/routes/datasets.d.ts.map +1 -1
  36. package/dist/routes/events.d.ts +3 -3
  37. package/dist/routes/files.d.ts +1 -0
  38. package/dist/routes/files.d.ts.map +1 -1
  39. package/dist/routes/logs.d.ts +1 -1
  40. package/dist/routes/models.d.ts +18 -1
  41. package/dist/routes/models.d.ts.map +1 -1
  42. package/dist/routes/objects.d.ts +3 -1
  43. package/dist/routes/objects.d.ts.map +1 -1
  44. package/dist/routes/pipelines.d.ts +6 -1
  45. package/dist/routes/pipelines.d.ts.map +1 -1
  46. package/dist/routes/rules.d.ts +1 -1
  47. package/dist/routes/share-grants.d.ts +264 -0
  48. package/dist/routes/share-grants.d.ts.map +1 -0
  49. package/dist/routes/shared-access.d.ts +155 -0
  50. package/dist/routes/shared-access.d.ts.map +1 -0
  51. package/dist/routes/syncs.d.ts +3 -0
  52. package/dist/routes/syncs.d.ts.map +1 -1
  53. package/dist/routes/workflows.d.ts +58 -55
  54. package/dist/routes/workflows.d.ts.map +1 -1
  55. package/dist/routes/ws/logs.d.ts +4 -4
  56. package/dist/schemas/agents.d.ts +385 -230
  57. package/dist/schemas/agents.d.ts.map +1 -1
  58. package/dist/schemas/ai-accounting.d.ts +1847 -295
  59. package/dist/schemas/ai-accounting.d.ts.map +1 -1
  60. package/dist/schemas/ai-limits.d.ts +2210 -0
  61. package/dist/schemas/ai-limits.d.ts.map +1 -0
  62. package/dist/schemas/auth.d.ts +195 -112
  63. package/dist/schemas/auth.d.ts.map +1 -1
  64. package/dist/schemas/datasets.d.ts +28 -22
  65. package/dist/schemas/datasets.d.ts.map +1 -1
  66. package/dist/schemas/events.d.ts +6 -6
  67. package/dist/schemas/files.d.ts +3 -0
  68. package/dist/schemas/files.d.ts.map +1 -1
  69. package/dist/schemas/logs.d.ts +6 -6
  70. package/dist/schemas/models.d.ts +214 -14
  71. package/dist/schemas/models.d.ts.map +1 -1
  72. package/dist/schemas/objects.d.ts +4 -4
  73. package/dist/schemas/pipelines.d.ts +42 -6
  74. package/dist/schemas/pipelines.d.ts.map +1 -1
  75. package/dist/schemas/rules.d.ts +6 -6
  76. package/dist/schemas/share-grants.d.ts +518 -0
  77. package/dist/schemas/share-grants.d.ts.map +1 -0
  78. package/dist/schemas/shared-access.d.ts +42 -0
  79. package/dist/schemas/shared-access.d.ts.map +1 -0
  80. package/dist/schemas/syncs.d.ts +7 -0
  81. package/dist/schemas/syncs.d.ts.map +1 -1
  82. package/dist/schemas/workflows.d.ts +200 -210
  83. package/dist/schemas/workflows.d.ts.map +1 -1
  84. package/dist/server.d.ts +5 -0
  85. package/dist/server.d.ts.map +1 -1
  86. package/dist/utils/http.d.ts +8 -4
  87. package/dist/utils/http.d.ts.map +1 -1
  88. package/package.json +4 -4
  89. package/src/auth/access-token-boundary.ts +17 -2
  90. package/src/auth/public-routes.ts +23 -0
  91. package/src/auth/scope.ts +3 -2
  92. package/src/auth/shared-access.ts +376 -0
  93. package/src/files/content.ts +39 -6
  94. package/src/index.ts +1 -0
  95. package/src/models/display.ts +91 -0
  96. package/src/openapi/security.ts +20 -1
  97. package/src/openapi/tags.ts +4 -0
  98. package/src/registerRoutes.ts +6 -0
  99. package/src/routes/actions.ts +5 -10
  100. package/src/routes/agent-api-gateway.ts +137 -38
  101. package/src/routes/agents.ts +58 -83
  102. package/src/routes/ai-accounting.ts +414 -23
  103. package/src/routes/auth.ts +280 -1
  104. package/src/routes/models.ts +12 -4
  105. package/src/routes/share-grants.ts +238 -0
  106. package/src/routes/shared-access.ts +165 -0
  107. package/src/routes/workflows.ts +3 -5
  108. package/src/routes/ws/agents.ts +17 -6
  109. package/src/schemas/agents.ts +38 -50
  110. package/src/schemas/ai-accounting.ts +88 -19
  111. package/src/schemas/ai-limits.ts +116 -0
  112. package/src/schemas/auth.ts +32 -0
  113. package/src/schemas/datasets.ts +2 -1
  114. package/src/schemas/files.ts +1 -0
  115. package/src/schemas/models.ts +33 -5
  116. package/src/schemas/share-grants.ts +109 -0
  117. package/src/schemas/shared-access.ts +31 -0
  118. package/src/schemas/workflows.ts +0 -2
  119. package/src/server.ts +91 -1
  120. package/src/utils/http.ts +33 -2
@@ -1,4 +1,4 @@
1
- import { createHash, randomBytes, timingSafeEqual } from "node:crypto"
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"
2
2
  import type { AuthSessionAudience, GroupDefinition, SixbHostView } from "@sixb/core"
3
3
  import {
4
4
  type AuthenticatedUserRequestSession,
@@ -6,6 +6,7 @@ import {
6
6
  AuthRuntimeError,
7
7
  clearCsrfCookieHeader,
8
8
  clearSessionCookieHeader,
9
+ createAccessTokenCredential,
9
10
  createCsrfCookieHeader,
10
11
  createSessionCookieHeader,
11
12
  createSessionCredential,
@@ -62,7 +63,12 @@ import {
62
63
  CreateAuthServiceAccountAccessTokenResponseSchema,
63
64
  CreateAuthServiceAccountBodySchema,
64
65
  CreateAuthServiceAccountResponseSchema,
66
+ CreateDeviceAuthorizationBodySchema,
67
+ CreateDeviceAuthorizationResponseSchema,
68
+ DeviceAuthorizationDecisionBodySchema,
65
69
  DisableAuthServiceAccountResponseSchema,
70
+ ExchangeDeviceAuthorizationBodySchema,
71
+ ExchangeDeviceAuthorizationResponseSchema,
66
72
  GetAuthAccessManagementOptionsResponseSchema,
67
73
  GetAuthInvitationOptionsResponseSchema,
68
74
  GetAuthMembershipOptionsResponseSchema,
@@ -136,6 +142,246 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
136
142
  async ({ request }) => customAuthExperienceAssetResponse(options.authExperience, request),
137
143
  { detail: { hide: true } }
138
144
  )
145
+ .post(
146
+ "/api/auth/device-authorizations",
147
+ async ({ body, request }) => {
148
+ const parsed = CreateDeviceAuthorizationBodySchema.parse(body)
149
+ const now = new Date()
150
+ const id = `dva_${randomUUID()}`
151
+ const deviceCode = `${id}.${randomBytes(32).toString("base64url")}`
152
+ const userCode = createDeviceUserCode()
153
+ const expiresAt = new Date(now.getTime() + DEVICE_AUTHORIZATION_TTL_MS)
154
+ try {
155
+ await requireAuthStorage(host).deviceAuthorizations.create({
156
+ id,
157
+ projectId: host.id,
158
+ deviceCodeHash: hashDeviceCode(deviceCode),
159
+ userCode,
160
+ clientName: parsed.clientName,
161
+ tokenName: parsed.tokenName,
162
+ tokenExpiresAt: new Date(now.getTime() + DEVICE_ACCESS_TOKEN_TTL_MS),
163
+ createdAt: now,
164
+ expiresAt,
165
+ })
166
+ } catch (error) {
167
+ return authRouteErrorResponse(error)
168
+ }
169
+ const verificationUri = new URL(
170
+ "/auth/device",
171
+ options.resolveAuthRequestOrigin(request)
172
+ ).toString()
173
+ const verificationUriComplete = new URL(verificationUri)
174
+ verificationUriComplete.searchParams.set("user_code", userCode)
175
+ return jsonResponse(
176
+ {
177
+ deviceCode,
178
+ userCode,
179
+ verificationUri,
180
+ verificationUriComplete: verificationUriComplete.toString(),
181
+ expiresAt: expiresAt.toISOString(),
182
+ interval: DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS,
183
+ },
184
+ 201
185
+ )
186
+ },
187
+ {
188
+ body: CreateDeviceAuthorizationBodySchema,
189
+ response: { 201: CreateDeviceAuthorizationResponseSchema, 429: ErrorResponseSchema },
190
+ detail: {
191
+ summary: "Start device authorization",
192
+ tags: [OPENAPI_TAGS.authSessions.name],
193
+ operationId: "createDeviceAuthorization",
194
+ },
195
+ }
196
+ )
197
+ .post(
198
+ "/api/auth/device-authorizations/token",
199
+ async ({ body }) => {
200
+ const { deviceCode } = ExchangeDeviceAuthorizationBodySchema.parse(body)
201
+ const id = parseDeviceAuthorizationId(deviceCode)
202
+ if (!id) return jsonResponse({ status: "expired" as const }, 200)
203
+ const storage = requireAuthStorage(host)
204
+ const authorization = await storage.deviceAuthorizations.getById({
205
+ projectId: host.id,
206
+ id,
207
+ })
208
+ const now = new Date()
209
+ if (
210
+ !authorization ||
211
+ authorization.deviceCodeHash !== hashDeviceCode(deviceCode) ||
212
+ authorization.expiresAt <= now ||
213
+ authorization.status === "consumed"
214
+ ) {
215
+ return jsonResponse({ status: "expired" as const }, 200)
216
+ }
217
+ if (authorization.status === "pending") {
218
+ return jsonResponse({ status: "pending" as const }, 200)
219
+ }
220
+ if (authorization.status === "denied") {
221
+ return jsonResponse({ status: "denied" as const }, 200)
222
+ }
223
+ if (!authorization.approvedUserId || !authorization.approvedSessionId) {
224
+ return jsonResponse({ status: "expired" as const }, 200)
225
+ }
226
+ const credential = createAccessTokenCredential("personal")
227
+ try {
228
+ await storage.completeDeviceAuthorization({
229
+ projectId: host.id,
230
+ id,
231
+ deviceCodeHash: hashDeviceCode(deviceCode),
232
+ completedAt: now,
233
+ accessToken: {
234
+ id: credential.tokenId,
235
+ projectId: host.id,
236
+ name: authorization.tokenName,
237
+ kind: "personal",
238
+ subjectType: "user",
239
+ subjectId: authorization.approvedUserId,
240
+ tokenHash: credential.tokenHash,
241
+ createdByPrincipal: { type: "user", id: authorization.approvedUserId },
242
+ createdBySessionId: authorization.approvedSessionId,
243
+ createdAt: now,
244
+ expiresAt: authorization.tokenExpiresAt,
245
+ },
246
+ })
247
+ } catch (error) {
248
+ if (error instanceof AuthStorageError && error.code === "invalid_device_authorization") {
249
+ return jsonResponse({ status: "expired" as const }, 200)
250
+ }
251
+ throw error
252
+ }
253
+ return jsonResponse(
254
+ { status: "approved" as const, accessToken: credential.tokenValue },
255
+ 200
256
+ )
257
+ },
258
+ {
259
+ body: ExchangeDeviceAuthorizationBodySchema,
260
+ response: { 200: ExchangeDeviceAuthorizationResponseSchema },
261
+ detail: {
262
+ summary: "Exchange an approved device authorization",
263
+ tags: [OPENAPI_TAGS.authSessions.name],
264
+ operationId: "exchangeDeviceAuthorization",
265
+ },
266
+ }
267
+ )
268
+ .get(
269
+ "/auth/device",
270
+ async ({ request }) => {
271
+ const rawUserCode = new URL(request.url).searchParams.get("user_code")
272
+ if (!rawUserCode) {
273
+ return authPageResponse(
274
+ [
275
+ "<h1>Authorize a device</h1>",
276
+ '<form method="get" action="/auth/device">',
277
+ '<input name="user_code" autocomplete="one-time-code" placeholder="BCDF-HJKM" aria-label="Device code" required autofocus>',
278
+ '<button type="submit">Continue</button>',
279
+ "</form>",
280
+ ].join("")
281
+ )
282
+ }
283
+ const userCode = normalizeDeviceUserCode(rawUserCode)
284
+ if (!userCode) return authPageResponse("<h1>Invalid authorization</h1>", 400)
285
+ const authorization = await requireAuthStorage(host).deviceAuthorizations.getByUserCode({
286
+ projectId: host.id,
287
+ userCode,
288
+ })
289
+ const now = new Date()
290
+ if (
291
+ !authorization ||
292
+ authorization.status !== "pending" ||
293
+ authorization.expiresAt <= now
294
+ ) {
295
+ return authPageResponse("<h1>This authorization has expired</h1>", 400)
296
+ }
297
+ const authOptions = resolveAuthOptions(options, request)
298
+ const session = await host.auth.getSession(request, authOptions)
299
+ if (!session.authenticated) return authPageResponse("<h1>Authentication required</h1>", 401)
300
+ const cookieOptions = host.auth.getCookieOptions(authOptions)
301
+ const csrf = resolveSessionCsrfToken({
302
+ request,
303
+ cookieOptions,
304
+ expiresAt: session.session.expiresAt,
305
+ })
306
+ const groups = session.groupIds.length
307
+ ? `<p>Groups: ${escapeHtml(session.groupIds.join(", "))}</p>`
308
+ : "<p>Groups: none</p>"
309
+ const response = authPageResponse(
310
+ [
311
+ "<h1>Authorize this device?</h1>",
312
+ `<p><strong>${escapeHtml(authorization.clientName)}</strong> is requesting access.</p>`,
313
+ `<p>Code: <strong>${escapeHtml(authorization.userCode)}</strong></p>`,
314
+ `<p>Token: ${escapeHtml(authorization.tokenName)}</p>`,
315
+ `<p>Expires: ${escapeHtml(authorization.tokenExpiresAt.toLocaleDateString("en-US"))}</p>`,
316
+ groups,
317
+ '<form method="post" action="/auth/device">',
318
+ `<input type="hidden" name="userCode" value="${escapeHtml(userCode)}">`,
319
+ `<input type="hidden" name="csrfToken" value="${escapeHtml(csrf.token)}">`,
320
+ '<button name="decision" value="approve" type="submit">Authorize</button>',
321
+ '<button name="decision" value="deny" type="submit">Deny</button>',
322
+ "</form>",
323
+ ].join("")
324
+ )
325
+ if (csrf.setCookie) response.headers.append("set-cookie", csrf.setCookie)
326
+ return response
327
+ },
328
+ { detail: { hide: true } }
329
+ )
330
+ .post(
331
+ "/auth/device",
332
+ async ({ body, request }) => {
333
+ const parsed = DeviceAuthorizationDecisionBodySchema.parse(body)
334
+ const authOptions = resolveAuthOptions(options, request)
335
+ const session = await host.auth.getSession(request, authOptions)
336
+ if (!session.authenticated) return authPageResponse("<h1>Authentication required</h1>", 401)
337
+ if (!sessionCanAccessApplication(host, session, authOptions.audience)) {
338
+ return authPageResponse("<h1>Access denied</h1>", 403)
339
+ }
340
+ const csrfHeaders = new Headers(request.headers)
341
+ csrfHeaders.set("x-sixb-csrf", parsed.csrfToken)
342
+ if (
343
+ !verifyDoubleSubmitCsrf(
344
+ new Request(request.url, { method: "POST", headers: csrfHeaders }),
345
+ {
346
+ cookieName: host.auth.getCookieOptions(authOptions).csrfCookieName,
347
+ }
348
+ )
349
+ ) {
350
+ return authPageResponse("<h1>Invalid authorization request</h1>", 403)
351
+ }
352
+ const storage = requireAuthStorage(host)
353
+ const authorization = await storage.deviceAuthorizations.getByUserCode({
354
+ projectId: host.id,
355
+ userCode: parsed.userCode,
356
+ })
357
+ if (!authorization) return authPageResponse("<h1>Invalid authorization</h1>", 400)
358
+ if (parsed.decision === "approve") {
359
+ await storage.deviceAuthorizations.approve({
360
+ projectId: host.id,
361
+ id: authorization.id,
362
+ userId: session.user.id,
363
+ sessionId: session.session.id,
364
+ approvedAt: new Date(),
365
+ })
366
+ return authPageResponse("<h1>Device authorized</h1><p>You can close this window.</p>")
367
+ }
368
+ await storage.deviceAuthorizations.deny({
369
+ projectId: host.id,
370
+ id: authorization.id,
371
+ deniedAt: new Date(),
372
+ })
373
+ return authPageResponse("<h1>Authorization denied</h1><p>You can close this window.</p>")
374
+ },
375
+ {
376
+ body: t.Object({
377
+ userCode: t.String(),
378
+ decision: t.Union([t.Literal("approve"), t.Literal("deny")]),
379
+ csrfToken: t.String(),
380
+ }),
381
+ parse: "urlencoded",
382
+ detail: { hide: true },
383
+ }
384
+ )
139
385
  .get(
140
386
  "/api/auth/session",
141
387
  async ({ request }) => {
@@ -1491,6 +1737,36 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
1491
1737
  )
1492
1738
  }
1493
1739
 
1740
+ const DEVICE_AUTHORIZATION_TTL_MS = 10 * 60 * 1000
1741
+ const DEVICE_ACCESS_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000
1742
+ const DEVICE_AUTHORIZATION_POLL_INTERVAL_SECONDS = 2
1743
+ const DEVICE_USER_CODE_ALPHABET = "BCDFGHJKLMNPQRSTVWXYZ23456789"
1744
+
1745
+ function hashDeviceCode(deviceCode: string): string {
1746
+ return createHash("sha256").update(deviceCode).digest("base64url")
1747
+ }
1748
+
1749
+ function parseDeviceAuthorizationId(deviceCode: string): string | null {
1750
+ const separator = deviceCode.indexOf(".")
1751
+ if (separator <= 0 || separator !== deviceCode.lastIndexOf(".")) return null
1752
+ const id = deviceCode.slice(0, separator)
1753
+ return /^dva_[A-Za-z0-9-]+$/.test(id) ? id : null
1754
+ }
1755
+
1756
+ function createDeviceUserCode(): string {
1757
+ const bytes = randomBytes(8)
1758
+ const characters = [...bytes].map(
1759
+ (value) => DEVICE_USER_CODE_ALPHABET[value % DEVICE_USER_CODE_ALPHABET.length]
1760
+ )
1761
+ return `${characters.slice(0, 4).join("")}-${characters.slice(4).join("")}`
1762
+ }
1763
+
1764
+ function normalizeDeviceUserCode(value: string): string | null {
1765
+ const compact = value.toUpperCase().replaceAll(/[^A-Z0-9]/g, "")
1766
+ if (compact.length !== 8) return null
1767
+ return `${compact.slice(0, 4)}-${compact.slice(4)}`
1768
+ }
1769
+
1494
1770
  // The pending cookie carries the preimage of the `requester` hash embedded in
1495
1771
  // the emailed callback URL. Only the browser that requested the link holds it,
1496
1772
  // so GET /auth/callback can distinguish that browser (sign in immediately) from
@@ -2349,6 +2625,9 @@ function authRouteErrorResponse(error: unknown): Response {
2349
2625
  }
2350
2626
 
2351
2627
  if (error instanceof AuthStorageError) {
2628
+ if (error.code === "device_authorization_limit_exceeded") {
2629
+ return jsonResponse({ error: error.message }, 429)
2630
+ }
2352
2631
  if (
2353
2632
  error.code === "missing_invitation" ||
2354
2633
  error.code === "missing_access_token" ||
@@ -1,22 +1,30 @@
1
1
  import type { LanguageModelEntry, SixbHostView } from "@sixb/core"
2
2
  import type { Elysia } from "elysia"
3
+ import { languageModelDisplay } from "../models/display"
3
4
  import { OPENAPI_TAGS } from "../openapi/tags"
4
5
  import { ModelCatalogSchema } from "../schemas/models"
5
6
 
6
- function serializeLanguageModel(entry: LanguageModelEntry, defaultRef: string) {
7
- return { provider: entry.provider, modelId: entry.modelId, isDefault: entry.ref === defaultRef }
7
+ async function serializeLanguageModel(entry: LanguageModelEntry, defaultEntry: LanguageModelEntry) {
8
+ return {
9
+ ...(await languageModelDisplay(entry)),
10
+ provider: entry.provider,
11
+ modelId: entry.modelId,
12
+ isDefault: entry.provider === defaultEntry.provider && entry.modelId === defaultEntry.modelId,
13
+ }
8
14
  }
9
15
 
10
16
  export function registerModelRoutes(app: Elysia, host: SixbHostView) {
11
17
  return app.get(
12
18
  "/api/models",
13
- () => {
19
+ async () => {
14
20
  const language = host.definitions.models?.language
15
21
  return ModelCatalogSchema.parse({
16
22
  language:
17
23
  language === undefined
18
24
  ? []
19
- : language.list().map((entry) => serializeLanguageModel(entry, language.default.ref)),
25
+ : await Promise.all(
26
+ language.list().map((entry) => serializeLanguageModel(entry, language.default))
27
+ ),
20
28
  })
21
29
  },
22
30
  {
@@ -0,0 +1,238 @@
1
+ import {
2
+ AuthorizationError,
3
+ type SharedAccessGrant,
4
+ ShareError,
5
+ type SixbHostView,
6
+ } from "@sixb/core"
7
+ import { ObjectNotFoundError } from "@sixb/core/storage"
8
+ import type { Elysia } from "elysia"
9
+ import { bearerSecurityRequirement } from "../auth/access-token-boundary"
10
+ import { requireRequestSixb } from "../auth/scope"
11
+ import { OPENAPI_TAGS } from "../openapi/tags"
12
+ import { ErrorResponseSchema } from "../schemas/common"
13
+ import {
14
+ IssueSharedAccessGrantBodySchema,
15
+ IssueSharedAccessGrantResponseSchema,
16
+ ListSharedAccessGrantsQuerySchema,
17
+ ListSharedAccessGrantsResponseSchema,
18
+ RevokeSharedAccessGrantResponseSchema,
19
+ SharedAccessGrantIdParamsSchema,
20
+ SharedAccessGrantSchema,
21
+ } from "../schemas/share-grants"
22
+
23
+ const INTERNAL_ERROR = "[SixbServer] Shared-access operation failed."
24
+ const STORAGE_UNAVAILABLE_ERROR =
25
+ "[SixbServer] Shared-access grant storage is not configured on this runtime."
26
+
27
+ export function registerShareGrantRoutes(app: Elysia, _host: SixbHostView) {
28
+ return app
29
+ .post(
30
+ "/api/share-grants",
31
+ async (context) => {
32
+ const { body, set } = context
33
+ setNoStore(set)
34
+ try {
35
+ const invitation = await requireRequestSixb(context).shares.issueById({
36
+ definitionId: body.definitionId,
37
+ target: body.target,
38
+ destinationPath: body.destinationPath,
39
+ expiresAt: new Date(body.expiresAt),
40
+ })
41
+ const grant = serializeSharedAccessGrant(invitation.grant)
42
+
43
+ set.status = 201
44
+ return IssueSharedAccessGrantResponseSchema.parse({
45
+ grant,
46
+ url: sharedAccessUrl(grant.id, grant.destinationPath, invitation.secret),
47
+ })
48
+ } catch (error) {
49
+ return handleShareGrantRouteError(error, set)
50
+ }
51
+ },
52
+ {
53
+ body: IssueSharedAccessGrantBodySchema,
54
+ response: {
55
+ 201: IssueSharedAccessGrantResponseSchema,
56
+ 400: ErrorResponseSchema,
57
+ 401: ErrorResponseSchema,
58
+ 403: ErrorResponseSchema,
59
+ 404: ErrorResponseSchema,
60
+ 500: ErrorResponseSchema,
61
+ 501: ErrorResponseSchema,
62
+ },
63
+ error: sharedAccessValidationError("Invalid shared-access grant request."),
64
+ detail: {
65
+ summary: "Issue a shared-access grant",
66
+ tags: [OPENAPI_TAGS.sharedAccess.name],
67
+ operationId: "issueSharedAccessGrant",
68
+ security: bearerSecurityRequirement("issueSharedAccessGrant"),
69
+ },
70
+ }
71
+ )
72
+ .get(
73
+ "/api/share-grants",
74
+ async (context) => {
75
+ const { query, set } = context
76
+ setNoStore(set)
77
+ try {
78
+ const result = await requireRequestSixb(context).shares.listById({
79
+ definitionId: query.definitionId,
80
+ primaryId: query.primaryId,
81
+ includeRevoked: query.includeRevoked,
82
+ includeExpired: query.includeExpired,
83
+ limit: query.limit,
84
+ offset: query.offset,
85
+ })
86
+
87
+ return ListSharedAccessGrantsResponseSchema.parse({
88
+ grants: result.grants.map(serializeSharedAccessGrant),
89
+ total: result.total,
90
+ hasMore: result.hasMore,
91
+ })
92
+ } catch (error) {
93
+ return handleShareGrantRouteError(error, set)
94
+ }
95
+ },
96
+ {
97
+ query: ListSharedAccessGrantsQuerySchema,
98
+ response: {
99
+ 200: ListSharedAccessGrantsResponseSchema,
100
+ 400: ErrorResponseSchema,
101
+ 401: ErrorResponseSchema,
102
+ 403: ErrorResponseSchema,
103
+ 404: ErrorResponseSchema,
104
+ 500: ErrorResponseSchema,
105
+ 501: ErrorResponseSchema,
106
+ },
107
+ error: sharedAccessValidationError("Invalid shared-access grant query."),
108
+ detail: {
109
+ summary: "List shared-access grants",
110
+ tags: [OPENAPI_TAGS.sharedAccess.name],
111
+ operationId: "listSharedAccessGrants",
112
+ security: bearerSecurityRequirement("listSharedAccessGrants"),
113
+ },
114
+ }
115
+ )
116
+ .delete(
117
+ "/api/share-grants/:grantId",
118
+ async (context) => {
119
+ const { params, set } = context
120
+ setNoStore(set)
121
+ try {
122
+ const grant = await requireRequestSixb(context).shares.revoke(params.grantId)
123
+ if (!grant) {
124
+ set.status = 404
125
+ return { error: "[SixbServer] Shared-access grant not found." }
126
+ }
127
+
128
+ return RevokeSharedAccessGrantResponseSchema.parse({
129
+ grant: serializeSharedAccessGrant(grant),
130
+ })
131
+ } catch (error) {
132
+ return handleShareGrantRouteError(error, set)
133
+ }
134
+ },
135
+ {
136
+ params: SharedAccessGrantIdParamsSchema,
137
+ response: {
138
+ 200: RevokeSharedAccessGrantResponseSchema,
139
+ 400: ErrorResponseSchema,
140
+ 401: ErrorResponseSchema,
141
+ 403: ErrorResponseSchema,
142
+ 404: ErrorResponseSchema,
143
+ 500: ErrorResponseSchema,
144
+ 501: ErrorResponseSchema,
145
+ },
146
+ error: sharedAccessValidationError("Invalid shared-access grant id."),
147
+ detail: {
148
+ summary: "Revoke a shared-access grant",
149
+ tags: [OPENAPI_TAGS.sharedAccess.name],
150
+ operationId: "revokeSharedAccessGrant",
151
+ security: bearerSecurityRequirement("revokeSharedAccessGrant"),
152
+ },
153
+ }
154
+ )
155
+ }
156
+
157
+ function serializeSharedAccessGrant(grant: SharedAccessGrant) {
158
+ return SharedAccessGrantSchema.parse({
159
+ id: grant.id,
160
+ definitionId: grant.definitionId,
161
+ target: grant.target,
162
+ issuedBy: grant.issuedBy,
163
+ destinationPath: grant.destinationPath,
164
+ createdAt: grant.createdAt.toISOString(),
165
+ expiresAt: grant.expiresAt.toISOString(),
166
+ ...(grant.revokedAt === undefined ? {} : { revokedAt: grant.revokedAt.toISOString() }),
167
+ ...(grant.revokedBy === undefined ? {} : { revokedBy: grant.revokedBy }),
168
+ })
169
+ }
170
+
171
+ function sharedAccessUrl(grantId: string, destinationPath: string, secret: string): string {
172
+ return `/shared/${encodeURIComponent(grantId)}${destinationPath}#${encodeURIComponent(secret)}`
173
+ }
174
+
175
+ function handleShareGrantRouteError(
176
+ error: unknown,
177
+ set: { status?: number | string }
178
+ ): { error: string } {
179
+ if (error instanceof ShareError) {
180
+ set.status = shareErrorStatus(error)
181
+ if (error.reason === "storage_failure") return { error: INTERNAL_ERROR }
182
+ if (error.reason === "storage_unavailable") return { error: STORAGE_UNAVAILABLE_ERROR }
183
+ if (error.reason === "unauthenticated") return { error: "Authentication required." }
184
+ return { error: error.message }
185
+ }
186
+ if (error instanceof AuthorizationError) {
187
+ set.status = 403
188
+ return { error: error.message }
189
+ }
190
+ if (error instanceof ObjectNotFoundError) {
191
+ set.status = 404
192
+ return { error: error.message }
193
+ }
194
+
195
+ set.status = 500
196
+ return { error: INTERNAL_ERROR }
197
+ }
198
+
199
+ function shareErrorStatus(error: ShareError): number {
200
+ switch (error.reason) {
201
+ case "invalid_input":
202
+ return 400
203
+ case "not_found":
204
+ return 404
205
+ case "unauthenticated":
206
+ return 401
207
+ case "storage_unavailable":
208
+ return 501
209
+ case "storage_failure":
210
+ return 500
211
+ }
212
+ }
213
+
214
+ function sharedAccessValidationError(message: string) {
215
+ return ({
216
+ code,
217
+ set,
218
+ }: {
219
+ code: unknown
220
+ set: { status?: number | string; headers?: unknown }
221
+ }) => {
222
+ if (code !== "VALIDATION") return
223
+ setNoStore(set)
224
+ set.status = 400
225
+ return { error: message }
226
+ }
227
+ }
228
+
229
+ function setNoStore(set: { headers?: unknown }): void {
230
+ if (set.headers instanceof Headers) {
231
+ set.headers.set("cache-control", "no-store")
232
+ return
233
+ }
234
+ if (!set.headers || typeof set.headers !== "object" || Array.isArray(set.headers)) {
235
+ set.headers = {}
236
+ }
237
+ ;(set.headers as Record<string, string>)["cache-control"] = "no-store"
238
+ }