@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.
- package/LICENSE +21 -0
- package/README.md +123 -0
- package/dist/auth/access-token-boundary.d.ts +23 -0
- package/dist/auth/access-token-boundary.d.ts.map +1 -0
- package/dist/auth/application-access.d.ts +4 -0
- package/dist/auth/application-access.d.ts.map +1 -0
- package/dist/auth/browser-origin.d.ts +62 -0
- package/dist/auth/browser-origin.d.ts.map +1 -0
- package/dist/auth/csrf.d.ts +2 -0
- package/dist/auth/csrf.d.ts.map +1 -0
- package/dist/auth/guard.d.ts +35 -0
- package/dist/auth/guard.d.ts.map +1 -0
- package/dist/auth/public-routes.d.ts +8 -0
- package/dist/auth/public-routes.d.ts.map +1 -0
- package/dist/auth/responses.d.ts +11 -0
- package/dist/auth/responses.d.ts.map +1 -0
- package/dist/auth/return-to.d.ts +3 -0
- package/dist/auth/return-to.d.ts.map +1 -0
- package/dist/auth/scope.d.ts +43 -0
- package/dist/auth/scope.d.ts.map +1 -0
- package/dist/auth/session-activity.d.ts +4 -0
- package/dist/auth/session-activity.d.ts.map +1 -0
- package/dist/auth/session-cookies.d.ts +12 -0
- package/dist/auth/session-cookies.d.ts.map +1 -0
- package/dist/files/content.d.ts +141 -0
- package/dist/files/content.d.ts.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11522 -0
- package/dist/index.js.map +78 -0
- package/dist/openapi/security.d.ts +26 -0
- package/dist/openapi/security.d.ts.map +1 -0
- package/dist/openapi/tags.d.ts +151 -0
- package/dist/openapi/tags.d.ts.map +1 -0
- package/dist/registerRoutes.d.ts +31 -0
- package/dist/registerRoutes.d.ts.map +1 -0
- package/dist/routes/action-runs.d.ts +244 -0
- package/dist/routes/action-runs.d.ts.map +1 -0
- package/dist/routes/actions.d.ts +183 -0
- package/dist/routes/actions.d.ts.map +1 -0
- package/dist/routes/agent-api-gateway.d.ts +4 -0
- package/dist/routes/agent-api-gateway.d.ts.map +1 -0
- package/dist/routes/agents.d.ts +1061 -0
- package/dist/routes/agents.d.ts.map +1 -0
- package/dist/routes/auth.d.ts +1366 -0
- package/dist/routes/auth.d.ts.map +1 -0
- package/dist/routes/connectors.d.ts +108 -0
- package/dist/routes/connectors.d.ts.map +1 -0
- package/dist/routes/datasets.d.ts +339 -0
- package/dist/routes/datasets.d.ts.map +1 -0
- package/dist/routes/events.d.ts +116 -0
- package/dist/routes/events.d.ts.map +1 -0
- package/dist/routes/files.d.ts +340 -0
- package/dist/routes/files.d.ts.map +1 -0
- package/dist/routes/links.d.ts +175 -0
- package/dist/routes/links.d.ts.map +1 -0
- package/dist/routes/logs.d.ts +88 -0
- package/dist/routes/logs.d.ts.map +1 -0
- package/dist/routes/objects.d.ts +450 -0
- package/dist/routes/objects.d.ts.map +1 -0
- package/dist/routes/ontology.d.ts +240 -0
- package/dist/routes/ontology.d.ts.map +1 -0
- package/dist/routes/pipelines.d.ts +399 -0
- package/dist/routes/pipelines.d.ts.map +1 -0
- package/dist/routes/project.d.ts +56 -0
- package/dist/routes/project.d.ts.map +1 -0
- package/dist/routes/projections.d.ts +916 -0
- package/dist/routes/projections.d.ts.map +1 -0
- package/dist/routes/rules.d.ts +165 -0
- package/dist/routes/rules.d.ts.map +1 -0
- package/dist/routes/status.d.ts +81 -0
- package/dist/routes/status.d.ts.map +1 -0
- package/dist/routes/syncs.d.ts +294 -0
- package/dist/routes/syncs.d.ts.map +1 -0
- package/dist/routes/telemetry.d.ts +241 -0
- package/dist/routes/telemetry.d.ts.map +1 -0
- package/dist/routes/webhook-runs.d.ts +89 -0
- package/dist/routes/webhook-runs.d.ts.map +1 -0
- package/dist/routes/webhooks.d.ts +60 -0
- package/dist/routes/webhooks.d.ts.map +1 -0
- package/dist/routes/workflows.d.ts +973 -0
- package/dist/routes/workflows.d.ts.map +1 -0
- package/dist/routes/ws/agents.d.ts +99 -0
- package/dist/routes/ws/agents.d.ts.map +1 -0
- package/dist/routes/ws/events.d.ts +89 -0
- package/dist/routes/ws/events.d.ts.map +1 -0
- package/dist/routes/ws/index.d.ts +31 -0
- package/dist/routes/ws/index.d.ts.map +1 -0
- package/dist/routes/ws/log-subscription-hub.d.ts +47 -0
- package/dist/routes/ws/log-subscription-hub.d.ts.map +1 -0
- package/dist/routes/ws/logs.d.ts +110 -0
- package/dist/routes/ws/logs.d.ts.map +1 -0
- package/dist/schemas/actions.d.ts +644 -0
- package/dist/schemas/actions.d.ts.map +1 -0
- package/dist/schemas/agents.d.ts +3157 -0
- package/dist/schemas/agents.d.ts.map +1 -0
- package/dist/schemas/auth.d.ts +2023 -0
- package/dist/schemas/auth.d.ts.map +1 -0
- package/dist/schemas/common.d.ts +30 -0
- package/dist/schemas/common.d.ts.map +1 -0
- package/dist/schemas/connectors.d.ts +82 -0
- package/dist/schemas/connectors.d.ts.map +1 -0
- package/dist/schemas/datasets.d.ts +744 -0
- package/dist/schemas/datasets.d.ts.map +1 -0
- package/dist/schemas/event-payloads.d.ts +477 -0
- package/dist/schemas/event-payloads.d.ts.map +1 -0
- package/dist/schemas/events.d.ts +665 -0
- package/dist/schemas/events.d.ts.map +1 -0
- package/dist/schemas/files.d.ts +241 -0
- package/dist/schemas/files.d.ts.map +1 -0
- package/dist/schemas/links.d.ts +90 -0
- package/dist/schemas/links.d.ts.map +1 -0
- package/dist/schemas/logs.d.ts +231 -0
- package/dist/schemas/logs.d.ts.map +1 -0
- package/dist/schemas/objects.d.ts +288 -0
- package/dist/schemas/objects.d.ts.map +1 -0
- package/dist/schemas/ontology.d.ts +778 -0
- package/dist/schemas/ontology.d.ts.map +1 -0
- package/dist/schemas/pipelines.d.ts +1373 -0
- package/dist/schemas/pipelines.d.ts.map +1 -0
- package/dist/schemas/project.d.ts +9 -0
- package/dist/schemas/project.d.ts.map +1 -0
- package/dist/schemas/projections.d.ts +6992 -0
- package/dist/schemas/projections.d.ts.map +1 -0
- package/dist/schemas/rules.d.ts +204 -0
- package/dist/schemas/rules.d.ts.map +1 -0
- package/dist/schemas/status.d.ts +189 -0
- package/dist/schemas/status.d.ts.map +1 -0
- package/dist/schemas/syncs.d.ts +538 -0
- package/dist/schemas/syncs.d.ts.map +1 -0
- package/dist/schemas/telemetry.d.ts +265 -0
- package/dist/schemas/telemetry.d.ts.map +1 -0
- package/dist/schemas/webhook-runs.d.ts +169 -0
- package/dist/schemas/webhook-runs.d.ts.map +1 -0
- package/dist/schemas/workflows.d.ts +1720 -0
- package/dist/schemas/workflows.d.ts.map +1 -0
- package/dist/server.d.ts +64 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/tsconfig.json +5 -0
- package/dist/utils/http.d.ts +23 -0
- package/dist/utils/http.d.ts.map +1 -0
- package/dist/utils/request-body.d.ts +15 -0
- package/dist/utils/request-body.d.ts.map +1 -0
- package/dist/utils/ws.d.ts +10 -0
- package/dist/utils/ws.d.ts.map +1 -0
- package/package.json +68 -0
- package/src/auth/access-token-boundary.ts +68 -0
- package/src/auth/application-access.ts +16 -0
- package/src/auth/browser-origin.ts +367 -0
- package/src/auth/csrf.ts +1 -0
- package/src/auth/guard.ts +169 -0
- package/src/auth/public-routes.ts +87 -0
- package/src/auth/responses.ts +54 -0
- package/src/auth/return-to.ts +21 -0
- package/src/auth/scope.ts +64 -0
- package/src/auth/session-activity.ts +19 -0
- package/src/auth/session-cookies.ts +43 -0
- package/src/files/content.ts +419 -0
- package/src/index.ts +2 -0
- package/src/openapi/security.ts +37 -0
- package/src/openapi/tags.ts +151 -0
- package/src/registerRoutes.ts +49 -0
- package/src/routes/action-runs.ts +238 -0
- package/src/routes/actions.ts +126 -0
- package/src/routes/agent-api-gateway.ts +260 -0
- package/src/routes/agents.ts +943 -0
- package/src/routes/auth.ts +2233 -0
- package/src/routes/connectors.ts +69 -0
- package/src/routes/datasets.ts +402 -0
- package/src/routes/events.ts +55 -0
- package/src/routes/files.ts +675 -0
- package/src/routes/links.ts +143 -0
- package/src/routes/logs.ts +65 -0
- package/src/routes/objects.ts +838 -0
- package/src/routes/ontology.ts +138 -0
- package/src/routes/pipelines.ts +332 -0
- package/src/routes/project.ts +16 -0
- package/src/routes/projections.ts +251 -0
- package/src/routes/rules.ts +124 -0
- package/src/routes/status.ts +53 -0
- package/src/routes/syncs.ts +243 -0
- package/src/routes/telemetry.ts +207 -0
- package/src/routes/webhook-runs.ts +81 -0
- package/src/routes/webhooks.ts +508 -0
- package/src/routes/workflows.ts +1333 -0
- package/src/routes/ws/agents.ts +301 -0
- package/src/routes/ws/events.ts +278 -0
- package/src/routes/ws/index.ts +12 -0
- package/src/routes/ws/log-subscription-hub.ts +375 -0
- package/src/routes/ws/logs.ts +117 -0
- package/src/schemas/actions.ts +123 -0
- package/src/schemas/agents.ts +293 -0
- package/src/schemas/auth.ts +317 -0
- package/src/schemas/common.ts +60 -0
- package/src/schemas/connectors.ts +21 -0
- package/src/schemas/datasets.ts +107 -0
- package/src/schemas/event-payloads.ts +79 -0
- package/src/schemas/events.ts +117 -0
- package/src/schemas/files.ts +82 -0
- package/src/schemas/links.ts +38 -0
- package/src/schemas/logs.ts +76 -0
- package/src/schemas/objects.ts +759 -0
- package/src/schemas/ontology.ts +77 -0
- package/src/schemas/pipelines.ts +150 -0
- package/src/schemas/project.ts +5 -0
- package/src/schemas/projections.ts +144 -0
- package/src/schemas/rules.ts +98 -0
- package/src/schemas/status.ts +51 -0
- package/src/schemas/syncs.ts +83 -0
- package/src/schemas/telemetry.ts +59 -0
- package/src/schemas/webhook-runs.ts +40 -0
- package/src/schemas/workflows.ts +229 -0
- package/src/server.ts +383 -0
- package/src/utils/http.ts +108 -0
- package/src/utils/request-body.ts +62 -0
- package/src/utils/ws.ts +59 -0
|
@@ -0,0 +1,2233 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto"
|
|
2
|
+
import type { AuthSessionAudience, GroupDefinition, OntologySource, Sixb } from "@sixb/core"
|
|
3
|
+
import {
|
|
4
|
+
type AuthenticatedUserRequestSession,
|
|
5
|
+
type AuthRequestResult,
|
|
6
|
+
AuthRuntimeError,
|
|
7
|
+
clearCsrfCookieHeader,
|
|
8
|
+
clearSessionCookieHeader,
|
|
9
|
+
createCsrfCookieHeader,
|
|
10
|
+
createSessionCookieHeader,
|
|
11
|
+
createSessionCredential,
|
|
12
|
+
generateCsrfToken,
|
|
13
|
+
getCookie,
|
|
14
|
+
isMagicLinkAuthStrategy,
|
|
15
|
+
isOidcAuthStrategy,
|
|
16
|
+
type MagicLinkAuthStrategy,
|
|
17
|
+
type MemberSummary,
|
|
18
|
+
shouldUseSecureCookies,
|
|
19
|
+
verifyDoubleSubmitCsrf,
|
|
20
|
+
} from "@sixb/core/internal/auth"
|
|
21
|
+
import {
|
|
22
|
+
type AccessTokenRecord,
|
|
23
|
+
type AuthStorage,
|
|
24
|
+
AuthStorageError,
|
|
25
|
+
type InvitationRecord,
|
|
26
|
+
type ServiceAccountRecord,
|
|
27
|
+
type UserRecord,
|
|
28
|
+
} from "@sixb/core/storage"
|
|
29
|
+
import { type Elysia, t } from "elysia"
|
|
30
|
+
import { bearerSecurityRequirement } from "../auth/access-token-boundary"
|
|
31
|
+
import { sessionCanAccessApplication } from "../auth/application-access"
|
|
32
|
+
import {
|
|
33
|
+
type AuthInvitationDestinationOptions,
|
|
34
|
+
type AuthInvitationRedirectContext,
|
|
35
|
+
type AuthInvitationRedirectInput,
|
|
36
|
+
type AuthRedirectContext,
|
|
37
|
+
BrowserOriginError,
|
|
38
|
+
type ResolveAuthRedirectContext,
|
|
39
|
+
type ResolveRequestAuthContext,
|
|
40
|
+
} from "../auth/browser-origin"
|
|
41
|
+
import { CSRF_TOKEN_RESPONSE_HEADER_NAME } from "../auth/csrf"
|
|
42
|
+
import { hasForegroundSessionActivity } from "../auth/session-activity"
|
|
43
|
+
import { createSessionRenewalCookieHeaders } from "../auth/session-cookies"
|
|
44
|
+
import { SIXB_CSRF_SECURITY_REQUIREMENT } from "../openapi/security"
|
|
45
|
+
import { OPENAPI_TAGS } from "../openapi/tags"
|
|
46
|
+
import {
|
|
47
|
+
AuthMemberParamsSchema,
|
|
48
|
+
AuthServiceAccountParamsSchema,
|
|
49
|
+
AuthSessionResponseSchema,
|
|
50
|
+
AuthSignOutResponseSchema,
|
|
51
|
+
CreateAuthInvitationBodySchema,
|
|
52
|
+
CreateAuthInvitationResponseSchema,
|
|
53
|
+
CreateAuthPersonalAccessTokenBodySchema,
|
|
54
|
+
CreateAuthPersonalAccessTokenResponseSchema,
|
|
55
|
+
CreateAuthServiceAccountAccessTokenBodySchema,
|
|
56
|
+
CreateAuthServiceAccountAccessTokenResponseSchema,
|
|
57
|
+
CreateAuthServiceAccountBodySchema,
|
|
58
|
+
CreateAuthServiceAccountResponseSchema,
|
|
59
|
+
DisableAuthServiceAccountResponseSchema,
|
|
60
|
+
GetAuthAccessManagementOptionsResponseSchema,
|
|
61
|
+
GetAuthInvitationOptionsResponseSchema,
|
|
62
|
+
GetAuthMembershipOptionsResponseSchema,
|
|
63
|
+
ListAuthAccessTokensResponseSchema,
|
|
64
|
+
ListAuthInvitationsQuerySchema,
|
|
65
|
+
ListAuthInvitationsResponseSchema,
|
|
66
|
+
ListAuthMembersQuerySchema,
|
|
67
|
+
ListAuthMembersResponseSchema,
|
|
68
|
+
ListAuthServiceAccountAccessTokensResponseSchema,
|
|
69
|
+
ListAuthServiceAccountsResponseSchema,
|
|
70
|
+
ListAuthSessionsResponseSchema,
|
|
71
|
+
ReactivateAuthMemberResponseSchema,
|
|
72
|
+
RevokeAuthAccessTokenParamsSchema,
|
|
73
|
+
RevokeAuthAccessTokenResponseSchema,
|
|
74
|
+
RevokeAuthInvitationParamsSchema,
|
|
75
|
+
RevokeAuthInvitationResponseSchema,
|
|
76
|
+
RevokeAuthServiceAccountAccessTokenParamsSchema,
|
|
77
|
+
RevokeAuthServiceAccountAccessTokenResponseSchema,
|
|
78
|
+
RevokeAuthSessionParamsSchema,
|
|
79
|
+
RevokeAuthSessionResponseSchema,
|
|
80
|
+
SignOutAllResponseSchema,
|
|
81
|
+
SuspendAuthMemberResponseSchema,
|
|
82
|
+
UpdateAuthMemberGroupsBodySchema,
|
|
83
|
+
UpdateAuthMemberGroupsResponseSchema,
|
|
84
|
+
} from "../schemas/auth"
|
|
85
|
+
import { ErrorResponseSchema } from "../schemas/common"
|
|
86
|
+
import { parseDate, parseOptionalInt, toIsoString } from "../utils/http"
|
|
87
|
+
|
|
88
|
+
type ResolvedCookieOptions = Parameters<typeof createCsrfCookieHeader>[0]["options"]
|
|
89
|
+
type AuthenticatedAuthSessionResponse = {
|
|
90
|
+
readonly authenticated: true
|
|
91
|
+
readonly csrfToken: string
|
|
92
|
+
readonly applicationAccess: {
|
|
93
|
+
readonly allowed: boolean
|
|
94
|
+
readonly audience: AuthSessionAudience
|
|
95
|
+
}
|
|
96
|
+
readonly user: {
|
|
97
|
+
readonly id: string
|
|
98
|
+
readonly email: string
|
|
99
|
+
readonly displayName?: string
|
|
100
|
+
readonly avatarUrl?: string
|
|
101
|
+
readonly groupIds: readonly string[]
|
|
102
|
+
}
|
|
103
|
+
readonly session: {
|
|
104
|
+
readonly id: string
|
|
105
|
+
readonly expiresAt: string
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface AuthRoutesOptions {
|
|
110
|
+
readonly resolveAuthContext: ResolveRequestAuthContext
|
|
111
|
+
readonly resolveAuthRedirectContext: ResolveAuthRedirectContext
|
|
112
|
+
readonly getInvitationDestinationOptions: (request: Request) => AuthInvitationDestinationOptions
|
|
113
|
+
readonly resolveAuthRequestOrigin: (request: Request) => string
|
|
114
|
+
readonly resolveInvitationRedirectContext: (
|
|
115
|
+
request: Request,
|
|
116
|
+
input: AuthInvitationRedirectInput
|
|
117
|
+
) => AuthInvitationRedirectContext
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function registerAuthRoutes(
|
|
121
|
+
app: Elysia,
|
|
122
|
+
sixb: Sixb<readonly OntologySource[]>,
|
|
123
|
+
options: AuthRoutesOptions
|
|
124
|
+
) {
|
|
125
|
+
return app
|
|
126
|
+
.get(
|
|
127
|
+
"/api/auth/session",
|
|
128
|
+
async ({ request }) => {
|
|
129
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
130
|
+
let session = await sixb.auth.getSession(request, authOptions)
|
|
131
|
+
if (!session.authenticated) {
|
|
132
|
+
return jsonResponse({ authenticated: false as const }, 200)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
let applicationAccessAllowed = sessionCanAccessApplication(
|
|
136
|
+
sixb,
|
|
137
|
+
session,
|
|
138
|
+
authOptions.audience
|
|
139
|
+
)
|
|
140
|
+
if (applicationAccessAllowed && hasForegroundSessionActivity(request)) {
|
|
141
|
+
session = await sixb.auth.getSession(request, {
|
|
142
|
+
...authOptions,
|
|
143
|
+
sessionActivity: "foreground",
|
|
144
|
+
})
|
|
145
|
+
if (!session.authenticated) {
|
|
146
|
+
return jsonResponse({ authenticated: false as const }, 200)
|
|
147
|
+
}
|
|
148
|
+
applicationAccessAllowed = sessionCanAccessApplication(
|
|
149
|
+
sixb,
|
|
150
|
+
session,
|
|
151
|
+
authOptions.audience
|
|
152
|
+
)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const cookieOptions = sixb.auth.getCookieOptions(authOptions)
|
|
156
|
+
const csrf = resolveSessionCsrfToken({
|
|
157
|
+
request,
|
|
158
|
+
cookieOptions,
|
|
159
|
+
expiresAt: session.session.expiresAt,
|
|
160
|
+
})
|
|
161
|
+
const renewal =
|
|
162
|
+
session.sessionRenewed === true
|
|
163
|
+
? createSessionRenewalCookieHeaders({
|
|
164
|
+
sixb,
|
|
165
|
+
request,
|
|
166
|
+
session,
|
|
167
|
+
csrfToken: csrf.token,
|
|
168
|
+
})
|
|
169
|
+
: null
|
|
170
|
+
return authSessionJsonResponse(
|
|
171
|
+
{
|
|
172
|
+
authenticated: true as const,
|
|
173
|
+
csrfToken: csrf.token,
|
|
174
|
+
applicationAccess: {
|
|
175
|
+
allowed: applicationAccessAllowed,
|
|
176
|
+
audience: authOptions.audience,
|
|
177
|
+
},
|
|
178
|
+
user: {
|
|
179
|
+
id: session.user.id,
|
|
180
|
+
email: session.user.email,
|
|
181
|
+
displayName: session.user.displayName,
|
|
182
|
+
avatarUrl: session.user.avatarUrl,
|
|
183
|
+
groupIds: [...session.groupIds],
|
|
184
|
+
},
|
|
185
|
+
session: {
|
|
186
|
+
id: session.session.id,
|
|
187
|
+
expiresAt: toIsoString(session.session.expiresAt),
|
|
188
|
+
},
|
|
189
|
+
},
|
|
190
|
+
renewal?.headers ?? (csrf.setCookie ? [csrf.setCookie] : [])
|
|
191
|
+
)
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
response: { 200: AuthSessionResponseSchema },
|
|
195
|
+
detail: {
|
|
196
|
+
summary: "Get current auth session",
|
|
197
|
+
tags: [OPENAPI_TAGS.authSessions.name],
|
|
198
|
+
operationId: "getAuthSession",
|
|
199
|
+
},
|
|
200
|
+
}
|
|
201
|
+
)
|
|
202
|
+
.post(
|
|
203
|
+
"/api/auth/sign-out",
|
|
204
|
+
async ({ request }) => {
|
|
205
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
206
|
+
const session = await sixb.auth.getSession(request, authOptions)
|
|
207
|
+
const cookieOptions = sixb.auth.getCookieOptions(authOptions)
|
|
208
|
+
if (
|
|
209
|
+
session.authenticated &&
|
|
210
|
+
!verifyDoubleSubmitCsrf(request, {
|
|
211
|
+
cookieName: cookieOptions.csrfCookieName,
|
|
212
|
+
})
|
|
213
|
+
) {
|
|
214
|
+
return jsonResponse({ error: "CSRF verification failed" }, 403)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
if (session.authenticated) {
|
|
218
|
+
await sixb.storage.auth?.sessions.revoke({
|
|
219
|
+
projectId: sixb.id,
|
|
220
|
+
id: session.session.id,
|
|
221
|
+
revokedAt: new Date(),
|
|
222
|
+
})
|
|
223
|
+
// Drop the cached session immediately so it isn't honored for the cache TTL.
|
|
224
|
+
sixb.auth.invalidateSession(session.session.id)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
|
|
228
|
+
headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }))
|
|
229
|
+
headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }))
|
|
230
|
+
|
|
231
|
+
return new Response(JSON.stringify({ success: true }), {
|
|
232
|
+
status: 200,
|
|
233
|
+
headers,
|
|
234
|
+
})
|
|
235
|
+
},
|
|
236
|
+
{
|
|
237
|
+
response: {
|
|
238
|
+
200: AuthSignOutResponseSchema,
|
|
239
|
+
403: ErrorResponseSchema,
|
|
240
|
+
},
|
|
241
|
+
detail: {
|
|
242
|
+
summary: "Sign out current auth session",
|
|
243
|
+
tags: [OPENAPI_TAGS.authSessions.name],
|
|
244
|
+
operationId: "signOut",
|
|
245
|
+
security: SIXB_CSRF_SECURITY_REQUIREMENT,
|
|
246
|
+
},
|
|
247
|
+
}
|
|
248
|
+
)
|
|
249
|
+
.get(
|
|
250
|
+
"/api/auth/sessions",
|
|
251
|
+
async ({ request }) => {
|
|
252
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
253
|
+
const session = await sixb.auth.getSession(request, authOptions)
|
|
254
|
+
if (!session.authenticated) {
|
|
255
|
+
return jsonResponse({ error: "Authentication required" }, 401)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const sessions = await requireAuthStorage(sixb).sessions.listActiveByUserId({
|
|
259
|
+
projectId: sixb.id,
|
|
260
|
+
userId: session.user.id,
|
|
261
|
+
now: new Date(),
|
|
262
|
+
})
|
|
263
|
+
|
|
264
|
+
return jsonResponse(
|
|
265
|
+
{
|
|
266
|
+
sessions: sessions.map((entry) => ({
|
|
267
|
+
id: entry.id,
|
|
268
|
+
audience: entry.audience,
|
|
269
|
+
current: entry.id === session.session.id,
|
|
270
|
+
createdAt: toIsoString(entry.createdAt),
|
|
271
|
+
expiresAt: toIsoString(entry.expiresAt),
|
|
272
|
+
lastSeenAt: entry.lastSeenAt ? toIsoString(entry.lastSeenAt) : undefined,
|
|
273
|
+
userAgent: entry.userAgent,
|
|
274
|
+
ipAddress: entry.ipAddress,
|
|
275
|
+
})),
|
|
276
|
+
},
|
|
277
|
+
200
|
|
278
|
+
)
|
|
279
|
+
},
|
|
280
|
+
{
|
|
281
|
+
response: {
|
|
282
|
+
200: ListAuthSessionsResponseSchema,
|
|
283
|
+
401: ErrorResponseSchema,
|
|
284
|
+
},
|
|
285
|
+
detail: {
|
|
286
|
+
summary: "List active sessions for the current user",
|
|
287
|
+
tags: [OPENAPI_TAGS.authSessions.name],
|
|
288
|
+
operationId: "listAuthSessions",
|
|
289
|
+
},
|
|
290
|
+
}
|
|
291
|
+
)
|
|
292
|
+
.post(
|
|
293
|
+
"/api/auth/sessions/:sessionId/revoke",
|
|
294
|
+
async ({ request, params }) => {
|
|
295
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
296
|
+
const session = await sixb.auth.getSession(request, authOptions)
|
|
297
|
+
const cookieOptions = sixb.auth.getCookieOptions(authOptions)
|
|
298
|
+
if (!session.authenticated) {
|
|
299
|
+
return jsonResponse({ error: "Authentication required" }, 401)
|
|
300
|
+
}
|
|
301
|
+
if (!verifyDoubleSubmitCsrf(request, { cookieName: cookieOptions.csrfCookieName })) {
|
|
302
|
+
return jsonResponse({ error: "CSRF verification failed" }, 403)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const { sessionId } = RevokeAuthSessionParamsSchema.parse(params)
|
|
306
|
+
const storage = requireAuthStorage(sixb)
|
|
307
|
+
const target = await storage.sessions.getById({ projectId: sixb.id, id: sessionId })
|
|
308
|
+
// Only the caller's own sessions are revocable. A missing or foreign
|
|
309
|
+
// session id returns the same 404 so it cannot probe other accounts.
|
|
310
|
+
if (!target || target.userId !== session.user.id) {
|
|
311
|
+
return jsonResponse({ error: "Session not found" }, 404)
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
await storage.sessions.revoke({ projectId: sixb.id, id: sessionId, revokedAt: new Date() })
|
|
315
|
+
sixb.auth.invalidateSession(sessionId)
|
|
316
|
+
|
|
317
|
+
const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
|
|
318
|
+
// Revoking the session backing this request also clears its cookies.
|
|
319
|
+
if (sessionId === session.session.id) {
|
|
320
|
+
headers.append(
|
|
321
|
+
"set-cookie",
|
|
322
|
+
clearSessionCookieHeader({ request, options: cookieOptions })
|
|
323
|
+
)
|
|
324
|
+
headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }))
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
return new Response(JSON.stringify({ success: true }), { status: 200, headers })
|
|
328
|
+
},
|
|
329
|
+
{
|
|
330
|
+
params: RevokeAuthSessionParamsSchema,
|
|
331
|
+
response: {
|
|
332
|
+
200: RevokeAuthSessionResponseSchema,
|
|
333
|
+
401: ErrorResponseSchema,
|
|
334
|
+
403: ErrorResponseSchema,
|
|
335
|
+
404: ErrorResponseSchema,
|
|
336
|
+
},
|
|
337
|
+
detail: {
|
|
338
|
+
summary: "Revoke one of the current user's sessions",
|
|
339
|
+
tags: [OPENAPI_TAGS.authSessions.name],
|
|
340
|
+
operationId: "revokeAuthSession",
|
|
341
|
+
security: SIXB_CSRF_SECURITY_REQUIREMENT,
|
|
342
|
+
},
|
|
343
|
+
}
|
|
344
|
+
)
|
|
345
|
+
.post(
|
|
346
|
+
"/api/auth/sign-out-all",
|
|
347
|
+
async ({ request }) => {
|
|
348
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
349
|
+
const session = await sixb.auth.getSession(request, authOptions)
|
|
350
|
+
const cookieOptions = sixb.auth.getCookieOptions(authOptions)
|
|
351
|
+
if (!session.authenticated) {
|
|
352
|
+
return jsonResponse({ error: "Authentication required" }, 401)
|
|
353
|
+
}
|
|
354
|
+
if (!verifyDoubleSubmitCsrf(request, { cookieName: cookieOptions.csrfCookieName })) {
|
|
355
|
+
return jsonResponse({ error: "CSRF verification failed" }, 403)
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Global sign-out: revoke every active session for the user across all
|
|
359
|
+
// audiences. Other audiences' cookies remain client-side but their
|
|
360
|
+
// sessions are revoked, so the next request re-authenticates.
|
|
361
|
+
const revoked = await requireAuthStorage(sixb).sessions.revokeActiveForUser({
|
|
362
|
+
projectId: sixb.id,
|
|
363
|
+
userId: session.user.id,
|
|
364
|
+
revokedAt: new Date(),
|
|
365
|
+
})
|
|
366
|
+
for (const revokedSession of revoked) {
|
|
367
|
+
sixb.auth.invalidateSession(revokedSession.id)
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
const headers = new Headers({ "content-type": "application/json; charset=utf-8" })
|
|
371
|
+
headers.append("set-cookie", clearSessionCookieHeader({ request, options: cookieOptions }))
|
|
372
|
+
headers.append("set-cookie", clearCsrfCookieHeader({ request, options: cookieOptions }))
|
|
373
|
+
|
|
374
|
+
return new Response(JSON.stringify({ success: true, revokedCount: revoked.length }), {
|
|
375
|
+
status: 200,
|
|
376
|
+
headers,
|
|
377
|
+
})
|
|
378
|
+
},
|
|
379
|
+
{
|
|
380
|
+
response: {
|
|
381
|
+
200: SignOutAllResponseSchema,
|
|
382
|
+
401: ErrorResponseSchema,
|
|
383
|
+
403: ErrorResponseSchema,
|
|
384
|
+
},
|
|
385
|
+
detail: {
|
|
386
|
+
summary: "Sign out the current user everywhere (all devices and apps)",
|
|
387
|
+
tags: [OPENAPI_TAGS.authSessions.name],
|
|
388
|
+
operationId: "signOutAll",
|
|
389
|
+
security: SIXB_CSRF_SECURITY_REQUIREMENT,
|
|
390
|
+
},
|
|
391
|
+
}
|
|
392
|
+
)
|
|
393
|
+
.get(
|
|
394
|
+
"/api/auth/access-management-options",
|
|
395
|
+
async ({ request }) => {
|
|
396
|
+
try {
|
|
397
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
398
|
+
const session = requireAuthenticatedUserSession(
|
|
399
|
+
await sixb.auth.getSession(request, {
|
|
400
|
+
...authOptions,
|
|
401
|
+
credentialSource: "any",
|
|
402
|
+
})
|
|
403
|
+
)
|
|
404
|
+
if (session instanceof Response) {
|
|
405
|
+
return session
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const assignableGroupIds = new Set(session.groupIds)
|
|
409
|
+
|
|
410
|
+
return jsonResponse(
|
|
411
|
+
{
|
|
412
|
+
groups: sixb.security
|
|
413
|
+
.listGroups()
|
|
414
|
+
// V1 avoids privilege escalation by only offering groups the
|
|
415
|
+
// current session already has. Runtime token auth still
|
|
416
|
+
// intersects groups at request time as a second boundary.
|
|
417
|
+
.filter((group) => assignableGroupIds.has(group.id))
|
|
418
|
+
.map(serializeGroupOption),
|
|
419
|
+
},
|
|
420
|
+
200
|
|
421
|
+
)
|
|
422
|
+
} catch (error) {
|
|
423
|
+
return authRouteErrorResponse(error)
|
|
424
|
+
}
|
|
425
|
+
},
|
|
426
|
+
{
|
|
427
|
+
response: {
|
|
428
|
+
200: GetAuthAccessManagementOptionsResponseSchema,
|
|
429
|
+
401: ErrorResponseSchema,
|
|
430
|
+
500: ErrorResponseSchema,
|
|
431
|
+
},
|
|
432
|
+
detail: {
|
|
433
|
+
summary: "Get auth access-token management options",
|
|
434
|
+
tags: [OPENAPI_TAGS.authAccessTokens.name],
|
|
435
|
+
operationId: "getAuthAccessManagementOptions",
|
|
436
|
+
security: bearerSecurityRequirement("getAuthAccessManagementOptions"),
|
|
437
|
+
},
|
|
438
|
+
}
|
|
439
|
+
)
|
|
440
|
+
.get(
|
|
441
|
+
"/api/auth/access-tokens",
|
|
442
|
+
async ({ request }) => {
|
|
443
|
+
try {
|
|
444
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
445
|
+
const session = requireAuthenticatedUserSession(
|
|
446
|
+
await sixb.auth.getSession(request, {
|
|
447
|
+
...authOptions,
|
|
448
|
+
credentialSource: "any",
|
|
449
|
+
})
|
|
450
|
+
)
|
|
451
|
+
if (session instanceof Response) {
|
|
452
|
+
return session
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const { accessTokens } = await sixb.auth.listPersonalAccessTokens(request, authOptions)
|
|
456
|
+
|
|
457
|
+
return jsonResponse(
|
|
458
|
+
{
|
|
459
|
+
accessTokens: accessTokens.map((accessToken) =>
|
|
460
|
+
serializeAccessToken(accessToken, { subjectLabel: session.user.email })
|
|
461
|
+
),
|
|
462
|
+
},
|
|
463
|
+
200
|
|
464
|
+
)
|
|
465
|
+
} catch (error) {
|
|
466
|
+
return authRouteErrorResponse(error)
|
|
467
|
+
}
|
|
468
|
+
},
|
|
469
|
+
{
|
|
470
|
+
response: {
|
|
471
|
+
200: ListAuthAccessTokensResponseSchema,
|
|
472
|
+
401: ErrorResponseSchema,
|
|
473
|
+
500: ErrorResponseSchema,
|
|
474
|
+
},
|
|
475
|
+
detail: {
|
|
476
|
+
summary: "List personal access tokens for the current user",
|
|
477
|
+
tags: [OPENAPI_TAGS.authAccessTokens.name],
|
|
478
|
+
operationId: "listAuthAccessTokens",
|
|
479
|
+
security: bearerSecurityRequirement("listAuthAccessTokens"),
|
|
480
|
+
},
|
|
481
|
+
}
|
|
482
|
+
)
|
|
483
|
+
.post(
|
|
484
|
+
"/api/auth/access-tokens",
|
|
485
|
+
async ({ request, body }) => {
|
|
486
|
+
try {
|
|
487
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
488
|
+
const parsed = CreateAuthPersonalAccessTokenBodySchema.parse(body)
|
|
489
|
+
const session = requireAuthenticatedUserSession(
|
|
490
|
+
await sixb.auth.getSession(request, {
|
|
491
|
+
...authOptions,
|
|
492
|
+
credentialSource: "any",
|
|
493
|
+
})
|
|
494
|
+
)
|
|
495
|
+
if (session instanceof Response) {
|
|
496
|
+
return session
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
const expiresAt = parseRequiredFutureDate(parsed.expiresAt)
|
|
500
|
+
const result = await sixb.auth.createPersonalAccessToken(
|
|
501
|
+
request,
|
|
502
|
+
{ name: parsed.name, expiresAt, groupIds: parsed.groupIds },
|
|
503
|
+
authOptions
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
// The raw token is only returned on creation. Storage keeps a hash, so
|
|
507
|
+
// Atlas can never reveal it again after this response leaves the page.
|
|
508
|
+
return jsonResponse(
|
|
509
|
+
{
|
|
510
|
+
accessToken: serializeAccessToken(result.accessToken, {
|
|
511
|
+
subjectLabel: session.user.email,
|
|
512
|
+
}),
|
|
513
|
+
tokenValue: result.tokenValue,
|
|
514
|
+
},
|
|
515
|
+
201
|
|
516
|
+
)
|
|
517
|
+
} catch (error) {
|
|
518
|
+
return authRouteErrorResponse(error)
|
|
519
|
+
}
|
|
520
|
+
},
|
|
521
|
+
{
|
|
522
|
+
body: CreateAuthPersonalAccessTokenBodySchema,
|
|
523
|
+
response: {
|
|
524
|
+
201: CreateAuthPersonalAccessTokenResponseSchema,
|
|
525
|
+
400: ErrorResponseSchema,
|
|
526
|
+
401: ErrorResponseSchema,
|
|
527
|
+
403: ErrorResponseSchema,
|
|
528
|
+
500: ErrorResponseSchema,
|
|
529
|
+
},
|
|
530
|
+
detail: {
|
|
531
|
+
summary: "Create a personal access token",
|
|
532
|
+
tags: [OPENAPI_TAGS.authAccessTokens.name],
|
|
533
|
+
operationId: "createAuthPersonalAccessToken",
|
|
534
|
+
security: bearerSecurityRequirement("createAuthPersonalAccessToken"),
|
|
535
|
+
},
|
|
536
|
+
}
|
|
537
|
+
)
|
|
538
|
+
.post(
|
|
539
|
+
"/api/auth/access-tokens/:tokenId/revoke",
|
|
540
|
+
async ({ request, params }) => {
|
|
541
|
+
try {
|
|
542
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
543
|
+
const session = requireAuthenticatedUserSession(
|
|
544
|
+
await sixb.auth.getSession(request, {
|
|
545
|
+
...authOptions,
|
|
546
|
+
credentialSource: "any",
|
|
547
|
+
})
|
|
548
|
+
)
|
|
549
|
+
if (session instanceof Response) {
|
|
550
|
+
return session
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
const { tokenId } = RevokeAuthAccessTokenParamsSchema.parse(params)
|
|
554
|
+
const result = await sixb.auth.revokePersonalAccessToken(
|
|
555
|
+
request,
|
|
556
|
+
{ tokenId },
|
|
557
|
+
authOptions
|
|
558
|
+
)
|
|
559
|
+
return jsonResponse(
|
|
560
|
+
{
|
|
561
|
+
accessToken: serializeAccessToken(result.accessToken, {
|
|
562
|
+
subjectLabel: session.user.email,
|
|
563
|
+
}),
|
|
564
|
+
},
|
|
565
|
+
200
|
|
566
|
+
)
|
|
567
|
+
} catch (error) {
|
|
568
|
+
return authRouteErrorResponse(error)
|
|
569
|
+
}
|
|
570
|
+
},
|
|
571
|
+
{
|
|
572
|
+
params: RevokeAuthAccessTokenParamsSchema,
|
|
573
|
+
response: {
|
|
574
|
+
200: RevokeAuthAccessTokenResponseSchema,
|
|
575
|
+
401: ErrorResponseSchema,
|
|
576
|
+
403: ErrorResponseSchema,
|
|
577
|
+
404: ErrorResponseSchema,
|
|
578
|
+
500: ErrorResponseSchema,
|
|
579
|
+
},
|
|
580
|
+
detail: {
|
|
581
|
+
summary: "Revoke one of the current user's personal access tokens",
|
|
582
|
+
tags: [OPENAPI_TAGS.authAccessTokens.name],
|
|
583
|
+
operationId: "revokeAuthAccessToken",
|
|
584
|
+
security: bearerSecurityRequirement("revokeAuthAccessToken"),
|
|
585
|
+
},
|
|
586
|
+
}
|
|
587
|
+
)
|
|
588
|
+
.get(
|
|
589
|
+
"/api/auth/service-accounts",
|
|
590
|
+
async ({ request }) => {
|
|
591
|
+
try {
|
|
592
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
593
|
+
const session = requireAuthenticatedUserSession(
|
|
594
|
+
await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
|
|
595
|
+
)
|
|
596
|
+
if (session instanceof Response) return session
|
|
597
|
+
|
|
598
|
+
const { serviceAccounts } = await sixb.auth.listServiceAccounts(request, authOptions)
|
|
599
|
+
|
|
600
|
+
return jsonResponse(
|
|
601
|
+
{
|
|
602
|
+
serviceAccounts: serviceAccounts.map(({ serviceAccount, groupIds }) =>
|
|
603
|
+
serializeServiceAccount(serviceAccount, groupIds)
|
|
604
|
+
),
|
|
605
|
+
},
|
|
606
|
+
200
|
|
607
|
+
)
|
|
608
|
+
} catch (error) {
|
|
609
|
+
return authRouteErrorResponse(error)
|
|
610
|
+
}
|
|
611
|
+
},
|
|
612
|
+
{
|
|
613
|
+
response: {
|
|
614
|
+
200: ListAuthServiceAccountsResponseSchema,
|
|
615
|
+
401: ErrorResponseSchema,
|
|
616
|
+
403: ErrorResponseSchema,
|
|
617
|
+
500: ErrorResponseSchema,
|
|
618
|
+
},
|
|
619
|
+
detail: {
|
|
620
|
+
summary: "List auth service accounts",
|
|
621
|
+
tags: [OPENAPI_TAGS.authServiceAccounts.name],
|
|
622
|
+
operationId: "listAuthServiceAccounts",
|
|
623
|
+
security: bearerSecurityRequirement("listAuthServiceAccounts"),
|
|
624
|
+
},
|
|
625
|
+
}
|
|
626
|
+
)
|
|
627
|
+
.post(
|
|
628
|
+
"/api/auth/service-accounts",
|
|
629
|
+
async ({ request, body }) => {
|
|
630
|
+
try {
|
|
631
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
632
|
+
const parsed = CreateAuthServiceAccountBodySchema.parse(body)
|
|
633
|
+
const session = requireAuthenticatedUserSession(
|
|
634
|
+
await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
|
|
635
|
+
)
|
|
636
|
+
if (session instanceof Response) return session
|
|
637
|
+
|
|
638
|
+
const result = await sixb.auth.createServiceAccount(
|
|
639
|
+
request,
|
|
640
|
+
{
|
|
641
|
+
id: parsed.id,
|
|
642
|
+
name: parsed.name,
|
|
643
|
+
description: optionalTrimmed(parsed.description),
|
|
644
|
+
groupIds: parsed.groupIds,
|
|
645
|
+
},
|
|
646
|
+
{ ...authOptions, credentialSource: "any" }
|
|
647
|
+
)
|
|
648
|
+
|
|
649
|
+
return jsonResponse(
|
|
650
|
+
{
|
|
651
|
+
serviceAccount: serializeServiceAccount(
|
|
652
|
+
result.serviceAccount,
|
|
653
|
+
result.groupMemberships.map((membership) => membership.groupId)
|
|
654
|
+
),
|
|
655
|
+
},
|
|
656
|
+
201
|
|
657
|
+
)
|
|
658
|
+
} catch (error) {
|
|
659
|
+
return authRouteErrorResponse(error)
|
|
660
|
+
}
|
|
661
|
+
},
|
|
662
|
+
{
|
|
663
|
+
body: CreateAuthServiceAccountBodySchema,
|
|
664
|
+
response: {
|
|
665
|
+
201: CreateAuthServiceAccountResponseSchema,
|
|
666
|
+
400: ErrorResponseSchema,
|
|
667
|
+
401: ErrorResponseSchema,
|
|
668
|
+
403: ErrorResponseSchema,
|
|
669
|
+
500: ErrorResponseSchema,
|
|
670
|
+
},
|
|
671
|
+
detail: {
|
|
672
|
+
summary: "Create an auth service account",
|
|
673
|
+
tags: [OPENAPI_TAGS.authServiceAccounts.name],
|
|
674
|
+
operationId: "createAuthServiceAccount",
|
|
675
|
+
security: bearerSecurityRequirement("createAuthServiceAccount"),
|
|
676
|
+
},
|
|
677
|
+
}
|
|
678
|
+
)
|
|
679
|
+
.post(
|
|
680
|
+
"/api/auth/service-accounts/:serviceAccountId/disable",
|
|
681
|
+
async ({ request, params }) => {
|
|
682
|
+
try {
|
|
683
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
684
|
+
const session = requireAuthenticatedUserSession(
|
|
685
|
+
await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
|
|
686
|
+
)
|
|
687
|
+
if (session instanceof Response) return session
|
|
688
|
+
|
|
689
|
+
const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params)
|
|
690
|
+
const result = await sixb.auth.disableServiceAccount(
|
|
691
|
+
request,
|
|
692
|
+
{ serviceAccountId },
|
|
693
|
+
authOptions
|
|
694
|
+
)
|
|
695
|
+
|
|
696
|
+
return jsonResponse(
|
|
697
|
+
{
|
|
698
|
+
serviceAccount: serializeServiceAccount(result.serviceAccount, result.groupIds),
|
|
699
|
+
},
|
|
700
|
+
200
|
|
701
|
+
)
|
|
702
|
+
} catch (error) {
|
|
703
|
+
return authRouteErrorResponse(error)
|
|
704
|
+
}
|
|
705
|
+
},
|
|
706
|
+
{
|
|
707
|
+
params: AuthServiceAccountParamsSchema,
|
|
708
|
+
response: {
|
|
709
|
+
200: DisableAuthServiceAccountResponseSchema,
|
|
710
|
+
401: ErrorResponseSchema,
|
|
711
|
+
403: ErrorResponseSchema,
|
|
712
|
+
404: ErrorResponseSchema,
|
|
713
|
+
500: ErrorResponseSchema,
|
|
714
|
+
},
|
|
715
|
+
detail: {
|
|
716
|
+
summary: "Disable an auth service account",
|
|
717
|
+
tags: [OPENAPI_TAGS.authServiceAccounts.name],
|
|
718
|
+
operationId: "disableAuthServiceAccount",
|
|
719
|
+
security: bearerSecurityRequirement("disableAuthServiceAccount"),
|
|
720
|
+
},
|
|
721
|
+
}
|
|
722
|
+
)
|
|
723
|
+
.get(
|
|
724
|
+
"/api/auth/service-accounts/:serviceAccountId/access-tokens",
|
|
725
|
+
async ({ request, params }) => {
|
|
726
|
+
try {
|
|
727
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
728
|
+
const session = requireAuthenticatedUserSession(
|
|
729
|
+
await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
|
|
730
|
+
)
|
|
731
|
+
if (session instanceof Response) return session
|
|
732
|
+
|
|
733
|
+
const { serviceAccountId } = AuthServiceAccountParamsSchema.parse(params)
|
|
734
|
+
const { serviceAccount, accessTokens } = await sixb.auth.listServiceAccountAccessTokens(
|
|
735
|
+
request,
|
|
736
|
+
{ serviceAccountId },
|
|
737
|
+
authOptions
|
|
738
|
+
)
|
|
739
|
+
|
|
740
|
+
return jsonResponse(
|
|
741
|
+
{
|
|
742
|
+
accessTokens: accessTokens.map((accessToken) =>
|
|
743
|
+
serializeAccessToken(accessToken, { subjectLabel: serviceAccount.name })
|
|
744
|
+
),
|
|
745
|
+
},
|
|
746
|
+
200
|
|
747
|
+
)
|
|
748
|
+
} catch (error) {
|
|
749
|
+
return authRouteErrorResponse(error)
|
|
750
|
+
}
|
|
751
|
+
},
|
|
752
|
+
{
|
|
753
|
+
params: AuthServiceAccountParamsSchema,
|
|
754
|
+
response: {
|
|
755
|
+
200: ListAuthServiceAccountAccessTokensResponseSchema,
|
|
756
|
+
401: ErrorResponseSchema,
|
|
757
|
+
403: ErrorResponseSchema,
|
|
758
|
+
404: ErrorResponseSchema,
|
|
759
|
+
500: ErrorResponseSchema,
|
|
760
|
+
},
|
|
761
|
+
detail: {
|
|
762
|
+
summary: "List access tokens for an auth service account",
|
|
763
|
+
tags: [OPENAPI_TAGS.authServiceAccounts.name],
|
|
764
|
+
operationId: "listAuthServiceAccountAccessTokens",
|
|
765
|
+
security: bearerSecurityRequirement("listAuthServiceAccountAccessTokens"),
|
|
766
|
+
},
|
|
767
|
+
}
|
|
768
|
+
)
|
|
769
|
+
.post(
|
|
770
|
+
"/api/auth/service-accounts/:serviceAccountId/access-tokens",
|
|
771
|
+
async ({ request, params, body }) => {
|
|
772
|
+
try {
|
|
773
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
774
|
+
const parsedParams = AuthServiceAccountParamsSchema.parse(params)
|
|
775
|
+
const parsed = CreateAuthServiceAccountAccessTokenBodySchema.parse(body)
|
|
776
|
+
const session = requireAuthenticatedUserSession(
|
|
777
|
+
await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
|
|
778
|
+
)
|
|
779
|
+
if (session instanceof Response) return session
|
|
780
|
+
|
|
781
|
+
const expiresAt = parseRequiredFutureDate(parsed.expiresAt)
|
|
782
|
+
const result = await sixb.auth.createServiceAccountAccessToken(
|
|
783
|
+
request,
|
|
784
|
+
{
|
|
785
|
+
serviceAccountId: parsedParams.serviceAccountId,
|
|
786
|
+
name: parsed.name,
|
|
787
|
+
expiresAt,
|
|
788
|
+
groupIds: parsed.groupIds,
|
|
789
|
+
},
|
|
790
|
+
{ ...authOptions, credentialSource: "any" }
|
|
791
|
+
)
|
|
792
|
+
|
|
793
|
+
return jsonResponse(
|
|
794
|
+
{
|
|
795
|
+
accessToken: serializeAccessToken(result.accessToken, {
|
|
796
|
+
subjectLabel: result.serviceAccount.name,
|
|
797
|
+
}),
|
|
798
|
+
tokenValue: result.tokenValue,
|
|
799
|
+
},
|
|
800
|
+
201
|
|
801
|
+
)
|
|
802
|
+
} catch (error) {
|
|
803
|
+
return authRouteErrorResponse(error)
|
|
804
|
+
}
|
|
805
|
+
},
|
|
806
|
+
{
|
|
807
|
+
params: AuthServiceAccountParamsSchema,
|
|
808
|
+
body: CreateAuthServiceAccountAccessTokenBodySchema,
|
|
809
|
+
response: {
|
|
810
|
+
201: CreateAuthServiceAccountAccessTokenResponseSchema,
|
|
811
|
+
400: ErrorResponseSchema,
|
|
812
|
+
401: ErrorResponseSchema,
|
|
813
|
+
403: ErrorResponseSchema,
|
|
814
|
+
404: ErrorResponseSchema,
|
|
815
|
+
500: ErrorResponseSchema,
|
|
816
|
+
},
|
|
817
|
+
detail: {
|
|
818
|
+
summary: "Create an access token for an auth service account",
|
|
819
|
+
tags: [OPENAPI_TAGS.authServiceAccounts.name],
|
|
820
|
+
operationId: "createAuthServiceAccountAccessToken",
|
|
821
|
+
security: bearerSecurityRequirement("createAuthServiceAccountAccessToken"),
|
|
822
|
+
},
|
|
823
|
+
}
|
|
824
|
+
)
|
|
825
|
+
.post(
|
|
826
|
+
"/api/auth/service-accounts/:serviceAccountId/access-tokens/:tokenId/revoke",
|
|
827
|
+
async ({ request, params }) => {
|
|
828
|
+
try {
|
|
829
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
830
|
+
const parsed = RevokeAuthServiceAccountAccessTokenParamsSchema.parse(params)
|
|
831
|
+
const session = requireAuthenticatedUserSession(
|
|
832
|
+
await sixb.auth.getSession(request, { ...authOptions, credentialSource: "any" })
|
|
833
|
+
)
|
|
834
|
+
if (session instanceof Response) return session
|
|
835
|
+
|
|
836
|
+
const result = await sixb.auth.revokeServiceAccountAccessToken(
|
|
837
|
+
request,
|
|
838
|
+
{ serviceAccountId: parsed.serviceAccountId, tokenId: parsed.tokenId },
|
|
839
|
+
authOptions
|
|
840
|
+
)
|
|
841
|
+
|
|
842
|
+
return jsonResponse(
|
|
843
|
+
{
|
|
844
|
+
accessToken: serializeAccessToken(result.accessToken, {
|
|
845
|
+
subjectLabel: result.serviceAccount.name,
|
|
846
|
+
}),
|
|
847
|
+
},
|
|
848
|
+
200
|
|
849
|
+
)
|
|
850
|
+
} catch (error) {
|
|
851
|
+
return authRouteErrorResponse(error)
|
|
852
|
+
}
|
|
853
|
+
},
|
|
854
|
+
{
|
|
855
|
+
params: RevokeAuthServiceAccountAccessTokenParamsSchema,
|
|
856
|
+
response: {
|
|
857
|
+
200: RevokeAuthServiceAccountAccessTokenResponseSchema,
|
|
858
|
+
401: ErrorResponseSchema,
|
|
859
|
+
403: ErrorResponseSchema,
|
|
860
|
+
404: ErrorResponseSchema,
|
|
861
|
+
500: ErrorResponseSchema,
|
|
862
|
+
},
|
|
863
|
+
detail: {
|
|
864
|
+
summary: "Revoke an access token for an auth service account",
|
|
865
|
+
tags: [OPENAPI_TAGS.authServiceAccounts.name],
|
|
866
|
+
operationId: "revokeAuthServiceAccountAccessToken",
|
|
867
|
+
security: bearerSecurityRequirement("revokeAuthServiceAccountAccessToken"),
|
|
868
|
+
},
|
|
869
|
+
}
|
|
870
|
+
)
|
|
871
|
+
.post(
|
|
872
|
+
"/api/auth/invitations",
|
|
873
|
+
async ({ request, body }) => {
|
|
874
|
+
try {
|
|
875
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
876
|
+
const parsed = CreateAuthInvitationBodySchema.parse(body)
|
|
877
|
+
const deliveryContext = resolveInvitationDeliveryContext(options, request, {
|
|
878
|
+
destinationId: parsed.destinationId,
|
|
879
|
+
returnTo: parsed.returnTo,
|
|
880
|
+
})
|
|
881
|
+
if (deliveryContext instanceof Response) {
|
|
882
|
+
return deliveryContext
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
const result = await sixb.auth.invite(
|
|
886
|
+
request,
|
|
887
|
+
{
|
|
888
|
+
email: parsed.email,
|
|
889
|
+
groupIds: parsed.groupIds,
|
|
890
|
+
expiresAt: parseDate(parsed.expiresAt),
|
|
891
|
+
returnTo: deliveryContext.returnTo,
|
|
892
|
+
},
|
|
893
|
+
{
|
|
894
|
+
...authOptions,
|
|
895
|
+
delivery: {
|
|
896
|
+
audience: deliveryContext.audience,
|
|
897
|
+
returnTo: deliveryContext.returnTo,
|
|
898
|
+
requestOrigin: deliveryContext.requestOrigin,
|
|
899
|
+
},
|
|
900
|
+
}
|
|
901
|
+
)
|
|
902
|
+
|
|
903
|
+
return jsonResponse(
|
|
904
|
+
{
|
|
905
|
+
invitation: serializeInvitation(result.invitation),
|
|
906
|
+
delivery: result.delivery,
|
|
907
|
+
},
|
|
908
|
+
201
|
|
909
|
+
)
|
|
910
|
+
} catch (error) {
|
|
911
|
+
return authRouteErrorResponse(error)
|
|
912
|
+
}
|
|
913
|
+
},
|
|
914
|
+
{
|
|
915
|
+
body: CreateAuthInvitationBodySchema,
|
|
916
|
+
response: {
|
|
917
|
+
201: CreateAuthInvitationResponseSchema,
|
|
918
|
+
400: ErrorResponseSchema,
|
|
919
|
+
401: ErrorResponseSchema,
|
|
920
|
+
403: ErrorResponseSchema,
|
|
921
|
+
404: ErrorResponseSchema,
|
|
922
|
+
429: ErrorResponseSchema,
|
|
923
|
+
500: ErrorResponseSchema,
|
|
924
|
+
},
|
|
925
|
+
detail: {
|
|
926
|
+
summary: "Create an auth invitation",
|
|
927
|
+
tags: [OPENAPI_TAGS.authInvitations.name],
|
|
928
|
+
operationId: "createAuthInvitation",
|
|
929
|
+
security: SIXB_CSRF_SECURITY_REQUIREMENT,
|
|
930
|
+
},
|
|
931
|
+
}
|
|
932
|
+
)
|
|
933
|
+
.get(
|
|
934
|
+
"/api/auth/invitation-options",
|
|
935
|
+
async ({ request }) => {
|
|
936
|
+
try {
|
|
937
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
938
|
+
return jsonResponse(
|
|
939
|
+
{
|
|
940
|
+
...(await sixb.auth.getInvitationOptions(request, authOptions)),
|
|
941
|
+
...options.getInvitationDestinationOptions(request),
|
|
942
|
+
},
|
|
943
|
+
200
|
|
944
|
+
)
|
|
945
|
+
} catch (error) {
|
|
946
|
+
return authRouteErrorResponse(error)
|
|
947
|
+
}
|
|
948
|
+
},
|
|
949
|
+
{
|
|
950
|
+
response: {
|
|
951
|
+
200: GetAuthInvitationOptionsResponseSchema,
|
|
952
|
+
401: ErrorResponseSchema,
|
|
953
|
+
500: ErrorResponseSchema,
|
|
954
|
+
},
|
|
955
|
+
detail: {
|
|
956
|
+
summary: "Get auth invitation options",
|
|
957
|
+
tags: [OPENAPI_TAGS.authInvitations.name],
|
|
958
|
+
operationId: "getAuthInvitationOptions",
|
|
959
|
+
},
|
|
960
|
+
}
|
|
961
|
+
)
|
|
962
|
+
.get(
|
|
963
|
+
"/api/auth/invitations",
|
|
964
|
+
async ({ request, query }) => {
|
|
965
|
+
try {
|
|
966
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
967
|
+
const parsed = ListAuthInvitationsQuerySchema.parse(query)
|
|
968
|
+
const result = await sixb.auth.listInvitations(
|
|
969
|
+
request,
|
|
970
|
+
{
|
|
971
|
+
email: parsed.email,
|
|
972
|
+
statuses: parsed.status ? [parsed.status] : undefined,
|
|
973
|
+
limit: parseOptionalInt(parsed.limit),
|
|
974
|
+
offset: parseOptionalInt(parsed.offset),
|
|
975
|
+
order: parsed.order,
|
|
976
|
+
},
|
|
977
|
+
authOptions
|
|
978
|
+
)
|
|
979
|
+
|
|
980
|
+
return jsonResponse(
|
|
981
|
+
{
|
|
982
|
+
invitations: result.invitations.map(serializeInvitation),
|
|
983
|
+
hasMore: result.hasMore,
|
|
984
|
+
total: result.total,
|
|
985
|
+
},
|
|
986
|
+
200
|
|
987
|
+
)
|
|
988
|
+
} catch (error) {
|
|
989
|
+
return authRouteErrorResponse(error)
|
|
990
|
+
}
|
|
991
|
+
},
|
|
992
|
+
{
|
|
993
|
+
query: ListAuthInvitationsQuerySchema,
|
|
994
|
+
response: {
|
|
995
|
+
200: ListAuthInvitationsResponseSchema,
|
|
996
|
+
400: ErrorResponseSchema,
|
|
997
|
+
401: ErrorResponseSchema,
|
|
998
|
+
403: ErrorResponseSchema,
|
|
999
|
+
404: ErrorResponseSchema,
|
|
1000
|
+
500: ErrorResponseSchema,
|
|
1001
|
+
},
|
|
1002
|
+
detail: {
|
|
1003
|
+
summary: "List auth invitations",
|
|
1004
|
+
tags: [OPENAPI_TAGS.authInvitations.name],
|
|
1005
|
+
operationId: "listAuthInvitations",
|
|
1006
|
+
},
|
|
1007
|
+
}
|
|
1008
|
+
)
|
|
1009
|
+
.post(
|
|
1010
|
+
"/api/auth/invitations/:invitationId/revoke",
|
|
1011
|
+
async ({ request, params }) => {
|
|
1012
|
+
try {
|
|
1013
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
1014
|
+
const parsed = RevokeAuthInvitationParamsSchema.parse(params)
|
|
1015
|
+
const result = await sixb.auth.revokeInvitation(
|
|
1016
|
+
request,
|
|
1017
|
+
{
|
|
1018
|
+
invitationId: parsed.invitationId,
|
|
1019
|
+
},
|
|
1020
|
+
authOptions
|
|
1021
|
+
)
|
|
1022
|
+
|
|
1023
|
+
return jsonResponse(
|
|
1024
|
+
{
|
|
1025
|
+
invitation: serializeInvitation(result.invitation),
|
|
1026
|
+
},
|
|
1027
|
+
200
|
|
1028
|
+
)
|
|
1029
|
+
} catch (error) {
|
|
1030
|
+
return authRouteErrorResponse(error)
|
|
1031
|
+
}
|
|
1032
|
+
},
|
|
1033
|
+
{
|
|
1034
|
+
params: RevokeAuthInvitationParamsSchema,
|
|
1035
|
+
response: {
|
|
1036
|
+
200: RevokeAuthInvitationResponseSchema,
|
|
1037
|
+
400: ErrorResponseSchema,
|
|
1038
|
+
401: ErrorResponseSchema,
|
|
1039
|
+
403: ErrorResponseSchema,
|
|
1040
|
+
404: ErrorResponseSchema,
|
|
1041
|
+
500: ErrorResponseSchema,
|
|
1042
|
+
},
|
|
1043
|
+
detail: {
|
|
1044
|
+
summary: "Revoke an auth invitation",
|
|
1045
|
+
tags: [OPENAPI_TAGS.authInvitations.name],
|
|
1046
|
+
operationId: "revokeAuthInvitation",
|
|
1047
|
+
security: SIXB_CSRF_SECURITY_REQUIREMENT,
|
|
1048
|
+
},
|
|
1049
|
+
}
|
|
1050
|
+
)
|
|
1051
|
+
.get(
|
|
1052
|
+
"/api/auth/membership-options",
|
|
1053
|
+
async ({ request }) => {
|
|
1054
|
+
try {
|
|
1055
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
1056
|
+
return jsonResponse(await sixb.auth.getMembershipOptions(request, authOptions), 200)
|
|
1057
|
+
} catch (error) {
|
|
1058
|
+
return authRouteErrorResponse(error)
|
|
1059
|
+
}
|
|
1060
|
+
},
|
|
1061
|
+
{
|
|
1062
|
+
response: {
|
|
1063
|
+
200: GetAuthMembershipOptionsResponseSchema,
|
|
1064
|
+
401: ErrorResponseSchema,
|
|
1065
|
+
500: ErrorResponseSchema,
|
|
1066
|
+
},
|
|
1067
|
+
detail: {
|
|
1068
|
+
summary: "Get auth membership management options",
|
|
1069
|
+
tags: [OPENAPI_TAGS.authMembers.name],
|
|
1070
|
+
operationId: "getAuthMembershipOptions",
|
|
1071
|
+
},
|
|
1072
|
+
}
|
|
1073
|
+
)
|
|
1074
|
+
.get(
|
|
1075
|
+
"/api/auth/members",
|
|
1076
|
+
async ({ request, query }) => {
|
|
1077
|
+
try {
|
|
1078
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
1079
|
+
const parsed = ListAuthMembersQuerySchema.parse(query)
|
|
1080
|
+
const result = await sixb.auth.listMembers(
|
|
1081
|
+
request,
|
|
1082
|
+
{
|
|
1083
|
+
limit: parseOptionalInt(parsed.limit),
|
|
1084
|
+
offset: parseOptionalInt(parsed.offset),
|
|
1085
|
+
order: parsed.order,
|
|
1086
|
+
},
|
|
1087
|
+
authOptions
|
|
1088
|
+
)
|
|
1089
|
+
|
|
1090
|
+
return jsonResponse(
|
|
1091
|
+
{
|
|
1092
|
+
members: result.members.map(serializeMemberSummary),
|
|
1093
|
+
hasMore: result.hasMore,
|
|
1094
|
+
total: result.total,
|
|
1095
|
+
},
|
|
1096
|
+
200
|
|
1097
|
+
)
|
|
1098
|
+
} catch (error) {
|
|
1099
|
+
return authRouteErrorResponse(error)
|
|
1100
|
+
}
|
|
1101
|
+
},
|
|
1102
|
+
{
|
|
1103
|
+
query: ListAuthMembersQuerySchema,
|
|
1104
|
+
response: {
|
|
1105
|
+
200: ListAuthMembersResponseSchema,
|
|
1106
|
+
400: ErrorResponseSchema,
|
|
1107
|
+
401: ErrorResponseSchema,
|
|
1108
|
+
500: ErrorResponseSchema,
|
|
1109
|
+
},
|
|
1110
|
+
detail: {
|
|
1111
|
+
summary: "List auth members",
|
|
1112
|
+
tags: [OPENAPI_TAGS.authMembers.name],
|
|
1113
|
+
operationId: "listAuthMembers",
|
|
1114
|
+
},
|
|
1115
|
+
}
|
|
1116
|
+
)
|
|
1117
|
+
.patch(
|
|
1118
|
+
"/api/auth/members/:userId/groups",
|
|
1119
|
+
async ({ request, params, body }) => {
|
|
1120
|
+
try {
|
|
1121
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
1122
|
+
const parsedParams = AuthMemberParamsSchema.parse(params)
|
|
1123
|
+
const parsed = UpdateAuthMemberGroupsBodySchema.parse(body)
|
|
1124
|
+
const result = await sixb.auth.updateMemberGroups(
|
|
1125
|
+
request,
|
|
1126
|
+
{ userId: parsedParams.userId, groupIds: parsed.groupIds },
|
|
1127
|
+
authOptions
|
|
1128
|
+
)
|
|
1129
|
+
|
|
1130
|
+
return jsonResponse({ member: serializeManagedMember(result.user, result.groupIds) }, 200)
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
return authRouteErrorResponse(error)
|
|
1133
|
+
}
|
|
1134
|
+
},
|
|
1135
|
+
{
|
|
1136
|
+
params: AuthMemberParamsSchema,
|
|
1137
|
+
body: UpdateAuthMemberGroupsBodySchema,
|
|
1138
|
+
response: {
|
|
1139
|
+
200: UpdateAuthMemberGroupsResponseSchema,
|
|
1140
|
+
400: ErrorResponseSchema,
|
|
1141
|
+
401: ErrorResponseSchema,
|
|
1142
|
+
403: ErrorResponseSchema,
|
|
1143
|
+
404: ErrorResponseSchema,
|
|
1144
|
+
500: ErrorResponseSchema,
|
|
1145
|
+
},
|
|
1146
|
+
detail: {
|
|
1147
|
+
summary: "Update an auth member's groups",
|
|
1148
|
+
tags: [OPENAPI_TAGS.authMembers.name],
|
|
1149
|
+
operationId: "updateAuthMemberGroups",
|
|
1150
|
+
security: SIXB_CSRF_SECURITY_REQUIREMENT,
|
|
1151
|
+
},
|
|
1152
|
+
}
|
|
1153
|
+
)
|
|
1154
|
+
.post(
|
|
1155
|
+
"/api/auth/members/:userId/suspend",
|
|
1156
|
+
async ({ request, params }) => {
|
|
1157
|
+
try {
|
|
1158
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
1159
|
+
const parsed = AuthMemberParamsSchema.parse(params)
|
|
1160
|
+
const result = await sixb.auth.suspendMember(
|
|
1161
|
+
request,
|
|
1162
|
+
{ userId: parsed.userId },
|
|
1163
|
+
authOptions
|
|
1164
|
+
)
|
|
1165
|
+
|
|
1166
|
+
return jsonResponse({ member: serializeManagedMember(result.user, result.groupIds) }, 200)
|
|
1167
|
+
} catch (error) {
|
|
1168
|
+
return authRouteErrorResponse(error)
|
|
1169
|
+
}
|
|
1170
|
+
},
|
|
1171
|
+
{
|
|
1172
|
+
params: AuthMemberParamsSchema,
|
|
1173
|
+
response: {
|
|
1174
|
+
200: SuspendAuthMemberResponseSchema,
|
|
1175
|
+
401: ErrorResponseSchema,
|
|
1176
|
+
403: ErrorResponseSchema,
|
|
1177
|
+
404: ErrorResponseSchema,
|
|
1178
|
+
500: ErrorResponseSchema,
|
|
1179
|
+
},
|
|
1180
|
+
detail: {
|
|
1181
|
+
summary: "Suspend an auth member",
|
|
1182
|
+
tags: [OPENAPI_TAGS.authMembers.name],
|
|
1183
|
+
operationId: "suspendAuthMember",
|
|
1184
|
+
security: SIXB_CSRF_SECURITY_REQUIREMENT,
|
|
1185
|
+
},
|
|
1186
|
+
}
|
|
1187
|
+
)
|
|
1188
|
+
.post(
|
|
1189
|
+
"/api/auth/members/:userId/reactivate",
|
|
1190
|
+
async ({ request, params }) => {
|
|
1191
|
+
try {
|
|
1192
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
1193
|
+
const parsed = AuthMemberParamsSchema.parse(params)
|
|
1194
|
+
const result = await sixb.auth.reactivateMember(
|
|
1195
|
+
request,
|
|
1196
|
+
{ userId: parsed.userId },
|
|
1197
|
+
authOptions
|
|
1198
|
+
)
|
|
1199
|
+
|
|
1200
|
+
return jsonResponse({ member: serializeManagedMember(result.user, result.groupIds) }, 200)
|
|
1201
|
+
} catch (error) {
|
|
1202
|
+
return authRouteErrorResponse(error)
|
|
1203
|
+
}
|
|
1204
|
+
},
|
|
1205
|
+
{
|
|
1206
|
+
params: AuthMemberParamsSchema,
|
|
1207
|
+
response: {
|
|
1208
|
+
200: ReactivateAuthMemberResponseSchema,
|
|
1209
|
+
401: ErrorResponseSchema,
|
|
1210
|
+
403: ErrorResponseSchema,
|
|
1211
|
+
404: ErrorResponseSchema,
|
|
1212
|
+
500: ErrorResponseSchema,
|
|
1213
|
+
},
|
|
1214
|
+
detail: {
|
|
1215
|
+
summary: "Reactivate an auth member",
|
|
1216
|
+
tags: [OPENAPI_TAGS.authMembers.name],
|
|
1217
|
+
operationId: "reactivateAuthMember",
|
|
1218
|
+
security: SIXB_CSRF_SECURITY_REQUIREMENT,
|
|
1219
|
+
},
|
|
1220
|
+
}
|
|
1221
|
+
)
|
|
1222
|
+
.post(
|
|
1223
|
+
"/auth/sign-in",
|
|
1224
|
+
async ({ body, request }) => {
|
|
1225
|
+
const strategy = sixb.auth.getStrategy()
|
|
1226
|
+
const authRedirect = resolveAuthRedirectContext(options, request, {
|
|
1227
|
+
audience: body.audience,
|
|
1228
|
+
returnTo: body.returnTo,
|
|
1229
|
+
})
|
|
1230
|
+
if (authRedirect instanceof Response) {
|
|
1231
|
+
return authRedirect
|
|
1232
|
+
}
|
|
1233
|
+
|
|
1234
|
+
const authStorage = requireAuthStorage(sixb)
|
|
1235
|
+
|
|
1236
|
+
if (isMagicLinkAuthStrategy(strategy)) {
|
|
1237
|
+
const pending = createMagicLinkPendingCredential()
|
|
1238
|
+
const result = await strategy.requestMagicLink({
|
|
1239
|
+
projectId: sixb.id,
|
|
1240
|
+
authStorage,
|
|
1241
|
+
email: body.email ?? "",
|
|
1242
|
+
audience: authRedirect.audience,
|
|
1243
|
+
returnTo: authRedirect.returnTo,
|
|
1244
|
+
requestOrigin: authRedirect.requestOrigin,
|
|
1245
|
+
requesterHash: pending.hash,
|
|
1246
|
+
})
|
|
1247
|
+
|
|
1248
|
+
const response = htmlMessageResponse(
|
|
1249
|
+
"If this email can sign in, we sent a link. Check your inbox to continue.",
|
|
1250
|
+
200,
|
|
1251
|
+
"Check your email"
|
|
1252
|
+
)
|
|
1253
|
+
// Same-device fast path: this browser keeps the preimage of the
|
|
1254
|
+
// `requester` hash embedded in the emailed callback URL, so opening
|
|
1255
|
+
// the link here signs in without the confirmation click. Always
|
|
1256
|
+
// answer with a pending cookie of identical shape (a missing
|
|
1257
|
+
// Set-Cookie for ineligible emails would leak which addresses can
|
|
1258
|
+
// sign in), but only rotate the stored secret when a link was
|
|
1259
|
+
// actually delivered — a rate-limited or skipped request must not
|
|
1260
|
+
// orphan the hash in the previously emailed, still-valid link.
|
|
1261
|
+
const existingPending = getCookie(request, MAGIC_LINK_PENDING_COOKIE_NAME)?.trim()
|
|
1262
|
+
response.headers.append(
|
|
1263
|
+
"set-cookie",
|
|
1264
|
+
magicLinkPendingCookieHeader({
|
|
1265
|
+
request,
|
|
1266
|
+
sixb,
|
|
1267
|
+
value: result.status === "sent" ? pending.secret : existingPending || pending.secret,
|
|
1268
|
+
maxAgeSeconds: magicLinkPendingCookieMaxAgeSeconds(strategy),
|
|
1269
|
+
})
|
|
1270
|
+
)
|
|
1271
|
+
return response
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
if (isOidcAuthStrategy(strategy)) {
|
|
1275
|
+
const result = await strategy.startOidcSignIn({
|
|
1276
|
+
projectId: sixb.id,
|
|
1277
|
+
authStorage,
|
|
1278
|
+
audience: authRedirect.audience,
|
|
1279
|
+
returnTo: authRedirect.returnTo,
|
|
1280
|
+
requestOrigin: authRedirect.requestOrigin,
|
|
1281
|
+
})
|
|
1282
|
+
return redirectResponse(result.redirectTo)
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
return strategyNotImplementedResponse("Sign-in is not implemented yet.")
|
|
1286
|
+
},
|
|
1287
|
+
{
|
|
1288
|
+
body: t.Object({
|
|
1289
|
+
audience: t.Optional(t.String()),
|
|
1290
|
+
email: t.Optional(t.String()),
|
|
1291
|
+
returnTo: t.Optional(t.String()),
|
|
1292
|
+
}),
|
|
1293
|
+
parse: "urlencoded",
|
|
1294
|
+
detail: { hide: true },
|
|
1295
|
+
}
|
|
1296
|
+
)
|
|
1297
|
+
.get(
|
|
1298
|
+
"/auth/sign-in",
|
|
1299
|
+
async ({ request }) => {
|
|
1300
|
+
const strategy = sixb.auth.getStrategy()
|
|
1301
|
+
const url = new URL(request.url)
|
|
1302
|
+
const authRedirect = resolveAuthRedirectContext(options, request, {
|
|
1303
|
+
audience: url.searchParams.get("audience"),
|
|
1304
|
+
returnTo: url.searchParams.get("returnTo"),
|
|
1305
|
+
})
|
|
1306
|
+
if (authRedirect instanceof Response) {
|
|
1307
|
+
return authRedirect
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
if (isMagicLinkAuthStrategy(strategy)) {
|
|
1311
|
+
return signInFormResponse(authRedirect)
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
if (isOidcAuthStrategy(strategy)) {
|
|
1315
|
+
const result = await strategy.startOidcSignIn({
|
|
1316
|
+
projectId: sixb.id,
|
|
1317
|
+
authStorage: requireAuthStorage(sixb),
|
|
1318
|
+
audience: authRedirect.audience,
|
|
1319
|
+
returnTo: authRedirect.returnTo,
|
|
1320
|
+
requestOrigin: authRedirect.requestOrigin,
|
|
1321
|
+
})
|
|
1322
|
+
return redirectResponse(result.redirectTo)
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
return strategyNotImplementedResponse("Sign-in is not implemented yet.")
|
|
1326
|
+
},
|
|
1327
|
+
{ detail: { hide: true } }
|
|
1328
|
+
)
|
|
1329
|
+
.get(
|
|
1330
|
+
"/auth/callback",
|
|
1331
|
+
async ({ request }) => {
|
|
1332
|
+
const strategy = sixb.auth.getStrategy()
|
|
1333
|
+
|
|
1334
|
+
if (isMagicLinkAuthStrategy(strategy)) {
|
|
1335
|
+
const url = new URL(request.url)
|
|
1336
|
+
const magicLinkId = url.searchParams.get("magicLinkId")?.trim()
|
|
1337
|
+
const token = url.searchParams.get("token")?.trim()
|
|
1338
|
+
|
|
1339
|
+
if (!magicLinkId || !token) {
|
|
1340
|
+
return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// Read-only peek so the page can greet the user by email and dead
|
|
1344
|
+
// links fail before the confirmation click. Email security scanners
|
|
1345
|
+
// (Safe Links, Avanan, Mimecast, ...) prefetch emailed URLs, so this
|
|
1346
|
+
// GET must not consume the single-use token — a scanner would
|
|
1347
|
+
// invalidate the link before the user ever opens it. The strategy
|
|
1348
|
+
// owns the validity rules (including token verification, so a bare
|
|
1349
|
+
// magicLinkId cannot disclose the account email).
|
|
1350
|
+
let email: string | undefined
|
|
1351
|
+
if (strategy.peekMagicLink) {
|
|
1352
|
+
try {
|
|
1353
|
+
const peeked = await strategy.peekMagicLink({
|
|
1354
|
+
projectId: sixb.id,
|
|
1355
|
+
authStorage: requireAuthStorage(sixb),
|
|
1356
|
+
magicLinkId,
|
|
1357
|
+
token,
|
|
1358
|
+
})
|
|
1359
|
+
if (!peeked) {
|
|
1360
|
+
return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
|
|
1361
|
+
}
|
|
1362
|
+
email = peeked.email
|
|
1363
|
+
} catch {
|
|
1364
|
+
return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
// Same-device fast path: only the browser that requested this link
|
|
1369
|
+
// holds the preimage of the URL's `requester` hash, so it may sign in
|
|
1370
|
+
// straight from the navigation. Scanners and other browsers get the
|
|
1371
|
+
// confirmation page; POST /auth/callback completes the sign-in there.
|
|
1372
|
+
const requesterHash = url.searchParams.get("requester")?.trim()
|
|
1373
|
+
const pendingSecret = getCookie(request, MAGIC_LINK_PENDING_COOKIE_NAME)?.trim()
|
|
1374
|
+
if (
|
|
1375
|
+
requesterHash &&
|
|
1376
|
+
pendingSecret &&
|
|
1377
|
+
matchesMagicLinkRequester(pendingSecret, requesterHash)
|
|
1378
|
+
) {
|
|
1379
|
+
return completeMagicLinkCallback({
|
|
1380
|
+
sixb,
|
|
1381
|
+
strategy,
|
|
1382
|
+
options,
|
|
1383
|
+
request,
|
|
1384
|
+
magicLinkId,
|
|
1385
|
+
token,
|
|
1386
|
+
clearPendingCookie: true,
|
|
1387
|
+
})
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
return magicLinkConfirmResponse({ magicLinkId, token, email })
|
|
1391
|
+
}
|
|
1392
|
+
|
|
1393
|
+
if (isOidcAuthStrategy(strategy)) {
|
|
1394
|
+
const now = new Date()
|
|
1395
|
+
const sessionCredential = createSessionCredential()
|
|
1396
|
+
const device = resolveSessionDevice(request)
|
|
1397
|
+
|
|
1398
|
+
try {
|
|
1399
|
+
const authOptions = resolveAuthOptions(options, request)
|
|
1400
|
+
const result = await strategy.completeOidcSignIn({
|
|
1401
|
+
projectId: sixb.id,
|
|
1402
|
+
authStorage: requireAuthStorage(sixb),
|
|
1403
|
+
requestUrl: request.url,
|
|
1404
|
+
requestOrigin: options.resolveAuthRequestOrigin(request),
|
|
1405
|
+
session: {
|
|
1406
|
+
id: sessionCredential.sessionId,
|
|
1407
|
+
audience: authOptions.audience,
|
|
1408
|
+
tokenHash: sessionCredential.tokenHash,
|
|
1409
|
+
createdAt: now,
|
|
1410
|
+
...sixb.auth.createSessionDeadlines(now),
|
|
1411
|
+
...device,
|
|
1412
|
+
},
|
|
1413
|
+
})
|
|
1414
|
+
|
|
1415
|
+
return sessionCallbackCompletionResponse({
|
|
1416
|
+
sixb,
|
|
1417
|
+
request,
|
|
1418
|
+
apiOrigin: options.resolveAuthRequestOrigin(request),
|
|
1419
|
+
sessionCredential,
|
|
1420
|
+
audience: result.session.audience,
|
|
1421
|
+
expiresAt: result.session.expiresAt,
|
|
1422
|
+
returnTo: result.returnTo,
|
|
1423
|
+
})
|
|
1424
|
+
} catch (error) {
|
|
1425
|
+
logAuthCallbackError("OIDC", error)
|
|
1426
|
+
return htmlMessageResponse("This sign-in attempt could not be completed.", 400)
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
return strategyNotImplementedResponse("Auth callback is not implemented yet.")
|
|
1431
|
+
},
|
|
1432
|
+
{ detail: { hide: true } }
|
|
1433
|
+
)
|
|
1434
|
+
.post(
|
|
1435
|
+
"/auth/callback",
|
|
1436
|
+
async ({ body, request }) => {
|
|
1437
|
+
const strategy = sixb.auth.getStrategy()
|
|
1438
|
+
|
|
1439
|
+
if (!isMagicLinkAuthStrategy(strategy)) {
|
|
1440
|
+
return strategyNotImplementedResponse("Auth callback is not implemented yet.")
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
const magicLinkId = body.magicLinkId?.trim()
|
|
1444
|
+
const token = body.token?.trim()
|
|
1445
|
+
if (!magicLinkId || !token) {
|
|
1446
|
+
return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
return completeMagicLinkCallback({ sixb, strategy, options, request, magicLinkId, token })
|
|
1450
|
+
},
|
|
1451
|
+
{
|
|
1452
|
+
body: t.Object({
|
|
1453
|
+
magicLinkId: t.Optional(t.String()),
|
|
1454
|
+
token: t.Optional(t.String()),
|
|
1455
|
+
}),
|
|
1456
|
+
parse: "urlencoded",
|
|
1457
|
+
detail: { hide: true },
|
|
1458
|
+
}
|
|
1459
|
+
)
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
// The pending cookie carries the preimage of the `requester` hash embedded in
|
|
1463
|
+
// the emailed callback URL. Only the browser that requested the link holds it,
|
|
1464
|
+
// so GET /auth/callback can distinguish that browser (sign in immediately) from
|
|
1465
|
+
// scanners and other devices (confirmation page). It is an anti-burn shortcut,
|
|
1466
|
+
// not an auth credential — the magic-link token still authenticates the sign-in.
|
|
1467
|
+
const MAGIC_LINK_PENDING_COOKIE_NAME = "sixb_pending"
|
|
1468
|
+
// Fallback when a strategy doesn't expose its link TTL; matches the default
|
|
1469
|
+
// magic-link TTL. An expired cookie only costs the confirmation click.
|
|
1470
|
+
const MAGIC_LINK_PENDING_COOKIE_FALLBACK_MAX_AGE_SECONDS = 15 * 60
|
|
1471
|
+
|
|
1472
|
+
function magicLinkPendingCookieMaxAgeSeconds(strategy: MagicLinkAuthStrategy): number {
|
|
1473
|
+
return strategy.magicLinkTtlMs && strategy.magicLinkTtlMs > 0
|
|
1474
|
+
? Math.max(1, Math.trunc(strategy.magicLinkTtlMs / 1000))
|
|
1475
|
+
: MAGIC_LINK_PENDING_COOKIE_FALLBACK_MAX_AGE_SECONDS
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
function createMagicLinkPendingCredential(): {
|
|
1479
|
+
readonly secret: string
|
|
1480
|
+
readonly hash: string
|
|
1481
|
+
} {
|
|
1482
|
+
const secret = randomBytes(32).toString("base64url")
|
|
1483
|
+
return { secret, hash: hashMagicLinkPendingSecret(secret) }
|
|
1484
|
+
}
|
|
1485
|
+
|
|
1486
|
+
function hashMagicLinkPendingSecret(secret: string): string {
|
|
1487
|
+
return createHash("sha256").update(secret).digest("base64url")
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
function matchesMagicLinkRequester(pendingSecret: string, requesterHash: string): boolean {
|
|
1491
|
+
const expected = Buffer.from(hashMagicLinkPendingSecret(pendingSecret))
|
|
1492
|
+
const provided = Buffer.from(requesterHash)
|
|
1493
|
+
return expected.length === provided.length && timingSafeEqual(expected, provided)
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
// SameSite=Lax, not Strict: the emailed link arrives as a cross-site top-level
|
|
1497
|
+
// navigation and the cookie must accompany that GET for the fast path to work.
|
|
1498
|
+
function magicLinkPendingCookieHeader(params: {
|
|
1499
|
+
readonly request: Request
|
|
1500
|
+
readonly sixb: Sixb<readonly OntologySource[]>
|
|
1501
|
+
readonly value: string
|
|
1502
|
+
readonly maxAgeSeconds: number
|
|
1503
|
+
}): string {
|
|
1504
|
+
const parts = [
|
|
1505
|
+
`${MAGIC_LINK_PENDING_COOKIE_NAME}=${params.value}`,
|
|
1506
|
+
"Path=/auth/callback",
|
|
1507
|
+
"SameSite=Lax",
|
|
1508
|
+
"HttpOnly",
|
|
1509
|
+
`Max-Age=${params.maxAgeSeconds}`,
|
|
1510
|
+
]
|
|
1511
|
+
if (shouldUseSecureCookies(params.request, params.sixb.auth.getCookieOptions())) {
|
|
1512
|
+
parts.push("Secure")
|
|
1513
|
+
}
|
|
1514
|
+
return parts.join("; ")
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
// Shared by POST /auth/callback (confirmation click) and the same-device fast
|
|
1518
|
+
// path on GET. Consumes the single-use token and mints the session cookies.
|
|
1519
|
+
async function completeMagicLinkCallback(input: {
|
|
1520
|
+
readonly sixb: Sixb<readonly OntologySource[]>
|
|
1521
|
+
readonly strategy: MagicLinkAuthStrategy
|
|
1522
|
+
readonly options: AuthRoutesOptions
|
|
1523
|
+
readonly request: Request
|
|
1524
|
+
readonly magicLinkId: string
|
|
1525
|
+
readonly token: string
|
|
1526
|
+
readonly clearPendingCookie?: boolean
|
|
1527
|
+
}): Promise<Response> {
|
|
1528
|
+
const authOptions = resolveAuthOptions(input.options, input.request)
|
|
1529
|
+
const now = new Date()
|
|
1530
|
+
const sessionCredential = createSessionCredential()
|
|
1531
|
+
const device = resolveSessionDevice(input.request)
|
|
1532
|
+
|
|
1533
|
+
try {
|
|
1534
|
+
const result = await input.strategy.completeMagicLinkSignIn({
|
|
1535
|
+
projectId: input.sixb.id,
|
|
1536
|
+
authStorage: requireAuthStorage(input.sixb),
|
|
1537
|
+
magicLinkId: input.magicLinkId,
|
|
1538
|
+
token: input.token,
|
|
1539
|
+
session: {
|
|
1540
|
+
id: sessionCredential.sessionId,
|
|
1541
|
+
audience: authOptions.audience,
|
|
1542
|
+
tokenHash: sessionCredential.tokenHash,
|
|
1543
|
+
createdAt: now,
|
|
1544
|
+
...input.sixb.auth.createSessionDeadlines(now),
|
|
1545
|
+
...device,
|
|
1546
|
+
},
|
|
1547
|
+
})
|
|
1548
|
+
|
|
1549
|
+
const response = sessionCallbackCompletionResponse({
|
|
1550
|
+
sixb: input.sixb,
|
|
1551
|
+
request: input.request,
|
|
1552
|
+
apiOrigin: input.options.resolveAuthRequestOrigin(input.request),
|
|
1553
|
+
sessionCredential,
|
|
1554
|
+
audience: result.session.audience,
|
|
1555
|
+
expiresAt: result.session.expiresAt,
|
|
1556
|
+
returnTo: result.returnTo,
|
|
1557
|
+
})
|
|
1558
|
+
if (input.clearPendingCookie) {
|
|
1559
|
+
response.headers.append(
|
|
1560
|
+
"set-cookie",
|
|
1561
|
+
magicLinkPendingCookieHeader({
|
|
1562
|
+
request: input.request,
|
|
1563
|
+
sixb: input.sixb,
|
|
1564
|
+
value: "",
|
|
1565
|
+
maxAgeSeconds: 0,
|
|
1566
|
+
})
|
|
1567
|
+
)
|
|
1568
|
+
}
|
|
1569
|
+
return response
|
|
1570
|
+
} catch {
|
|
1571
|
+
return htmlMessageResponse("This sign-in link is invalid or expired.", 400)
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
// Best-effort client metadata for the active-sessions view. `x-forwarded-for`
|
|
1576
|
+
// only reflects the real client behind a trusted proxy; both values are display
|
|
1577
|
+
// only and never used for authorization.
|
|
1578
|
+
function resolveSessionDevice(request: Request): {
|
|
1579
|
+
readonly userAgent?: string
|
|
1580
|
+
readonly ipAddress?: string
|
|
1581
|
+
} {
|
|
1582
|
+
return {
|
|
1583
|
+
userAgent: request.headers.get("user-agent")?.trim() || undefined,
|
|
1584
|
+
ipAddress:
|
|
1585
|
+
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
|
|
1586
|
+
request.headers.get("x-real-ip")?.trim() ||
|
|
1587
|
+
undefined,
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
function sessionCallbackCompletionResponse(input: {
|
|
1592
|
+
readonly sixb: Sixb<readonly OntologySource[]>
|
|
1593
|
+
readonly request: Request
|
|
1594
|
+
readonly apiOrigin: string
|
|
1595
|
+
readonly sessionCredential: ReturnType<typeof createSessionCredential>
|
|
1596
|
+
readonly audience: AuthSessionAudience
|
|
1597
|
+
readonly expiresAt: Date
|
|
1598
|
+
readonly returnTo: string
|
|
1599
|
+
}): Response {
|
|
1600
|
+
const cookieOptions = input.sixb.auth.getCookieOptions({ audience: input.audience })
|
|
1601
|
+
const headers = new Headers({
|
|
1602
|
+
"cache-control": "no-store",
|
|
1603
|
+
})
|
|
1604
|
+
headers.append(
|
|
1605
|
+
"set-cookie",
|
|
1606
|
+
createSessionCookieHeader({
|
|
1607
|
+
request: input.request,
|
|
1608
|
+
value: input.sessionCredential.cookieValue,
|
|
1609
|
+
expiresAt: input.expiresAt,
|
|
1610
|
+
options: cookieOptions,
|
|
1611
|
+
})
|
|
1612
|
+
)
|
|
1613
|
+
headers.append(
|
|
1614
|
+
"set-cookie",
|
|
1615
|
+
createCsrfCookieHeader({
|
|
1616
|
+
request: input.request,
|
|
1617
|
+
value: generateCsrfToken(),
|
|
1618
|
+
expiresAt: input.expiresAt,
|
|
1619
|
+
options: cookieOptions,
|
|
1620
|
+
})
|
|
1621
|
+
)
|
|
1622
|
+
|
|
1623
|
+
return authCallbackCompletionResponse(input.returnTo, headers, input.apiOrigin)
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1626
|
+
// OAuth and magic-link callbacks can arrive as a cross-site navigation, and a direct
|
|
1627
|
+
// 3xx after setting SameSite=Strict cookies keeps the chained request cross-site — the
|
|
1628
|
+
// cookies get dropped. That only matters when the return target is on the API origin
|
|
1629
|
+
// itself (e.g. /docs); there, finish on a Sixb document first and navigate from it.
|
|
1630
|
+
// Any other origin doesn't need our cookies on the navigation, so redirect straight
|
|
1631
|
+
// through — the page the user is on (email client or the confirmation page with its
|
|
1632
|
+
// loading button) stays visible until the app renders.
|
|
1633
|
+
function authCallbackCompletionResponse(
|
|
1634
|
+
returnTo: string,
|
|
1635
|
+
headers: Headers,
|
|
1636
|
+
apiOrigin: string
|
|
1637
|
+
): Response {
|
|
1638
|
+
if (!isSameOriginReturnTarget(returnTo, apiOrigin)) {
|
|
1639
|
+
headers.set("location", returnTo)
|
|
1640
|
+
return new Response(null, { status: 303, headers })
|
|
1641
|
+
}
|
|
1642
|
+
|
|
1643
|
+
return authCallbackCompletionDocumentResponse(returnTo, headers)
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
function isSameOriginReturnTarget(returnTo: string, apiOrigin: string): boolean {
|
|
1647
|
+
try {
|
|
1648
|
+
return new URL(returnTo).origin === apiOrigin
|
|
1649
|
+
} catch {
|
|
1650
|
+
return true
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
// `style-src 'unsafe-inline'` lets the shared auth-page stylesheet apply; the page
|
|
1655
|
+
// stays script-free and everything else is locked down by `default-src 'none'`.
|
|
1656
|
+
function authCallbackCompletionDocumentResponse(returnTo: string, headers: Headers): Response {
|
|
1657
|
+
headers.set("content-type", "text/html; charset=utf-8")
|
|
1658
|
+
headers.set(
|
|
1659
|
+
"content-security-policy",
|
|
1660
|
+
`default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; navigate-to ${resolveNavigateToSources(
|
|
1661
|
+
returnTo
|
|
1662
|
+
)}`
|
|
1663
|
+
)
|
|
1664
|
+
headers.set("referrer-policy", "no-referrer")
|
|
1665
|
+
headers.set("x-content-type-options", "nosniff")
|
|
1666
|
+
|
|
1667
|
+
return new Response(
|
|
1668
|
+
authPageDocument(
|
|
1669
|
+
[
|
|
1670
|
+
"<h1>Signing you in…</h1>",
|
|
1671
|
+
`<p>If you are not redirected automatically, <a href="${escapeHtml(returnTo)}">continue</a>.</p>`,
|
|
1672
|
+
].join(""),
|
|
1673
|
+
"Signing in",
|
|
1674
|
+
[
|
|
1675
|
+
'<meta name="referrer" content="no-referrer">',
|
|
1676
|
+
`<meta http-equiv="refresh" content="0;url=${escapeHtml(returnTo)}">`,
|
|
1677
|
+
].join("")
|
|
1678
|
+
),
|
|
1679
|
+
{
|
|
1680
|
+
status: 200,
|
|
1681
|
+
headers,
|
|
1682
|
+
}
|
|
1683
|
+
)
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
function resolveAuthOptions(
|
|
1687
|
+
options: AuthRoutesOptions,
|
|
1688
|
+
request: Request
|
|
1689
|
+
): ReturnType<ResolveRequestAuthContext> {
|
|
1690
|
+
return options.resolveAuthContext(request)
|
|
1691
|
+
}
|
|
1692
|
+
|
|
1693
|
+
function resolveAuthRedirectContext(
|
|
1694
|
+
options: AuthRoutesOptions,
|
|
1695
|
+
request: Request,
|
|
1696
|
+
input: Parameters<ResolveAuthRedirectContext>[1]
|
|
1697
|
+
): AuthRedirectContext | Response {
|
|
1698
|
+
try {
|
|
1699
|
+
return options.resolveAuthRedirectContext(request, input)
|
|
1700
|
+
} catch (error) {
|
|
1701
|
+
if (error instanceof BrowserOriginError) {
|
|
1702
|
+
return htmlMessageResponse("This sign-in request is invalid.", 400)
|
|
1703
|
+
}
|
|
1704
|
+
|
|
1705
|
+
throw error
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
function resolveInvitationDeliveryContext(
|
|
1710
|
+
options: AuthRoutesOptions,
|
|
1711
|
+
request: Request,
|
|
1712
|
+
input: AuthInvitationRedirectInput
|
|
1713
|
+
): AuthInvitationRedirectContext | Response {
|
|
1714
|
+
try {
|
|
1715
|
+
return options.resolveInvitationRedirectContext(request, input)
|
|
1716
|
+
} catch (error) {
|
|
1717
|
+
if (error instanceof BrowserOriginError) {
|
|
1718
|
+
return jsonResponse({ error: "Invitation destination is not allowed" }, 400)
|
|
1719
|
+
}
|
|
1720
|
+
|
|
1721
|
+
throw error
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
function resolveSessionCsrfToken(input: {
|
|
1726
|
+
readonly request: Request
|
|
1727
|
+
readonly cookieOptions: ResolvedCookieOptions
|
|
1728
|
+
readonly expiresAt: Date
|
|
1729
|
+
}): { readonly token: string; readonly setCookie?: string } {
|
|
1730
|
+
const existing = getCookie(input.request, input.cookieOptions.csrfCookieName)
|
|
1731
|
+
if (existing) {
|
|
1732
|
+
return { token: existing }
|
|
1733
|
+
}
|
|
1734
|
+
|
|
1735
|
+
const token = generateCsrfToken()
|
|
1736
|
+
return {
|
|
1737
|
+
token,
|
|
1738
|
+
setCookie: createCsrfCookieHeader({
|
|
1739
|
+
request: input.request,
|
|
1740
|
+
value: token,
|
|
1741
|
+
expiresAt: input.expiresAt,
|
|
1742
|
+
options: input.cookieOptions,
|
|
1743
|
+
}),
|
|
1744
|
+
}
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
function authSessionJsonResponse(
|
|
1748
|
+
body: AuthenticatedAuthSessionResponse,
|
|
1749
|
+
setCookies: readonly string[]
|
|
1750
|
+
): Response {
|
|
1751
|
+
const headers = new Headers({
|
|
1752
|
+
"content-type": "application/json; charset=utf-8",
|
|
1753
|
+
[CSRF_TOKEN_RESPONSE_HEADER_NAME]: body.csrfToken,
|
|
1754
|
+
})
|
|
1755
|
+
for (const setCookie of setCookies) headers.append("set-cookie", setCookie)
|
|
1756
|
+
return jsonResponse(body, 200, headers)
|
|
1757
|
+
}
|
|
1758
|
+
|
|
1759
|
+
function redirectResponse(location: string): Response {
|
|
1760
|
+
return new Response(null, {
|
|
1761
|
+
status: 303,
|
|
1762
|
+
headers: {
|
|
1763
|
+
location,
|
|
1764
|
+
"cache-control": "no-store",
|
|
1765
|
+
},
|
|
1766
|
+
})
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
function strategyNotImplementedResponse(message: string): Response {
|
|
1770
|
+
return new Response(message, {
|
|
1771
|
+
status: 501,
|
|
1772
|
+
headers: {
|
|
1773
|
+
"content-type": "text/plain; charset=utf-8",
|
|
1774
|
+
"cache-control": "no-store",
|
|
1775
|
+
},
|
|
1776
|
+
})
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
// Mirrors the Atlas design tokens (packages/ui/src/styles/globals.css) so the
|
|
1780
|
+
// server-rendered auth pages feel familiar. Self-contained: no external CSS, and dark mode
|
|
1781
|
+
// follows the system preference since these standalone pages have no client theme runtime.
|
|
1782
|
+
const AUTH_PAGE_STYLE = `<style>
|
|
1783
|
+
:root {
|
|
1784
|
+
color-scheme: light dark;
|
|
1785
|
+
--background: #fafafa;
|
|
1786
|
+
--foreground: #101010;
|
|
1787
|
+
--card: #ffffff;
|
|
1788
|
+
--primary: #0a0a0a;
|
|
1789
|
+
--primary-foreground: #ffffff;
|
|
1790
|
+
--border: #e2e2e2;
|
|
1791
|
+
--muted-foreground: #5f5f5f;
|
|
1792
|
+
--ring: #0a0a0a;
|
|
1793
|
+
--radius: 0.5rem;
|
|
1794
|
+
}
|
|
1795
|
+
@media (prefers-color-scheme: dark) {
|
|
1796
|
+
:root {
|
|
1797
|
+
--background: #0a0a0a;
|
|
1798
|
+
--foreground: #f4f4f4;
|
|
1799
|
+
--card: #141414;
|
|
1800
|
+
--primary: #f4f4f4;
|
|
1801
|
+
--primary-foreground: #0a0a0a;
|
|
1802
|
+
--border: #262626;
|
|
1803
|
+
--muted-foreground: #8a8a8a;
|
|
1804
|
+
--ring: #f4f4f4;
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
* { box-sizing: border-box; }
|
|
1808
|
+
html, body { height: 100%; }
|
|
1809
|
+
body {
|
|
1810
|
+
margin: 0;
|
|
1811
|
+
font-family: "SF Pro Text", "SF Pro Display", "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif;
|
|
1812
|
+
background: var(--background);
|
|
1813
|
+
color: var(--foreground);
|
|
1814
|
+
line-height: 1.5;
|
|
1815
|
+
-webkit-font-smoothing: antialiased;
|
|
1816
|
+
-moz-osx-font-smoothing: grayscale;
|
|
1817
|
+
}
|
|
1818
|
+
.shell {
|
|
1819
|
+
min-height: 100%;
|
|
1820
|
+
display: flex;
|
|
1821
|
+
align-items: center;
|
|
1822
|
+
justify-content: center;
|
|
1823
|
+
padding: 1.5rem;
|
|
1824
|
+
}
|
|
1825
|
+
.card {
|
|
1826
|
+
width: 100%;
|
|
1827
|
+
max-width: 20rem;
|
|
1828
|
+
/* Nudge above dead-center so the form sits a touch higher on the page. */
|
|
1829
|
+
transform: translateY(-6vh);
|
|
1830
|
+
}
|
|
1831
|
+
h1 {
|
|
1832
|
+
margin: 0 0 0.5rem;
|
|
1833
|
+
font-size: 1.25rem;
|
|
1834
|
+
font-weight: 600;
|
|
1835
|
+
letter-spacing: -0.01em;
|
|
1836
|
+
}
|
|
1837
|
+
p {
|
|
1838
|
+
margin: 0;
|
|
1839
|
+
color: var(--muted-foreground);
|
|
1840
|
+
font-size: 0.875rem;
|
|
1841
|
+
}
|
|
1842
|
+
p strong {
|
|
1843
|
+
color: var(--foreground);
|
|
1844
|
+
font-weight: 500;
|
|
1845
|
+
}
|
|
1846
|
+
a {
|
|
1847
|
+
color: var(--foreground);
|
|
1848
|
+
text-underline-offset: 0.2em;
|
|
1849
|
+
}
|
|
1850
|
+
form { margin: 1.75rem 0 0; }
|
|
1851
|
+
input[type="email"] {
|
|
1852
|
+
width: 100%;
|
|
1853
|
+
height: 2.5rem;
|
|
1854
|
+
padding: 0 0.875rem;
|
|
1855
|
+
font: inherit;
|
|
1856
|
+
font-size: 0.9375rem;
|
|
1857
|
+
color: var(--foreground);
|
|
1858
|
+
background: var(--card);
|
|
1859
|
+
border: 1px solid var(--border);
|
|
1860
|
+
border-radius: calc(var(--radius) - 2px);
|
|
1861
|
+
}
|
|
1862
|
+
input[type="email"]::placeholder { color: var(--muted-foreground); }
|
|
1863
|
+
input[type="email"]:focus {
|
|
1864
|
+
outline: none;
|
|
1865
|
+
border-color: var(--ring);
|
|
1866
|
+
box-shadow: 0 0 0 3px color-mix(in srgb, var(--ring) 18%, transparent);
|
|
1867
|
+
}
|
|
1868
|
+
button {
|
|
1869
|
+
width: 100%;
|
|
1870
|
+
height: 2.5rem;
|
|
1871
|
+
margin-top: 0.75rem;
|
|
1872
|
+
font: inherit;
|
|
1873
|
+
font-size: 0.875rem;
|
|
1874
|
+
font-weight: 500;
|
|
1875
|
+
color: var(--primary-foreground);
|
|
1876
|
+
background: var(--primary);
|
|
1877
|
+
border: none;
|
|
1878
|
+
border-radius: calc(var(--radius) - 2px);
|
|
1879
|
+
cursor: pointer;
|
|
1880
|
+
}
|
|
1881
|
+
button:hover:not(:disabled) { opacity: 0.9; }
|
|
1882
|
+
button:focus-visible {
|
|
1883
|
+
outline: 2px solid var(--ring);
|
|
1884
|
+
outline-offset: 2px;
|
|
1885
|
+
}
|
|
1886
|
+
button:disabled { cursor: default; }
|
|
1887
|
+
.spinner {
|
|
1888
|
+
display: inline-block;
|
|
1889
|
+
width: 1rem;
|
|
1890
|
+
height: 1rem;
|
|
1891
|
+
vertical-align: -0.2em;
|
|
1892
|
+
border: 2px solid color-mix(in srgb, var(--primary-foreground) 35%, transparent);
|
|
1893
|
+
border-top-color: var(--primary-foreground);
|
|
1894
|
+
border-radius: 50%;
|
|
1895
|
+
animation: spin 0.6s linear infinite;
|
|
1896
|
+
}
|
|
1897
|
+
@keyframes spin { to { transform: rotate(360deg); } }
|
|
1898
|
+
</style>`
|
|
1899
|
+
|
|
1900
|
+
function authPageDocument(body: string, title = "Sign in", head = ""): string {
|
|
1901
|
+
return [
|
|
1902
|
+
"<!doctype html>",
|
|
1903
|
+
'<html lang="en">',
|
|
1904
|
+
"<head>",
|
|
1905
|
+
'<meta charset="utf-8">',
|
|
1906
|
+
'<meta name="viewport" content="width=device-width, initial-scale=1">',
|
|
1907
|
+
`<title>${escapeHtml(title)}</title>`,
|
|
1908
|
+
head,
|
|
1909
|
+
AUTH_PAGE_STYLE,
|
|
1910
|
+
"</head>",
|
|
1911
|
+
"<body>",
|
|
1912
|
+
'<main class="shell">',
|
|
1913
|
+
'<section class="card">',
|
|
1914
|
+
body,
|
|
1915
|
+
"</section>",
|
|
1916
|
+
"</main>",
|
|
1917
|
+
"</body>",
|
|
1918
|
+
"</html>",
|
|
1919
|
+
].join("")
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
function authPageResponse(body: string, status = 200): Response {
|
|
1923
|
+
return new Response(authPageDocument(body), {
|
|
1924
|
+
status,
|
|
1925
|
+
headers: {
|
|
1926
|
+
"content-type": "text/html; charset=utf-8",
|
|
1927
|
+
"cache-control": "no-store",
|
|
1928
|
+
},
|
|
1929
|
+
})
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
function signInFormResponse(context: AuthRedirectContext): Response {
|
|
1933
|
+
return authPageResponse(
|
|
1934
|
+
[
|
|
1935
|
+
"<h1>Sign in</h1>",
|
|
1936
|
+
"<p>We'll email you a sign-in link.</p>",
|
|
1937
|
+
'<form method="post" action="/auth/sign-in">',
|
|
1938
|
+
`<input type="hidden" name="audience" value="${escapeHtml(context.audience)}">`,
|
|
1939
|
+
`<input type="hidden" name="returnTo" value="${escapeHtml(context.returnTo)}">`,
|
|
1940
|
+
'<input name="email" type="email" autocomplete="email" placeholder="you@example.com" aria-label="Email address" required autofocus>',
|
|
1941
|
+
'<button type="submit">Send sign-in link</button>',
|
|
1942
|
+
"</form>",
|
|
1943
|
+
].join("")
|
|
1944
|
+
)
|
|
1945
|
+
}
|
|
1946
|
+
|
|
1947
|
+
// Deliberately a plain form with no auto-submit: link scanners that execute
|
|
1948
|
+
// pages headlessly still won't press the button, so the token survives until a
|
|
1949
|
+
// person clicks Continue. The extra click also keeps the link reusable when a
|
|
1950
|
+
// phone opens it in a preview or hands it to a different default browser. The
|
|
1951
|
+
// inline script never submits anything — it only turns the clicked button into
|
|
1952
|
+
// a disabled spinner. The form POST is a normal navigation, so this page stays
|
|
1953
|
+
// visible (spinner and all) until the server responds; the pageshow handler
|
|
1954
|
+
// resets the button when the page is restored from the back/forward cache.
|
|
1955
|
+
function magicLinkConfirmResponse(input: {
|
|
1956
|
+
readonly magicLinkId: string
|
|
1957
|
+
readonly token: string
|
|
1958
|
+
// Absent when the strategy doesn't support the read-only peek.
|
|
1959
|
+
readonly email?: string
|
|
1960
|
+
}): Response {
|
|
1961
|
+
const response = authPageResponse(
|
|
1962
|
+
[
|
|
1963
|
+
"<h1>Sign in</h1>",
|
|
1964
|
+
input.email
|
|
1965
|
+
? `<p>You're signing in as <strong>${escapeHtml(input.email)}</strong>.</p>`
|
|
1966
|
+
: "<p>Click continue to finish signing in.</p>",
|
|
1967
|
+
'<form method="post" action="/auth/callback" id="confirm">',
|
|
1968
|
+
`<input type="hidden" name="magicLinkId" value="${escapeHtml(input.magicLinkId)}">`,
|
|
1969
|
+
`<input type="hidden" name="token" value="${escapeHtml(input.token)}">`,
|
|
1970
|
+
'<button type="submit" id="confirm-button">Continue</button>',
|
|
1971
|
+
"</form>",
|
|
1972
|
+
"<script>",
|
|
1973
|
+
'(function () {var button = document.getElementById("confirm-button");',
|
|
1974
|
+
'document.getElementById("confirm").addEventListener("submit", function () {',
|
|
1975
|
+
"button.disabled = true;",
|
|
1976
|
+
'button.setAttribute("aria-busy", "true");',
|
|
1977
|
+
'button.innerHTML = \'<span class="spinner" aria-hidden="true"></span>\';',
|
|
1978
|
+
"});",
|
|
1979
|
+
'window.addEventListener("pageshow", function (event) {',
|
|
1980
|
+
"if (!event.persisted) return;",
|
|
1981
|
+
"button.disabled = false;",
|
|
1982
|
+
'button.removeAttribute("aria-busy");',
|
|
1983
|
+
'button.textContent = "Continue";',
|
|
1984
|
+
"});})();",
|
|
1985
|
+
"</script>",
|
|
1986
|
+
].join("")
|
|
1987
|
+
)
|
|
1988
|
+
// The single-use token is in this page's URL; keep it out of cross-origin
|
|
1989
|
+
// referrers. Must stay `same-origin`, not `no-referrer` — a no-referrer policy
|
|
1990
|
+
// makes browsers send `Origin: null` on the form POST, which the browser-origin
|
|
1991
|
+
// guard rejects before the callback route runs.
|
|
1992
|
+
response.headers.set("referrer-policy", "same-origin")
|
|
1993
|
+
return response
|
|
1994
|
+
}
|
|
1995
|
+
|
|
1996
|
+
function resolveNavigateToSources(returnTo: string): string {
|
|
1997
|
+
try {
|
|
1998
|
+
return `'self' ${new URL(returnTo).origin}`
|
|
1999
|
+
} catch {
|
|
2000
|
+
return "'self'"
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
function htmlMessageResponse(message: string, status = 200, heading?: string): Response {
|
|
2005
|
+
return authPageResponse(
|
|
2006
|
+
[heading ? `<h1>${escapeHtml(heading)}</h1>` : "", `<p>${escapeHtml(message)}</p>`].join(""),
|
|
2007
|
+
status
|
|
2008
|
+
)
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
function requireAuthStorage(sixb: Sixb<readonly OntologySource[]>): AuthStorage {
|
|
2012
|
+
if (!sixb.storage.auth) {
|
|
2013
|
+
throw new Error("[SixbServer] Auth storage is required for auth routes.")
|
|
2014
|
+
}
|
|
2015
|
+
|
|
2016
|
+
return sixb.storage.auth
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
function serializeGroupOption(group: GroupDefinition) {
|
|
2020
|
+
return {
|
|
2021
|
+
id: group.id,
|
|
2022
|
+
...(group.label !== undefined ? { label: group.label } : {}),
|
|
2023
|
+
...(group.description !== undefined ? { description: group.description } : {}),
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
|
|
2027
|
+
function serializeAccessToken(
|
|
2028
|
+
accessToken: AccessTokenRecord,
|
|
2029
|
+
options: { readonly subjectLabel?: string } = {}
|
|
2030
|
+
) {
|
|
2031
|
+
const now = Date.now()
|
|
2032
|
+
const status = accessToken.revokedAt
|
|
2033
|
+
? "revoked"
|
|
2034
|
+
: accessToken.expiresAt.getTime() <= now
|
|
2035
|
+
? "expired"
|
|
2036
|
+
: "active"
|
|
2037
|
+
|
|
2038
|
+
return {
|
|
2039
|
+
id: accessToken.id,
|
|
2040
|
+
name: accessToken.name,
|
|
2041
|
+
kind: accessToken.kind,
|
|
2042
|
+
status,
|
|
2043
|
+
subjectType: accessToken.subjectType,
|
|
2044
|
+
subjectId: accessToken.subjectId,
|
|
2045
|
+
subjectLabel: options.subjectLabel,
|
|
2046
|
+
groupIds: accessToken.groupIds ? [...accessToken.groupIds] : undefined,
|
|
2047
|
+
createdAt: toIsoString(accessToken.createdAt),
|
|
2048
|
+
expiresAt: toIsoString(accessToken.expiresAt),
|
|
2049
|
+
revokedAt: accessToken.revokedAt ? toIsoString(accessToken.revokedAt) : undefined,
|
|
2050
|
+
lastUsedAt: accessToken.lastUsedAt ? toIsoString(accessToken.lastUsedAt) : undefined,
|
|
2051
|
+
lastUsedUserAgent: accessToken.lastUsedUserAgent,
|
|
2052
|
+
lastUsedIpAddress: accessToken.lastUsedIpAddress,
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
function serializeServiceAccount(
|
|
2057
|
+
serviceAccount: ServiceAccountRecord,
|
|
2058
|
+
groupIds: readonly string[]
|
|
2059
|
+
) {
|
|
2060
|
+
return {
|
|
2061
|
+
id: serviceAccount.id,
|
|
2062
|
+
name: serviceAccount.name,
|
|
2063
|
+
description: serviceAccount.description,
|
|
2064
|
+
status: serviceAccount.status,
|
|
2065
|
+
groupIds: [...groupIds],
|
|
2066
|
+
createdAt: toIsoString(serviceAccount.createdAt),
|
|
2067
|
+
updatedAt: toIsoString(serviceAccount.updatedAt),
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
|
|
2071
|
+
function parseRequiredFutureDate(value: string): Date {
|
|
2072
|
+
const date = parseDate(value)
|
|
2073
|
+
if (!date) {
|
|
2074
|
+
throw new Error("Expiration is required.")
|
|
2075
|
+
}
|
|
2076
|
+
|
|
2077
|
+
if (date.getTime() <= Date.now()) {
|
|
2078
|
+
throw new Error("Expiration must be in the future.")
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
return date
|
|
2082
|
+
}
|
|
2083
|
+
|
|
2084
|
+
function optionalTrimmed(value: string | undefined): string | undefined {
|
|
2085
|
+
const trimmed = value?.trim()
|
|
2086
|
+
return trimmed ? trimmed : undefined
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
// Token and service-account management can be driven by a personal access
|
|
2090
|
+
// token (for CLI credential rotation) as well as a browser session, so reject
|
|
2091
|
+
// unauthenticated requests with 401 and non-user principals (service-account
|
|
2092
|
+
// tokens) with 403. Service-account tokens are runtime credentials and must not
|
|
2093
|
+
// mint or manage further credentials.
|
|
2094
|
+
function requireAuthenticatedUserSession(
|
|
2095
|
+
session: AuthRequestResult
|
|
2096
|
+
): AuthenticatedUserRequestSession | Response {
|
|
2097
|
+
if (!session.authenticated) {
|
|
2098
|
+
return jsonResponse({ error: "Authentication required" }, 401)
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
if (!isAuthenticatedUserSession(session)) {
|
|
2102
|
+
return jsonResponse({ error: "User authentication is required" }, 403)
|
|
2103
|
+
}
|
|
2104
|
+
|
|
2105
|
+
return session
|
|
2106
|
+
}
|
|
2107
|
+
|
|
2108
|
+
function isAuthenticatedUserSession(
|
|
2109
|
+
session: AuthRequestResult & { readonly authenticated: true }
|
|
2110
|
+
): session is AuthenticatedUserRequestSession {
|
|
2111
|
+
return session.principal.type === "user"
|
|
2112
|
+
}
|
|
2113
|
+
|
|
2114
|
+
function serializeInvitation(invitation: InvitationRecord) {
|
|
2115
|
+
return {
|
|
2116
|
+
id: invitation.id,
|
|
2117
|
+
email: invitation.email,
|
|
2118
|
+
groupIds: [...invitation.groupIds],
|
|
2119
|
+
status: invitation.status,
|
|
2120
|
+
createdAt: toIsoString(invitation.createdAt),
|
|
2121
|
+
updatedAt: toIsoString(invitation.updatedAt),
|
|
2122
|
+
expiresAt: toIsoString(invitation.expiresAt),
|
|
2123
|
+
acceptedAt: invitation.acceptedAt ? toIsoString(invitation.acceptedAt) : undefined,
|
|
2124
|
+
revokedAt: invitation.revokedAt ? toIsoString(invitation.revokedAt) : undefined,
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
|
|
2128
|
+
function serializeMemberSummary(member: MemberSummary) {
|
|
2129
|
+
return {
|
|
2130
|
+
...serializeManagedMember(member.user, member.groupIds),
|
|
2131
|
+
capabilities: member.capabilities,
|
|
2132
|
+
}
|
|
2133
|
+
}
|
|
2134
|
+
|
|
2135
|
+
function serializeManagedMember(user: UserRecord, groupIds: readonly string[]) {
|
|
2136
|
+
return {
|
|
2137
|
+
user: serializeMemberUser(user),
|
|
2138
|
+
groupIds: [...groupIds],
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
|
|
2142
|
+
function serializeMemberUser(user: UserRecord) {
|
|
2143
|
+
return {
|
|
2144
|
+
id: user.id,
|
|
2145
|
+
email: user.email,
|
|
2146
|
+
displayName: user.displayName,
|
|
2147
|
+
avatarUrl: user.avatarUrl,
|
|
2148
|
+
status: user.status,
|
|
2149
|
+
createdAt: toIsoString(user.createdAt),
|
|
2150
|
+
updatedAt: toIsoString(user.updatedAt),
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
|
|
2154
|
+
function escapeHtml(value: string): string {
|
|
2155
|
+
return value
|
|
2156
|
+
.replaceAll("&", "&")
|
|
2157
|
+
.replaceAll("<", "<")
|
|
2158
|
+
.replaceAll(">", ">")
|
|
2159
|
+
.replaceAll('"', """)
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
function authRouteErrorResponse(error: unknown): Response {
|
|
2163
|
+
if (error instanceof AuthRuntimeError) {
|
|
2164
|
+
if (error.code === "authentication_required") {
|
|
2165
|
+
return jsonResponse({ error: error.message }, 401)
|
|
2166
|
+
}
|
|
2167
|
+
|
|
2168
|
+
if (error.code === "authorization_denied") {
|
|
2169
|
+
return jsonResponse({ error: error.message }, 403)
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
if (error.code === "invalid_auth_input") {
|
|
2173
|
+
return jsonResponse({ error: error.message }, 400)
|
|
2174
|
+
}
|
|
2175
|
+
|
|
2176
|
+
if (error.code === "rate_limited") {
|
|
2177
|
+
return jsonResponse({ error: error.message }, 429)
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
return jsonResponse({ error: error.message }, 500)
|
|
2181
|
+
}
|
|
2182
|
+
|
|
2183
|
+
if (error instanceof AuthStorageError) {
|
|
2184
|
+
if (
|
|
2185
|
+
error.code === "missing_invitation" ||
|
|
2186
|
+
error.code === "missing_access_token" ||
|
|
2187
|
+
error.code === "missing_service_account" ||
|
|
2188
|
+
error.code === "missing_user"
|
|
2189
|
+
) {
|
|
2190
|
+
return jsonResponse({ error: error.message }, 404)
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
return jsonResponse({ error: error.message }, 400)
|
|
2194
|
+
}
|
|
2195
|
+
|
|
2196
|
+
if (error instanceof Error) {
|
|
2197
|
+
const status =
|
|
2198
|
+
error.message.startsWith("Invalid date:") ||
|
|
2199
|
+
error.message.startsWith("Invalid integer:") ||
|
|
2200
|
+
error.message.startsWith("Expiration ")
|
|
2201
|
+
? 400
|
|
2202
|
+
: 500
|
|
2203
|
+
return jsonResponse({ error: error.message }, status)
|
|
2204
|
+
}
|
|
2205
|
+
|
|
2206
|
+
return jsonResponse({ error: String(error) }, 500)
|
|
2207
|
+
}
|
|
2208
|
+
|
|
2209
|
+
function logAuthCallbackError(kind: string, error: unknown): void {
|
|
2210
|
+
if (process.env.NODE_ENV !== "development" && process.env.SIXB_AUTH_DEBUG !== "1") {
|
|
2211
|
+
return
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
const detail =
|
|
2215
|
+
error instanceof AuthStorageError
|
|
2216
|
+
? `${error.name}(${error.code}): ${error.message}`
|
|
2217
|
+
: error instanceof Error
|
|
2218
|
+
? `${error.name}: ${error.message}`
|
|
2219
|
+
: String(error)
|
|
2220
|
+
|
|
2221
|
+
console.error(`[SixbServer] ${kind} auth callback failed: ${detail}`)
|
|
2222
|
+
}
|
|
2223
|
+
|
|
2224
|
+
function jsonResponse(body: unknown, status: number, headersInit?: HeadersInit): Response {
|
|
2225
|
+
const headers = new Headers(headersInit)
|
|
2226
|
+
headers.set("content-type", headers.get("content-type") ?? "application/json; charset=utf-8")
|
|
2227
|
+
headers.set("cache-control", headers.get("cache-control") ?? "no-store")
|
|
2228
|
+
|
|
2229
|
+
return new Response(JSON.stringify(body), {
|
|
2230
|
+
status,
|
|
2231
|
+
headers,
|
|
2232
|
+
})
|
|
2233
|
+
}
|