@opencloudcms/oauth2 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (213) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +397 -2
  3. package/dist/audit/audit.service.d.ts +18 -0
  4. package/dist/audit/audit.service.js +61 -0
  5. package/dist/audit/audit.service.js.map +1 -0
  6. package/dist/bff/auth.controller.d.ts +41 -0
  7. package/dist/bff/auth.controller.js +269 -0
  8. package/dist/bff/auth.controller.js.map +1 -0
  9. package/dist/bff/cookies.d.ts +11 -0
  10. package/dist/bff/cookies.js +43 -0
  11. package/dist/bff/cookies.js.map +1 -0
  12. package/dist/bff/oidc-client.d.ts +73 -0
  13. package/dist/bff/oidc-client.js +158 -0
  14. package/dist/bff/oidc-client.js.map +1 -0
  15. package/dist/bff/session-refresher.d.ts +27 -0
  16. package/dist/bff/session-refresher.js +95 -0
  17. package/dist/bff/session-refresher.js.map +1 -0
  18. package/dist/bff/session.store.d.ts +88 -0
  19. package/dist/bff/session.store.js +167 -0
  20. package/dist/bff/session.store.js.map +1 -0
  21. package/dist/clients/clients.d.ts +37 -0
  22. package/dist/clients/clients.js +107 -0
  23. package/dist/clients/clients.js.map +1 -0
  24. package/dist/config/schema.d.ts +91 -0
  25. package/dist/config/schema.js +129 -0
  26. package/dist/config/schema.js.map +1 -0
  27. package/dist/constants.d.ts +45 -0
  28. package/dist/constants.js +42 -0
  29. package/dist/constants.js.map +1 -0
  30. package/dist/cors/cors-origins.controller.d.ts +19 -0
  31. package/dist/cors/cors-origins.controller.js +122 -0
  32. package/dist/cors/cors-origins.controller.js.map +1 -0
  33. package/dist/cors/cors-origins.service.d.ts +73 -0
  34. package/dist/cors/cors-origins.service.js +287 -0
  35. package/dist/cors/cors-origins.service.js.map +1 -0
  36. package/dist/cors/customer-cors.middleware.d.ts +22 -0
  37. package/dist/cors/customer-cors.middleware.js +84 -0
  38. package/dist/cors/customer-cors.middleware.js.map +1 -0
  39. package/dist/customers/account.controller.d.ts +91 -0
  40. package/dist/customers/account.controller.js +443 -0
  41. package/dist/customers/account.controller.js.map +1 -0
  42. package/dist/customers/auth-hooks.d.ts +47 -0
  43. package/dist/customers/auth-hooks.js +79 -0
  44. package/dist/customers/auth-hooks.js.map +1 -0
  45. package/dist/customers/customer-auth.controller.d.ts +54 -0
  46. package/dist/customers/customer-auth.controller.js +287 -0
  47. package/dist/customers/customer-auth.controller.js.map +1 -0
  48. package/dist/customers/customer-sessions.revoker.d.ts +21 -0
  49. package/dist/customers/customer-sessions.revoker.js +47 -0
  50. package/dist/customers/customer-sessions.revoker.js.map +1 -0
  51. package/dist/customers/customer.service.d.ts +53 -0
  52. package/dist/customers/customer.service.js +229 -0
  53. package/dist/customers/customer.service.js.map +1 -0
  54. package/dist/customers/customers-admin.controller.d.ts +21 -0
  55. package/dist/customers/customers-admin.controller.js +134 -0
  56. package/dist/customers/customers-admin.controller.js.map +1 -0
  57. package/dist/customers/identifier.d.ts +6 -0
  58. package/dist/customers/identifier.js +27 -0
  59. package/dist/customers/identifier.js.map +1 -0
  60. package/dist/customers/sign-in-settings.controller.d.ts +27 -0
  61. package/dist/customers/sign-in-settings.controller.js +112 -0
  62. package/dist/customers/sign-in-settings.controller.js.map +1 -0
  63. package/dist/customers/sign-in-settings.service.d.ts +35 -0
  64. package/dist/customers/sign-in-settings.service.js +130 -0
  65. package/dist/customers/sign-in-settings.service.js.map +1 -0
  66. package/dist/db/migrations/index.d.ts +2 -0
  67. package/dist/db/migrations/index.js +14 -0
  68. package/dist/db/migrations/index.js.map +1 -0
  69. package/dist/db/migrations/oauth2_0001_init.d.ts +2 -0
  70. package/dist/db/migrations/oauth2_0001_init.js +127 -0
  71. package/dist/db/migrations/oauth2_0001_init.js.map +1 -0
  72. package/dist/db/migrations/oauth2_0002_user_locale.d.ts +3 -0
  73. package/dist/db/migrations/oauth2_0002_user_locale.js +13 -0
  74. package/dist/db/migrations/oauth2_0002_user_locale.js.map +1 -0
  75. package/dist/db/migrations/oauth2_0003_groups.d.ts +6 -0
  76. package/dist/db/migrations/oauth2_0003_groups.js +46 -0
  77. package/dist/db/migrations/oauth2_0003_groups.js.map +1 -0
  78. package/dist/db/migrations/oauth2_0004_customers.d.ts +3 -0
  79. package/dist/db/migrations/oauth2_0004_customers.js +108 -0
  80. package/dist/db/migrations/oauth2_0004_customers.js.map +1 -0
  81. package/dist/db/types.d.ts +176 -0
  82. package/dist/db/types.js +3 -0
  83. package/dist/db/types.js.map +1 -0
  84. package/dist/errors.d.ts +28 -0
  85. package/dist/errors.js +115 -0
  86. package/dist/errors.js.map +1 -0
  87. package/dist/groups/groups.controller.d.ts +28 -0
  88. package/dist/groups/groups.controller.js +126 -0
  89. package/dist/groups/groups.controller.js.map +1 -0
  90. package/dist/groups/groups.service.d.ts +38 -0
  91. package/dist/groups/groups.service.js +134 -0
  92. package/dist/groups/groups.service.js.map +1 -0
  93. package/dist/guard/auth.guard.d.ts +29 -0
  94. package/dist/guard/auth.guard.js +119 -0
  95. package/dist/guard/auth.guard.js.map +1 -0
  96. package/dist/guard/current-user.decorator.d.ts +33 -0
  97. package/dist/guard/current-user.decorator.js +16 -0
  98. package/dist/guard/current-user.decorator.js.map +1 -0
  99. package/dist/guard/customer-auth.decorator.d.ts +26 -0
  100. package/dist/guard/customer-auth.decorator.js +16 -0
  101. package/dist/guard/customer-auth.decorator.js.map +1 -0
  102. package/dist/guard/customer-authenticator.d.ts +58 -0
  103. package/dist/guard/customer-authenticator.js +215 -0
  104. package/dist/guard/customer-authenticator.js.map +1 -0
  105. package/dist/guard/public.decorator.d.ts +2 -0
  106. package/dist/guard/public.decorator.js +8 -0
  107. package/dist/guard/public.decorator.js.map +1 -0
  108. package/dist/guard/session-auth.service.d.ts +28 -0
  109. package/dist/guard/session-auth.service.js +125 -0
  110. package/dist/guard/session-auth.service.js.map +1 -0
  111. package/dist/idp/identity-linker.d.ts +19 -0
  112. package/dist/idp/identity-linker.js +93 -0
  113. package/dist/idp/identity-linker.js.map +1 -0
  114. package/dist/idp/identity-provider.d.ts +54 -0
  115. package/dist/idp/identity-provider.js +36 -0
  116. package/dist/idp/identity-provider.js.map +1 -0
  117. package/dist/idp/idp.controller.d.ts +36 -0
  118. package/dist/idp/idp.controller.js +232 -0
  119. package/dist/idp/idp.controller.js.map +1 -0
  120. package/dist/idp/oidc.identity-provider.d.ts +42 -0
  121. package/dist/idp/oidc.identity-provider.js +96 -0
  122. package/dist/idp/oidc.identity-provider.js.map +1 -0
  123. package/dist/index.d.ts +50 -0
  124. package/dist/index.js +98 -0
  125. package/dist/index.js.map +1 -0
  126. package/dist/interaction/customer-interaction.controller.d.ts +64 -0
  127. package/dist/interaction/customer-interaction.controller.js +336 -0
  128. package/dist/interaction/customer-interaction.controller.js.map +1 -0
  129. package/dist/interaction/interaction.controller.d.ts +36 -0
  130. package/dist/interaction/interaction.controller.js +175 -0
  131. package/dist/interaction/interaction.controller.js.map +1 -0
  132. package/dist/interaction/interaction.service.d.ts +40 -0
  133. package/dist/interaction/interaction.service.js +102 -0
  134. package/dist/interaction/interaction.service.js.map +1 -0
  135. package/dist/maintenance/cleanup.service.d.ts +22 -0
  136. package/dist/maintenance/cleanup.service.js +77 -0
  137. package/dist/maintenance/cleanup.service.js.map +1 -0
  138. package/dist/oauth2.module.d.ts +37 -0
  139. package/dist/oauth2.module.js +214 -0
  140. package/dist/oauth2.module.js.map +1 -0
  141. package/dist/otp/otp-guard.d.ts +7 -0
  142. package/dist/otp/otp-guard.js +27 -0
  143. package/dist/otp/otp-guard.js.map +1 -0
  144. package/dist/otp/otp.service.d.ts +57 -0
  145. package/dist/otp/otp.service.js +202 -0
  146. package/dist/otp/otp.service.js.map +1 -0
  147. package/dist/otp/otp.types.d.ts +36 -0
  148. package/dist/otp/otp.types.js +34 -0
  149. package/dist/otp/otp.types.js.map +1 -0
  150. package/dist/otp/storefront-boot-check.d.ts +13 -0
  151. package/dist/otp/storefront-boot-check.js +53 -0
  152. package/dist/otp/storefront-boot-check.js.map +1 -0
  153. package/dist/permissions.d.ts +12 -0
  154. package/dist/permissions.js +24 -0
  155. package/dist/permissions.js.map +1 -0
  156. package/dist/provider/kysely.adapter.d.ts +27 -0
  157. package/dist/provider/kysely.adapter.js +79 -0
  158. package/dist/provider/kysely.adapter.js.map +1 -0
  159. package/dist/provider/provider.factory.d.ts +101 -0
  160. package/dist/provider/provider.factory.js +377 -0
  161. package/dist/provider/provider.factory.js.map +1 -0
  162. package/dist/provider/provider.service.d.ts +60 -0
  163. package/dist/provider/provider.service.js +200 -0
  164. package/dist/provider/provider.service.js.map +1 -0
  165. package/dist/provider/signing-keys.d.ts +19 -0
  166. package/dist/provider/signing-keys.js +41 -0
  167. package/dist/provider/signing-keys.js.map +1 -0
  168. package/dist/register-migrations.d.ts +1 -0
  169. package/dist/register-migrations.js +7 -0
  170. package/dist/register-migrations.js.map +1 -0
  171. package/dist/security/crypto.d.ts +6 -0
  172. package/dist/security/crypto.js +29 -0
  173. package/dist/security/crypto.js.map +1 -0
  174. package/dist/security/email.d.ts +1 -0
  175. package/dist/security/email.js +7 -0
  176. package/dist/security/email.js.map +1 -0
  177. package/dist/security/origin.d.ts +1 -0
  178. package/dist/security/origin.js +15 -0
  179. package/dist/security/origin.js.map +1 -0
  180. package/dist/security/password.d.ts +12 -0
  181. package/dist/security/password.js +92 -0
  182. package/dist/security/password.js.map +1 -0
  183. package/dist/security/rate-limiter.d.ts +25 -0
  184. package/dist/security/rate-limiter.js +52 -0
  185. package/dist/security/rate-limiter.js.map +1 -0
  186. package/dist/security/return-to.d.ts +6 -0
  187. package/dist/security/return-to.js +33 -0
  188. package/dist/security/return-to.js.map +1 -0
  189. package/dist/security/validate.d.ts +3 -0
  190. package/dist/security/validate.js +14 -0
  191. package/dist/security/validate.js.map +1 -0
  192. package/dist/settings/settings.provider.d.ts +11 -0
  193. package/dist/settings/settings.provider.js +20 -0
  194. package/dist/settings/settings.provider.js.map +1 -0
  195. package/dist/setup/bootstrap.service.d.ts +24 -0
  196. package/dist/setup/bootstrap.service.js +117 -0
  197. package/dist/setup/bootstrap.service.js.map +1 -0
  198. package/dist/setup/setup-state.d.ts +8 -0
  199. package/dist/setup/setup-state.js +42 -0
  200. package/dist/setup/setup-state.js.map +1 -0
  201. package/dist/setup/setup.controller.d.ts +23 -0
  202. package/dist/setup/setup.controller.js +96 -0
  203. package/dist/setup/setup.controller.js.map +1 -0
  204. package/dist/users/password.controller.d.ts +19 -0
  205. package/dist/users/password.controller.js +87 -0
  206. package/dist/users/password.controller.js.map +1 -0
  207. package/dist/users/user.service.d.ts +114 -0
  208. package/dist/users/user.service.js +336 -0
  209. package/dist/users/user.service.js.map +1 -0
  210. package/dist/users/users.controller.d.ts +43 -0
  211. package/dist/users/users.controller.js +188 -0
  212. package/dist/users/users.controller.js.map +1 -0
  213. package/package.json +75 -3
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionRefresher = exports.REFRESH_MARGIN_MS = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const session_store_1 = require("./session.store");
6
+ /** Refresh when the access token has less than this left (spec §6.5 step 4). */
7
+ exports.REFRESH_MARGIN_MS = 60_000;
8
+ /** A request that lost the refresh lease polls this often, for at most the lease length. */
9
+ const LEASE_POLL_MS = 100;
10
+ const LEASE_WAIT_MS = session_store_1.REFRESH_LEASE_SEC * 1000;
11
+ /**
12
+ * Access-token refresh of a BFF session (admin or customer store, with that realm's OidcClient).
13
+ *
14
+ * In-process single-flight per session in front of the DB lease (R18): concurrent requests of one
15
+ * session await the same refresh. No DB connection or transaction is held while the HTTP call to
16
+ * /oauth2/token runs (that endpoint needs the same pool).
17
+ */
18
+ class SessionRefresher {
19
+ sessions;
20
+ oidc;
21
+ logger = new common_1.Logger('OAuth2');
22
+ refreshing = new Map();
23
+ constructor(sessions, oidc) {
24
+ this.sessions = sessions;
25
+ this.oidc = oidc;
26
+ }
27
+ /** True when the session's access token is within REFRESH_MARGIN_MS of expiry (or past it). */
28
+ needsRefresh(session, now = Date.now()) {
29
+ return !!session.accessExpiresAt && session.accessExpiresAt.getTime() - now < exports.REFRESH_MARGIN_MS;
30
+ }
31
+ /** False when the session vanished or the refresh failed or timed out (the caller destroys the session). */
32
+ refresh(read) {
33
+ const inFlight = this.refreshing.get(read.idHash);
34
+ if (inFlight)
35
+ return inFlight;
36
+ const p = this.refreshLeased(read).finally(() => this.refreshing.delete(read.idHash));
37
+ this.refreshing.set(read.idHash, p);
38
+ return p;
39
+ }
40
+ async refreshLeased(read) {
41
+ const seen = read.accessExpiresAt?.getTime() ?? -Infinity;
42
+ const fresher = (row) => (row?.accessExpiresAt?.getTime() ?? -Infinity) > seen;
43
+ let row;
44
+ try {
45
+ row = await this.sessions.claimRefresh(read.idHash);
46
+ }
47
+ catch (e) {
48
+ this.warn('Refresh lease claim failed', e);
49
+ return false;
50
+ }
51
+ if (!row)
52
+ return this.awaitOtherRefresh(read.idHash, fresher);
53
+ // Winner. Another instance may have finished between our read and the claim.
54
+ if (fresher(row) || !row.refreshToken) {
55
+ await this.sessions.releaseRefresh(read.idHash).catch(() => { });
56
+ return fresher(row);
57
+ }
58
+ try {
59
+ const tokens = await this.oidc.refresh(row.refreshToken);
60
+ await this.sessions.completeRefresh(read.idHash, tokens);
61
+ return true;
62
+ }
63
+ catch (e) {
64
+ this.warn('Token refresh failed', e);
65
+ await this.sessions.releaseRefresh(read.idHash).catch(() => { });
66
+ return false;
67
+ }
68
+ }
69
+ /** Loser of the lease: poll until the holder has stored newer tokens (→ reuse) or give up. */
70
+ async awaitOtherRefresh(idHash, fresher) {
71
+ const deadline = Date.now() + LEASE_WAIT_MS;
72
+ while (Date.now() < deadline) {
73
+ await new Promise((r) => setTimeout(r, LEASE_POLL_MS));
74
+ let row;
75
+ try {
76
+ row = await this.sessions.getByHash(idHash);
77
+ }
78
+ catch {
79
+ return false;
80
+ }
81
+ if (!row)
82
+ return false;
83
+ if (fresher(row))
84
+ return true;
85
+ }
86
+ this.logger.warn('Timed out waiting for another refresh of the session');
87
+ return false;
88
+ }
89
+ /** Error name only: messages may carry token-endpoint responses. */
90
+ warn(what, e) {
91
+ this.logger.warn(`${what}: ${e?.name ?? 'Error'}`);
92
+ }
93
+ }
94
+ exports.SessionRefresher = SessionRefresher;
95
+ //# sourceMappingURL=session-refresher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-refresher.js","sourceRoot":"","sources":["../../src/bff/session-refresher.ts"],"names":[],"mappings":";;;AAAA,2CAAwC;AAExC,mDAAwF;AAExF,gFAAgF;AACnE,QAAA,iBAAiB,GAAG,MAAM,CAAC;AACxC,4FAA4F;AAC5F,MAAM,aAAa,GAAG,GAAG,CAAC;AAC1B,MAAM,aAAa,GAAG,iCAAiB,GAAG,IAAI,CAAC;AAE/C;;;;;;GAMG;AACH,MAAa,gBAAgB;IAKR;IACA;IALF,MAAM,GAAG,IAAI,eAAM,CAAC,QAAQ,CAAC,CAAC;IAC9B,UAAU,GAAG,IAAI,GAAG,EAA4B,CAAC;IAElE,YACmB,QAAsB,EACtB,IAAgB;QADhB,aAAQ,GAAR,QAAQ,CAAc;QACtB,SAAI,GAAJ,IAAI,CAAY;IAChC,CAAC;IAEJ,+FAA+F;IAC/F,YAAY,CAAC,OAAmB,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE;QAChD,OAAO,CAAC,CAAC,OAAO,CAAC,eAAe,IAAI,OAAO,CAAC,eAAe,CAAC,OAAO,EAAE,GAAG,GAAG,GAAG,yBAAiB,CAAC;IAClG,CAAC;IAED,4GAA4G;IAC5G,OAAO,CAAC,IAAgB;QACtB,MAAM,QAAQ,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAClD,IAAI,QAAQ;YAAE,OAAO,QAAQ,CAAC;QAC9B,MAAM,CAAC,GAAG,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC,OAAO,CA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EAAE,IAAI,IAAI,OAAO,EAAE,CAAC,CAAC;IAChE,CAAC;CACF;AAzED,4CAyEC"}
@@ -0,0 +1,88 @@
1
+ import { type Kysely } from 'kysely';
2
+ import type { OAuth2Config } from '../config/schema';
3
+ import type { AuthTables } from '../db/types';
4
+ import type { TokenSet } from './oidc-client';
5
+ /** A BFF session with its tokens opened. Expiry is NOT checked here (the guard does that). */
6
+ export interface SessionRow {
7
+ idHash: string;
8
+ /** The session's owner: `user_id` (admin) or `customer_id` (customer), per the store's `ownerColumn`. */
9
+ userId: string;
10
+ accessToken: string;
11
+ refreshToken?: string;
12
+ idToken: string;
13
+ accessExpiresAt?: Date;
14
+ idleExpiresAt: Date;
15
+ absoluteExpiresAt: Date;
16
+ createdAt: Date;
17
+ lastSeenAt: Date;
18
+ ip?: string;
19
+ userAgent?: string;
20
+ }
21
+ /** How long a claimed refresh lease is valid (R18). */
22
+ export declare const REFRESH_LEASE_SEC = 10;
23
+ /** Session lifetimes of one realm: admin reads them from the auth settings, customers from `storefront.ttl`. */
24
+ export interface SessionTtlSource {
25
+ getTtls(): Promise<{
26
+ sessionIdle: number;
27
+ sessionAbsolute: number;
28
+ }>;
29
+ }
30
+ /** Which table a store keeps its sessions in; both tables have the same columns apart from the owner column. */
31
+ export type SessionTable = {
32
+ table: 'auth_sessions';
33
+ ownerColumn: 'user_id';
34
+ } | {
35
+ table: 'auth_customer_sessions';
36
+ ownerColumn: 'customer_id';
37
+ };
38
+ export declare const ADMIN_SESSION_TABLE: SessionTable;
39
+ export declare const CUSTOMER_SESSION_TABLE: SessionTable;
40
+ /**
41
+ * Server-side store of BFF sessions (`auth_sessions` for admin, spec §4; `auth_customer_sessions` for the
42
+ * site's customers). The browser only holds the cookie value. Registered through factories: the admin store
43
+ * under its class token (and ADMIN_SESSIONS), the customer store under CUSTOMER_SESSIONS.
44
+ */
45
+ export declare class SessionStore {
46
+ private readonly settings;
47
+ private readonly key;
48
+ /** Queries name the table at runtime; both tables share their columns, so the builder is typed loosely. */
49
+ private readonly db;
50
+ private readonly table;
51
+ private readonly ownerColumn;
52
+ constructor(db: Kysely<AuthTables>, cfg: OAuth2Config, settings: SessionTtlSource, where?: SessionTable);
53
+ /** `userId` is the owner: an admin user id or a customer id, per the store's table. */
54
+ create(userId: string, tokens: TokenSet, meta: {
55
+ ip?: string;
56
+ userAgent?: string;
57
+ }): Promise<{
58
+ cookieValue: string;
59
+ idHash: string;
60
+ }>;
61
+ get(cookieValue: string): Promise<SessionRow | undefined>;
62
+ /** Same as get(), by `sha256(cookie)`. */
63
+ getByHash(idHash: string): Promise<SessionRow | undefined>;
64
+ /**
65
+ * Claims the refresh lease (R18) with one atomic UPDATE: succeeds only when no unexpired lease exists.
66
+ * Returns the (decrypted) row for the winner, undefined when the session is gone or someone else holds
67
+ * the lease. No transaction stays open: the caller does the HTTP refresh afterwards.
68
+ */
69
+ claimRefresh(idHash: string): Promise<SessionRow | undefined>;
70
+ /**
71
+ * Stores the refreshed tokens and releases the lease. A refresh/id token missing from the response
72
+ * keeps the stored one.
73
+ */
74
+ completeRefresh(idHash: string, tokens: TokenSet): Promise<void>;
75
+ /** Releases the lease without changing tokens (refresh failed or turned out unnecessary). */
76
+ releaseRefresh(idHash: string): Promise<void>;
77
+ /** Slides the idle expiry to min(now + idle, absolute); a no-op if last seen < 60 s before `now`. */
78
+ touch(idHash: string, now?: Date): Promise<void>;
79
+ /**
80
+ * The provider Grant behind a session: its stored refresh token is the id of the adapter's
81
+ * `RefreshToken` row, which carries the grant id. Undefined when the session or token is gone.
82
+ */
83
+ grantIdOf(idHash: string): Promise<string | undefined>;
84
+ /** Deletes every session of `ownerId` (a user or customer id, per the store's table), except `exceptIdHash`. */
85
+ deleteByOwner(ownerId: string, exceptIdHash?: string): Promise<void>;
86
+ delete(idHash: string): Promise<void>;
87
+ private toRow;
88
+ }
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SessionStore = exports.CUSTOMER_SESSION_TABLE = exports.ADMIN_SESSION_TABLE = exports.REFRESH_LEASE_SEC = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const kysely_1 = require("kysely");
6
+ const crypto_1 = require("../security/crypto");
7
+ /** touch() writes at most once per this many ms. */
8
+ const TOUCH_INTERVAL_MS = 60_000;
9
+ /** How long a claimed refresh lease is valid (R18). */
10
+ exports.REFRESH_LEASE_SEC = 10;
11
+ exports.ADMIN_SESSION_TABLE = { table: 'auth_sessions', ownerColumn: 'user_id' };
12
+ exports.CUSTOMER_SESSION_TABLE = { table: 'auth_customer_sessions', ownerColumn: 'customer_id' };
13
+ /**
14
+ * Server-side store of BFF sessions (`auth_sessions` for admin, spec §4; `auth_customer_sessions` for the
15
+ * site's customers). The browser only holds the cookie value. Registered through factories: the admin store
16
+ * under its class token (and ADMIN_SESSIONS), the customer store under CUSTOMER_SESSIONS.
17
+ */
18
+ class SessionStore {
19
+ settings;
20
+ key;
21
+ /** Queries name the table at runtime; both tables share their columns, so the builder is typed loosely. */
22
+ db;
23
+ table;
24
+ ownerColumn;
25
+ constructor(db, cfg, settings, where = exports.ADMIN_SESSION_TABLE) {
26
+ this.settings = settings;
27
+ this.db = db;
28
+ this.key = (0, crypto_1.deriveKey)(cfg.secret, 'token');
29
+ this.table = where.table;
30
+ this.ownerColumn = where.ownerColumn;
31
+ }
32
+ /** `userId` is the owner: an admin user id or a customer id, per the store's table. */
33
+ async create(userId, tokens, meta) {
34
+ const ttl = await this.settings.getTtls();
35
+ const cookieValue = (0, node_crypto_1.randomBytes)(32).toString('base64url');
36
+ const idHash = (0, crypto_1.sha256)(cookieValue);
37
+ const now = new Date();
38
+ await this.db
39
+ .insertInto(this.table)
40
+ .values({
41
+ id_hash: idHash,
42
+ [this.ownerColumn]: userId,
43
+ access_token_enc: (0, crypto_1.seal)(this.key, tokens.accessToken),
44
+ refresh_token_enc: tokens.refreshToken ? (0, crypto_1.seal)(this.key, tokens.refreshToken) : null,
45
+ id_token_enc: tokens.idToken ? (0, crypto_1.seal)(this.key, tokens.idToken) : null,
46
+ access_expires_at: accessExpiry(now, tokens),
47
+ idle_expires_at: new Date(now.getTime() + Math.min(ttl.sessionIdle, ttl.sessionAbsolute) * 1000),
48
+ absolute_expires_at: new Date(now.getTime() + ttl.sessionAbsolute * 1000),
49
+ created_at: now,
50
+ last_seen_at: now,
51
+ ip: meta.ip ?? null,
52
+ user_agent: meta.userAgent ?? null,
53
+ })
54
+ .execute();
55
+ return { cookieValue, idHash };
56
+ }
57
+ async get(cookieValue) {
58
+ if (!cookieValue)
59
+ return undefined;
60
+ return this.getByHash((0, crypto_1.sha256)(cookieValue));
61
+ }
62
+ /** Same as get(), by `sha256(cookie)`. */
63
+ async getByHash(idHash) {
64
+ const row = await this.db.selectFrom(this.table).selectAll().where('id_hash', '=', idHash).executeTakeFirst();
65
+ return row ? this.toRow(row) : undefined;
66
+ }
67
+ /**
68
+ * Claims the refresh lease (R18) with one atomic UPDATE: succeeds only when no unexpired lease exists.
69
+ * Returns the (decrypted) row for the winner, undefined when the session is gone or someone else holds
70
+ * the lease. No transaction stays open: the caller does the HTTP refresh afterwards.
71
+ */
72
+ async claimRefresh(idHash) {
73
+ const row = await this.db
74
+ .updateTable(this.table)
75
+ .set({ refresh_lease_until: (0, kysely_1.sql) `now() + make_interval(secs => ${exports.REFRESH_LEASE_SEC})` })
76
+ .where('id_hash', '=', idHash)
77
+ .where((eb) => eb.or([eb('refresh_lease_until', 'is', null), eb('refresh_lease_until', '<', (0, kysely_1.sql) `now()`)]))
78
+ .returningAll()
79
+ .executeTakeFirst();
80
+ return row ? this.toRow(row) : undefined;
81
+ }
82
+ /**
83
+ * Stores the refreshed tokens and releases the lease. A refresh/id token missing from the response
84
+ * keeps the stored one.
85
+ */
86
+ async completeRefresh(idHash, tokens) {
87
+ const now = new Date();
88
+ await this.db
89
+ .updateTable(this.table)
90
+ .set({
91
+ access_token_enc: (0, crypto_1.seal)(this.key, tokens.accessToken),
92
+ access_expires_at: accessExpiry(now, tokens),
93
+ ...(tokens.refreshToken ? { refresh_token_enc: (0, crypto_1.seal)(this.key, tokens.refreshToken) } : {}),
94
+ ...(tokens.idToken ? { id_token_enc: (0, crypto_1.seal)(this.key, tokens.idToken) } : {}),
95
+ refresh_lease_until: null,
96
+ })
97
+ .where('id_hash', '=', idHash)
98
+ .execute();
99
+ }
100
+ /** Releases the lease without changing tokens (refresh failed or turned out unnecessary). */
101
+ async releaseRefresh(idHash) {
102
+ await this.db.updateTable(this.table).set({ refresh_lease_until: null }).where('id_hash', '=', idHash).execute();
103
+ }
104
+ /** Slides the idle expiry to min(now + idle, absolute); a no-op if last seen < 60 s before `now`. */
105
+ async touch(idHash, now = new Date()) {
106
+ const ttl = await this.settings.getTtls();
107
+ const idle = new Date(now.getTime() + ttl.sessionIdle * 1000);
108
+ await this.db
109
+ .updateTable(this.table)
110
+ .set({
111
+ last_seen_at: now,
112
+ idle_expires_at: (0, kysely_1.sql) `least(${idle}::timestamptz, absolute_expires_at)`,
113
+ })
114
+ .where('id_hash', '=', idHash)
115
+ .where('last_seen_at', '<', new Date(now.getTime() - TOUCH_INTERVAL_MS))
116
+ .execute();
117
+ }
118
+ /**
119
+ * The provider Grant behind a session: its stored refresh token is the id of the adapter's
120
+ * `RefreshToken` row, which carries the grant id. Undefined when the session or token is gone.
121
+ */
122
+ async grantIdOf(idHash) {
123
+ const refreshToken = (await this.getByHash(idHash))?.refreshToken;
124
+ if (!refreshToken)
125
+ return undefined;
126
+ const row = await this.db
127
+ .selectFrom('auth_oidc_payloads')
128
+ .select('grant_id')
129
+ .where('kind', '=', 'RefreshToken')
130
+ .where('id', '=', refreshToken)
131
+ .executeTakeFirst();
132
+ return row?.grant_id ?? undefined;
133
+ }
134
+ /** Deletes every session of `ownerId` (a user or customer id, per the store's table), except `exceptIdHash`. */
135
+ async deleteByOwner(ownerId, exceptIdHash) {
136
+ let q = this.db.deleteFrom(this.table).where(this.ownerColumn, '=', ownerId);
137
+ if (exceptIdHash)
138
+ q = q.where('id_hash', '<>', exceptIdHash);
139
+ await q.execute();
140
+ }
141
+ async delete(idHash) {
142
+ await this.db.deleteFrom(this.table).where('id_hash', '=', idHash).execute();
143
+ }
144
+ toRow(raw) {
145
+ const r = raw;
146
+ const opt = (v) => (v ? (0, crypto_1.open)(this.key, v) : undefined);
147
+ return {
148
+ idHash: r.id_hash,
149
+ userId: raw[this.ownerColumn],
150
+ accessToken: opt(r.access_token_enc) ?? '',
151
+ refreshToken: opt(r.refresh_token_enc),
152
+ idToken: opt(r.id_token_enc) ?? '',
153
+ accessExpiresAt: r.access_expires_at ? new Date(r.access_expires_at) : undefined,
154
+ idleExpiresAt: new Date(r.idle_expires_at),
155
+ absoluteExpiresAt: new Date(r.absolute_expires_at),
156
+ createdAt: new Date(r.created_at),
157
+ lastSeenAt: new Date(r.last_seen_at),
158
+ ip: r.ip ?? undefined,
159
+ userAgent: r.user_agent ?? undefined,
160
+ };
161
+ }
162
+ }
163
+ exports.SessionStore = SessionStore;
164
+ function accessExpiry(now, t) {
165
+ return t.expiresIn !== undefined ? new Date(now.getTime() + t.expiresIn * 1000) : null;
166
+ }
167
+ //# sourceMappingURL=session.store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.store.js","sourceRoot":"","sources":["../../src/bff/session.store.ts"],"names":[],"mappings":";;;AAAA,6CAA0C;AAC1C,mCAA2D;AAG3D,+CAAmE;AAoBnE,oDAAoD;AACpD,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,uDAAuD;AAC1C,QAAA,iBAAiB,GAAG,EAAE,CAAC;AAYvB,QAAA,mBAAmB,GAAiB,EAAE,KAAK,EAAE,eAAe,EAAE,WAAW,EAAE,SAAS,EAAE,CAAC;AACvF,QAAA,sBAAsB,GAAiB,EAAE,KAAK,EAAE,wBAAwB,EAAE,WAAW,EAAE,aAAa,EAAE,CAAC;AAKpH;;;;GAIG;AACH,MAAa,YAAY;IAUJ;IATF,GAAG,CAAS;IAC7B,2GAA2G;IA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,CAAC,OAAO;YACjB,MAAM,EAAG,GAA8B,CAAC,IAAI,CAAC,WAAW,CAAE;YAC1D,WAAW,EAAE,GAAG,CAAC,CAAC,CAAC,gBAAgB,CAAC,IAAI,EAAE;YAC1C,YAAY,EAAE,GAAG,CAAC,CAAC,CAAC,iBAAiB,CAAC;YACtC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,EAAE;YAClC,eAAe,EAAE,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,iBAAyB,CAAC,CAAC,CAAC,CAAC,SAAS;YACxF,aAAa,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC,eAAe,CAAC;YAC1C,iBAAiB,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC,mBAAmB,CAAC;YAClD,SAAS,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC,UAAkB,CAAC;YACzC,UAAU,EAAE,IAAI,IAAI,CAAC,CAAC,CAAC,YAAoB,CAAC;YAC5C,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,SAAS;YACrB,SAAS,EAAE,CAAC,CAAC,UAAU,IAAI,SAAS;SACrC,CAAC;IACJ,CAAC;CACF;AAhKD,oCAgKC;AAED,SAAS,YAAY,CAAC,GAAS,EAAE,CAAW;IAC1C,OAAO,CAAC,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACzF,CAAC"}
@@ -0,0 +1,37 @@
1
+ import type { OAuth2Config } from '../config/schema';
2
+ export declare const ADMIN_SCOPES: readonly ["openid", "profile", "email", "offline_access"];
3
+ export type Realm = 'admin' | 'customer';
4
+ /**
5
+ * Spec "Clients and realms": every per-client behaviour of the provider (interaction URL, granted scopes,
6
+ * refresh tokens, TTLs, account lookup) is read from here instead of comparing against ADMIN_CLIENT_ID.
7
+ */
8
+ export interface ClientSpec {
9
+ id: string;
10
+ realm: Realm;
11
+ kind: 'confidential' | 'public';
12
+ redirectUris: string[];
13
+ postLogoutRedirectUris: string[];
14
+ /** Issue (rotating) refresh tokens, bound to the grant rather than to the provider browser session. */
15
+ refreshTokens: boolean;
16
+ /** Interaction URL path: the provider redirects to `${loginPath}?uid=<uid>`. */
17
+ loginPath: string;
18
+ /** Fixed scopes granted on every login (first-party clients, no consent screen). */
19
+ scopes: readonly string[];
20
+ }
21
+ /** The account realm of a built-in client id; `undefined` for anything else (never an account realm). */
22
+ export declare function realmOf(clientId: string | undefined): Realm | undefined;
23
+ /** The storefront BFF's client secret: derived from OPENCLOUDCMS_SECRET (own HKDF label), never stored. */
24
+ export declare function storefrontClientSecret(cfg: Pick<OAuth2Config, 'secret'>): string;
25
+ /**
26
+ * The clients of this instance. Admin always; with `storefront.enabled` the storefront BFF, the mobile
27
+ * client (only when `storefront.mobile.redirectUris` is configured) and the web client (redirect URIs from
28
+ * the admin-managed CORS origins, `webRedirectUris`).
29
+ */
30
+ export declare function buildClients(cfg: OAuth2Config, webRedirectUris: string[]): ClientSpec[];
31
+ export declare function webClientSpec(cfg: OAuth2Config, redirectUris: string[]): ClientSpec;
32
+ /**
33
+ * oidc-provider client metadata of a spec. Confidential clients authenticate with client_secret_basic;
34
+ * public ones with `none` (PKCE is required for every client by the provider config). The secret is
35
+ * added by the caller (static clients only); stored copies never carry it.
36
+ */
37
+ export declare function clientMetadata(spec: ClientSpec): Record<string, unknown>;
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ADMIN_SCOPES = void 0;
4
+ exports.realmOf = realmOf;
5
+ exports.storefrontClientSecret = storefrontClientSecret;
6
+ exports.buildClients = buildClients;
7
+ exports.webClientSpec = webClientSpec;
8
+ exports.clientMetadata = clientMetadata;
9
+ const constants_1 = require("../constants");
10
+ const crypto_1 = require("../security/crypto");
11
+ exports.ADMIN_SCOPES = ['openid', 'profile', 'email', 'offline_access'];
12
+ const REALMS = {
13
+ [constants_1.ADMIN_CLIENT_ID]: 'admin',
14
+ [constants_1.STOREFRONT_CLIENT_ID]: 'customer',
15
+ [constants_1.STOREFRONT_MOBILE_CLIENT_ID]: 'customer',
16
+ [constants_1.STOREFRONT_WEB_CLIENT_ID]: 'customer',
17
+ };
18
+ /** The account realm of a built-in client id; `undefined` for anything else (never an account realm). */
19
+ function realmOf(clientId) {
20
+ return clientId !== undefined && Object.hasOwn(REALMS, clientId) ? REALMS[clientId] : undefined;
21
+ }
22
+ /** The storefront BFF's client secret: derived from OPENCLOUDCMS_SECRET (own HKDF label), never stored. */
23
+ function storefrontClientSecret(cfg) {
24
+ return (0, crypto_1.deriveKey)(cfg.secret, 'client-secret-storefront').toString('base64url');
25
+ }
26
+ /**
27
+ * The clients of this instance. Admin always; with `storefront.enabled` the storefront BFF, the mobile
28
+ * client (only when `storefront.mobile.redirectUris` is configured) and the web client (redirect URIs from
29
+ * the admin-managed CORS origins, `webRedirectUris`).
30
+ */
31
+ function buildClients(cfg, webRedirectUris) {
32
+ const clients = [
33
+ {
34
+ id: constants_1.ADMIN_CLIENT_ID,
35
+ realm: 'admin',
36
+ kind: 'confidential',
37
+ redirectUris: [`${cfg.publicUrl}/api/auth/callback`],
38
+ postLogoutRedirectUris: [`${cfg.publicUrl}/admin/login`],
39
+ refreshTokens: true,
40
+ loginPath: '/admin/login',
41
+ scopes: exports.ADMIN_SCOPES,
42
+ },
43
+ ];
44
+ const sf = cfg.storefront;
45
+ if (!sf?.enabled)
46
+ return clients;
47
+ clients.push({
48
+ id: constants_1.STOREFRONT_CLIENT_ID,
49
+ realm: 'customer',
50
+ kind: 'confidential',
51
+ redirectUris: [`${cfg.publicUrl}/api/customer/auth/callback`],
52
+ postLogoutRedirectUris: [`${cfg.publicUrl}/`],
53
+ refreshTokens: true,
54
+ loginPath: sf.loginPath,
55
+ scopes: constants_1.CUSTOMER_SCOPES,
56
+ });
57
+ if (sf.mobile?.redirectUris?.length) {
58
+ clients.push({
59
+ id: constants_1.STOREFRONT_MOBILE_CLIENT_ID,
60
+ realm: 'customer',
61
+ kind: 'public',
62
+ redirectUris: [...sf.mobile.redirectUris],
63
+ postLogoutRedirectUris: [...sf.mobile.redirectUris],
64
+ refreshTokens: true,
65
+ loginPath: sf.loginPath,
66
+ scopes: constants_1.CUSTOMER_SCOPES,
67
+ });
68
+ }
69
+ clients.push(webClientSpec(cfg, webRedirectUris));
70
+ return clients;
71
+ }
72
+ function webClientSpec(cfg, redirectUris) {
73
+ return {
74
+ id: constants_1.STOREFRONT_WEB_CLIENT_ID,
75
+ realm: 'customer',
76
+ kind: 'public',
77
+ redirectUris: [...redirectUris],
78
+ postLogoutRedirectUris: [...redirectUris],
79
+ refreshTokens: true,
80
+ loginPath: cfg.storefront.loginPath,
81
+ scopes: constants_1.CUSTOMER_SCOPES,
82
+ };
83
+ }
84
+ /**
85
+ * oidc-provider client metadata of a spec. Confidential clients authenticate with client_secret_basic;
86
+ * public ones with `none` (PKCE is required for every client by the provider config). The secret is
87
+ * added by the caller (static clients only); stored copies never carry it.
88
+ */
89
+ function clientMetadata(spec) {
90
+ const meta = {
91
+ client_id: spec.id,
92
+ token_endpoint_auth_method: spec.kind === 'confidential' ? 'client_secret_basic' : 'none',
93
+ redirect_uris: spec.redirectUris,
94
+ post_logout_redirect_uris: spec.postLogoutRedirectUris,
95
+ grant_types: spec.refreshTokens ? ['authorization_code', 'refresh_token'] : ['authorization_code'],
96
+ response_types: ['code'],
97
+ id_token_signed_response_alg: 'ES256',
98
+ };
99
+ // The admin client's metadata stays exactly as before this change.
100
+ if (spec.realm === 'customer')
101
+ meta.scope = spec.scopes.join(' ');
102
+ // Custom-scheme redirect URIs (com.example.app:/cb) are only valid for native clients.
103
+ if (spec.id === constants_1.STOREFRONT_MOBILE_CLIENT_ID)
104
+ meta.application_type = 'native';
105
+ return meta;
106
+ }
107
+ //# sourceMappingUR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B,SAAS,EAAE,GAAG,CAAC,UAAU,CAAC,SAAS;QACnC,MAAM,EAAE,2BAAe;KACxB,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAgB,cAAc,CAAC,IAAgB;IAC7C,MAAM,IAAI,GAA4B;QACpC,SAAS,EAAE,IAAI,CAAC,EAAE;QAClB,0BAA0B,EAAE,IAAI,CAAC,IAAI,KAAK,cAAc,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,CAAC,MAAM;QACzF,aAAa,EAAE,IAAI,CAAC,YAAY;QAChC,yBAAyB,EAAE,IAAI,CAAC,sBAAsB;QACtD,WAAW,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,oBAAoB,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC,CAAC,oBAAoB,CAAC;QAClG,cAAc,EAAE,CAAC,MAAM,CAAC;QACxB,4BAA4B,EAAE,OAAO;KACtC,CAAC;IACF,mEAAmE;IACnE,IAAI,IAAI,CAAC,KAAK,KAAK,UAAU;QAAE,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAClE,uFAAuF;IACvF,IAAI,IAAI,CAAC,EAAE,KAAK,uCAA2B;QAAE,IAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC;IAC9E,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,91 @@
1
+ import { ConfigError } from '../errors';
2
+ export { ConfigError };
3
+ export type Ttls = {
4
+ accessToken: number;
5
+ refreshToken: number;
6
+ sessionIdle: number;
7
+ sessionAbsolute: number;
8
+ authorizationCode: number;
9
+ interaction: number;
10
+ };
11
+ export type OtpLimits = {
12
+ ttlSec: number;
13
+ maxAttempts: number;
14
+ resendSec: number;
15
+ perIdentifierPerHour: number;
16
+ perIpPerHour: number;
17
+ };
18
+ export type StorefrontTtls = Pick<Ttls, 'accessToken' | 'refreshToken' | 'sessionIdle' | 'sessionAbsolute'>;
19
+ export type StorefrontConfig = {
20
+ enabled: boolean;
21
+ loginPath: string;
22
+ phoneRegion: string;
23
+ mobile?: {
24
+ redirectUris: string[];
25
+ };
26
+ otp: OtpLimits;
27
+ ttl: StorefrontTtls;
28
+ };
29
+ type RateRule = {
30
+ limit: number;
31
+ windowSec: number;
32
+ };
33
+ export type OAuth2Config = {
34
+ publicUrl: string;
35
+ internalUrl: string;
36
+ secret: Buffer;
37
+ ttl: Ttls;
38
+ password: {
39
+ minLength: number;
40
+ };
41
+ rateLimit: {
42
+ loginPerEmail: RateRule;
43
+ loginPerIp: RateRule;
44
+ };
45
+ idp: {
46
+ oidc?: {
47
+ issuer: string;
48
+ clientId: string;
49
+ clientSecret: string;
50
+ label: string;
51
+ };
52
+ };
53
+ admin: {
54
+ email?: string;
55
+ password?: string;
56
+ name?: string;
57
+ forceReset: boolean;
58
+ };
59
+ storefront: StorefrontConfig;
60
+ };
61
+ /** Non-secret part of `auth` in opencloudcms.config.ts. */
62
+ export type AuthFileConfig = {
63
+ publicUrl?: string;
64
+ ttl?: Partial<Ttls>;
65
+ password?: {
66
+ minLength?: number;
67
+ };
68
+ rateLimit?: {
69
+ loginPerEmail?: Partial<RateRule>;
70
+ loginPerIp?: Partial<RateRule>;
71
+ };
72
+ idp?: {
73
+ oidc?: {
74
+ issuer: string;
75
+ clientId: string;
76
+ clientSecret: string;
77
+ label?: string;
78
+ };
79
+ };
80
+ storefront?: {
81
+ enabled?: boolean;
82
+ loginPath?: string;
83
+ phoneRegion?: string;
84
+ mobile?: {
85
+ redirectUris: string[];
86
+ };
87
+ otp?: Partial<OtpLimits>;
88
+ ttl?: Partial<StorefrontTtls>;
89
+ };
90
+ };
91
+ export declare function loadConfig(env: NodeJS.ProcessEnv, file?: Partial<AuthFileConfig>): OAuth2Config;