@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ánh Nguyễn
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,398 @@
1
- # Temporary Holding Version
1
+ # @opencloudcms/oauth2
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Authentication for OpenCloudCMS: an embedded OAuth2/OIDC authorization server (`oidc-provider`) plus
4
+ backends-for-frontend (BFF) that keep all tokens on the server. The admin browser only ever holds an opaque,
5
+ httpOnly `oc_session` cookie; a storefront's shoppers (customers) get their own `oc_customer` cookie, and mobile apps
6
+ or storefronts on another domain use standard authorization code + PKCE.
7
+
8
+ - Authorization code + PKCE (S256 only), `refresh_token` grant, several clients in two account realms (admin users,
9
+ storefront customers), see [Clients and realms](#clients-and-realms).
10
+ - Local email/password (argon2id) and an optional generic OIDC identity provider.
11
+ - Permission groups (`super-admin` system group, `contenter`, `reviewer`), `@RequirePermission(...)`, user management API, first-run setup, audit events.
12
+ - Global `AuthGuard` on every `/api/**` route (opt out per handler with `@Public()`).
13
+ - Hourly cleanup of expired sessions and provider payloads.
14
+ - Storefront customers: phone or email, one-time code (OTP, pluggable generator and senders) or password,
15
+ `@CustomerAuth()` routes, customer auth hooks, sign-in methods and CORS origins managed in the admin. A project's
16
+ own customer routes go under `/api/store/**`: that is the only project prefix that gets customer-scope CORS.
17
+
18
+ ## Wiring
19
+
20
+ ```ts
21
+ import { OPENCLOUDCMS_DB } from '@opencloudcms/core';
22
+ import { OAuth2Module } from '@opencloudcms/oauth2';
23
+
24
+ @Module({
25
+ imports: [
26
+ OpenCloudCmsModule.forRoot({ /* ... */ }),
27
+ OAuth2Module.forRoot({
28
+ dbToken: OPENCLOUDCMS_DB, // DI token of the app's Kysely instance
29
+ auth: { /* non-secret auth options (the `auth` option of OpenCloudCmsModule.forRoot) */ },
30
+ publicPathPrefixes: ['/api/content/'], // default, see below
31
+ }),
32
+ ],
33
+ })
34
+ export class AppModule {}
35
+ ```
36
+
37
+ The package does not depend on `@opencloudcms/core`; you hand it the Kysely token.
38
+
39
+ Create the host app with `NestFactory.create(AppModule, { bodyParser: false })`. oidc-provider must read its
40
+ own request bodies, so Nest's default parser cannot run on `/oauth2`; `@opencloudcms/core` registers the JSON and
41
+ urlencoded parsers for the rest of the app (it skips `/oauth2/*` except the `/oauth2/interaction/*`
42
+ controllers, which need JSON). Without `bodyParser: false`, oidc-provider warns "already parsed request body
43
+ detected" (once) and falls back to the body Nest already parsed. It keeps working, but set the option so
44
+ oidc-provider reads its own requests as designed.
45
+
46
+ ### Migrations
47
+
48
+ Importing `@opencloudcms/oauth2` registers its core migrations (`oauth2_0001_init`, `oauth2_0002_user_locale`,
49
+ `oauth2_0003_groups`, `oauth2_0004_customers`) with `@opencloudcms/db`'s
50
+ `coreMigrator()`. Any process that runs migrations must therefore load the package first:
51
+
52
+ - The `opencloudcms` CLI and `@opencloudcms/core` do this themselves (`import '@opencloudcms/oauth2/migrations'`, a
53
+ Nest-free side-effect entry), so `opencloudcms migrate:up` / `migrate:status`, `autoMigrate` and the Content
54
+ Type Builder all see `core/oauth2_0001_init`.
55
+ - In your own scripts that use `@opencloudcms/db` without `@opencloudcms/core`, import `@opencloudcms/oauth2` (or
56
+ `@opencloudcms/oauth2/migrations`) **before** calling `coreMigrator(...)`, otherwise Kysely reports a missing
57
+ migration.
58
+
59
+ ## Configuration
60
+
61
+ `OPENCLOUDCMS_SECRET` is mandatory. `OPENCLOUDCMS_PUBLIC_URL` is optional outside production (default
62
+ `http://localhost:${PORT ?? 4000}`) and mandatory when `NODE_ENV=production`; the app refuses to start without them.
63
+ Env values override the `auth` option (of `OpenCloudCmsModule.forRoot`, or `OAuth2Module.forRoot` when wired by hand).
64
+
65
+ | Key | Default | Env |
66
+ |---|---|---|
67
+ | `publicUrl` | dev: `http://localhost:${PORT ?? 4000}`; production: required | `OPENCLOUDCMS_PUBLIC_URL` (issuer is `<publicUrl>/oauth2`; a trailing `/` is ignored) |
68
+ | secret | required, at least 32 bytes | `OPENCLOUDCMS_SECRET` |
69
+ | `ttl.accessToken` | 900 s | `OPENCLOUDCMS_AUTH_TTL_ACCESS` |
70
+ | `ttl.refreshToken` | 30 days | `OPENCLOUDCMS_AUTH_TTL_REFRESH` (clamped to the absolute session TTL) |
71
+ | `ttl.sessionIdle` | 7 days | `OPENCLOUDCMS_AUTH_TTL_SESSION_IDLE` |
72
+ | `ttl.sessionAbsolute` | 30 days | `OPENCLOUDCMS_AUTH_TTL_SESSION_ABSOLUTE` |
73
+ | `ttl.authorizationCode` | 60 s | config only |
74
+ | `ttl.interaction` | 10 min | config only |
75
+ | `password.minLength` | 12 (max 256) | config only |
76
+ | `rateLimit.login` | 5 / 15 min per email, 20 / 15 min per IP | config only |
77
+ | `idp.oidc` | disabled | `OPENCLOUDCMS_IDP_OIDC_ISSUER`, `OPENCLOUDCMS_IDP_OIDC_CLIENT_ID`, `OPENCLOUDCMS_IDP_OIDC_CLIENT_SECRET`, `OPENCLOUDCMS_IDP_OIDC_LABEL` |
78
+ | admin seed | none | `OPENCLOUDCMS_ADMIN_EMAIL`, `OPENCLOUDCMS_ADMIN_PASSWORD`, `OPENCLOUDCMS_ADMIN_NAME`, `OPENCLOUDCMS_ADMIN_FORCE_RESET` |
79
+ | `storefront.enabled` | `false` | config only (customer clients, routes and tables in use) |
80
+ | `storefront.loginPath` | `/account/login` | config only (the site's sign-in page; the provider sends `?uid=<interaction>`) |
81
+ | `storefront.phoneRegion` | `VN` | config only (region of phone numbers typed without `+`) |
82
+ | `storefront.mobile.redirectUris` | none (no mobile client) | config only |
83
+ | `storefront.otp` | `ttlSec: 300`, `maxAttempts: 5`, `resendSec: 60`, `perIdentifierPerHour: 5`, `perIpPerHour: 30` | config only |
84
+ | `storefront.ttl` | `accessToken: 900`, `refreshToken: 7776000` (90 days), `sessionIdle: 2592000` (30 days), `sessionAbsolute: 7776000` | config only; separate from the admin TTLs |
85
+
86
+ The BFF always calls its own provider at `http://127.0.0.1:${PORT ?? 4000}` (with the public URL's
87
+ `X-Forwarded-Proto`/`X-Forwarded-Host`; for an http public URL the provider applies that host only to
88
+ loopback peers, and only when it equals the public URL's host). There is no `internalUrl` setting and no `OPENCLOUDCMS_INTERNAL_URL`
89
+ (removed; a leftover value is ignored).
90
+
91
+ The rate limiter is in memory, so limits are per instance. It tracks at most 10 000 keys and drops the
92
+ oldest when full.
93
+
94
+ ## Endpoints
95
+
96
+ | Route | Purpose |
97
+ |---|---|
98
+ | `GET /api/auth/setup`, `POST /api/auth/setup` | First-run state / create the first super admin (public) |
99
+ | `GET /api/auth/login`, `GET /api/auth/callback` | Start / finish the browser login (BFF) |
100
+ | `GET /api/auth/me`, `POST /api/auth/logout` | Current user / end the session |
101
+ | `POST /api/auth/password` | Change own password |
102
+ | `GET/POST /api/admin/users`, `PATCH/DELETE /api/admin/users/:id`, `POST /api/admin/users/:id/password`, `DELETE /api/admin/users/:id/identities/:identityId` | User management (`settings.users`); create needs `groupIds` (≥ 1), `PATCH` takes `groupIds?` |
103
+ | `GET /api/admin/groups` | Groups with `roles` and `userCount` (`settings.groups` or `settings.users`) |
104
+ | `POST /api/admin/groups`, `PATCH/DELETE /api/admin/groups/:id`, `GET /api/admin/permissions` | Group management (`settings.groups`) |
105
+ | `/oauth2/*` | The OIDC provider (discovery, auth, token, jwks, end_session) and login interaction (`/oauth2/interaction/:uid`) |
106
+ | `/oauth2/interaction/:uid/idp/:provider`, `/oauth2/idp/:provider/callback` | External IdP sign-in |
107
+ | `GET /api/admin/customers?q=&limit=&offset=`, `GET /api/admin/customers/:id` | Customers, searched by identifier (`customers.read`) |
108
+ | `PATCH /api/admin/customers/:id` `{ status?: 'active' \| 'disabled', name? }` | Disable / rename a customer; disabling ends their sessions and grants (`customers.manage`) |
109
+ | `GET/PUT /api/admin/customer-auth/settings`, `POST …/preview` | Customer sign-in methods (`settings.customer-auth`), see [Admin settings](#admin-settings-customer-sign-in-and-cors) |
110
+ | `GET/POST /api/admin/cors-origins`, `PATCH/DELETE /api/admin/cors-origins/:id` | CORS origins and web redirect URIs (`settings.cors`) |
111
+
112
+ The customer routes (`/api/customer/**`, `/oauth2/interaction/:uid/customer/*`) are listed in
113
+ [Customer endpoints](#customer-endpoints).
114
+
115
+ Errors under `/api/**` look like `{ "error": { "code", "message", "issues"? } }`; failures inside the redirect chain
116
+ answer `302 /admin/login?error=<code>`.
117
+
118
+ ## Groups and permissions
119
+
120
+ Permissions are a fixed list (`PERMISSIONS` / `Permission`, defined in `@opencloudcms/schema` and re-exported here):
121
+ `content.read`, `content.create`, `content.update`, `content.delete`, `content.submit`, `content.publish`,
122
+ `settings.users`, `settings.groups`, `settings.content-types`, `settings.languages`, `customers.read`,
123
+ `customers.manage`, `settings.customer-auth`, `settings.cors`.
124
+
125
+ A **group** (`auth_groups`: `key`, `name`, `roles text[]`, `system`) holds a set of permissions; a user
126
+ (`auth_user_groups`) belongs to any number of groups and their effective permissions are the union, recomputed
127
+ on every request. Migration `oauth2_0003_groups` renames the former role tables to `auth_groups` and
128
+ `auth_user_groups` (`role_id` → `group_id`; see the root `CHANGELOG.md`), turns `super_admin` into the system group `super-admin` (existing
129
+ users keep it) and seeds two groups:
130
+
131
+ | Key | Name | Permissions |
132
+ |---|---|---|
133
+ | `super-admin` | Super Admin | all, including permissions added later (`system`: cannot be edited or deleted) |
134
+ | `contenter` | Contenter | `content.read`, `content.create`, `content.update`, `content.delete`, `content.submit` |
135
+ | `reviewer` | Reviewer | `content.read`, `content.update`, `content.publish` |
136
+
137
+ The setup wizard and the env admin seed put the user in `super-admin`. Removing the last active Super Admin
138
+ (removing the group, disabling or deleting the user) answers `409 last_super_admin`; the check holds row locks,
139
+ so two concurrent requests cannot both pass. Group keys match `^[a-z][a-z0-9-]{0,63}$` (taken → `409
140
+ group_key_taken`), names are 1–100 characters, unknown permissions → 422, changing a system group → `409
141
+ system_group`. Deleting a group removes it from its users.
142
+
143
+ Protect your own routes with `@RequirePermission(...)` (all listed permissions are required; on a class it
144
+ applies to every handler, and a method decorator adds to it). Missing → `403 { error: { code: 'forbidden',
145
+ message: 'Missing permission: <perm>' } }`; no session → 401. A route without the decorator needs only a
146
+ session. `@CurrentUser()` gives `{ id, email, name, locale, groups: { key, name }[], permissions, isSuperAdmin }`,
147
+ and `GET /api/auth/me` returns the same.
148
+
149
+ ```ts
150
+ @RequirePermission('content.publish')
151
+ @Post('feeds/rebuild')
152
+ rebuild(@CurrentUser() user: RequestUser) { /* ... */ }
153
+ ```
154
+
155
+ The former role decorator is removed (see the root `CHANGELOG.md`): guard each route with the permission it really needs.
156
+
157
+ **Escalation rules.** A user who is not a Super Admin (403 `forbidden` otherwise):
158
+
159
+ - cannot add to a group a permission they do not hold themselves (keeping or removing existing ones is fine);
160
+ - can only assign or remove (on create or `PATCH groupIds`) groups that are not `system` and whose permissions
161
+ are all within their own;
162
+ - cannot modify a Super Admin user at all: no name/email/status/group change, password reset, identity unlink
163
+ or delete.
164
+
165
+ These checks run before the last-Super-Admin rule. Group and user-group changes are audited (`group.create`,
166
+ `group.update`, `group.delete`, `user.groups.update`).
167
+
168
+ ## Setup flow
169
+
170
+ 1. Start the app against an empty database. `GET /api/auth/setup` returns `{ "required": true }` and every
171
+ protected API answers `409 setup_required`.
172
+ 2. `POST /api/auth/setup` with `{ email, name, password }` creates the first super admin (group `super-admin`). Afterwards it
173
+ answers `409 setup_already_completed`.
174
+ 3. Sign in through `GET /api/auth/login`. Access tokens refresh transparently on the server.
175
+
176
+ Alternatively seed the admin from env (`OPENCLOUDCMS_ADMIN_EMAIL`, `OPENCLOUDCMS_ADMIN_PASSWORD`, optional
177
+ `OPENCLOUDCMS_ADMIN_NAME`) at boot.
178
+
179
+ > **Warning: the setup wizard has no token.** While `auth_users` is empty, whoever reaches
180
+ > `POST /api/auth/setup` first becomes super admin. The only mitigation is a WARN log on every boot.
181
+ > In production, seed the admin through the environment variables above so the endpoint is never exposed
182
+ > on an empty database.
183
+
184
+ ## Running behind a reverse proxy
185
+
186
+ The package does not call `app.set('trust proxy', ...)`. Blindly trusting `X-Forwarded-For` would let any
187
+ client spoof its IP and dodge the per-IP login limit. If you terminate TLS in a proxy, set it yourself with
188
+ the exact number of proxy hops:
189
+
190
+ ```ts
191
+ const app = await NestFactory.create<NestExpressApplication>(AppModule, { bodyParser: false });
192
+ app.set('trust proxy', 1); // one proxy in front
193
+ ```
194
+
195
+ > **Warning.** Without it, every request appears to come from the proxy: **all users share one per-IP rate-limit
196
+ > bucket** (admin login, customer sign-in, OTP requests), so a few clients can lock everybody out. Set
197
+ `OPENCLOUDCMS_PUBLIC_URL` to the public https origin; the BFF reaches the provider on the loopback address by
198
+ itself, so nothing else is needed.
199
+
200
+ With an **http** public URL, the provider takes `Host` from `X-Forwarded-Host` only for loopback peers and
201
+ only when the value equals the public URL's host (that is how the BFF's own calls are handled). A client
202
+ header passed through by a same-host proxy is ignored, so no extra proxy configuration is needed.
203
+
204
+ ## Public path prefixes
205
+
206
+ `AuthGuard` protects every `/api/**` route, except routes whose path starts with one of
207
+ `publicPathPrefixes` (default `['/api/content/']`, the published-content delivery API). Matching is
208
+ case-insensitive, like Express routing, and needs the trailing slash: `/api/content/x` is public,
209
+ `/api/contents` is not. Pass `publicPathPrefixes: []` to protect everything.
210
+
211
+ ## Recovery
212
+
213
+ There is no password reset by email. Another super admin can reset the password, or set
214
+ `OPENCLOUDCMS_ADMIN_EMAIL`, `OPENCLOUDCMS_ADMIN_PASSWORD` and `OPENCLOUDCMS_ADMIN_FORCE_RESET=true` for one boot to reset
215
+ that existing account's password and re-activate it (remove the flag and password variable afterwards, or it resets on every boot).
216
+
217
+ ## Clients and realms
218
+
219
+ Clients are data, not a constant. Every client belongs to an **account realm**: `admin` (accounts in `auth_users`)
220
+ or `customer` (accounts in `auth_customers`). The account lookup, grants, interaction routes and guards all resolve
221
+ the realm from the client, so an account of one realm can never obtain tokens or sessions for a client of the other
222
+ (a browser signed in to the admin that opens a storefront authorize URL lands on the customer sign-in page).
223
+
224
+ | Client id | Realm | Kind | Redirect URIs | Present when |
225
+ |---|---|---|---|---|
226
+ | `opencloudcms-admin` | admin | confidential (BFF `/api/auth`) | `<publicUrl>/api/auth/callback` | always |
227
+ | `opencloudcms-storefront` | customer | confidential (the site's BFF `/api/customer/auth`; secret derived from `OPENCLOUDCMS_SECRET`) | `<publicUrl>/api/customer/auth/callback` | `storefront.enabled` |
228
+ | `opencloudcms-storefront-mobile` | customer | public, PKCE, refresh tokens | `storefront.mobile.redirectUris` | `storefront.enabled` and redirect URIs configured |
229
+ | `opencloudcms-storefront-web` | customer | public, PKCE, refresh tokens | the redirect URIs of the admin-managed CORS origins | `storefront.enabled` |
230
+
231
+ Customer clients get the scopes `openid profile email phone offline_access` and the storefront TTLs. Their
232
+ interaction URL is the site's `storefront.loginPath`.
233
+
234
+ ## Customer sign-in (storefront)
235
+
236
+ ```ts
237
+ // src/app.module.ts of a project
238
+ OpenCloudCmsModule.forRoot({
239
+ // ...
240
+ auth: { storefront: { enabled: true, mobile: { redirectUris: ['com.mystore.app:/oauth/callback'] } } },
241
+ authHooks: [authHooks], // src/extensions/auth.hooks.ts
242
+ otp: { senders: { sms: mySmsSender, email: myEmailSender } }, // generator: RandomOtpGenerator by default
243
+ });
244
+ ```
245
+
246
+ A **customer** has one or more identifiers: `email` (trimmed, lower-cased) and/or `phone` (normalized to E.164 with
247
+ `storefront.phoneRegion`: `0912 345 678`, `84912345678` and `+84912345678` are the same number). An identifier
248
+ belongs to at most one customer. Customers sign in with:
249
+
250
+ - **a one-time code (OTP)**: request a code for an identifier, then verify it. The first successful verification of
251
+ an unknown identifier creates the customer (sign-up). Codes are 6 digits, stored as HMAC-SHA256, single use,
252
+ expire after `otp.ttlSec`, allow `otp.maxAttempts` attempts, can be re-sent after `otp.resendSec`, and are rate
253
+ limited per identifier and per IP. A new code invalidates the previous one.
254
+ - **a password**: identifier + password, for a customer who set one (a customer may have none). Forgot password is a
255
+ `reset` code followed by a new password; it ends all of the customer's sessions.
256
+
257
+ Requesting a code (sign-in or reset) answers `202` immediately for known, unknown and disabled identifiers alike;
258
+ sending runs in the background and a sender failure is only logged and audited (`customer.otp_failed`).
259
+
260
+ ### The site (BFF)
261
+
262
+ `GET /api/customer/auth/login?returnTo=/account` starts the sign-in (as the confidential storefront client; tokens
263
+ never reach the browser). The provider redirects to `storefront.loginPath?uid=<uid>`, where the site's page posts
264
+ to the interaction routes below and follows the `redirectTo` they answer. The callback sets `oc_customer`
265
+ (httpOnly, `path=/`, its own table `auth_customer_sessions`) and redirects to `returnTo` (a same-site path).
266
+ Failures redirect to `storefront.loginPath?error=<code>`.
267
+
268
+ ### Mobile apps and storefronts on another domain
269
+
270
+ Standard OAuth: open `/oauth2/auth` (system browser) with `client_id=opencloudcms-storefront-mobile` (or
271
+ `-web`), PKCE S256 and one of the client's redirect URIs; the provider shows the site's sign-in page; exchange the
272
+ code at `/oauth2/token`, refresh there, revoke at `/oauth2/token/revocation`. Customer routes accept the access token
273
+ as `Authorization: Bearer <token>`. A browser storefront on another domain needs its origin allowed with *Customer API
274
+ & sign-in* (see [Admin settings](#admin-settings-customer-sign-in-and-cors)); its redirect URIs become the web
275
+ client's.
276
+
277
+ ### Customer endpoints
278
+
279
+ All answer `Cache-Control: no-store`; errors are `{ error: { code, message, issues? } }`. Cookie requests that
280
+ change something need a same-origin `Origin` header (`403 origin_mismatch`); bearer requests do not.
281
+
282
+ | Route | Purpose |
283
+ |---|---|
284
+ | `GET /api/customer/auth/methods` | Public: `{ email: { otp, password } \| null, phone: … \| null }`, the methods the admin turned on (`null` = kind off) |
285
+ | `GET /api/customer/auth/login?returnTo=`, `GET /api/customer/auth/callback` | Start / finish the site's sign-in (BFF) |
286
+ | `POST /oauth2/interaction/:uid/customer/otp` `{ identifier }` | Send a sign-in code → `202 { resendAfterSec }` |
287
+ | `POST /oauth2/interaction/:uid/customer/otp/verify` `{ identifier, code, name? }` | Verify it (unknown identifier: sign-up, `name` optional) → `{ redirectTo }` |
288
+ | `POST /oauth2/interaction/:uid/customer/password` `{ identifier, password }` | Password sign-in → `{ redirectTo }` |
289
+ | `GET /api/customer/auth/me` | `{ id, name, identifiers: { kind, value, verified }[] }` (cookie or bearer) |
290
+ | `POST /api/customer/auth/logout` | Cookie: ends the session and clears `oc_customer`; bearer: revokes the grant → `{ redirectTo }` |
291
+ | `POST /api/customer/account/password` `{ currentPassword?, newPassword }` | Set (no password yet) or change (current required; ends the other sessions) → 204 |
292
+ | `PATCH /api/customer/account` `{ name }` | Rename |
293
+ | `POST /api/customer/account/identifiers` `{ identifier }`, `POST …/identifiers/verify` `{ identifier, code }`, `DELETE …/identifiers/:id` | Add (verified by a code) / remove an identifier |
294
+ | `POST /api/customer/auth/password-reset` `{ identifier }`, `POST …/password-reset/confirm` `{ identifier, code, newPassword }` | Forgot password (public) |
295
+
296
+ Error codes: `invalid_identifier` 422, `identifier_kind_disabled` 422, `method_disabled` 422, `invalid_code` 401
297
+ (every refused code: wrong, expired, used up or never issued — customers never get `code_expired`; the real reason is
298
+ audited as `customer.otp_failed`), `invalid_credentials` 401, `account_disabled` 403, `rate_limited` 429 (`Retry-After`),
299
+ `unauthenticated` 401. An expired interaction answers `200 { redirectTo }` that starts over.
300
+
301
+ ### Your own customer routes: `@CustomerAuth()`
302
+
303
+ The prefix `/api/customer/**` belongs to this package; put project routes under `/api/store/**`. That prefix is the
304
+ convention: `@opencloudcms/core` applies customer-scope CORS to `/api/store/**` only, so a `@CustomerAuth()` route
305
+ elsewhere still authenticates customers but cannot be called from another origin's browser.
306
+
307
+ ```ts
308
+ import { CurrentCustomer, CustomerAuth, type RequestCustomer } from '@opencloudcms/core';
309
+
310
+ @CustomerAuth()
311
+ @Controller('api/store/orders')
312
+ export class OrdersController {
313
+ @Get()
314
+ list(@CurrentCustomer() customer: RequestCustomer) { /* customer.id, .name, .identifiers, .via, .clientId */ }
315
+ }
316
+ ```
317
+
318
+ `@CustomerAuth()` (on a class or a handler, on any path) authenticates with the customer realm only: the
319
+ `oc_customer` cookie or a customer bearer token. An admin session never satisfies it, and a customer credential never
320
+ satisfies any other route (admin routes keep requiring an admin session). A disabled customer is signed out on their
321
+ next request. Never take the customer id from the request body: use `@CurrentCustomer()`.
322
+
323
+ ### OTP: generator and senders
324
+
325
+ OTP has two pluggable parts. The `OtpService` issues and verifies codes; it never knows a fixed code.
326
+
327
+ - `generator: OtpGenerator` (`generate(): string`): `RandomOtpGenerator` (default, 6 crypto-random digits) or
328
+ `FixedOtpGenerator('123456')` (development and tests).
329
+ - `senders: { sms?: OtpSender, email?: OtpSender }` (`send({ channel, to, code, purpose, locale })`): one per
330
+ channel, supplied by the project (your SMS gateway, your mailer). `ConsoleOtpSender` logs the recipient and the code
331
+ (development).
332
+
333
+ **Production guard.** With `NODE_ENV=production` and `storefront.enabled`, the app refuses to start if the
334
+ generator is `FixedOtpGenerator`, or if an **enabled** identifier kind's channel (`phone` → `sms`, `email` →
335
+ `email`) has no sender or a `ConsoleOtpSender`. Turning such a kind on later in the admin answers
336
+ `409 otp_sender_missing`.
337
+
338
+ ### Customer auth hooks
339
+
340
+ ```ts
341
+ // src/extensions/auth.hooks.ts
342
+ import { AuthHookError, defineAuthHooks } from '@opencloudcms/core';
343
+
344
+ export default defineAuthHooks({
345
+ beforeSignUp: async (input) => ({ name: input.name ?? 'Shopper' }), // or throw new AuthHookError('code', 'message')
346
+ afterSignUp: async (customer, ctx) => {},
347
+ afterSignIn: async (customer, ctx) => {}, // ctx.method: 'otp' | 'password', ctx.clientId
348
+ afterSignOut: async (customer, ctx) => {},
349
+ afterPasswordChange: async (customer, ctx) => {}, // ctx.reason: 'set' | 'change' | 'reset'
350
+ });
351
+ ```
352
+
353
+ Pass them as `authHooks: [...]`. `ctx = { db, ip?, userAgent? }`. `after*` hooks run after the change is committed;
354
+ a `beforeSignUp` that throws `AuthHookError(code, message)` refuses the sign-up with `422 <code>`.
355
+
356
+ `afterSignIn` fires once per completed sign-in: for the site, in the BFF callback; for the mobile and web clients, when
357
+ the client exchanges the authorization code at `/oauth2/token`. That includes **silent SSO**: when a web or mobile
358
+ client gets a code without the sign-in page (the customer still has a provider session), the code exchange fires
359
+ `afterSignIn` again, with the `method` of the original sign-in. Treat it as "a client obtained tokens for this
360
+ customer", not "the customer typed a code or password".
361
+
362
+ ## Admin settings: customer sign-in and CORS
363
+
364
+ Both are stored in the database, audited and applied without a restart: each instance re-reads them at most every
365
+ 30 s, and immediately after its own write.
366
+
367
+ **Settings → Customer sign-in** (`settings.customer-auth`; `GET/PUT /api/admin/customer-auth/settings`, audited
368
+ `customer_auth.settings_update`). For each identifier kind (email, phone): on or off, and which methods it allows
369
+ (OTP, password). Defaults: both kinds on with both methods. A kind that is off answers `422 identifier_kind_disabled`
370
+ wherever it is used; a method that is off answers `422 method_disabled`; at least one kind with one method must stay
371
+ on (`422 no_sign_in_method`). Turning a kind off keeps the identifiers; the page first shows how many customers would
372
+ be left without a usable sign-in (`POST …/preview`) and asks to confirm.
373
+
374
+ **Settings → CORS origins** (`settings.cors`; `/api/admin/cors-origins`, audited `cors.create|update|delete`).
375
+ Each allowed origin (exact `scheme://host[:port]`, `https` except `localhost` / `127.0.0.1`) has a label and what it
376
+ may call from a browser:
377
+
378
+ - **Content API**: `/api/content/**`, methods `GET, HEAD, OPTIONS`;
379
+ - **Customer API & sign-in**: `/oauth2/token`, `/oauth2/token/revocation`, userinfo, `/api/customer/**` and the
380
+ project's routes under `/api/store/**` (only that prefix: a `@CustomerAuth()` route elsewhere gets no CORS), methods `GET, POST, PATCH, DELETE, OPTIONS`; plus its **redirect URIs** (same origin),
381
+ which become the `opencloudcms-storefront-web` client's redirect and post-logout URIs.
382
+
383
+ CORS answers allow the headers `Authorization, Content-Type`, always send `Vary: Origin` and never allow credentials:
384
+ cross-origin calls use `Authorization: Bearer`, never cookies. Origins from code (`cors.origins` of
385
+ `OpenCloudCmsModule.forRoot`) stay valid with the content scope and are shown read-only on the page.
386
+
387
+ ## Known limits
388
+
389
+ - The in-memory rate limiter (also used for OTP limits) is correct for a single instance only.
390
+ - Behind a proxy, set `trust proxy` (see [Running behind a reverse proxy](#running-behind-a-reverse-proxy)), or all
391
+ users share one per-IP rate-limit bucket.
392
+ - The per-identifier OTP limit (`otp.perIdentifierPerHour`, default 5 per hour) is keyed by the identifier, not by who
393
+ asks: a stranger who knows a customer's phone number or email can use up that budget and delay the customer's code
394
+ sign-in (and password reset) for up to an hour. Password sign-in is not affected. Raise the limit, or add your own
395
+ abuse checks (CAPTCHA, per-device limits) in front of the sign-in page, if that matters for your shop.
396
+ - Signing keys are not rotated automatically.
397
+ - The BFFs assume the admin UI, the site and the API share one origin.
398
+ - No SMS or email delivery ships with the package: bring your own `OtpSender`s.
@@ -0,0 +1,18 @@
1
+ import type { Kysely, Transaction } from 'kysely';
2
+ import type { AuthTables } from '../db/types';
3
+ export type AuditType = 'login_succeeded' | 'login_failed' | 'logout' | 'setup_completed' | 'admin_seeded_from_env' | 'admin_force_reset' | 'user_created' | 'user_disabled' | 'user_enabled' | 'user_deleted' | 'password_reset_by_admin' | 'password_changed' | 'idp_linked' | 'user.locale.update' | 'group.create' | 'group.update' | 'group.delete' | 'user.groups.update' | 'user.identity.unlink' | 'customer.otp_failed' | 'customer.update' | 'customer_auth.settings_update' | 'customer.otp_sent' | 'customer.signup' | 'customer.login_succeeded' | 'customer.login_failed' | 'customer.logout' | 'customer.password_set' | 'customer.password_changed' | 'customer.password_reset' | 'cors.create' | 'cors.update' | 'cors.delete' | 'content.submit' | 'content.withdraw' | 'content.reject' | 'content.publish' | 'content.approve';
4
+ export interface AuditEvent {
5
+ type: AuditType;
6
+ userId?: string;
7
+ actorId?: string;
8
+ /** The storefront customer the event is about (`auth_audit_events.customer_id`). For `customer.*` events it defaults to `meta.customerId`. */
9
+ customerId?: string;
10
+ ip?: string;
11
+ userAgent?: string;
12
+ meta?: Record<string, unknown>;
13
+ }
14
+ export declare class AuditService {
15
+ private readonly db;
16
+ constructor(db: Kysely<AuthTables>);
17
+ record(e: AuditEvent, trx?: Transaction<AuthTables>): Promise<void>;
18
+ }
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AuditService = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const constants_1 = require("../constants");
18
+ const SENSITIVE = ['password', 'token', 'cookie'];
19
+ function scrub(meta) {
20
+ const out = {};
21
+ for (const [k, v] of Object.entries(meta ?? {})) {
22
+ const lk = k.toLowerCase();
23
+ if (SENSITIVE.some((s) => lk.includes(s)))
24
+ continue;
25
+ out[k] = v;
26
+ }
27
+ return out;
28
+ }
29
+ const customerIdOf = (e) => {
30
+ if (e.customerId)
31
+ return e.customerId;
32
+ const fromMeta = e.meta?.customerId;
33
+ return e.type.startsWith('customer.') && typeof fromMeta === 'string' ? fromMeta : null;
34
+ };
35
+ let AuditService = class AuditService {
36
+ db;
37
+ constructor(db) {
38
+ this.db = db;
39
+ }
40
+ async record(e, trx) {
41
+ await (trx ?? this.db)
42
+ .insertInto('auth_audit_events')
43
+ .values({
44
+ type: e.type,
45
+ user_id: e.userId ?? null,
46
+ actor_id: e.actorId ?? null,
47
+ customer_id: customerIdOf(e),
48
+ ip: e.ip ?? null,
49
+ user_agent: e.userAgent ?? null,
50
+ meta: JSON.stringify(scrub(e.meta)),
51
+ })
52
+ .execute();
53
+ }
54
+ };
55
+ exports.AuditService = AuditService;
56
+ exports.AuditService = AuditService = __decorate([
57
+ (0, common_1.Injectable)(),
58
+ __param(0, (0, common_1.Inject)(constants_1.OAUTH2_DB)),
59
+ __metadata("design:paramtypes", [Function])
60
+ ], AuditService);
61
+ //# sourceMappingURL=audit.service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audit.service.js","sourceRoot":"","sources":["../../src/audit/audit.service.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAoD;AAEpD,4CAAyC;AA0BzC,MAAM,SAAS,GAAG,CAAC,UAAU,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;AAElD,SAAS,KAAK,CAAC,IAAyC;IACtD,MAAM,GAAG,GAA4B,EAAE,CAAC;IACxC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI,EAAE,CAAC,EAAE,CAAC;QAChD,MAAM,EAAE,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC;QAC3B,IAAI,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;YAAE,SAAS;QACpD,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IACb,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,YAAY,GAAG,CAAC,CAAa,EAAiB,EAAE;IACpD,IAAI,CAAC,CAAC,UAAU;QAAE,OAAO,CAAC,CAAC,UAAU,CAAC;IACtC,MAAM,QAAQ,GAAG,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC;IACpC,OAAO,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;AAC1F,CAAC,CAAC;AAGK,IAAM,YAAY,GAAlB,MAAM,YAAY;IACyB;IAAhD,YAAgD,EAAsB;QAAtB,OAAE,GAAF,EAAE,CAAoB;IAAG,CAAC;IAE1E,KAAK,CAAC,MAAM,CAAC,CAAa,EAAE,GAA6B;QACvD,MAAM,CAAC,GAAG,IAAI,IAAI,CAAC,EAAE,CAAC;aACnB,UAAU,CAAC,mBAAmB,CAAC;aAC/B,MAAM,CAAC;YACN,IAAI,EAAE,CAAC,CAAC,IAAI;YACZ,OAAO,EAAE,CAAC,CAAC,MAAM,IAAI,IAAI;YACzB,QAAQ,EAAE,CAAC,CAAC,OAAO,IAAI,IAAI;YAC3B,WAAW,EAAE,YAAY,CAAC,CAAC,CAAC;YAC5B,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,IAAI;YAChB,UAAU,EAAE,CAAC,CAAC,SAAS,IAAI,IAAI;YAC/B,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;SACpC,CAAC;aACD,OAAO,EAAE,CAAC;IACf,CAAC;CACF,CAAA;AAjBY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,mBAAU,GAAE;IAEE,WAAA,IAAA,eAAM,EAAC,qBAAS,CAAC,CAAA;;GADnB,YAAY,CAiBxB"}
@@ -0,0 +1,41 @@
1
+ import type { Request, Response } from 'express';
2
+ import { AuditService } from '../audit/audit.service';
3
+ import type { OAuth2Config } from '../config/schema';
4
+ import type { RequestUser } from '../guard/current-user.decorator';
5
+ import { SessionAuthenticator, type AuthenticatedRequest } from '../guard/session-auth.service';
6
+ import { SetupState } from '../setup/setup-state';
7
+ import type { AuthSettingsProvider } from '../settings/settings.provider';
8
+ import { UserService, type GrantRevoker } from '../users/user.service';
9
+ import { OidcClient } from './oidc-client';
10
+ import { SessionStore } from './session.store';
11
+ /**
12
+ * BFF side of spec §6.3 (steps 1–2 and 6), §6.5 (`me`) and §6.6 (`logout`): the server is the confidential
13
+ * client; the browser only ever gets `oc_login` (sealed PKCE/state) and `oc_session` (random id). No token
14
+ * leaves the server. login/callback/me are public (spec §3); logout goes through AuthGuard (Origin + session).
15
+ */
16
+ export declare class AuthController {
17
+ private readonly settings;
18
+ private readonly oidc;
19
+ private readonly sessions;
20
+ private readonly users;
21
+ private readonly setup;
22
+ private readonly auth;
23
+ private readonly audit;
24
+ private readonly revoker;
25
+ private readonly logger;
26
+ private readonly cookieKey;
27
+ private readonly secure;
28
+ constructor(cfg: OAuth2Config, settings: AuthSettingsProvider, oidc: OidcClient, sessions: SessionStore, users: UserService, setup: SetupState, auth: SessionAuthenticator, audit: AuditService, revoker: GrantRevoker);
29
+ login(req: Request, res: Response): Promise<void>;
30
+ callback(req: Request, res: Response): Promise<void>;
31
+ /** Public so it can answer setup_required itself; otherwise the guard's own session validation. */
32
+ me(req: AuthenticatedRequest, res: Response): Promise<RequestUser>;
33
+ /** Guarded (session + Origin): updates the caller's admin language; answers like `GET /me`. */
34
+ updateMe(req: AuthenticatedRequest, body: unknown): Promise<RequestUser>;
35
+ logout(req: AuthenticatedRequest, res: Response): Promise<{
36
+ redirectTo: string;
37
+ }>;
38
+ /** Logs the error name only: messages may echo request data, and nothing token-/cookie-bearing is logged. */
39
+ private fail;
40
+ private readLoginState;
41
+ }