Repository navigation
Expand file tree
/
Copy pathauth-plugin.ts
More file actions
4031 lines (3863 loc) · 213 KB
/
Copy pathauth-plugin.ts
File metadata and controls
4031 lines (3863 loc) · 213 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
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Plugin, PluginContext, IHttpServer } from '@objectstack/core';
import type { BetterAuthOptions } from 'better-auth';
import {
AuthConfig,
type AudienceConfig,
AUDIENCE_POSTURES,
audiencePermitsSelfRegistration,
isAudiencePosture,
type SocialProviderConfig,
type SettingsChangeHandler,
type SettingsUnsubscribe,
SystemObjectName,
} from '@objectstack/spec/system';
// [#11767] The shared bootstrap population predicate — the audience gate's
// bootstrap bypass and plugin-security's first-user detection must answer the
// same question. [#14157] The dev-admin seed no longer GATES on it (a
// directory row is not a login); it still reads it to find the seed account
// among existing users when re-arming the credential hint.
import { isHumanUserRow, OPEN_POSTURE_VERIFICATION_OFF_WARNING } from './audience-posture.js';
// [#14157] The dev-admin seed's own precondition — "does a login exist?".
import { decideDevAdminSeedGate } from './dev-admin-seed-gate.js';
import {
// ADR-0048 — the Setup/Studio/Account apps moved to their own packages
// (@objectstack/{setup,studio,account}); plugin-auth no longer registers them.
SystemOverviewDashboard,
SystemOverviewDatasets,
} from '@objectstack/platform-objects/apps';
import { SysOrganizationDetailPage, SysUserDetailPage } from '@objectstack/platform-objects/pages';
import { PLATFORM_OWNER_EMAIL_ENV, resolvePlatformOwnerEmail, resolveTenancyPosture } from '@objectstack/types';
import { inProcessSessionReadInput } from '@objectstack/types';
import { postureEnforcesWall, type OrgScopingEntitlement } from '@objectstack/spec/security';
import type { AuthSessionApi, IDataEngine, IEmailService, II18nService, IObjectQLEngine, ISmsService } from '@objectstack/spec/contracts';
import {
AuthManager,
resolveOidcProviderEnabled,
readMcpServerEnabledEnv,
isOAuthEligibleBaseUrl,
ipMatchesRange,
// [#16384] The one place `'/api/v1/auth'` is written — see its docblock in
// auth-manager.ts. This file no longer carries an independent copy.
DEFAULT_AUTH_BASE_PATH,
type AuthManagerOptions,
} from './auth-manager.js';
import { isDefaultOrganizationBootstrapTrigger } from './ensure-default-organization.js';
import { ensureDefaultOrganizationExists } from './default-organization-invariant.js';
import { recoverInternalFieldsForSystemRead } from './internal-field-readback.js';
import { runAttributedToUser } from './auth-actor-attribution.js';
import { withSystemContext } from './objectql-adapter.js';
import type { AuthEventAuditSurface } from './auth-session-audit.js';
import { createTenancyService, type TenancyService } from './tenancy-service.js';
import {
isMembershipPolicy,
MEMBERSHIP_POLICIES,
type MembershipPolicy,
} from './reconcile-membership.js';
import { runOneTimeMembershipBackfill } from './membership-backfill-ledger.js';
import { createEnsureDefaultOrganizationOnce } from './default-org-bootstrap-once.js';
import {
registerIdentityWriteGuard,
registerManagedUpdateWhitelist,
type SecondaryStorageLike,
} from './identity-write-guard.js';
import { registerLastAdminGuard } from './last-admin-guard.js';
import { registerApiKeyRestoreGuard } from './api-key-restore-guard.js';
import { registerMembershipEndedSessionTrigger } from './membership-ended-session.js';
import { registerMemberRoleCanonicalization } from './member-role-canonical.js';
import { SYS_USER_PROFILE_EDIT_FIELDS } from './sys-user-writable-fields.js';
import { MANAGED_EXTENSION_EDITABLE_FIELDS } from './managed-extension-fields.js';
import { runSetInitialPassword } from './set-initial-password.js';
import { runRegisterSsoProviderFromForm, runRegisterSamlProviderFromForm, runRequestDomainVerification, runVerifyDomain } from './register-sso-provider.js';
import { runResendVerificationEmail } from './send-verification-email.js';
import { runSysSessionRevoke, sysSessionRevokeDepsFor } from './sys-session-revoke.js';
import { readJsonRequestBody } from './request-json-body.js';
import type { CounterStore } from './rate-limit-storage.js';
import { authIdentityManifest } from './manifest.js';
import { scheduleLegacySsoSecretMigration } from './sso-client-secret.js';
import {
devSeedAdminEmail,
isDevAdminSeedArmed,
probeWalledOwnerAccountState,
warnIfWalledOwnerCannotVerify,
type WalledOwnerAccountState,
} from './walled-owner-verification-path.js';
import {
probeSignInPathWiring,
probeSignInReachability,
reportIfNoSignInAccountExists,
type SignInPathConfigView,
} from './boot-sign-in-reachability.js';
import { judgePlatformAdmin, isPlatformAdminUser, type PlatformAdminActor } from './platform-admin-gate.js';
import {
runAdminBanUser,
runAdminUnbanUser,
type AdminBanEndpointDeps,
} from './admin-ban-endpoints.js';
/**
* The `settings` slot, as this plugin reads it.
*
* [#4251] `service-settings` registers its `SettingsService` here and the slot
* carries no `packages/spec` contract, so this declares the two resolver methods
* this plugin calls. Structural on purpose — plugin-auth must not depend on
* service-settings, which is optional (both readers below already return early
* when the slot is empty or the method is missing).
*/
interface SettingsReadSurface {
/** Resolve one key; `source` distinguishes a stored/env value from a manifest default. */
get(
namespace: string,
key: string,
ctx?: Record<string, unknown>,
): Promise<{ value?: unknown; source?: string } | undefined>;
/** Resolve a whole namespace as `key → { value, source }`. */
getNamespace(
namespace: string,
ctx?: Record<string, unknown>,
): Promise<{ values: Record<string, { value?: unknown; source?: string } | undefined> }>;
/**
* Re-run a binding when the namespace changes — how the brand name, SMS
* locale and auth namespace stay live without a redeploy. Optional: an
* implementation without a change bus leaves the initial read in place, which
* is what the `typeof … === 'function'` guards at each call site already say.
*
* The handler and unsubscribe types are the SPEC's
* (`@objectstack/spec/system`), not re-declared here — the change bus has a
* published contract even though the slot does not.
*/
subscribe?(
namespace: string | undefined,
handler: SettingsChangeHandler,
): SettingsUnsubscribe;
/**
* [#23367] Persist one key — used ONCE, to record when this deployment
* started enforcing the API-key lifecycle policy
* ({@link AuthPlugin.recordApiKeyPolicyStart}). Optional, like `subscribe`.
*/
set?(
namespace: string,
key: string,
value: unknown,
ctx?: Record<string, unknown>,
): Promise<unknown>;
}
/** [#23367] The auth setting that records when the API-key lifecycle policy took effect. */
const API_KEY_POLICY_STARTED_AT_KEY = 'api_key_policy_started_at';
/**
* [#24222] What the in-process session read answers, as `AuthSessionApi` declares
* it. better-auth's own handle answers `null` for no session, hence the
* `| null` at each read.
*/
type SessionRead = Awaited<ReturnType<NonNullable<AuthSessionApi['getSession']>>>;
/**
* The `protocol` slot's metadata reader, as the user-import route uses it.
*
* [#4251] `protocol` is a deliberately UNCONTRACTED slot (see
* `UNCONTRACTED_SLOTS` in `eslint.config.mjs`), so the one method this route
* needs is declared here rather than erased. It reads `sys_user`'s field
* definitions so imported values are coerced to their declared types —
* best-effort by contract: without it the import still runs, uncoerced.
*/
interface MetaItemReaderSurface {
getMetaItem(ref: { type: string; name: string }): Promise<any>;
}
/**
* Auth Plugin Options
* Extends AuthConfig from spec with additional runtime options
*/
export interface AuthPluginOptions extends Partial<AuthConfig> {
/**
* ADR-0093 D1 — deployment membership policy. `'auto'` (default) auto-binds
* every new user to the single-org default org via the reconciler; invite-only
* deployments set `'invite-only'` to grant membership solely through explicit
* flows (invite / add-member / SSO JIT / host hooks).
* @default 'auto'
*/
membershipPolicy?: MembershipPolicy;
/**
* Whether to automatically register auth routes
* @default true
*/
registerRoutes?: boolean;
/**
* Base path for auth routes
* @default '/api/v1/auth'
*/
basePath?: string;
/**
* Override the datasource that owns the identity tables (sys_user,
* sys_session, …) when AuthPlugin's manifest is registered.
*
* Defaults to `'cloud'` (control-plane DB) so the historical
* single-tenant control-plane behaviour is preserved. Per-project
* kernels in objectos pass `'default'` so identity tables live in the
* project's own database — each project owns its own users.
*/
manifestDatasource?: string;
/**
* `additionalOrgRoles` was REMOVED in ADR-0108 (#3723) — see
* {@link AuthManagerOptions} for the FROM → TO migration. The membership-role
* vocabulary is closed (`owner` / `admin` / `delegated_admin` / `member`);
* an app's own business roles are POSITIONS, assigned through
* `sys_user_position` or an invitation carrying placement (ADR-0105 D8).
*/
/**
* The single-org default-organization OWNER BIND (a pre-repo decision whose
* old label collides with this repo's ADR series — see the citation note
* under ADR-0093 D9; the membership guarantee it backs is D9). When enabled
* (default), the plugin binds the platform admin as `owner` of the
* `Default Organization` (slug `default`) — or promotes the `member` row the
* membership reconciler gave them there — on `kernel:ready` and after every
* write matched by `isDefaultOrganizationBootstrapTrigger` (a `sys_user`
* insert or email/email_verified update — the config-anchor trigger set —
* plus the legacy `sys_user_permission_set` insert that `single`-posture
* first-user promotion still writes), recreating the organization if it went
* missing. Inert in multi-org mode — the enterprise organizations package
* owns the bootstrap there.
*
* ⚠️ BREAKING (ADR-0131 D3): `false` no longer means "no organization".
* Under the `single` posture the Default Organization is a boot invariant —
* created in `start()` whatever this option says, before the application
* seeds load, and a failure to create it fails the boot — because every row
* has an owner and `single` derives it from that organization. `false` now
* turns off only the owner bind.
* @default true
*/
autoDefaultOrganization?: boolean;
/**
* Pass-through to better-auth's `databaseHooks` option. Used by
* platform consumers (objectos kernel) to attach a
* `user.create.after` hook that auto-provisions a personal
* organization for JIT-created SSO users.
*
* This is the seam to use because it is the ONE hook point every user
* creation path flows through (email signup, social/OIDC sign-in,
* admin-created accounts, SSO JIT) and ADR-0093 D2 gives such invariants a
* single owner there. It is NOT because better-auth's adapter escapes the
* data layer: it writes through the same ObjectQL instance and its
* middleware/lifecycle-hook chain does run — see
* `AuthManagerOptions.databaseHooks` for the hop-by-hop correction (#4802).
*/
databaseHooks?: BetterAuthOptions['databaseHooks'];
/**
* [#20861] The HOST declares that it signs humans into this deployment
* through a handoff route of its OWN — a sign-in path that is not a
* login-page provider, and that mints the session without writing a
* `sys_account` row. A hosted kernel whose owner enters through the control
* plane's handoff is the case this exists for: that owner signs in whether or
* not the login page shows any platform sign-in button.
*
* It has ONE reader, the `no_sign_in_account_at_boot` boot report
* (`boot-sign-in-reachability.ts`): with it declared, "human `sys_user` rows,
* zero `sys_account` rows" is this deployment's healthy state rather than an
* unrecoverable dead end, and the shape is recorded at `debug`, naming this
* declaration, instead of at `error`.
*
* ⛔ A declaration, never an inference and never a silencer. Set it only where
* the host really mounts such a route; declared without one, it turns the loud
* report of a deployment nobody can sign in to into a quiet one. It changes
* nothing the login page is told — `getPublicConfig()` returns the same with
* or without it, and no provider is registered. It is read from this option
* alone (no env var, no setting), so the code that wires the handoff is the
* one place it can be stated.
* @default false
*/
hostSignInHandoff?: boolean;
/**
* Whether this plugin registers the platform's default record page for
* `sys_organization`: `sys_organization_detail`, the Members / Invitations /
* Teams tab strip (`SysOrganizationDetailPage`, `@objectstack/platform-objects`).
*
* A deployment holds at most ONE `isDefault: true` record page per object; a
* second is refused at registration with `DEFAULT_RECORD_PAGE_CONFLICT`
* (maintainer ruling A on objectstack#23015, record 6134056653). A host that
* ships its OWN default record page for `sys_organization` passes `false`, so
* its page is the single default by composition. Neither registration order
* nor a precedence rule decides it: ruling A takes neither.
*
* `false` removes exactly one registration, `sys_organization_detail`.
* Everything else stays: the `sys_organization` object and every other
* identity object, the `sys_user_detail` record page, the System Overview
* dashboard, and the auth routes and services. The host's page then owns what
* the platform page gave. Set `false` with no default record page of the
* host's own, and `sys_organization`'s record view opens the synthesized
* default layout, without the Members / Invitations / Teams tabs.
*
* Only an explicit `false` removes the page; `true` and an absent key keep
* it. Read from this option alone (no env var, no setting), so the code that
* composes the host's own page is the one place the choice is stated.
* @default true
*/
registerOrganizationRecordPage?: boolean;
}
/**
* Is this plain-HTTP issuer on a LOOPBACK host (#22073)? Asked only of an issuer
* the transport rule has already accepted (`isOAuthEligibleBaseUrl`), to pick
* the plain-HTTP notice's level: loopback ⇒ `info`, private / link-local ⇒
* `warn`.
*
* The loopback half of that rule's own allow-list, in its own terms: the
* `localhost` / `*.localhost` names it accepts, its `127.0.0.0/8` block judged
* by the same ADR-0069 D5 matcher (`ipMatchesRange`), and `::1`. The hostname
* is WHATWG-canonical, as the rule reads it — `127.1`, `0x7f.1` and
* `[0:0:0:0:0:0:0:1]` arrive here as `127.0.0.1` and `[::1]`. Every other
* accepted host — RFC 1918, link-local, unique-local — is not loopback and
* keeps the warning. `mcp-oauth-plaintext-notice.test.ts` pins both sides.
*/
function isLoopbackIssuer(issuer: string): boolean {
let host: string;
try {
host = new URL(issuer).hostname.toLowerCase();
} catch {
return false;
}
if (host === 'localhost' || host.endsWith('.localhost')) return true;
if (host === '[::1]') return true;
return ipMatchesRange(host, '127.0.0.0/8');
}
/**
* Authentication Plugin
*
* Provides authentication and identity services for ObjectStack applications.
*
* **Dual-Mode Operation:**
* - **Server mode** (HonoServerPlugin active): Registers HTTP routes at basePath,
* forwarding all auth requests to better-auth's universal handler.
* - **MSW/Mock mode** (no HTTP server): Gracefully skips route registration but
* still registers the `auth` service, allowing HttpDispatcher.handleAuth() to
* simulate auth flows (sign-up, sign-in, etc.) for development and testing.
*
* Features:
* - Session management
* - User registration/login
* - OAuth providers (Google, GitHub, etc.)
* - Organization/team support
* - 2FA, passkeys, magic links
*
* This plugin registers:
* - `auth` service (auth manager instance) — always
* - `app.com.objectstack.system` service (system object definitions) — always
* - HTTP routes for authentication endpoints — only when HTTP server is available
*
* Integrates with better-auth library to provide comprehensive
* authentication capabilities including email/password, OAuth, 2FA,
* magic links, passkeys, and organization support.
*/
export class AuthPlugin implements Plugin {
name = 'com.objectstack.auth';
/**
* Services init() registers on every path (ADR-0116, #4131) — lets the
* kernel name this plugin when a consumer requires one before it inits.
*/
providesServices = ['auth', 'tenancy'];
type = 'standard' as const;
version = '1.0.0';
dependencies: string[] = ['com.objectstack.engine.objectql'];
/**
* What that dependency is FOR, stated so the kernel can check it (#4187).
* `init()` resolves both synchronously with no fallback: `data` builds the
* AuthManager config, `manifest` registers the auth objects. ObjectQL
* registers both unconditionally and the hard dependency above hoists it
* ahead, so this never changes whether the boot succeeds — it changes what
* a broken composition SAYS, and replaces the trailing `// manifest service
* required` comment with the machine-checked form of the same claim.
*/
requiresServices = ['data', 'manifest'];
/**
* `com.objectstack.service.settings` — order-if-present (ADR-0116, #10250).
*
* `start()` registers `kernel:ready` hooks that reach
* {@link ensureAuthSettingsBound} → {@link bindAuthSettings}, which resolves
* the `settings` service and reads `getNamespace('auth')`.
* `SettingsServicePlugin` binds its data engine from ITS `kernel:ready`
* hook, registered in ITS `start()`, so the plugin that starts first
* registers the earlier hook and the earlier hook runs first. Start order is
* the topological order over these declarations (`resolvePluginOrder`, used
* for BOTH phases in `ObjectKernel.bootstrap`), so declaring the edge is
* what puts the bind ahead of the read.
*
* Without it the order was WRONG on the shipped composition, not merely
* incidental: `os serve` does `kernel.use(new AuthPlugin(...))` before the
* capability loop registers `SettingsServicePlugin`, and `resolvePluginOrder`
* preserves insertion order for plugins with no edge between them — so auth
* started first and its reads landed in the pre-bind window, where
* `SettingsService`'s empty in-memory fallback answers with the manifest
* DEFAULTS and `source: 'default'` while the workspace's saved `sys_setting`
* rows sit unread. Everything `applySettings()` derives was therefore
* computed from defaults at boot — the ADR-0093 membership policy the D6
* backfill runs under, and the `google_*` social-provider config — and
* `settings.subscribe('auth', …)` only re-applies on a LATER change, so a
* workspace that configured auth in Setup and never touched it again kept
* booting with the wrong values.
*
* SOFT, not hard: a kernel with no settings service must still boot auth —
* `bindAuthSettings` returns early when the service is absent and the
* deployment's env / options config stands. ADR-0049 — declared is enforced:
* `auth-settings-ordering.pin.test.ts` resolves a hostile registry that uses
* auth BEFORE settings and proves the DECLARATION is what moves the order.
*
* `com.objectstack.organization-ownership-boot-guard` — the v18 boot guard
* (`@objectstack/runtime`'s `ORGANIZATION_OWNERSHIP_BOOT_GUARD_PLUGIN_NAME`,
* spelled here because this package does not depend on the runtime;
* ADR-0131 D10 item 5), order-if-present: `start()` creates the Default
* Organization, and on a kernel that composes the guard (`os serve`) a
* database the guard refuses must be left as the guard found it, so the
* organization is created only once the guard has judged.
*/
optionalDependencies = ['com.objectstack.service.settings', 'com.objectstack.organization-ownership-boot-guard'];
private options: AuthPluginOptions;
private authManager: AuthManager | null = null;
/** ADR-0093 D4 — the tenancy service registered in init(); reused at kernel:ready. */
private tenancy: TenancyService | null = null;
/** [ADR-0131 D3] Whether `start()` created the Default Organization (a fresh install). */
private defaultOrganizationCreatedAtBoot = false;
private configuredSocialProviders: SocialProviderConfig | undefined;
// ADR-0092 D6 — the EFFECTIVE better-auth secondaryStorage (host-supplied or
// the kernel-cache adapter wired in init). The identity write guard's
// session-snapshot refresh reads through this; undefined = refresh no-ops.
private effectiveSecondaryStorage: AuthManagerOptions['secondaryStorage'];
/**
* Memoized `bindAuthSettings()` run — see {@link ensureAuthSettingsBound}.
*/
private authSettingsBinding: Promise<void> | null = null;
constructor(options: AuthPluginOptions = {}) {
this.options = {
registerRoutes: true,
basePath: DEFAULT_AUTH_BASE_PATH,
...options
};
}
/**
* Open-source provider fallback: enable Google sign-in from conventional
* provider env vars when the application did not configure Google itself.
* Enterprise / product packages can contribute richer provider sets through
* the `auth:configure` hook below.
*/
private applyEnvSocialProviderFallbacks(config: AuthManagerOptions & AuthPluginOptions): void {
const env = (globalThis as any)?.process?.env as Record<string, string | undefined> | undefined;
if (String(env?.OS_AUTH_GOOGLE_ENABLED ?? 'true').toLowerCase() === 'false') return;
const googleClientId = env?.GOOGLE_CLIENT_ID;
const googleClientSecret = env?.GOOGLE_CLIENT_SECRET;
if (!googleClientId || !googleClientSecret) return;
const socialProviders = {
...(config.socialProviders ?? {}),
} as NonNullable<AuthPluginOptions['socialProviders']>;
if (!socialProviders.google) {
socialProviders.google = {
clientId: googleClientId,
clientSecret: googleClientSecret,
enabled: true,
};
config.socialProviders = socialProviders;
}
}
async init(ctx: PluginContext): Promise<void> {
ctx.logger.info('Initializing Auth Plugin...');
// Validate required configuration
if (!this.options.secret) {
throw new Error('AuthPlugin: secret is required');
}
// Get data engine service for database operations. This plugin declares a
// hard dependency on ObjectQL (which registers `data` unconditionally), so
// the service is always present here.
//
// There used to be an `if (!dataEngine) warn('…auth will use in-memory
// storage')` guard under this line. It could never fire and the fallback it
// named did not exist: `getService` THROWS for an unregistered service, it
// does not return undefined, and the hard dependency means a kernel without
// the engine fails earlier still with "Dependency … not found". A branch
// that advertises a tolerance the composition forbids is worse than no
// branch — it reads as a supported degraded mode (#4187). AuthManager keeps
// its own `dataEngine?` guards because it is usable outside this plugin.
const dataEngine = ctx.getService<IDataEngine>('data');
const authConfig: AuthManagerOptions & AuthPluginOptions = {
...this.options,
dataEngine,
logger: ctx.logger,
// ADR-0093 D2/D3 — the membership reconciler consults the tenancy service
// (lazily, at hook-fire time — the service is registered below, after the
// `auth` service) to resolve the target org. membershipPolicy defaults to
// 'auto' in the reconciler.
getTenancy: () => {
try {
return ctx.getService<TenancyService>('tenancy');
} catch {
return undefined;
}
},
// [#8144] The compliance ledger's non-CRUD ingress, resolved LAZILY at
// session-hook fire time (i.e. per request, long after boot). AuditPlugin
// is an optional pair in the CLI, so a miss is the ordinary case, not a
// degradation to report: no audit plugin means no `login`/`logout` rows,
// which is exactly the behaviour before this card. Deliberately NOT an
// `optionalDependencies` entry — nothing in `init()` consumes it, so
// there is no boot ordering to constrain.
getAuditSink: () => {
try {
return ctx.getService<AuthEventAuditSurface>('audit');
} catch {
return undefined;
}
},
// [#24154] The `i18n` service, resolved LAZILY at send time: the
// invitation mail names the membership role by the option label the
// console reads through this same service. `getService` throws for an
// unregistered service; the mail then names the authored label.
getI18n: () => {
try {
return ctx.getService<II18nService>('i18n');
} catch {
return undefined;
}
},
};
// ADR-0069 D2 — cross-node rate-limit counters, backed by the kernel
// `cache` service and resolved LAZILY (#4772).
//
// This used to be an eager `getServiceAsync('cache')` probe right here,
// whose answer was frozen for the life of the process. `init()` runs before
// CacheServicePlugin registers the service (21ms earlier in a showcase cold
// start), so the probe resolved `undefined` in deployments that HAVE a cache
// configured, and the warning it printed sent operators to provision Redis
// for a problem they did not have. Worse than the misdiagnosis: the
// degradation was real and permanent — the counters never reached the shared
// store even once it came up, so a multi-node deployment's limits were never
// enforced globally. `createLazyCacheRateLimitStorage` resolves the service
// at the moment a counter is consumed, which is strictly after `kernel:ready`
// and therefore after ANY plugin ordering, and warns only when a counter
// genuinely has nowhere shared to count.
//
// Deliberately `rateLimit.customStorage`, NOT `secondaryStorage`: a
// `secondaryStorage` also relocates the SESSION of record into the cache
// (better-auth's `createSession` skips the `sys_session` row and
// `findSession` answers from the snapshot without reading the database),
// which would silently disable the ADR-0069 D4 session controls — idle
// timeout, absolute max and concurrent cap all revoke by writing that row.
// Whether the session of record should live in the cache at all is #4785.
// A host that supplies `secondaryStorage` itself still wins and keeps
// better-auth's own `storage: 'secondary-storage'` counters.
//
// The SAME resolution carries ObjectStack's own per-number OTP send budget
// (#2780) below — that counter had the identical hole (#4790): it counted
// in `secondaryStorage` when a host supplied one and per-process otherwise,
// which under the standard `serve` composition (nobody supplies one) meant
// every node granted the same phone number its own cooldown + hourly cap.
// The currency there is paid SMS, so an N-node deployment was billed for up
// to N× the declared budget.
//
// The `cache` service is registered ASYNC — `getService` throws for it, so
// resolve via `getServiceAsync` and treat any failure (not registered, or
// not yet ready) as "no shared cache, ask again later".
const resolveCache = async (): Promise<CounterStore | undefined> => {
let cache: any;
try {
cache = await (ctx as { getServiceAsync?: (n: string) => Promise<unknown> })
.getServiceAsync?.('cache');
} catch {
return undefined;
}
if (cache && typeof cache.get === 'function' && typeof cache.set === 'function') return cache;
return undefined;
};
{
const { createLazyCacheRateLimitStorage, createLazyCounterStore } = await import(
'./rate-limit-storage.js'
);
if (!authConfig.secondaryStorage) {
authConfig.rateLimitStorage = createLazyCacheRateLimitStorage({
resolveCache,
logger: ctx.logger,
});
}
// #4790 — ObjectStack's own counters. Wired even when the host supplied a
// `secondaryStorage` (AuthManager prefers that store for the budget and
// then never calls this resolver), so the two decisions stay independent.
authConfig.sharedCounterStore = createLazyCounterStore({
resolveCache,
logger: ctx.logger,
subject: 'per-number OTP send budget',
degradedImpact:
'The budget is still enforced, but PER NODE: every node grants the same phone number its own ' +
'cooldown and hourly cap, so an N-node deployment can send up to N× the configured number of ' +
'PAID SMS to one number',
});
}
this.applyEnvSocialProviderFallbacks(authConfig);
// Open extension point for packages that contribute auth providers
// (enterprise SSO, hosted control-plane SSO, etc.) without forking
// framework's AuthPlugin. Handlers mutate the draft config in place.
await ctx.trigger('auth:configure', authConfig, ctx);
this.configuredSocialProviders = authConfig.socialProviders
? { ...authConfig.socialProviders }
: undefined;
// [ADR-0105 D8] Lazy handle to plugin-security's `invitation-placement`
// service. LAZY on purpose: plugin-security starts after plugin-auth, so
// an eager lookup here would always miss and silently disable scoped
// invitations. Resolved per hook invocation instead; `undefined` (no
// plugin-security) makes a placement-carrying invitation fail closed.
authConfig.invitationPlacement = async () => {
try {
const svc =
(await (ctx as { getServiceAsync?: (n: string) => Promise<unknown> }).getServiceAsync?.(
'invitation-placement',
)) ?? ctx.getService?.('invitation-placement');
return svc as never;
} catch {
return undefined;
}
};
// Initialize auth manager with data engine
this.authManager = new AuthManager(authConfig);
// ADR-0092 D6 — remember the storage better-auth will actually use so the
// identity write guard can keep cached session snapshots coherent.
this.effectiveSecondaryStorage = authConfig.secondaryStorage;
// Register auth service
ctx.registerService('auth', this.authManager);
// ADR-0093 D4 / ADR-0105 D1 — register the `tenancy` service (single source
// of truth for the tenancy POSTURE). Registered AFTER `auth` so `auth` stays
// the plugin's first service registration (consumers and tests rely on that
// ordering). The `isolated` posture derives `isolationActive` from the
// presence of the `org-scoping` service (registered by
// @objectstack/organizations when installed), so that package needs no
// change to light it up; `group` is enforced by the open engine and
// never probes. `getService` is a cheap registry lookup and org-scoping
// registers AFTER plugin-auth, so the probe is deferred to first read
// (start()/request time).
const requestedPosture = resolveTenancyPosture();
// [#11184 / cloud#1509] Fail-closed clause of the 2026-08-23 ruling
// (「1509 选择 env 指定 owner 邮箱」): a WALLED posture must declare its
// platform owner. Under `group`/`isolated` the "first registrant becomes
// platform admin" bootstrap path is removed (plugin-security's
// `bootstrapPlatformAdmin` grants the cross-tenant `admin_full_access`
// only to the account matching the declared owner email), so a walled
// deployment with no owner declared would otherwise boot into a state
// with NO way to ever mint a platform admin — or, worse, tempt a silent
// fallback to first-registrant elevation, the exact hole cloud#1509
// measured. Refuse startup instead, naming the variable — the same
// fail-fast direction as `resolveTenancyPosture`'s own throw and the
// ADR-0093 D5 degraded-tenancy guard. A throw here aborts kernel boot
// (Phase 1 `init()` failures propagate). The `single` posture never
// consults the variable: "first user is owner" stays as ruled.
if (postureEnforcesWall(requestedPosture) && !resolvePlatformOwnerEmail()) {
throw new Error(
`[auth] tenancy posture '${requestedPosture}' requires ${PLATFORM_OWNER_EMAIL_ENV} to be set. ` +
'Under walled postures the first self-registrant is NOT promoted to platform admin; ' +
'the platform-admin grant goes only to the account whose email matches the declared ' +
'owner. Refusing to boot rather than silently reverting to first-registrant elevation. ' +
`Set ${PLATFORM_OWNER_EMAIL_ENV} to the operator's email address, or set ` +
"OS_TENANCY_POSTURE=single to run single-org.",
);
}
const tenancy: TenancyService = createTenancyService({
requested: requestedPosture,
probeIsolation: () => {
try {
return !!ctx.getService('org-scoping');
} catch {
return false;
}
},
// [ADR-0105 D12] Which walled postures the installed multi-org runtime
// entitles. The open side ASKS rather than assuming "package present ⇒
// every posture": whether `group` and `isolated` are one commercial tier
// or two is packaging policy, and that belongs to the commercial runtime.
// A runtime that declares nothing keeps today's behavior (both).
probeEntitledPostures: () => {
try {
return ctx.getService<OrgScopingEntitlement>('org-scoping')?.supportedPostures;
} catch {
return undefined;
}
},
getEngine: () => {
try {
return ctx.getService('objectql');
} catch {
return undefined;
}
},
logger: ctx.logger,
});
ctx.registerService('tenancy', tenancy);
this.tenancy = tenancy;
// Only an explicit `false` leaves the organization page out — see
// `AuthPluginOptions.registerOrganizationRecordPage`.
const registerOrganizationRecordPage = this.options.registerOrganizationRecordPage !== false;
ctx.getService<{ register(m: any): void }>('manifest').register({
// The header, `objects` and `objectExtensions`, from the ONE builder
// `IdentityObjectsPlugin` registers on its own in a reduced kernel, so the
// two paths cannot carry different lists. In it:
// - [ADR-0108 / #3723] `objects` registered as authored: nothing widens
// the `sys_invitation.role` / `sys_member.role` selects at boot. The
// closed four-name vocabulary those objects declare statically
// (`BUILTIN_MEMBERSHIP_ROLE_OPTIONS`) is the whole list, and it is the
// write-side guardrail that keeps an ungoverned capability grant
// unrepresentable.
// - [#8009] `objectExtensions` carries
// `sys_sso_provider.oidc_client_secret`, the encrypted home of the OIDC
// client secret that used to sit in cleartext inside `oidc_config`. See
// `manifest.ts` for why the field is declared there and not on the
// object file.
...authIdentityManifest({ datasource: this.options.manifestDatasource }),
// ADR-0048 — Setup/Studio/Account apps (and the Setup nav contributions)
// moved to their own one-app packages (@objectstack/{setup,studio,account}),
// each registering under its own package id so /apps/<packageId> resolves
// unambiguously. plugin-auth keeps only the auth objects + their pages.
// Slotted record-detail pages for system objects — currently
// sys_organization gets a Members / Invitations / Teams tab strip
// (see SysOrganizationDetailPage for the rationale and the
// intentionally-omitted OAuth / SSO tabs).
//
// `registerOrganizationRecordPage: false` leaves the organization page
// out, for a host that ships its own `sys_organization` default record
// page: one default per object per deployment, kept by composition
// (ruling A on objectstack#23015). `SysUserDetailPage` is registered
// either way.
pages: [...(registerOrganizationRecordPage ? [SysOrganizationDetailPage] : []), SysUserDetailPage],
// List views for each Setup-nav object are defined on the schema
// itself via the canonical `listViews` map (e.g.
// sys_user.listViews.{all_users,unverified,two_factor}). Registering
// top-level views here is the legacy pre-M10.30c pattern — it caused
// duplicate "Users"/"Roles"/"Sessions" tabs to appear alongside the
// schema-derived ones, sometimes referencing nonexistent fields
// (e.g. legacy `users.view` had phone/status/active columns that do
// not exist on sys_user). Schema-embedded listViews is the single
// source of truth.
dashboards: [SystemOverviewDashboard],
// ADR-0021 — datasets backing the System Overview dashboard's widgets.
datasets: SystemOverviewDatasets,
// ADR-0135 D6 / cloud#551 — surface "SSO Providers" (sys_sso_provider) in the
// Setup app's Access Control group, but ONLY when the external-IdP RP is
// wired (self-host `OS_SSO_ENABLED`, or the cloud per-env `planAllowsSso`
// arriving via `plugins.sso`). Without the gate the entry would render an
// empty list + a "Register" button whose endpoint 404s when SSO is off.
// Owning-plugin-contributes pattern (ADR-0029 K2), mirroring plugin-security.
...(this.authManager.isSsoWired()
? {
navigationContributions: [
{
app: 'setup',
group: 'group_access_control',
// After Roles/Permission-Sets (100) and Sharing (200), near API Keys (300).
priority: 250,
items: [
{
id: 'nav_sso_providers',
type: 'object',
label: 'SSO Providers',
objectName: 'sys_sso_provider',
icon: 'log-in',
requiredPermissions: ['manage_platform_settings'],
},
],
},
],
}
: {}),
});
if (!registerOrganizationRecordPage) {
// A deliberate composition, said once at boot so a missing tab strip is
// never left to be diagnosed from its absence.
ctx.logger.info(
'[auth] sys_organization_detail is not registered (registerOrganizationRecordPage: false): the host ' +
'composes its own default record page for sys_organization. Without one, the organization record ' +
'view opens the synthesized default layout, with no Members / Invitations / Teams tabs.',
);
}
// [ADR-0108 / #3723] There is no organization-role derivation any more.
//
// A `kernel:ready` hook used to walk the registered `position` /
// `permission` metadata and widen both the better-auth role map and the two
// `role` selects, so every host got app-declared roles with no wiring. That
// made an UNGOVERNED capability channel automatic in every deployment: a
// name stored in `sys_member.role` is projected into
// `current_user.positions` with none of ADR-0090 D12's controls. Positions
// are the governed channel, and an invitation carrying placement
// (ADR-0105 D8) is the one-step admission flow that replaces it.
ctx.logger.info('Auth Plugin initialized successfully');
}
async start(ctx: PluginContext): Promise<void> {
ctx.logger.info('Starting Auth Plugin...');
if (!this.authManager) {
throw new Error('Auth manager not initialized');
}
// [ADR-0131 D3] The Default Organization is a BOOT INVARIANT under the
// `single` posture: it owns every row, so it exists before the application
// seeds load (every `AppPlugin` declares this plugin in its
// `optionalDependencies`, so the kernel starts it first) and before the
// server accepts a request (`kernel:listening` follows every `start()`).
// A failure THROWS and fails the boot — never warn-only.
//
// Judged on the posture IN FORCE (`tenancy.posture`), the same judge
// `AppPlugin` uses to decide on its inline seed: a degraded walled request
// behaves as `single` and seeds inline, so it needs the owner too.
//
// ⛔ Not gated on `autoDefaultOrganization`. That option governs the
// platform admin's OWNER BIND (below, on `kernel:ready`); whether the
// organization exists is not an onboarding convenience any more — under
// `single` no row is org-less (ADR-0131 D11).
if (this.tenancy?.posture === 'single') {
let ql: IDataEngine | undefined;
try { ql = ctx.getService<IDataEngine>('objectql'); } catch { ql = undefined; }
// An engine that can neither read nor write (mock mode — the same guard
// `ensureDefaultOrganization` opens with) writes no row that needs an
// owner. A real composition always has one: `objectql` is this plugin's
// hard dependency.
if (ql && typeof ql.find === 'function' && typeof ql.insert === 'function') {
const invariant = await ensureDefaultOrganizationExists(ql, { logger: ctx.logger });
if (invariant.created) this.defaultOrganizationCreatedAtBoot = true;
if (invariant.ambiguous) {
ctx.logger.warn(
`[auth] the 'single' tenancy posture holds ${invariant.ambiguous.organizationCount} organizations and none `
+ 'is the Default Organization (slug \'default\'), so no owner is derivable: system writes and seed rows '
+ 'that need one are refused (ADR-0131 D9). The tenancy organization census names the remedies.',
);
}
}
}
// [#8009] Move any provider row still holding a CLEARTEXT OIDC client
// secret in `oidc_config` into the encrypted column. Registered
// unconditionally (not under `registerRoutes`) because the disposition of
// an already-stored secret does not depend on whether this process serves
// the auth routes. The returned unsubscribe is deliberately dropped: the
// engine outlives the plugin and there is no `stop()` to unwind it in.
ctx.hook('kernel:ready', async () => {
let ql: IDataEngine | undefined;
try { ql = ctx.getService<IDataEngine>('objectql'); } catch { ql = undefined; }
if (!ql) {
try { ql = ctx.getService<IDataEngine>('data'); } catch { ql = undefined; }
}
if (!ql) return;
scheduleLegacySsoSecretMigration(ql, ctx.logger);
});
// [#23367, ruling A] Record when this deployment started enforcing the
// API-key lifecycle policy — ONCE, in the `auth` settings, so the anchor
// survives restarts and every node reads the same instant (⛔ never the
// process start). On `kernel:bootstrapped`, strictly after every
// `kernel:ready` handler, because the settings engine binds from one of
// them and a write inside that window is refused
// (`SETTINGS_ENGINE_NOT_BOUND`). Registered independently of
// `registerRoutes`: the policy is judged wherever keys are admitted.
ctx.hook('kernel:bootstrapped', async () => {
await this.recordApiKeyPolicyStart(ctx);
});
// Setup App translations are now loaded by `PlatformObjectsPlugin`
// (in @objectstack/platform-objects). Translation bundles belong with
// the package that defines them; auth-plugin no longer piggy-backs on
// its kernel:ready hook for this.
// Bind the auth manager's live SERVICE COMPOSITION on `kernel:ready`: the
// outbound mail transport, the SMS transport, the deployment email locale,
// the brand name and the SMS locale.
//
// Registered independently of `registerRoutes`, the shape the sibling
// hooks below already use and already name ("Registered independently of
// `registerRoutes` so an embedding that serves no auth routes still gets
// the diagnosis"). `registerRoutes` answers "should this plugin mount its
// own `/api/v1/auth/*` routes on the kernel's `http-server`" — a
// TRANSPORT-MOUNTING question. Everything bound here is SERVICE
// COMPOSITION, true of an embedding regardless of who serves the routes.
//
// Gating the two together left every routes-less embedding with no mail
// transport, no locale on either channel and no brand binding — and
// silently, because the `logger.info` lines that would have reported the
// wiring sat inside the same skipped block. The population is not an edge
// case: every cloud tenant environment kernel constructs this plugin with
// `registerRoutes: false` by design, since the per-env kernel has no
// `http-server` and the host worker proxies the auth routes to it. The
// consequence was that the `localization.locale` precedence rung below
// could not reach a tenant environment at all — not degraded, absent.
//
// Registered BEFORE the route hook so that, when routes ARE mounted, the
// composition still completes ahead of them: the ordering the single
// combined hook used to give for free.
ctx.hook('kernel:ready', async () => {
// Inject the email service if available so better-auth callbacks
// (sendResetPassword / sendVerificationEmail / sendInvitationEmail
// / sendMagicLink) can actually deliver mail. Resolved here on
// kernel:ready so EmailServicePlugin has had a chance to register.
if (this.authManager) {
await this.ensureAuthSettingsBound(ctx);
// [#20389] The `open` posture's verification opt-out is LOUD: once per
// boot, after the settings namespace (which carries the
// OS_AUTH_REQUIRE_EMAIL_VERIFICATION env override) has been applied,
// read from the same advertisement the login UI reads.
if (
this.authManager.getAudience().posture === 'open' &&
this.authManager.getPublicConfig?.()?.emailPassword?.requireEmailVerification === false
) {
ctx.logger.warn(OPEN_POSTURE_VERIFICATION_OFF_WARNING);
}
let emailSvc: IEmailService | undefined;
try { emailSvc = ctx.getService<IEmailService>('email'); } catch { emailSvc = undefined; }
if (emailSvc) {
this.authManager.setEmailService(emailSvc);
ctx.logger.info('Auth: email service wired (transactional mail enabled)');
} else {
// No email service. The verification / password-reset callbacks now
// THROW when invoked without a transport (so an explicit resend
// reports a real error rather than faking success). If verification
// is REQUIRED, that means every signup would be stuck — surface the
// misconfiguration loudly at boot instead of one failure per signup.
const requiresEmail = !!this.authManager.getPublicConfig?.()?.emailPassword?.requireEmailVerification;
if (requiresEmail) {
// [#20389] The second remedy is only real where the posture lets the
// deployment turn verification off: `email_domain` refuses it.
const disableRemedy = this.authManager.getAudience().posture === 'email_domain'
? "; verification cannot be turned off under the 'email_domain' audience posture."
: ' or disable verification (OS_AUTH_REQUIRE_EMAIL_VERIFICATION=false).';
ctx.logger.error(
'Auth: email verification is REQUIRED but NO email service is registered — '
+ 'verification & password-reset emails will FAIL and new users will be locked '
+ 'out at sign-in. Register an email service (e.g. EmailServicePlugin + OS_EMAIL_*)'
+ disableRemedy,
);
} else {
ctx.logger.info('Auth: no email service registered — transactional mail disabled');
}
}
// #2780 — inject the SMS service so the phoneNumber plugin's OTP
// callbacks (send-otp / password-reset OTP) and the import
// SMS-invite path can deliver. Same lazy-resolution contract as
// the email service: absent ⇒ OTP endpoints keep failing loudly
// (NOT_SUPPORTED) while phone+password sign-in still works.
let smsSvc: ISmsService | undefined;
try { smsSvc = ctx.getService<ISmsService>('sms'); } catch { smsSvc = undefined; }
if (smsSvc) {
this.authManager.setSmsService(smsSvc);
if (this.authManager.isPhoneNumberEnabled()) {
ctx.logger.info(
this.authManager.isPhoneOtpDeliverable()
? 'Auth: sms service wired (phone-number OTP sign-in / reset enabled)'
: 'Auth: sms service present but NOT configured with a real provider — phone-number OTP stays disabled in production',
);
}
} else if (this.authManager.isPhoneNumberEnabled()) {
ctx.logger.info('Auth: no sms service registered — phone-number OTP disabled (password sign-in only)');
}
// #8195 / #14319 — the locale named on every auth EMAIL, so the
// localized `sys_email_template` rows are reachable through the
// platform's own send path instead of sitting dormant.
//
// This binds the DEPLOYMENT rung, resolved here at the plugin
// layer. Since the 2026-09-02 ruling (#14319) it is the SECOND rung:
// a request-triggered send whose recipient IS the requester takes
// that caller's own `Accept-Language` first, resolved at send time in
// `AuthManager` (`authEmailLocaleFromRequest`, which carries the
// ruling text). What is bound here answers when the request named no
// locale this platform ships a row for, or when there is no request
// at all — invitations, scheduled and admin-initiated mail.
//
// ⚠️ The superseded 2026-08-13 ruling made this rung the WHOLE answer