Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
2221 lines (2139 loc) · 83 KB
/
Copy pathindex.ts
File metadata and controls
2221 lines (2139 loc) · 83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { isNonEmptyString } from "@openclaw-enterprise/utils";
import { createHmac, randomUUID } from "node:crypto";
import type { FastifyReply, FastifyRequest } from "fastify";
import { APIError, betterAuth, type Auth, type BetterAuthOptions } from "better-auth";
import { splitSetCookieHeader } from "better-auth/cookies";
import { memoryAdapter, type MemoryDB } from "better-auth/adapters/memory";
import { apiKey } from "@better-auth/api-key";
import type { ApiKey } from "@better-auth/api-key/types";
import type { AuditEvent, ServicePrincipal } from "@openclaw-enterprise/contracts";
import {
NativeIAMDriver,
createAuthPrincipalSeed,
validateAuthAccountPrincipalSeed,
type AuthPrincipalSeed,
type AuthPrincipalSeedOptions,
} from "@openclaw-enterprise/iam";
import {
PostgresHumanAuthentication,
CallerStateDeniedError,
ScopeViolationError,
type HumanAuthenticationActivation,
type HumanAuthenticationActivationHooks,
type HumanAuthenticationActor,
type HumanAuthenticationRecovery,
type HumanAuthenticationAccount,
createPostgresAuthBinding,
type SchemaAuthPoolV1,
type SchemaAuthAdapterOptionsV1,
type PostgresPlatformState,
type PreparedPasswordAccount,
type PlatformUnitOfWork,
} from "@openclaw-enterprise/occ";
import type { IAMDriver } from "@openclaw-enterprise/contracts";
import {
createHumanLogin,
googleProviderId,
CALLBACK_DENIALS,
PASSWORD_DENIAL_AUDIT_UNAVAILABLE,
} from "./human-login.ts";
import type { ExternalProviderName } from "./human-login.ts";
import { googleLoginConfiguration, type GoogleSignInConfiguration } from "./google.ts";
import { oidcLoginConfiguration, oidcProviderId, type OidcSignInConfiguration } from "./oidc.ts";
import { resolveOidcEnrollmentPolicy } from "./oidc-enrollment.ts";
import { sessionBindingKey, sessionKeyHeader, sessionKeyMatches } from "./session-binding.ts";
import { sessionAuthority } from "./session-authority.ts";
import { createServiceKeyVerification } from "./service-key-verification.ts";
import { passwordSignOut } from "./password-sign-out.ts";
import {
authLibraryFailureEvent,
authLibraryLog,
withAuthLogContext,
type AuthLibraryOperation,
type AuthLogRequest,
} from "./library-log.ts";
import { scryptPasswordHasher, type PasswordHasher } from "./password-hasher.ts";
import { resolveClientAddress, type ClientAddressConfiguration } from "./client-address.ts";
import {
SignInRateLimited,
keyedAdmission,
admissionKey,
passwordFailureAdmission,
passwordFailureBudget,
type PasswordSignInAdmission,
type PasswordSlowLaneOptions,
} from "./admission.ts";
import {
issueKnownDevice,
knownDeviceFromCookieHeader,
knownDeviceSetCookie,
verifyKnownDevice,
type KnownDeviceAccountState,
} from "./known-device.ts";
export {
googleLoginConfiguration,
type GoogleLoginConfiguration,
type GoogleSignInConfiguration,
} from "./google.ts";
export {
oidcLoginConfiguration,
type OidcLoginConfiguration,
type OidcSignInConfiguration,
} from "./oidc.ts";
export { scryptPasswordHasher, type PasswordHasher } from "./password-hasher.ts";
/**
* Who may sign in with a password in the guarded profile: every enrolled account
* (`all`, the default) or only the recovery account (`recovery-only`).
*/
export type PasswordSignInPolicy = "all" | "recovery-only";
/** The slow-lane floors a composition may shorten or observe (see `passwordSlowLaneFloors`). */
export type PasswordSlowLaneFloors = Pick<
PasswordSlowLaneOptions,
"floorMs" | "maxFloorMs" | "waitFloor"
>;
export interface HumanLoginConfiguration {
readonly google?: GoogleSignInConfiguration;
readonly oidc?: OidcSignInConfiguration;
/** Set only for `recovery-only`; absent means every enrolled account keeps its password. */
readonly passwordSignIn?: "recovery-only";
}
/** Parses OCC_AUTH_PASSWORD_SIGN_IN; empty or unset keeps the default, `all`. */
export function passwordSignInPolicy(
environment: Readonly<Record<string, string | undefined>>,
): PasswordSignInPolicy {
const value = environment.OCC_AUTH_PASSWORD_SIGN_IN?.trim() ?? "";
if (value === "" || value === "all") {
return "all";
}
if (value === "recovery-only") {
return value;
}
throw new Error("OCC_AUTH_PASSWORD_SIGN_IN must be all or recovery-only.");
}
/**
* Parses every external sign-in provider. The recovery user ID
* (OCC_AUTH_RECOVERY_USER_ID) seeds the guarded profile, so it is required exactly
* when at least one provider is configured. Recovery-only password sign-in needs a
* provider: without one it would leave only the recovery account able to sign in.
*/
export function humanLoginConfiguration(
environment: Readonly<Record<string, string | undefined>>,
): HumanLoginConfiguration {
if (
Object.keys(environment).some(
(key) => key.startsWith("OCC_AUTH_GITHUB_") && environment[key] !== undefined,
)
) {
throw new Error(
"Direct GitHub sign-in settings are retired. Use OIDC; see docs/guides/deploy/oidc-upgrade.md.",
);
}
const google = googleLoginConfiguration(environment);
const oidc = oidcLoginConfiguration(environment);
const recoveryUserId = environment.OCC_AUTH_RECOVERY_USER_ID;
const passwordSignIn = passwordSignInPolicy(environment);
if (google === undefined && oidc === undefined) {
if (recoveryUserId !== undefined) {
throw new Error(
"External sign-in requires client ID, client secret and recovery user ID for Google or OIDC.",
);
}
if (passwordSignIn !== "all") {
throw new Error("OCC_AUTH_PASSWORD_SIGN_IN=recovery-only requires Google or OIDC sign-in.");
}
return {};
}
const recoveryMissing = recoveryUserId === undefined || recoveryUserId.trim().length === 0;
if (google !== undefined && recoveryMissing) {
throw new Error("Google sign-in requires client ID, client secret and recovery user ID.");
}
if (oidc !== undefined && recoveryMissing) {
throw new Error("OIDC sign-in requires its provider settings and a recovery user ID.");
}
return {
...(google === undefined ? {} : { google: { ...google, recoveryUserId: recoveryUserId! } }),
...(oidc === undefined ? {} : { oidc: { ...oidc, recoveryUserId: recoveryUserId! } }),
...(passwordSignIn === "all" ? {} : { passwordSignIn }),
};
}
export {
clientAddressConfiguration,
resolveClientAddress,
type ClientAddressConfiguration,
} from "./client-address.ts";
import type {
AdmissionHeaders,
AdmissionRequest,
AdmissionVerifier,
AdmittedCaller,
AdmittedSession,
} from "../admission/admission-verifier.ts";
import { AdmissionFailure, UNTRUSTED_ORIGIN_MESSAGE } from "../admission/admission-verifier.ts";
import { RequestFailure, unstorableTextFailure } from "../http/errors.ts";
import {
betterAuthIssuer,
deriveSharedCookieDomain,
validateAuthSecret,
validHttpBaseURL,
} from "./configuration.ts";
export {
betterAuthIssuer,
deriveSharedCookieDomain,
normalizeSharedCookieDomain,
hostnameMatchesSharedCookieDomain,
OCC_BETTER_AUTH_ISSUER_PREFIX,
} from "./configuration.ts";
const LOCAL_PASSWORD_MIN_LENGTH = 12;
const LOCAL_PASSWORD_MAX_LENGTH = 128;
export const OCC_AUTH_COOKIE_PREFIX = "openclaw_occ";
export const OCC_SHARED_AUTH_COOKIE_PREFIX = "openclaw_occ_shared";
export const OCC_SERVICE_KEY_HEADER = "x-api-key";
const SERVICE_KEY_CONFIG = "occ-service";
const serviceKeyVerification = createServiceKeyVerification();
// The createServiceKey schema allows 1 to 32 characters, which Ajv counts in code points.
// Better Auth counts UTF-16 units, so its own cap is twice that: a 32-emoji name is 64 units.
// The schema stays the authority; storage is unbounded text.
export const SERVICE_KEY_NAME_MAX_LENGTH = 32;
const SERVICE_KEY_NAME_MAX_UTF16_UNITS = SERVICE_KEY_NAME_MAX_LENGTH * 2;
type ControllerPlugins = (
| ReturnType<typeof apiKey>
| ReturnType<typeof createHumanLogin>["plugin"]
| ReturnType<typeof createServiceKeyVerification>["plugin"]
| typeof passwordSignOut
)[];
type ControllerBetterAuth = Auth<BetterAuthOptions & { plugins: ControllerPlugins }>;
export interface ServiceKey {
readonly id: string;
readonly servicePrincipalId: string;
readonly namespaceId?: string;
readonly name: string;
readonly expiresAt: string;
}
export interface ControllerAuthOptions {
readonly mode: "development" | "production";
readonly installationId: string;
readonly baseURL: string;
readonly secret: string;
readonly database?: BetterAuthOptions["database"];
readonly memoryDatabase?: MemoryDB;
readonly agentDomain: string;
/** Shared sessions are the default; native exchange keeps the parent session host-only. */
readonly sessionMode?: "shared-cookie" | "host-only-exchange";
readonly humanLogin?: ReturnType<typeof createHumanLogin>;
/** Trusted proxies whose client-address header keys sign-in admission. */
readonly clientAddress?: ClientAddressConfiguration;
/**
* Whether a user administers the Installation. Once the shared budget is spent, only
* administrators' passwords (and, with an external provider, the recovery account's) are
* still checked (slowly). Without it no administrator is.
*/
readonly passwordAdministrator?: (userId: string) => Promise<boolean>;
/** Replaces the in-memory failure-counting password admission (both profiles). */
readonly passwordAdmission?: PasswordSignInAdmission;
/**
* Replaces the default admission's slow-lane floors; budgets and slots stay
* `passwordFailureBudget`. The server leaves it unset; tests shorten the floor cap so
* paced refusals do not wait the full eight seconds, and observe when floors start.
*/
readonly passwordSlowLaneFloors?: PasswordSlowLaneFloors;
/**
* Hashes and verifies every local password. Default `scryptPasswordHasher`; the server
* leaves it unset. Tests that do not exercise hashing pass a cheap one built in their own
* helpers, so fixtures do not spend a full scrypt per account and sign-in.
*/
readonly passwordHasher?: PasswordHasher;
/**
* The password-only profile's known-device account state (see known-device.ts). Without
* it, and without an external provider, no known-device entries are issued.
*/
readonly knownDeviceState?: KnownDeviceAccountState;
/**
* Password-only profile: audits each password sign-in Better Auth accepted (with the
* account) or refused (without it). The guarded profile audits in State itself.
*/
readonly passwordSignInAudit?: {
accepted(userId: string): Promise<void>;
refused(): Promise<void>;
};
/** Receives runtime operational events, such as a sign-in lane entering the slow lane. */
readonly onOperationalEvent?: (event: Readonly<Record<string, unknown>>) => void;
}
/**
* The logged form of a limited sign-in lane's key: keyed by the auth secret, so a log
* reader cannot test candidate emails or addresses against it, and truncated. Stable for
* one secret, so repeated reports about one target correlate.
*/
export function signInLimitKeyHash(secret: string, key: string): string {
return createHmac("sha256", secret).update(`sign-in-limited\0${key}`).digest("hex").slice(0, 16);
}
export interface PostgresControllerAuthOptions extends Omit<
ControllerAuthOptions,
"database" | "memoryDatabase"
> {
readonly pool: SchemaAuthPoolV1;
readonly state?: PostgresPlatformState;
readonly iamDriver?: IAMDriver;
readonly defaultUserGroupIds?: readonly string[];
readonly google?: GoogleSignInConfiguration;
readonly oidc?: OidcSignInConfiguration;
/** Guarded profile only: `recovery-only` admits only the recovery account's password. */
readonly passwordSignIn?: "recovery-only";
/** Receives nonfatal startup conditions as structured log events. */
readonly onWarning?: (event: { readonly event: string; readonly message: string }) => void;
/** Counts an external sign-in callback that matched no pending attempt (not audited). */
readonly onUnmatchedCallback?: (provider: ExternalProviderName) => void;
}
export interface AuthenticatedAccount {
readonly id: string;
readonly email: string;
readonly name: string;
}
export type AuthenticatedSession = AdmittedSession;
/** A validated, hashed account that has not been written yet. */
export type PreparedAuthAccount = PreparedPasswordAccount;
export interface ProvisionAuthAccountInput {
readonly email: string;
readonly password: string;
readonly name?: string;
}
/** The administrator account writer requires its authority on the creating State unit. */
export type ProvisionAuthAccount = (
seed: AuthPrincipalSeed,
auditEvent: AuditEvent,
prepared: PreparedAuthAccount,
external: { readonly providerId: string; readonly subject: string } | undefined,
authority: {
readonly holdSession: (unit: PlatformUnitOfWork) => Promise<void>;
readonly authorize: (unit: PlatformUnitOfWork) => Promise<AuditEvent>;
},
) => Promise<void>;
export function createPostgresAuthAccountProvisioner({
state,
installationId,
}: {
readonly state: PostgresPlatformState;
readonly installationId: string;
}): ProvisionAuthAccount {
const persistence = new PostgresHumanAuthentication(
state,
installationId,
betterAuthIssuer(installationId),
);
return async (seed, auditEvent, prepared, external, authority) => {
if (
authority === undefined ||
typeof authority.holdSession !== "function" ||
typeof authority.authorize !== "function"
) {
throw new ScopeViolationError("Account provisioning requires complete assigning authority.");
}
await persistence.provisionPasswordAccount(prepared, seed, auditEvent, external, {
holdSession: authority.holdSession,
authorize: async (unit) => {
const currentAuditEvent = await authority.authorize(unit);
const current = await state.loadNativeIAMStateInTransaction(unit, installationId);
validateAuthAccountPrincipalSeed(seed, current, installationId);
return currentAuditEvent;
},
});
};
}
export {
AuthAccountRoleInvalidError,
AuthAccountRoleNotFoundError,
type AuthPrincipalSeed,
type AuthPrincipalSeedOptions,
} from "@openclaw-enterprise/iam";
export interface ControllerAuth {
readonly nativeBrowser?: PostgresHumanAuthentication["nativeBrowser"];
readonly auth: ControllerBetterAuth;
readonly issuer: string;
readonly sessionCookieName: string;
readonly sharedCookieDomain?: string;
readonly admissionVerifier: ControllerAdmissionVerifier;
/** Users this startup's activation left unenrolled (no Principal or not exactly one password). */
readonly activationSkipped?: readonly string[];
/** Who may sign in with a password: `recovery-only` only in the guarded profile. */
readonly passwordSignIn: PasswordSignInPolicy;
/**
* Recovery-only password sign-in: enabled accounts, other than the recovery account, with
* no identity for a configured provider. They cannot sign in until one is attached.
*/
readonly withoutExternalIdentity?: readonly string[];
readonly googleEnabled: boolean;
/** Provider-instance key for Google identities; set only while Google sign-in is configured. */
readonly googleProviderId?: string;
googleStart(request: FastifyRequest, reply: FastifyReply): Promise<void>;
googleCallback(request: FastifyRequest, reply: FastifyReply): Promise<void>;
googleResult(request: FastifyRequest, reply: FastifyReply): Promise<void>;
readonly oidcEnabled: boolean;
/** Provider-instance key for OIDC identities; set only while OIDC sign-in is configured. */
readonly oidcProviderId?: string;
/** What the Console needs to offer OIDC sign-in; set only while it is configured. */
readonly oidcSignIn?: { readonly label: string; readonly authorizationUrl: string };
oidcStart(request: FastifyRequest, reply: FastifyReply): Promise<void>;
oidcCallback(request: FastifyRequest, reply: FastifyReply): Promise<void>;
oidcResult(request: FastifyRequest, reply: FastifyReply): Promise<void>;
readAccount?(
userId: string,
actor: HumanAuthenticationActor,
): Promise<HumanAuthenticationAccount>;
attachGoogle?(
userId: string,
subject: string,
actor: HumanAuthenticationActor,
expectedVersion: number,
): Promise<unknown>;
attachOidc?(
userId: string,
subject: string,
actor: HumanAuthenticationActor,
expectedVersion: number,
): Promise<unknown>;
changeAccount?(
userId: string,
operation: "disable" | "enable" | "revoke",
actor: HumanAuthenticationActor,
expectedVersion: number,
): Promise<void>;
readRecovery?(actor: HumanAuthenticationActor): Promise<HumanAuthenticationRecovery>;
replaceRecovery?(
userId: string,
principalId: string,
expectedCurrentUserId: string,
actor: HumanAuthenticationActor,
expectedVersion: number,
): Promise<HumanAuthenticationRecovery & { changed: boolean }>;
enrolAccount?(
userId: string,
actor: HumanAuthenticationActor,
): Promise<{ principalId: string; version: number; created: boolean }>;
detachMethod?(
userId: string,
methodId: string,
actor: HumanAuthenticationActor,
expectedVersion: number,
): Promise<{ methodId: string; providerId: string }>;
/** "guarded" once State-owned human sign-in admission is active. */
readonly humanProfile: "password" | "guarded";
prepareAccount(input: ProvisionAuthAccountInput): Promise<PreparedAuthAccount>;
writePreparedAccount(prepared: PreparedAuthAccount): Promise<AuthenticatedAccount>;
createAccount(input: ProvisionAuthAccountInput): Promise<AuthenticatedAccount>;
deleteAccount(account: Pick<AuthenticatedAccount, "id">): Promise<void>;
principalSeed(
account: Pick<AuthenticatedAccount, "id">,
options: AuthPrincipalSeedOptions,
): AuthPrincipalSeed;
signInEmail(request: FastifyRequest, reply: FastifyReply): Promise<void>;
signOut(request: FastifyRequest, reply: FastifyReply): Promise<void>;
session(request: FastifyRequest, reply: FastifyReply): Promise<void>;
resolveSession(request: FastifyRequest): Promise<AuthenticatedSession | undefined>;
withSessionAuthority<T>(session: AuthenticatedSession, work: () => Promise<T>): Promise<T>;
holdSession(
unit: PlatformUnitOfWork,
session: AuthenticatedSession,
request: FastifyRequest,
): Promise<void>;
createServiceKey(input: {
readonly principal: ServicePrincipal;
readonly name: string;
readonly expiresIn?: number;
}): Promise<ServiceKey & { readonly key: string }>;
getServiceKey(id: string): Promise<ServiceKey | undefined>;
revokeServiceKey(key: ServiceKey): Promise<void>;
}
function authHeaders(headers: AdmissionHeaders | FastifyRequest["headers"] | undefined): Headers {
if (headers instanceof Headers) {
return new Headers(headers);
}
const prepared = new Headers();
for (const [name, value] of Object.entries(headers ?? {})) {
if (value === undefined) {
continue;
}
if (typeof value === "string") {
prepared.set(name, value);
continue;
}
for (const entry of value) {
prepared.append(name, entry);
}
}
return prepared;
}
function sessionHeaders(
headers: AdmissionHeaders | FastifyRequest["headers"],
cookieName: string,
): Headers {
const prepared = authHeaders(headers);
const count = (prepared.get("cookie") ?? "")
.split(";")
.filter((cookie) => cookie.slice(0, cookie.indexOf("=")).trim() === cookieName).length;
if (count > 1) {
throw new AdmissionFailure(401, "UNAUTHENTICATED", "The session cookie is ambiguous.");
}
return prepared;
}
function setAuthHeaders(reply: FastifyReply, headers?: Headers | null): void {
if (!headers) {
return;
}
const cookies: string[] = [];
headers.forEach((value, name) => {
if (name.toLowerCase() === "set-cookie") {
cookies.push(...splitSetCookieHeader(value));
return;
}
reply.header(name, value);
});
if (cookies.length > 0) {
reply.header("set-cookie", cookies);
}
}
function authFailure(error: unknown): { readonly status: number; readonly code: string } {
if (error instanceof AdmissionFailure || error instanceof RequestFailure) {
return { status: error.status, code: error.code };
}
if (error instanceof APIError || (typeof error === "object" && error !== null)) {
const candidate = error as Record<string, unknown>;
const status =
error instanceof APIError ? error.statusCode : (candidate.statusCode ?? candidate.status);
if (
typeof status === "number" &&
Number.isSafeInteger(status) &&
status >= 400 &&
status < 500
) {
return {
status,
code:
status === 401
? "UNAUTHENTICATED"
: status === 409
? "RESOURCE_CONFLICT"
: status === 429
? "RATE_LIMITED"
: "FORBIDDEN",
};
}
if (error instanceof APIError) {
if (
typeof status === "number" &&
Number.isSafeInteger(status) &&
status >= 500 &&
status < 600
) {
return { status: 503, code: "DEPENDENCY_UNAVAILABLE" };
}
return { status: 401, code: "UNAUTHENTICATED" };
}
}
return { status: 503, code: "DEPENDENCY_UNAVAILABLE" };
}
/** Better Auth refused a service-key name's length; the route answers 400, not a 503. */
export class ServiceKeyNameRefused extends Error {
constructor(cause: unknown) {
super("The service-key name was refused.", { cause });
this.name = "ServiceKeyNameRefused";
}
}
function serviceKeyNameRefusal(error: unknown): boolean {
const code = (error as { readonly body?: { readonly code?: unknown } } | null)?.body?.code;
return error instanceof Error && error.name === "APIError" && code === "INVALID_NAME_LENGTH";
}
/** A curated auth endpoint answered 5xx: its database or audit store failed. */
class AuthDependencyUnavailable extends Error {
constructor() {
super("Authentication dependency unavailable.");
this.name = "AuthDependencyUnavailable";
}
}
/**
* A rejected password whose denial audit could not be written. The response is 503 (audit
* outages fail closed), yet admission still counts it as a credential failure.
*/
class DenialAuditUnavailable extends Error {
constructor(cause: unknown) {
super("The sign-in denial could not be audited.", { cause });
this.name = "DenialAuditUnavailable";
}
}
// Only account disablement and provider unavailability have specific Console reasons.
// Other callback failures use the generic rejection or unavailable response.
const callbackReasons: Readonly<Record<(typeof CALLBACK_DENIALS)[number], string>> = {
ACCOUNT_DISABLED: "account-disabled",
PROVIDER_UNAVAILABLE: "provider-unavailable",
};
/** An audited callback refusal whose Console reason the callback redirect carries. */
class CallbackRefusal extends AdmissionFailure {
readonly consoleReason: string;
constructor(consoleReason: string) {
super(401, "UNAUTHENTICATED", "Authentication was not accepted.");
this.consoleReason = consoleReason;
}
}
async function callbackRefusal(response: Response): Promise<CallbackRefusal | undefined> {
try {
const body = (await response.json()) as { readonly code?: unknown } | null;
const code = CALLBACK_DENIALS.find((denial) => denial === body?.code);
return code === undefined ? undefined : new CallbackRefusal(callbackReasons[code]);
} catch {
return undefined;
}
}
async function deniedWithoutAudit(response: Response): Promise<boolean> {
try {
const body = (await response.json()) as { readonly code?: unknown } | null;
return body?.code === PASSWORD_DENIAL_AUDIT_UNAVAILABLE;
} catch {
return false;
}
}
// Credential rejections spend the password budget; dependency failures do not, except a
// rejection whose denial audit failed.
function countsAsSignInFailure(error: unknown): boolean {
if (error instanceof DenialAuditUnavailable) {
return true;
}
const { status } = authFailure(error);
return status >= 400 && status < 500;
}
function authBody(request: FastifyRequest): Record<string, unknown> {
return typeof request.body === "object" && request.body !== null && !Array.isArray(request.body)
? (request.body as Record<string, unknown>)
: {};
}
function ensureEmailPassword(input: Record<string, unknown>): { email: string; password: string } {
const { email, password } = input;
if (!isNonEmptyString(email) || !isNonEmptyString(password)) {
throw new AdmissionFailure(401, "UNAUTHENTICATED", "Email and password are required.");
}
return { email, password };
}
function untrustedOrigin(): AdmissionFailure {
return new AdmissionFailure(
403,
"FORBIDDEN",
"The browser origin is not trusted.",
"untrusted_origin",
);
}
function requireTrustedBrowserOrigin(request: FastifyRequest, expectedOrigin: string): void {
const origin = request.headers.origin;
if (Array.isArray(origin)) {
throw untrustedOrigin();
}
if (origin !== undefined) {
if (origin !== expectedOrigin) {
throw untrustedOrigin();
}
return;
}
if (request.headers["sec-fetch-site"] === "cross-site") {
throw untrustedOrigin();
}
}
/**
* Applies the optional x-occ-session-key header to a resolved cookie session.
* Absent keeps the cookie-only contract; a malformed, duplicated or foreign key
* rejects instead of acting on whichever session the shared cookie now carries.
*/
function requireSessionKey(headers: Headers, secret: string, sessionId: string | undefined): void {
const key = sessionKeyHeader(headers);
if (key === undefined) {
return;
}
if (key === null || (sessionId !== undefined && !sessionKeyMatches(secret, sessionId, key))) {
throw new AdmissionFailure(401, "UNAUTHENTICATED", "The session key does not match.");
}
}
function responseSessionId(response: unknown): string | undefined {
const session =
typeof response === "object" && response !== null
? (response as { readonly session?: unknown }).session
: undefined;
const id =
typeof session === "object" && session !== null
? (session as Record<string, unknown>).id
: undefined;
return isNonEmptyString(id) ? id : undefined;
}
function requireSessionMutationOrigin(headers: Headers, expectedOrigin: string): void {
const fetchSite = headers.get("sec-fetch-site");
if (
headers.get("origin") !== expectedOrigin ||
(fetchSite !== null && fetchSite !== "same-origin")
) {
throw untrustedOrigin();
}
}
function preparedId(
context: { generateId(options: { model: "user" | "account" }): string | false },
model: "user" | "account",
): string {
const generated = context.generateId({ model });
return typeof generated === "string" && generated.length > 0 ? generated : randomUUID();
}
function accountName(input: ProvisionAuthAccountInput): string {
return input.name?.trim() || input.email.trim();
}
function safeSessionResponse(
response: unknown,
secret: string,
): {
readonly authenticated: true;
readonly sessionKey: string;
readonly user: { readonly id: string; readonly email: string; readonly name: string };
} | null {
if (typeof response !== "object" || response === null) {
return null;
}
const { session, user } = response as { readonly session?: unknown; readonly user?: unknown };
if (
typeof session !== "object" ||
session === null ||
typeof user !== "object" ||
user === null
) {
return null;
}
const { id: sessionKey } = session as Record<string, unknown>;
const { id, email, name } = user as Record<string, unknown>;
if (
!isNonEmptyString(sessionKey) ||
!isNonEmptyString(id) ||
!isNonEmptyString(email) ||
!isNonEmptyString(name)
) {
return null;
}
return {
authenticated: true,
sessionKey: sessionBindingKey(secret, sessionKey),
user: { id, email, name },
};
}
function safeAuthenticatedSession(response: unknown): AuthenticatedSession | undefined {
if (typeof response !== "object" || response === null) {
return undefined;
}
const { session, user } = response as { readonly session?: unknown; readonly user?: unknown };
if (
typeof session !== "object" ||
session === null ||
typeof user !== "object" ||
user === null
) {
return undefined;
}
const { id, expiresAt } = session as Record<string, unknown>;
const { id: userId } = user as Record<string, unknown>;
if (!isNonEmptyString(id) || !isNonEmptyString(userId)) {
return undefined;
}
const expiry =
expiresAt instanceof Date
? expiresAt
: typeof expiresAt === "string"
? new Date(expiresAt)
: undefined;
if (expiry === undefined || Number.isNaN(expiry.getTime())) {
return undefined;
}
return { id, userId, expiresAt: expiry.toISOString() };
}
/** What an auth endpoint says when it fails: `refused` for a refusal, `action` names it. */
interface AuthEndpointFailure {
/** The one answer to every refusal, so it says nothing about the account or the factor. */
readonly refused: string;
/** Names the operation in the outage answer, for example "Sign-in". */
readonly action: string;
}
function waitDuration(seconds: number): string {
return seconds === 1 ? "1 second" : `${seconds} seconds`;
}
// The status already tells a rate limit and an outage apart from a refusal, and Retry-After
// already carries the wait, so these answers reveal nothing the refusal hides.
function authFailureMessage(error: unknown, status: number, failure: AuthEndpointFailure): string {
// A malformed request names its offending field, as on every API route. Every caller
// checks the Origin before it reads any credential, so naming the refused Origin
// reveals nothing about the session or password; keep it that way, because the
// endpoint's own message would misdirect a CLI user.
if (error instanceof RequestFailure) {
return error.message;
}
if (error instanceof AdmissionFailure && error.reason === "untrusted_origin") {
return UNTRUSTED_ORIGIN_MESSAGE;
}
if (status === 429) {
// Only the password limiter sets a wait; the external sign-in budgets refill each minute.
return error instanceof SignInRateLimited
? `Too many attempts. Wait ${waitDuration(error.retryAfterSeconds)}, then try again.`
: "Too many attempts. Wait a minute, then try again.";
}
if (status === 503) {
return `${failure.action} is temporarily unavailable. Try again shortly. If it continues, ask an operator to check the API logs.`;
}
return failure.refused;
}
/**
* The request an auth library call serves, for its log lines: never the path or query. Reading
* it never throws, so logging cannot change an answer.
*/
function authLogRequest(request: FastifyRequest): AuthLogRequest | undefined {
try {
const route = request.routeOptions.url;
return {
requestId: request.id,
method: request.method,
...(route === undefined ? {} : { route }),
};
} catch {
return undefined;
}
}
// The curated endpoints runPrivateEndpoint calls, as log operations.
function privateEndpointOperation(path: string): AuthLibraryOperation {
if (path === "/oce/password") {
return "sign-in-password";
}
if (path === "/oce/sign-out") {
return "sign-out";
}
if (path.endsWith("/callback")) {
return "provider-callback";
}
return path.endsWith("/result") ? "provider-result" : "provider-start";
}
async function sendAuthEndpoint(
operation: AuthLibraryOperation,
request: FastifyRequest,
reply: FastifyReply,
run: () => Promise<{
readonly response?: unknown;
readonly headers?: Headers | null;
readonly status?: number;
} | null>,
data: (response: unknown) => unknown,
failureText: AuthEndpointFailure,
): Promise<void> {
try {
const result = await withAuthLogContext(operation, authLogRequest(request), run);
setAuthHeaders(reply, result?.headers);
reply.status(result?.status ?? 200).send({
data: data(result?.response ?? null),
meta: { requestId: request.id },
});
} catch (error) {
const failure = authFailure(error);
if (error instanceof SignInRateLimited) {
reply.header("retry-after", String(error.retryAfterSeconds));
}
reply.status(failure.status).send({
error: {
code: failure.code,
message: authFailureMessage(error, failure.status, failureText),
},
meta: { requestId: request.id },
});
}
}
async function createOccAuthDatabase(
pool: SchemaAuthPoolV1,
): Promise<NonNullable<BetterAuthOptions["database"]>> {
const { database, schema } = await createPostgresAuthBinding(pool);
const { drizzleAdapter } = await import("better-auth/adapters/drizzle");
return drizzleAdapter(database, {
provider: "pg",
schema,
camelCase: true,
transaction: true,
} satisfies SchemaAuthAdapterOptionsV1);
}
export class ControllerAdmissionVerifier implements AdmissionVerifier {
readonly #auth: ControllerBetterAuth;
readonly #installationId: string;
readonly #issuer: string;
readonly #sessionCookieName: string;
readonly #secret: string;
readonly #browserOrigin: string;
constructor(
auth: ControllerBetterAuth,
installationId: string,
cookieName: string,
secret: string,
browserOrigin: string,
) {
this.#auth = auth;
this.#secret = secret;
this.#sessionCookieName = cookieName;
this.#browserOrigin = browserOrigin;
this.#installationId = installationId;
this.#issuer = betterAuthIssuer(installationId);
}
async verifyControllerRequest(request: AdmissionRequest): Promise<AdmittedCaller> {
const headers = authHeaders(request.headers);
if (
request.authorizationHeader === undefined &&
!headers.has(OCC_SERVICE_KEY_HEADER) &&
headers.has("cookie") &&
!["GET", "HEAD", "OPTIONS"].includes(request.method.toUpperCase())
) {
requireSessionMutationOrigin(headers, this.#browserOrigin);
}
return this.verify(request);
}
async verify(request: AdmissionRequest): Promise<AdmittedCaller> {
if (request.authorizationHeader !== undefined) {
throw new AdmissionFailure(
401,
"UNAUTHENTICATED",
"Controller API bearer authentication is disabled.",
"authorization_header",
);
}
if (request.requestedScope.installationId !== this.#installationId) {
throw new AdmissionFailure(403, "FORBIDDEN", "The admitted Installation does not match.");
}
const headers = authHeaders(request.headers);
const logRequest: AuthLogRequest = {
requestId: request.requestId,
method: request.method,
...(request.route === undefined ? {} : { route: request.route }),
};
// An explicitly supplied key never falls back to a potentially more privileged cookie.
if (headers.has(OCC_SERVICE_KEY_HEADER)) {
const result = await withAuthLogContext("verify-api-key", logRequest, () =>
serviceKeyVerification.verify(() =>
this.#auth.api.verifyApiKey({
body: { key: headers.get(OCC_SERVICE_KEY_HEADER)!, configId: SERVICE_KEY_CONFIG },
}),
),
);
if (!result.valid || !result.key) {
throw new AdmissionFailure(401, "UNAUTHENTICATED", "A valid service API key is required.");
}
const key = serviceKeyDetails(result.key, this.#installationId);
if (!key) {
throw new AdmissionFailure(401, "UNAUTHENTICATED", "A valid service API key is required.");
}
return {
externalIdentity: {
issuer: `${this.#issuer}:service-key`,
subject: key.servicePrincipalId,
},
admittedScope: {
installationId: this.#installationId,
...(key.namespaceId === undefined ? {} : { namespaceId: key.namespaceId }),
},
decisionId: `adm_${randomUUID()}`,
method: "api_key",
serviceKeyId: key.id,
};
}
const session = await withAuthLogContext("verify-session", logRequest, () =>
this.#auth.api.getSession({
headers: sessionHeaders(headers, this.#sessionCookieName),
query: { disableCookieCache: true, disableRefresh: true },
asResponse: false,
returnHeaders: true,
}),
);
const response = session && "response" in session ? session.response : session;