@fabrika/iam 0.9.0-dev.32 → 0.9.0-dev.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/fabrika.config.ts +47 -7
- package/migrations/0032_second_factor.sql +29 -0
- package/migrations/0033_oauth_grant_resources.sql +6 -0
- package/migrations/0034_oauth_device_authorizations.sql +24 -0
- package/migrations-postgres/0032_second_factor.sql +29 -0
- package/migrations-postgres/0033_oauth_grant_resources.sql +6 -0
- package/migrations-postgres/0034_oauth_device_authorizations.sql +24 -0
- package/package.json +12 -10
- package/src/admin/api-keys.ts +15 -5
- package/src/admin/grant-support.ts +10 -0
- package/src/admin/grants.ts +5 -2
- package/src/admin/handlers.ts +3 -0
- package/src/admin/principals.ts +2 -5
- package/src/admin/rpc.ts +8 -0
- package/src/admin/second-factor.ts +39 -0
- package/src/admin/sessions.ts +4 -4
- package/src/app.ts +1 -1
- package/src/auth/failure.ts +5 -0
- package/src/auth/http.ts +1 -1
- package/src/auth/invitations.ts +11 -3
- package/src/auth/login.ts +3 -2
- package/src/auth/oidc.ts +1 -1
- package/src/auth/password.ts +6 -6
- package/src/auth/routes.ts +11 -3
- package/src/auth/second-factor-challenge.ts +114 -0
- package/src/auth/second-factor.ts +276 -0
- package/src/auth/sessions.ts +72 -21
- package/src/auth.ts +19 -4
- package/src/catalog/cs.ts +32 -0
- package/src/catalog/en.ts +33 -0
- package/src/catalog/index.ts +28 -0
- package/src/catalog/uk.ts +33 -0
- package/src/data-key.ts +92 -0
- package/src/db.ts +12 -1
- package/src/env.ts +15 -2
- package/src/node/runtime.ts +7 -0
- package/src/oauth-client-auth.ts +6 -2
- package/src/oauth-config.ts +5 -5
- package/src/oauth-device-page.ts +173 -0
- package/src/oauth-device.ts +265 -0
- package/src/oauth-http.ts +53 -7
- package/src/oauth.ts +105 -37
- package/src/oidc-session.ts +25 -0
- package/src/repositories/audit.ts +4 -2
- package/src/repositories/oauth.ts +171 -4
- package/src/repositories/second-factors.ts +165 -0
- package/src/repositories/sessions.ts +17 -9
- package/src/second-factor-pages.ts +129 -0
- package/src/services.ts +11 -2
- package/src/tokens.ts +3 -3
- package/src/totp.ts +132 -0
- package/types/src/admin/api-keys.d.ts +3 -3
- package/types/src/admin/grant-support.d.ts +2 -0
- package/types/src/admin/handlers.d.ts +3 -0
- package/types/src/admin/second-factor.d.ts +5 -0
- package/types/src/auth/failure.d.ts +10 -0
- package/types/src/auth/http.d.ts +1 -1
- package/types/src/auth/invitations.d.ts +2 -1
- package/types/src/auth/password.d.ts +1 -1
- package/types/src/auth/second-factor-challenge.d.ts +34 -0
- package/types/src/auth/second-factor.d.ts +19 -0
- package/types/src/auth/sessions.d.ts +22 -9
- package/types/src/auth.d.ts +9 -3
- package/types/src/catalog/index.d.ts +28 -0
- package/types/src/data-key.d.ts +19 -0
- package/types/src/db.d.ts +4 -1
- package/types/src/env.d.ts +15 -2
- package/types/src/oauth-config.d.ts +3 -3
- package/types/src/oauth-device-page.d.ts +7 -0
- package/types/src/oauth-device.d.ts +51 -0
- package/types/src/oauth-http.d.ts +5 -2
- package/types/src/oauth.d.ts +34 -8
- package/types/src/oidc-session.d.ts +12 -0
- package/types/src/repositories/audit.d.ts +2 -1
- package/types/src/repositories/oauth.d.ts +48 -1
- package/types/src/repositories/second-factors.d.ts +68 -0
- package/types/src/repositories/sessions.d.ts +7 -3
- package/types/src/rpc-inputs.d.ts +23 -23
- package/types/src/second-factor-pages.d.ts +42 -0
- package/types/src/services.d.ts +4 -0
- package/types/src/totp.d.ts +32 -0
package/src/auth.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { API_KEY_PREFIX, isWorkloadKind, type PermissionEntry, type PrincipalType, type TokenPrincipalType } from '@fabrika/auth-core'
|
|
2
|
-
import type {
|
|
2
|
+
import type { SignedInSessionRow } from './db'
|
|
3
3
|
import type { Env } from './env'
|
|
4
4
|
import { hashToken, timingSafeEqualHex } from './secret'
|
|
5
5
|
import type { Config, Services } from './services'
|
|
@@ -11,23 +11,28 @@ export const LOCAL_DEV_ADMIN_ID = 'local-dev-admin'
|
|
|
11
11
|
export const LOCAL_DEV_ADMIN_EMAIL = 'admin@local.test'
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
|
-
* May this session still be used, given what the installation enables NOW?
|
|
14
|
+
* May this session still be used at `now` (unix seconds), given what the installation enables NOW?
|
|
15
15
|
*
|
|
16
16
|
* **Checked at USE, not at creation, and that is the point.** Turning a method off changes what the
|
|
17
17
|
* next login may do and nothing about what was already issued. Sessions live 30 days, so an
|
|
18
18
|
* installation that moved to password-only kept honouring every OIDC login for a month — and, for the
|
|
19
19
|
* bypass, every one of those is a global admin.
|
|
20
20
|
*
|
|
21
|
+
* An OIDC login is usable for `sessionCapSeconds` after it signed in; then the provider is asked again, so a person
|
|
22
|
+
* blocked there loses access within the cap. Measured here, from the login's sign-in, so it also ends logins issued
|
|
23
|
+
* before the cap was lowered, and the app sessions derived from them.
|
|
24
|
+
*
|
|
21
25
|
* The bypass carries `local_dev` as its own method rather than an exemption
|
|
22
26
|
* here, so this stays a total function over the enum: a method added later has to answer the question.
|
|
23
27
|
*/
|
|
24
28
|
export function sessionUsable(
|
|
25
|
-
session: Pick<
|
|
29
|
+
session: Pick<SignedInSessionRow, 'authentication_method' | 'expires_at' | 'signed_in_at'>,
|
|
26
30
|
config: Pick<Config, 'authentication' | 'localDevLogin'>,
|
|
31
|
+
now: number,
|
|
27
32
|
): boolean {
|
|
28
33
|
switch (session.authentication_method) {
|
|
29
34
|
case 'oidc':
|
|
30
|
-
return config.authentication.oidc.enabled
|
|
35
|
+
return config.authentication.oidc.enabled && now < sessionEndsAt(session, config)
|
|
31
36
|
case 'password':
|
|
32
37
|
return config.authentication.password.enabled
|
|
33
38
|
case 'local_dev':
|
|
@@ -38,6 +43,16 @@ export function sessionUsable(
|
|
|
38
43
|
}
|
|
39
44
|
}
|
|
40
45
|
|
|
46
|
+
/** When a session ends by its own clock: its expiry, or earlier for an OIDC login, its sign-in plus the installation's cap. */
|
|
47
|
+
export function sessionEndsAt(
|
|
48
|
+
session: Pick<SignedInSessionRow, 'authentication_method' | 'expires_at' | 'signed_in_at'>,
|
|
49
|
+
config: Pick<Config, 'authentication'>,
|
|
50
|
+
): number {
|
|
51
|
+
return session.authentication_method === 'oidc'
|
|
52
|
+
? Math.min(session.expires_at, session.signed_in_at + config.authentication.oidc.sessionCapSeconds)
|
|
53
|
+
: session.expires_at
|
|
54
|
+
}
|
|
55
|
+
|
|
41
56
|
/**
|
|
42
57
|
* Fixed identity for the SEEDED PROVISIONING KEY below. A stable `service` principal with this id is
|
|
43
58
|
* seeded into `principals` (migration `0001_init.sql`) so the audit the provisioning
|
package/src/catalog/cs.ts
CHANGED
|
@@ -90,6 +90,12 @@ export const cs: Catalog = {
|
|
|
90
90
|
return 'Registrace teď není k dispozici. Zkuste to později.'
|
|
91
91
|
case 'terminal_completion_refused':
|
|
92
92
|
return 'Toto přihlášení vypršelo nebo už bylo použito. Identifikujte se znovu.'
|
|
93
|
+
case 'second_factor_expired':
|
|
94
|
+
return 'Přihlášení vypršelo dřív, než jste zadali kód. Přihlaste se znovu.'
|
|
95
|
+
case 'second_factor_not_allowed':
|
|
96
|
+
return 'Dvoufázové přihlášení si nastavíte po přihlášení účtem administrátora.'
|
|
97
|
+
case 'second_factor_unavailable':
|
|
98
|
+
return 'Dvoufázové přihlášení teď není k dispozici. Zkuste to později.'
|
|
93
99
|
}
|
|
94
100
|
},
|
|
95
101
|
},
|
|
@@ -113,6 +119,32 @@ export const cs: Catalog = {
|
|
|
113
119
|
enrolledTitle: 'Terminál je zaregistrovaný',
|
|
114
120
|
enrolledText: (label) => `Tento prohlížeč je teď terminál ${label}. Jste odhlášeni. Které aplikace obsluhuje, nastaví administrátor.`,
|
|
115
121
|
},
|
|
122
|
+
secondFactor: {
|
|
123
|
+
challengeTitle: 'Dvoufázové přihlášení',
|
|
124
|
+
challengeText: 'Zadejte šestimístný kód z ověřovací aplikace, nebo jeden ze svých záložních kódů.',
|
|
125
|
+
codeLabel: 'Kód',
|
|
126
|
+
submit: 'Ověřit',
|
|
127
|
+
invalidCode: 'Tento kód neplatí. Zadejte aktuální kód, nebo záložní kód, který jste ještě nepoužili.',
|
|
128
|
+
throttled: 'Příliš mnoho chybných kódů. Počkejte 15 minut a zkuste to znovu.',
|
|
129
|
+
appCodesUnavailable: 'Kódy z ověřovací aplikace tu teď nejde ověřit. Použijte záložní kód, nebo se obraťte na administrátora.',
|
|
130
|
+
startOver: 'Přihlásit se znovu',
|
|
131
|
+
enrolTitle: 'Nastavit dvoufázové přihlášení',
|
|
132
|
+
enrolText:
|
|
133
|
+
'Po hesle nebo jednotném přihlášení si každé přihlášení k tomuto účtu vyžádá kód z ověřovací aplikace ve vašem telefonu. Dostanete také záložní kódy pro chvíle, kdy telefon nemáte po ruce.',
|
|
134
|
+
start: 'Nastavit ověřovací aplikaci',
|
|
135
|
+
scanText: 'Naskenujte QR kód ověřovací aplikací, nebo do ní opište klíč. Pak zadejte šestimístný kód, který zobrazí.',
|
|
136
|
+
secretLabel: 'Klíč',
|
|
137
|
+
confirmLabel: 'Kód z aplikace',
|
|
138
|
+
confirm: 'Zapnout dvoufázové přihlášení',
|
|
139
|
+
enrolledTitle: 'Dvoufázové přihlášení je zapnuté',
|
|
140
|
+
enrolledText: (enrolledOn, left) =>
|
|
141
|
+
`Od ${enrolledOn} si každé přihlášení k tomuto účtu vyžádá kód. Zbývající záložní kódy: ${left}. Při přechodu na nový telefon požádejte administrátora o zrušení ověřovací aplikace.`,
|
|
142
|
+
recoveryTitle: 'Uložte si záložní kódy',
|
|
143
|
+
recoveryText: 'Každý kód vás jednou přihlásí, když telefon nemáte po ruce. Zobrazují se jen teď: uložte je na bezpečné místo mimo telefon.',
|
|
144
|
+
continue: 'Pokračovat',
|
|
145
|
+
unavailableTitle: 'Dvoufázové přihlášení není k dispozici',
|
|
146
|
+
unavailableText: 'Tato instalace zatím neumí ukládat klíče ověřovacích aplikací. Požádejte jejího provozovatele o nastavení.',
|
|
147
|
+
},
|
|
116
148
|
invitation: {
|
|
117
149
|
title: 'Přijetí pozvánky',
|
|
118
150
|
text: 'Přijměte pozvánku. V dalším kroku se přihlásíte pozvanou adresou, nebo si zvolíte heslo, pokud pozvánka zakládá nový účet.',
|
package/src/catalog/en.ts
CHANGED
|
@@ -90,6 +90,12 @@ export const en: Catalog = {
|
|
|
90
90
|
return 'Enrolment is unavailable. Try again later.'
|
|
91
91
|
case 'terminal_completion_refused':
|
|
92
92
|
return 'This sign-in has expired or was already used. Identify again.'
|
|
93
|
+
case 'second_factor_expired':
|
|
94
|
+
return 'Your sign-in expired before the code was entered. Sign in again.'
|
|
95
|
+
case 'second_factor_not_allowed':
|
|
96
|
+
return 'Sign in with an administrator account to set up two-step sign-in.'
|
|
97
|
+
case 'second_factor_unavailable':
|
|
98
|
+
return 'Two-step sign-in is unavailable. Try again later.'
|
|
93
99
|
}
|
|
94
100
|
},
|
|
95
101
|
},
|
|
@@ -113,6 +119,33 @@ export const en: Catalog = {
|
|
|
113
119
|
enrolledTitle: 'Terminal enrolled',
|
|
114
120
|
enrolledText: (label) => `This browser is now the terminal ${label}. You are signed out. An administrator sets which applications it serves.`,
|
|
115
121
|
},
|
|
122
|
+
secondFactor: {
|
|
123
|
+
challengeTitle: 'Two-step sign-in',
|
|
124
|
+
challengeText: 'Enter the 6-digit code from your authenticator app, or one of your recovery codes.',
|
|
125
|
+
codeLabel: 'Code',
|
|
126
|
+
submit: 'Verify',
|
|
127
|
+
invalidCode: 'This code is not valid. Enter the current code, or a recovery code you have not used.',
|
|
128
|
+
throttled: 'Too many wrong codes. Wait 15 minutes, then try again.',
|
|
129
|
+
appCodesUnavailable: 'Codes from the authenticator app cannot be checked here right now. Use a recovery code, or ask an administrator.',
|
|
130
|
+
startOver: 'Sign in again',
|
|
131
|
+
enrolTitle: 'Set up two-step sign-in',
|
|
132
|
+
enrolText:
|
|
133
|
+
'After the password or single sign-on, every sign-in to this account will ask for a code from an authenticator app on your phone. You will also get recovery codes for when the phone is not at hand.',
|
|
134
|
+
start: 'Set up an authenticator app',
|
|
135
|
+
scanText: 'Scan the QR code with your authenticator app, or type the key into it. Then enter the 6-digit code it shows.',
|
|
136
|
+
secretLabel: 'Key',
|
|
137
|
+
confirmLabel: 'Code from the app',
|
|
138
|
+
confirm: 'Turn on two-step sign-in',
|
|
139
|
+
enrolledTitle: 'Two-step sign-in is on',
|
|
140
|
+
enrolledText: (enrolledOn, left) =>
|
|
141
|
+
`Since ${enrolledOn} every sign-in to this account asks for a code. Recovery codes left: ${left}. To move to a new phone, ask an administrator to reset your authenticator.`,
|
|
142
|
+
recoveryTitle: 'Save your recovery codes',
|
|
143
|
+
recoveryText:
|
|
144
|
+
'Each code signs you in once when your phone is not at hand. They are shown only now: store them somewhere safe, apart from your phone.',
|
|
145
|
+
continue: 'Continue',
|
|
146
|
+
unavailableTitle: 'Two-step sign-in is unavailable',
|
|
147
|
+
unavailableText: 'This installation cannot store authenticator keys yet. Ask its operator to set it up.',
|
|
148
|
+
},
|
|
116
149
|
invitation: {
|
|
117
150
|
title: 'Accept invitation',
|
|
118
151
|
text:
|
package/src/catalog/index.ts
CHANGED
|
@@ -75,6 +75,34 @@ export interface PageText {
|
|
|
75
75
|
readonly enrolledTitle: string
|
|
76
76
|
readonly enrolledText: (label: string) => string
|
|
77
77
|
}
|
|
78
|
+
/** The second factor (TOTP): the code a sign-in asks for, and enrolling an authenticator app. */
|
|
79
|
+
readonly secondFactor: {
|
|
80
|
+
readonly challengeTitle: string
|
|
81
|
+
readonly challengeText: string
|
|
82
|
+
readonly codeLabel: string
|
|
83
|
+
readonly submit: string
|
|
84
|
+
readonly invalidCode: string
|
|
85
|
+
/** Too many wrong codes for this account; the next attempt waits. */
|
|
86
|
+
readonly throttled: string
|
|
87
|
+
/** The data key is unset or does not open the secret: only a recovery code signs in. */
|
|
88
|
+
readonly appCodesUnavailable: string
|
|
89
|
+
readonly startOver: string
|
|
90
|
+
readonly enrolTitle: string
|
|
91
|
+
readonly enrolText: string
|
|
92
|
+
readonly start: string
|
|
93
|
+
readonly scanText: string
|
|
94
|
+
readonly secretLabel: string
|
|
95
|
+
readonly confirmLabel: string
|
|
96
|
+
readonly confirm: string
|
|
97
|
+
readonly enrolledTitle: string
|
|
98
|
+
/** `enrolledOn` is an ISO date; `left` the recovery codes not used yet. */
|
|
99
|
+
readonly enrolledText: (enrolledOn: string, left: number) => string
|
|
100
|
+
readonly recoveryTitle: string
|
|
101
|
+
readonly recoveryText: string
|
|
102
|
+
readonly continue: string
|
|
103
|
+
readonly unavailableTitle: string
|
|
104
|
+
readonly unavailableText: string
|
|
105
|
+
}
|
|
78
106
|
readonly invitation: {
|
|
79
107
|
readonly title: string
|
|
80
108
|
readonly text: string
|
package/src/catalog/uk.ts
CHANGED
|
@@ -91,6 +91,12 @@ export const uk: Catalog = {
|
|
|
91
91
|
return 'Реєстрація зараз недоступна. Спробуйте пізніше.'
|
|
92
92
|
case 'terminal_completion_refused':
|
|
93
93
|
return 'Цей вхід застарів або вже використаний. Ідентифікуйтеся ще раз.'
|
|
94
|
+
case 'second_factor_expired':
|
|
95
|
+
return 'Вхід завершився раніше, ніж ви ввели код. Увійдіть ще раз.'
|
|
96
|
+
case 'second_factor_not_allowed':
|
|
97
|
+
return 'Щоб налаштувати двоетапний вхід, увійдіть з обліковим записом адміністратора.'
|
|
98
|
+
case 'second_factor_unavailable':
|
|
99
|
+
return 'Двоетапний вхід зараз недоступний. Спробуйте пізніше.'
|
|
94
100
|
}
|
|
95
101
|
},
|
|
96
102
|
},
|
|
@@ -114,6 +120,33 @@ export const uk: Catalog = {
|
|
|
114
120
|
enrolledTitle: 'Термінал зареєстровано',
|
|
115
121
|
enrolledText: (label) => `Цей браузер тепер є терміналом «${label}». Ви вийшли. Які застосунки він обслуговує, визначає адміністратор.`,
|
|
116
122
|
},
|
|
123
|
+
secondFactor: {
|
|
124
|
+
challengeTitle: 'Двоетапний вхід',
|
|
125
|
+
challengeText: 'Введіть шестизначний код із застосунку автентифікації або один зі своїх резервних кодів.',
|
|
126
|
+
codeLabel: 'Код',
|
|
127
|
+
submit: 'Підтвердити',
|
|
128
|
+
invalidCode: 'Цей код недійсний. Введіть поточний код або резервний код, який ви ще не використали.',
|
|
129
|
+
throttled: 'Забагато неправильних кодів. Зачекайте 15 хвилин і спробуйте ще раз.',
|
|
130
|
+
appCodesUnavailable: 'Коди із застосунку автентифікації зараз не можна перевірити. Використайте резервний код або зверніться до адміністратора.',
|
|
131
|
+
startOver: 'Увійти ще раз',
|
|
132
|
+
enrolTitle: 'Налаштувати двоетапний вхід',
|
|
133
|
+
enrolText:
|
|
134
|
+
'Після пароля або єдиного входу кожен вхід до цього облікового запису вимагатиме код із застосунку автентифікації на вашому телефоні. Ви також отримаєте резервні коди на випадок, коли телефона немає під рукою.',
|
|
135
|
+
start: 'Налаштувати застосунок автентифікації',
|
|
136
|
+
scanText: 'Відскануйте QR-код застосунком автентифікації або введіть у нього ключ. Потім введіть шестизначний код, який він покаже.',
|
|
137
|
+
secretLabel: 'Ключ',
|
|
138
|
+
confirmLabel: 'Код із застосунку',
|
|
139
|
+
confirm: 'Увімкнути двоетапний вхід',
|
|
140
|
+
enrolledTitle: 'Двоетапний вхід увімкнено',
|
|
141
|
+
enrolledText: (enrolledOn, left) =>
|
|
142
|
+
`Від ${enrolledOn} кожен вхід до цього облікового запису вимагає код. Залишилося резервних кодів: ${left}. Щоб перейти на новий телефон, попросіть адміністратора скинути застосунок автентифікації.`,
|
|
143
|
+
recoveryTitle: 'Збережіть резервні коди',
|
|
144
|
+
recoveryText:
|
|
145
|
+
'Кожен код один раз впустить вас, коли телефона немає під рукою. Вони показуються лише зараз: збережіть їх у безпечному місці окремо від телефона.',
|
|
146
|
+
continue: 'Продовжити',
|
|
147
|
+
unavailableTitle: 'Двоетапний вхід недоступний',
|
|
148
|
+
unavailableText: 'Ця інсталяція ще не вміє зберігати ключі застосунків автентифікації. Попросіть її оператора налаштувати це.',
|
|
149
|
+
},
|
|
117
150
|
invitation: {
|
|
118
151
|
title: 'Прийняття запрошення',
|
|
119
152
|
text:
|
package/src/data-key.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// IAM's one value it must read back and so cannot hash: a TOTP secret. Sealed with Control's vault construction
|
|
2
|
+
// (`packages/control/src/vault.ts`): AES-256-GCM under a fresh data key per value, that data key wrapped by the
|
|
3
|
+
// installation's `FABRIKA_IAM_DATA_KEY`. Unlike the vault, both layers carry associated data naming the value's owner,
|
|
4
|
+
// so a writer of IAM's database who moves a sealed value into another row moves nothing that opens there.
|
|
5
|
+
|
|
6
|
+
const ALG = 'AES-GCM'
|
|
7
|
+
/** GCM's standard nonce, fresh per encryption. */
|
|
8
|
+
const IV_BYTES = 12
|
|
9
|
+
/** AES-256: the installation's key and each data key. */
|
|
10
|
+
export const DATA_KEY_BYTES = 32
|
|
11
|
+
|
|
12
|
+
/** The sealed pieces as stored: all base64, never a plaintext value or data key. */
|
|
13
|
+
export interface SealedValue {
|
|
14
|
+
readonly ciphertext: string
|
|
15
|
+
readonly valueIv: string
|
|
16
|
+
readonly wrappedDek: string
|
|
17
|
+
readonly dekIv: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Parse `FABRIKA_IAM_DATA_KEY` (base64 of 32 random bytes) once at boot. Unset or empty is null: nothing can be sealed,
|
|
22
|
+
* so TOTP enrolment is unavailable. Anything else that is not 32 bytes fails the boot; a short key would be a weak key
|
|
23
|
+
* nobody notices.
|
|
24
|
+
*/
|
|
25
|
+
export function parseDataKey(raw: string | undefined): Uint8Array<ArrayBuffer> | null {
|
|
26
|
+
if (raw === undefined || raw.trim() === '') return null
|
|
27
|
+
let decoded: Uint8Array<ArrayBuffer>
|
|
28
|
+
try {
|
|
29
|
+
decoded = fromBase64(raw.trim())
|
|
30
|
+
} catch {
|
|
31
|
+
throw new Error('FABRIKA_IAM_DATA_KEY is not base64 — generate it with: head -c 32 /dev/urandom | base64')
|
|
32
|
+
}
|
|
33
|
+
if (decoded.length !== DATA_KEY_BYTES) {
|
|
34
|
+
throw new Error(`FABRIKA_IAM_DATA_KEY must be ${DATA_KEY_BYTES} bytes — generate it with: head -c 32 /dev/urandom | base64`)
|
|
35
|
+
}
|
|
36
|
+
return decoded
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Seal `value` for `owner` (the associated data of both layers). */
|
|
40
|
+
export async function sealValue(dataKey: Uint8Array<ArrayBuffer>, owner: string, value: Uint8Array<ArrayBuffer>): Promise<SealedValue> {
|
|
41
|
+
const additionalData = utf8(owner)
|
|
42
|
+
const kek = await importKey(dataKey, ['encrypt'])
|
|
43
|
+
const dek = await crypto.subtle.generateKey({ name: ALG, length: 256 }, true, ['encrypt', 'decrypt'])
|
|
44
|
+
const valueIv = randomIv()
|
|
45
|
+
const ciphertext = await crypto.subtle.encrypt({ name: ALG, iv: valueIv, additionalData }, dek, value)
|
|
46
|
+
const dekIv = randomIv()
|
|
47
|
+
const wrappedDek = await crypto.subtle.encrypt({ name: ALG, iv: dekIv, additionalData }, kek, copy(await crypto.subtle.exportKey('raw', dek)))
|
|
48
|
+
return { ciphertext: toBase64(ciphertext), valueIv: toBase64(valueIv), wrappedDek: toBase64(wrappedDek), dekIv: toBase64(dekIv) }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Open a value `sealValue` sealed for `owner`. A wrong key, another owner or any tampered piece throws. */
|
|
52
|
+
export async function openValue(dataKey: Uint8Array<ArrayBuffer>, owner: string, sealed: SealedValue): Promise<Uint8Array<ArrayBuffer>> {
|
|
53
|
+
const additionalData = utf8(owner)
|
|
54
|
+
const kek = await importKey(dataKey, ['decrypt'])
|
|
55
|
+
const dekRaw = await crypto.subtle.decrypt({ name: ALG, iv: fromBase64(sealed.dekIv), additionalData }, kek, fromBase64(sealed.wrappedDek))
|
|
56
|
+
const dek = await crypto.subtle.importKey('raw', copy(dekRaw), { name: ALG }, false, ['decrypt'])
|
|
57
|
+
const value = await crypto.subtle.decrypt({ name: ALG, iv: fromBase64(sealed.valueIv), additionalData }, dek, fromBase64(sealed.ciphertext))
|
|
58
|
+
return copy(value)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function importKey(raw: Uint8Array<ArrayBuffer>, usages: KeyUsage[]): Promise<CryptoKey> {
|
|
62
|
+
return crypto.subtle.importKey('raw', raw, { name: ALG }, false, usages)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function randomIv(): Uint8Array<ArrayBuffer> {
|
|
66
|
+
return crypto.getRandomValues(new Uint8Array(new ArrayBuffer(IV_BYTES)))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function utf8(text: string): Uint8Array<ArrayBuffer> {
|
|
70
|
+
return copy(new TextEncoder().encode(text))
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A copy backed by a fresh `ArrayBuffer`, which WebCrypto's `BufferSource` requires. */
|
|
74
|
+
function copy(view: Uint8Array | ArrayBuffer): Uint8Array<ArrayBuffer> {
|
|
75
|
+
const source = view instanceof ArrayBuffer ? new Uint8Array(view) : view
|
|
76
|
+
const out = new Uint8Array(new ArrayBuffer(source.byteLength))
|
|
77
|
+
out.set(source)
|
|
78
|
+
return out
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function toBase64(view: Uint8Array | ArrayBuffer): string {
|
|
82
|
+
let binary = ''
|
|
83
|
+
for (const byte of view instanceof ArrayBuffer ? new Uint8Array(view) : view) binary += String.fromCharCode(byte)
|
|
84
|
+
return btoa(binary)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function fromBase64(value: string): Uint8Array<ArrayBuffer> {
|
|
88
|
+
const binary = atob(value)
|
|
89
|
+
const out = new Uint8Array(new ArrayBuffer(binary.length))
|
|
90
|
+
for (let index = 0; index < binary.length; index++) out[index] = binary.charCodeAt(index)
|
|
91
|
+
return out
|
|
92
|
+
}
|
package/src/db.ts
CHANGED
|
@@ -12,6 +12,7 @@ import { MembershipTransportKeyRepository } from './repositories/membership-tran
|
|
|
12
12
|
import { OAuthRepository } from './repositories/oauth'
|
|
13
13
|
import { PasswordPolicyRepository } from './repositories/password-policy'
|
|
14
14
|
import { PrincipalRepository } from './repositories/principals'
|
|
15
|
+
import { SecondFactorRepository } from './repositories/second-factors'
|
|
15
16
|
import { SessionRepository } from './repositories/sessions'
|
|
16
17
|
import { TerminalRepository } from './repositories/terminals'
|
|
17
18
|
import { WorkloadRepository } from './repositories/workloads'
|
|
@@ -60,7 +61,15 @@ export { MembershipTransportKeyRepository, type MembershipTransportKeyRow } from
|
|
|
60
61
|
export { type OAuthCodeRow, type OAuthGrantRow, type OAuthRefreshTokenRow, OAuthRepository } from './repositories/oauth'
|
|
61
62
|
export { PasswordPolicyRepository, type PasswordPolicyRow } from './repositories/password-policy'
|
|
62
63
|
export { PrincipalRepository, type PrincipalRow, type PrincipalStatus, principalStatus } from './repositories/principals'
|
|
63
|
-
export {
|
|
64
|
+
export { SecondFactorRepository, type SecondFactorRow, type SecondFactorStatus } from './repositories/second-factors'
|
|
65
|
+
export {
|
|
66
|
+
type AuthenticationMethod,
|
|
67
|
+
SessionRepository,
|
|
68
|
+
type SessionRow,
|
|
69
|
+
type SessionTerminal,
|
|
70
|
+
sessionTerminal,
|
|
71
|
+
type SignedInSessionRow,
|
|
72
|
+
} from './repositories/sessions'
|
|
64
73
|
export {
|
|
65
74
|
DEFAULT_TERMINAL_SESSION_TTL_SECONDS,
|
|
66
75
|
MAX_TERMINAL_SESSION_TTL_SECONDS,
|
|
@@ -90,6 +99,7 @@ export interface IamRepositories {
|
|
|
90
99
|
membershipTransport: MembershipTransportKeyRepository
|
|
91
100
|
brand: InstallationBrandRepository
|
|
92
101
|
passwordPolicy: PasswordPolicyRepository
|
|
102
|
+
secondFactors: SecondFactorRepository
|
|
93
103
|
}
|
|
94
104
|
|
|
95
105
|
/**
|
|
@@ -119,6 +129,7 @@ export function createIamRepositories(
|
|
|
119
129
|
membershipTransport: replacements.membershipTransport ?? new MembershipTransportKeyRepository(db),
|
|
120
130
|
brand: replacements.brand ?? new InstallationBrandRepository(db, writer),
|
|
121
131
|
passwordPolicy: replacements.passwordPolicy ?? new PasswordPolicyRepository(db, writer),
|
|
132
|
+
secondFactors: replacements.secondFactors ?? new SecondFactorRepository(db, writer),
|
|
122
133
|
}
|
|
123
134
|
}
|
|
124
135
|
|
package/src/env.ts
CHANGED
|
@@ -38,8 +38,9 @@ export interface Env {
|
|
|
38
38
|
*/
|
|
39
39
|
ADMIN_AUDIENCES?: string
|
|
40
40
|
/**
|
|
41
|
-
* JSON: the OAuth 2.1 authorization server
|
|
42
|
-
*
|
|
41
|
+
* JSON: the OAuth 2.1 authorization server's clients and resources (`src/oauth-config.ts`). Absent or empty means
|
|
42
|
+
* OAuth is off and its routes 404. On Bun, `FABRIKA_IAM_OAUTH_CONFIG`; a Cloudflare deploy computes it in
|
|
43
|
+
* `fabrika.config.ts`. Malformed fails the boot.
|
|
43
44
|
*/
|
|
44
45
|
OAUTH_CONFIG?: string
|
|
45
46
|
/**
|
|
@@ -52,6 +53,11 @@ export interface Env {
|
|
|
52
53
|
* `FABRIKA_IAM_AUDIT_RETENTION_DAYS`. A value that is not a whole number of days fails the boot.
|
|
53
54
|
*/
|
|
54
55
|
AUDIT_RETENTION_DAYS?: string
|
|
56
|
+
/**
|
|
57
|
+
* Hours an OIDC login stays usable after its sign-in; unset means 12. Deploy var `FABRIKA_IAM_OIDC_SESSION_HOURS`.
|
|
58
|
+
* Anything but a whole number of hours from 1 to 720 fails the boot.
|
|
59
|
+
*/
|
|
60
|
+
OIDC_SESSION_HOURS?: string
|
|
55
61
|
/** `local` / `stage` / `prod`. */
|
|
56
62
|
ENVIRONMENT: string
|
|
57
63
|
/** Explicit local-only human login bypass. Ignored unless `ENVIRONMENT=local`. */
|
|
@@ -104,6 +110,13 @@ export interface Env {
|
|
|
104
110
|
* `vars`. Rotate by changing the env value.
|
|
105
111
|
*/
|
|
106
112
|
FABRIKA_IAM_PROVISIONING_KEY: string
|
|
113
|
+
/**
|
|
114
|
+
* **Secret.** Base64 of 32 random bytes: the key that seals the one value IAM must read back, a person's TOTP secret
|
|
115
|
+
* (`src/data-key.ts`). Unset makes TOTP enrolment unavailable; a value that is not 32 bytes fails the boot. Losing it
|
|
116
|
+
* makes every enrolled authenticator unreadable, so those people sign in with a recovery code or an administrator's
|
|
117
|
+
* reset. Never placed in `vars`.
|
|
118
|
+
*/
|
|
119
|
+
FABRIKA_IAM_DATA_KEY?: string
|
|
107
120
|
/**
|
|
108
121
|
* OIDC provider issuer URL (e.g. `https://accounts.google.com`, an Auth0/Okta/Keycloak/Entra
|
|
109
122
|
* tenant). IAM discovers the endpoints from `${OIDC_ISSUER}/.well-known/openid-configuration`
|
package/src/node/runtime.ts
CHANGED
|
@@ -15,9 +15,11 @@ import { type EmailProviderRegistry, type EmailSender, emailSenderFromEnv, pickE
|
|
|
15
15
|
import { installationMailSender, isHttpOrigin } from '@fabrika/email/platform'
|
|
16
16
|
import { builtinEmailProviders } from '@fabrika/email/providers'
|
|
17
17
|
import { createBackgroundTasks, PostgresDatabase } from '@fabrika/platform-node'
|
|
18
|
+
import { parseDataKey } from '../data-key'
|
|
18
19
|
import { createPostgresIamRepositories } from '../db'
|
|
19
20
|
import type { Env, RequestContext } from '../env'
|
|
20
21
|
import { parseOAuthConfig } from '../oauth-config'
|
|
22
|
+
import { parseOidcSessionSeconds } from '../oidc-session'
|
|
21
23
|
import { BUN_PBKDF2_COST } from '../password-crypto'
|
|
22
24
|
import { parseRetention } from '../retention'
|
|
23
25
|
|
|
@@ -107,6 +109,9 @@ export async function createRuntime(source: Record<string, string | undefined> =
|
|
|
107
109
|
{ authLogDays: authLogRetentionDays, auditDays: auditRetentionDays },
|
|
108
110
|
{ authLogDays: 'FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS', auditDays: 'FABRIKA_IAM_AUDIT_RETENTION_DAYS' },
|
|
109
111
|
)
|
|
112
|
+
const oidcSessionHours = source['FABRIKA_IAM_OIDC_SESSION_HOURS']
|
|
113
|
+
parseOidcSessionSeconds(oidcSessionHours, 'FABRIKA_IAM_OIDC_SESSION_HOURS')
|
|
114
|
+
parseDataKey(source['FABRIKA_IAM_DATA_KEY'])
|
|
110
115
|
|
|
111
116
|
const config: ProcessConfig = {
|
|
112
117
|
port: parsePort(source['PORT']),
|
|
@@ -132,12 +137,14 @@ export async function createRuntime(source: Record<string, string | undefined> =
|
|
|
132
137
|
OAUTH_CONFIG: source['FABRIKA_IAM_OAUTH_CONFIG'] ?? '',
|
|
133
138
|
AUTH_LOG_RETENTION_DAYS: authLogRetentionDays,
|
|
134
139
|
AUDIT_RETENTION_DAYS: auditRetentionDays,
|
|
140
|
+
OIDC_SESSION_HOURS: oidcSessionHours,
|
|
135
141
|
ENVIRONMENT: environment,
|
|
136
142
|
LOCAL_DEV_LOGIN: source['LOCAL_DEV_LOGIN'] ?? '',
|
|
137
143
|
ISSUER: issuer,
|
|
138
144
|
// Empty off-local is refused by `getSigner`, not here — one owner for that rule.
|
|
139
145
|
FABRIKA_IAM_SIGNING_KEYS: source['FABRIKA_IAM_SIGNING_KEYS'] ?? '',
|
|
140
146
|
FABRIKA_IAM_PROVISIONING_KEY: source['FABRIKA_IAM_PROVISIONING_KEY'] ?? '',
|
|
147
|
+
FABRIKA_IAM_DATA_KEY: source['FABRIKA_IAM_DATA_KEY'],
|
|
141
148
|
OIDC_ENABLED: String(oidcEnabled),
|
|
142
149
|
PASSWORD_ENABLED: String(passwordEnabled),
|
|
143
150
|
OIDC_ISSUER: oidcIssuer,
|
package/src/oauth-client-auth.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { OAUTH_CLI_CLIENT_ID } from '@fabrika/auth-core'
|
|
1
2
|
import type { OAuthClientCredential, OAuthClientMetadataDocument } from '@fabrika/iam-contract'
|
|
2
3
|
import { createLocalJWKSet, errors, type JSONWebKeySet, type JWTPayload, jwtVerify } from 'jose'
|
|
3
4
|
import type { EstablishedClient } from './oauth'
|
|
@@ -24,14 +25,16 @@ export async function authenticateOAuthClient(
|
|
|
24
25
|
config: OAuthConfig,
|
|
25
26
|
input: { clientId: string; credential: OAuthClientCredential; audiences: string[] },
|
|
26
27
|
): Promise<EstablishedClient | null> {
|
|
28
|
+
// The CLI client is public: it holds no key, so it sends no assertion.
|
|
29
|
+
if (input.clientId === OAUTH_CLI_CLIENT_ID) return input.credential.method === 'none' ? { kind: 'cli', clientId: input.clientId } : null
|
|
27
30
|
const registration = config.clients.find((client) => client.clientId === input.clientId)
|
|
28
31
|
if (registration === undefined) return null
|
|
29
32
|
const metadata = await clientMetadata(registration)
|
|
30
33
|
if (metadata === null) return null
|
|
31
|
-
if (metadata.token_endpoint_auth_method === 'none') return input.credential.method === 'none' ? { registration, metadata } : null
|
|
34
|
+
if (metadata.token_endpoint_auth_method === 'none') return input.credential.method === 'none' ? { kind: 'managed', registration, metadata } : null
|
|
32
35
|
if (input.credential.method !== 'private_key_jwt') return null
|
|
33
36
|
const accepted = await verifyClientAssertion(services, metadata, input.credential.assertion, input.audiences)
|
|
34
|
-
return accepted ? { registration, metadata } : null
|
|
37
|
+
return accepted ? { kind: 'managed', registration, metadata } : null
|
|
35
38
|
}
|
|
36
39
|
|
|
37
40
|
/**
|
|
@@ -46,6 +49,7 @@ export async function authenticateRevokingClient(
|
|
|
46
49
|
input: { clientId: string; credential: OAuthClientCredential; audiences: string[] },
|
|
47
50
|
): Promise<boolean> {
|
|
48
51
|
if (input.credential.method !== 'none') return await authenticateOAuthClient(services, config, input) !== null
|
|
52
|
+
if (input.clientId === OAUTH_CLI_CLIENT_ID) return true
|
|
49
53
|
const registration = config.clients.find((client) => client.clientId === input.clientId)
|
|
50
54
|
if (registration === undefined) return false
|
|
51
55
|
const metadata = await clientMetadata(registration)
|
package/src/oauth-config.ts
CHANGED
|
@@ -16,12 +16,12 @@ const MAX_CLIENTS = 16
|
|
|
16
16
|
const MAX_RESOURCES = 32
|
|
17
17
|
const CONFIG_KEYS = ['clients', 'resources']
|
|
18
18
|
const CLIENT_KEYS = ['provider', 'clientId', 'redirectUris', 'metadataUrl']
|
|
19
|
-
const RESOURCE_KEYS = ['app', 'resource', 'defaultScopes', 'scopeGrants']
|
|
19
|
+
const RESOURCE_KEYS = ['app', 'resource', 'defaultScopes', 'scopeGrants', 'client']
|
|
20
20
|
|
|
21
21
|
/**
|
|
22
|
-
* Parse `OAUTH_CONFIG`. Absent or empty disables OAuth; anything malformed THROWS, so a typo fails the
|
|
23
|
-
*
|
|
24
|
-
*
|
|
22
|
+
* Parse `OAUTH_CONFIG`. Absent or empty disables OAuth; anything malformed THROWS, so a typo fails the boot instead of
|
|
23
|
+
* quietly serving fewer clients or scopes than the operator wrote. Unknown keys are refused for the same reason.
|
|
24
|
+
* `clients` may be empty: the command-line client is IAM's own and never listed.
|
|
25
25
|
*/
|
|
26
26
|
export function parseOAuthConfig(raw: string | undefined): OAuthConfig | null {
|
|
27
27
|
if (raw === undefined || raw.trim() === '') return null
|
|
@@ -29,7 +29,7 @@ export function parseOAuthConfig(raw: string | undefined): OAuthConfig | null {
|
|
|
29
29
|
const rawClients = prop(value, 'clients')
|
|
30
30
|
const rawResources = prop(value, 'resources')
|
|
31
31
|
if (
|
|
32
|
-
!hasOnlyKeys(value, CONFIG_KEYS) || !Array.isArray(rawClients) || rawClients.length
|
|
32
|
+
!hasOnlyKeys(value, CONFIG_KEYS) || !Array.isArray(rawClients) || rawClients.length > MAX_CLIENTS
|
|
33
33
|
|| !Array.isArray(rawResources)
|
|
34
34
|
|| rawResources.length === 0 || rawResources.length > MAX_RESOURCES
|
|
35
35
|
) {
|