@fabrika/iam 0.9.0-dev.32 → 0.9.0-dev.33
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 +11 -3
- package/migrations/0032_second_factor.sql +29 -0
- package/migrations-postgres/0032_second_factor.sql +29 -0
- package/package.json +11 -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/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 +12 -0
- package/src/node/runtime.ts +7 -0
- package/src/oauth.ts +7 -3
- package/src/oidc-session.ts +25 -0
- 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 +12 -0
- package/types/src/oidc-session.d.ts +12 -0
- package/types/src/repositories/second-factors.d.ts +68 -0
- package/types/src/repositories/sessions.d.ts +7 -3
- 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/fabrika.config.ts
CHANGED
|
@@ -165,7 +165,7 @@ const buildVars = (config: RemoteConfig | 'local', source: EnvironmentSource): R
|
|
|
165
165
|
// Only when named: an empty ADMIN_AUDIENCES means "no JWT may administer", so a `?? ''`
|
|
166
166
|
// default would lock the console out of every install instead of falling back to its app id.
|
|
167
167
|
...(config.adminAudiences === undefined ? {} : { ADMIN_AUDIENCES: config.adminAudiences }),
|
|
168
|
-
...
|
|
168
|
+
...settingVars(source),
|
|
169
169
|
HUMAN_EMAILS: source['FABRIKA_IAM_HUMAN_EMAILS'] ?? '[]',
|
|
170
170
|
IAM_BOOTSTRAP_ADMINS: source['FABRIKA_IAM_BOOTSTRAP_ADMINS'] ?? '[]',
|
|
171
171
|
ISSUER: `https://${config.domain}`,
|
|
@@ -180,13 +180,18 @@ const buildVars = (config: RemoteConfig | 'local', source: EnvironmentSource): R
|
|
|
180
180
|
}
|
|
181
181
|
}
|
|
182
182
|
|
|
183
|
-
/**
|
|
184
|
-
|
|
183
|
+
/**
|
|
184
|
+
* The operator's retention and OIDC session settings, only where set: unset keeps IAM's defaults (30 days, audit
|
|
185
|
+
* kept, a 12-hour OIDC login).
|
|
186
|
+
*/
|
|
187
|
+
const settingVars = (source: EnvironmentSource): Record<string, string> => {
|
|
185
188
|
const authLog = source['FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS']
|
|
186
189
|
const audit = source['FABRIKA_IAM_AUDIT_RETENTION_DAYS']
|
|
190
|
+
const oidcSession = source['FABRIKA_IAM_OIDC_SESSION_HOURS']
|
|
187
191
|
return {
|
|
188
192
|
...(authLog === undefined || authLog === '' ? {} : { AUTH_LOG_RETENTION_DAYS: authLog }),
|
|
189
193
|
...(audit === undefined || audit === '' ? {} : { AUDIT_RETENTION_DAYS: audit }),
|
|
194
|
+
...(oidcSession === undefined || oidcSession === '' ? {} : { OIDC_SESSION_HOURS: oidcSession }),
|
|
190
195
|
}
|
|
191
196
|
}
|
|
192
197
|
|
|
@@ -198,6 +203,7 @@ export const iamPipelineVars = (source: EnvironmentSource): string[] => {
|
|
|
198
203
|
'FABRIKA_IAM_OAUTH_CONFIG',
|
|
199
204
|
'FABRIKA_IAM_AUTH_LOG_RETENTION_DAYS',
|
|
200
205
|
'FABRIKA_IAM_AUDIT_RETENTION_DAYS',
|
|
206
|
+
'FABRIKA_IAM_OIDC_SESSION_HOURS',
|
|
201
207
|
'FABRIKA_IAM_OIDC_ENABLED',
|
|
202
208
|
'FABRIKA_IAM_PASSWORD_ENABLED',
|
|
203
209
|
'FABRIKA_EMAIL_PROVIDER',
|
|
@@ -215,6 +221,8 @@ export const iamPipelineSecrets = (source: EnvironmentSource): string[] => {
|
|
|
215
221
|
return [
|
|
216
222
|
'FABRIKA_IAM_SIGNING_KEYS',
|
|
217
223
|
'FABRIKA_IAM_PROVISIONING_KEY',
|
|
224
|
+
// Optional: an installation from before TOTP has none until its operator adds it, and must keep deploying.
|
|
225
|
+
...(source['FABRIKA_IAM_DATA_KEY'] ? ['FABRIKA_IAM_DATA_KEY'] : []),
|
|
218
226
|
...(authentication.oidcEnabled ? ['OIDC_CLIENT_SECRET'] : []),
|
|
219
227
|
...emailVariableNames(email, true),
|
|
220
228
|
]
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
-- A person's second factor: one TOTP authenticator and its one-time recovery codes. SQLite/D1 dialect;
|
|
2
|
+
-- `../migrations-postgres/0032_second_factor.sql` states the same outcome.
|
|
3
|
+
--
|
|
4
|
+
-- The TOTP secret is sealed under `FABRIKA_IAM_DATA_KEY` (`src/data-key.ts`): a fresh data key per value encrypts it
|
|
5
|
+
-- (AES-256-GCM), the installation's key wraps that data key, and the principal id is the associated data of both, so a
|
|
6
|
+
-- sealed value moved into another principal's row does not open. `confirmed_at` is NULL while the enrolment waits for
|
|
7
|
+
-- its first valid code; only a confirmed row asks a sign-in for a code. `last_step` is the TOTP time step of the last
|
|
8
|
+
-- accepted code, so a code is accepted once. `confirmation_id` names the one confirmation that wrote the
|
|
9
|
+
-- recovery codes, so a repeated confirmation in the same second writes none. A recovery code is stored as its SHA-256 hash only.
|
|
10
|
+
CREATE TABLE second_factors (
|
|
11
|
+
principal_id TEXT PRIMARY KEY REFERENCES principals(id) ON DELETE CASCADE,
|
|
12
|
+
ciphertext TEXT NOT NULL,
|
|
13
|
+
value_iv TEXT NOT NULL,
|
|
14
|
+
wrapped_dek TEXT NOT NULL,
|
|
15
|
+
dek_iv TEXT NOT NULL,
|
|
16
|
+
created_at INTEGER NOT NULL,
|
|
17
|
+
confirmed_at INTEGER,
|
|
18
|
+
last_step INTEGER,
|
|
19
|
+
confirmation_id TEXT
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
CREATE TABLE second_factor_recovery_codes (
|
|
23
|
+
code_hash TEXT PRIMARY KEY,
|
|
24
|
+
principal_id TEXT NOT NULL REFERENCES principals(id) ON DELETE CASCADE,
|
|
25
|
+
created_at INTEGER NOT NULL,
|
|
26
|
+
used_at INTEGER
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
CREATE INDEX idx_second_factor_recovery_codes_principal ON second_factor_recovery_codes(principal_id);
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
-- A person's second factor: one TOTP authenticator and its one-time recovery codes. Postgres dialect;
|
|
2
|
+
-- `../migrations/0032_second_factor.sql` states the same outcome.
|
|
3
|
+
--
|
|
4
|
+
-- The TOTP secret is sealed under `FABRIKA_IAM_DATA_KEY` (`src/data-key.ts`): a fresh data key per value encrypts it
|
|
5
|
+
-- (AES-256-GCM), the installation's key wraps that data key, and the principal id is the associated data of both, so a
|
|
6
|
+
-- sealed value moved into another principal's row does not open. `confirmed_at` is NULL while the enrolment waits for
|
|
7
|
+
-- its first valid code; only a confirmed row asks a sign-in for a code. `last_step` is the TOTP time step of the last
|
|
8
|
+
-- accepted code, so a code is accepted once. `confirmation_id` names the one confirmation that wrote the
|
|
9
|
+
-- recovery codes, so a repeated confirmation in the same second writes none. A recovery code is stored as its SHA-256 hash only.
|
|
10
|
+
CREATE TABLE second_factors (
|
|
11
|
+
principal_id TEXT PRIMARY KEY REFERENCES principals(id) ON DELETE CASCADE,
|
|
12
|
+
ciphertext TEXT NOT NULL,
|
|
13
|
+
value_iv TEXT NOT NULL,
|
|
14
|
+
wrapped_dek TEXT NOT NULL,
|
|
15
|
+
dek_iv TEXT NOT NULL,
|
|
16
|
+
created_at INTEGER NOT NULL,
|
|
17
|
+
confirmed_at INTEGER,
|
|
18
|
+
last_step INTEGER,
|
|
19
|
+
confirmation_id TEXT
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
CREATE TABLE second_factor_recovery_codes (
|
|
23
|
+
code_hash TEXT PRIMARY KEY,
|
|
24
|
+
principal_id TEXT NOT NULL REFERENCES principals(id) ON DELETE CASCADE,
|
|
25
|
+
created_at INTEGER NOT NULL,
|
|
26
|
+
used_at INTEGER
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
CREATE INDEX idx_second_factor_recovery_codes_principal ON second_factor_recovery_codes(principal_id);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/iam",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.33",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/contember/fabrika-platform.git",
|
|
@@ -56,16 +56,17 @@
|
|
|
56
56
|
"prune:auth-log": "bun src/node/prune.ts"
|
|
57
57
|
},
|
|
58
58
|
"dependencies": {
|
|
59
|
-
"@fabrika/app": "0.9.0-dev.
|
|
60
|
-
"@fabrika/auth": "0.9.0-dev.
|
|
61
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
62
|
-
"@fabrika/email": "0.9.0-dev.
|
|
63
|
-
"@fabrika/iam-contract": "0.9.0-dev.
|
|
64
|
-
"@fabrika/platform": "0.9.0-dev.
|
|
65
|
-
"@fabrika/platform-node": "0.9.0-dev.
|
|
66
|
-
"@fabrika/provider-cloudflare": "0.9.0-dev.
|
|
67
|
-
"@fabrika/proxy-core": "0.9.0-dev.
|
|
59
|
+
"@fabrika/app": "0.9.0-dev.33",
|
|
60
|
+
"@fabrika/auth": "0.9.0-dev.33",
|
|
61
|
+
"@fabrika/auth-core": "0.9.0-dev.33",
|
|
62
|
+
"@fabrika/email": "0.9.0-dev.33",
|
|
63
|
+
"@fabrika/iam-contract": "0.9.0-dev.33",
|
|
64
|
+
"@fabrika/platform": "0.9.0-dev.33",
|
|
65
|
+
"@fabrika/platform-node": "0.9.0-dev.33",
|
|
66
|
+
"@fabrika/provider-cloudflare": "0.9.0-dev.33",
|
|
67
|
+
"@fabrika/proxy-core": "0.9.0-dev.33",
|
|
68
68
|
"jose": "^5.9.0",
|
|
69
|
+
"uqr": "^0.1.3",
|
|
69
70
|
"zod": "^3.25.76"
|
|
70
71
|
}
|
|
71
72
|
}
|
package/src/admin/api-keys.ts
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
type ApiKeyDto,
|
|
6
6
|
type ApiKeyIdInput,
|
|
7
7
|
type CursorList,
|
|
8
|
+
type GetApiKeyResponse,
|
|
8
9
|
type ListApiKeysInput,
|
|
9
10
|
type OkResponse,
|
|
10
11
|
type ProvisionApiKeyRequest,
|
|
@@ -18,7 +19,7 @@ import { contractGrantProblem } from '../contract-rules'
|
|
|
18
19
|
import { type CredentialRow, type GrantRow, type PrincipalRow, principalStatus } from '../db'
|
|
19
20
|
import { generateToken, hashToken } from '../secret'
|
|
20
21
|
import { type AdminContext, adminEvent, fail } from './context'
|
|
21
|
-
import { appField, parseRoleOrInline, parseScope, RoleKnownCache, toGrantDtos } from './grant-support'
|
|
22
|
+
import { appField, grantAuthorLabels, parseRoleOrInline, parseScope, RoleKnownCache, toGrantDtos } from './grant-support'
|
|
22
23
|
import { cursorOf, groupBy, normalizeLimit } from './pagination'
|
|
23
24
|
|
|
24
25
|
/**
|
|
@@ -67,8 +68,8 @@ async function apiKeyPrincipal(c: AdminContext, principalId: string): Promise<Pr
|
|
|
67
68
|
return principal
|
|
68
69
|
}
|
|
69
70
|
|
|
70
|
-
/** One key with its grants and its live credential, for the console's key page. */
|
|
71
|
-
export async function getApiKeyUseCase(c: AdminContext, input: ApiKeyIdInput): Promise<
|
|
71
|
+
/** One key with its grants, each naming who granted it, and its live credential, for the console's key page. */
|
|
72
|
+
export async function getApiKeyUseCase(c: AdminContext, input: ApiKeyIdInput): Promise<GetApiKeyResponse> {
|
|
72
73
|
const { principalId } = input
|
|
73
74
|
const { grants, credentials } = c.services.repositories
|
|
74
75
|
const principal = await apiKeyPrincipal(c, principalId)
|
|
@@ -77,8 +78,17 @@ export async function getApiKeyUseCase(c: AdminContext, input: ApiKeyIdInput): P
|
|
|
77
78
|
}
|
|
78
79
|
// `listCredentialsForPrincipal` is newest-first and rotation revokes every older key, so this is the live one.
|
|
79
80
|
const live = (await credentials.listCredentialsForPrincipal(principalId)).find((row) => row.revoked_at === null)
|
|
80
|
-
const
|
|
81
|
-
|
|
81
|
+
const rows = await grants.listGrants(principalId)
|
|
82
|
+
const dto = await toApiKeyDto(c, principal, rows, new RoleKnownCache(c.services))
|
|
83
|
+
const authors = await grantAuthorLabels(rows, c.services)
|
|
84
|
+
return {
|
|
85
|
+
...dto,
|
|
86
|
+
grants: dto.grants.map((grant) => ({
|
|
87
|
+
...grant,
|
|
88
|
+
grantedByLabel: grant.grantedBy === null ? null : authors.get(grant.grantedBy) ?? grant.grantedBy,
|
|
89
|
+
})),
|
|
90
|
+
credential: credentialDto(live),
|
|
91
|
+
}
|
|
82
92
|
}
|
|
83
93
|
|
|
84
94
|
function credentialDto(live: CredentialRow | undefined): ApiKeyDetail['credential'] {
|
|
@@ -70,6 +70,16 @@ export async function toGrantDtos(rows: GrantRow[], services: Services, cache: R
|
|
|
70
70
|
return out
|
|
71
71
|
}
|
|
72
72
|
|
|
73
|
+
/** The label of each principal who granted one of `rows`; an author no longer known reads as its id. */
|
|
74
|
+
export async function grantAuthorLabels(rows: GrantRow[], services: Services): Promise<Map<string, string>> {
|
|
75
|
+
const authors = [...new Set(rows.flatMap((row) => row.granted_by === null ? [] : [row.granted_by]))]
|
|
76
|
+
return new Map(
|
|
77
|
+
await Promise.all(
|
|
78
|
+
authors.map(async (author) => [author, (await services.repositories.principals.getPrincipalById(author))?.label ?? author] as const),
|
|
79
|
+
),
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
|
|
73
83
|
/** The set of app ids IAM knows about — the live registry derived from the schema tables. */
|
|
74
84
|
export function knownApps(c: AdminContext): Promise<string[]> {
|
|
75
85
|
return c.services.repositories.appSchema.listKnownApps()
|
package/src/admin/grants.ts
CHANGED
|
@@ -147,7 +147,10 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
|
|
|
147
147
|
other.id !== grant.id && other.app === grant.app && other.role_key === authorization.roleKey
|
|
148
148
|
&& other.scope_type === scope.scopeType && other.scope_value === scope.scopeValue
|
|
149
149
|
)
|
|
150
|
-
|
|
150
|
+
const held = principal.type === 'user'
|
|
151
|
+
? 'This user already has that role in this scope. Edit the existing access instead.'
|
|
152
|
+
: 'This key already has that role in this scope. Edit the existing grant instead.'
|
|
153
|
+
if (await duplicate()) return fail(409, held)
|
|
151
154
|
let updated: GrantRow | null
|
|
152
155
|
try {
|
|
153
156
|
updated = await c.services.repositories.grants.updateGrant(
|
|
@@ -177,7 +180,7 @@ export async function updateGrantUseCase(c: AdminContext, input: UpdateGrantInpu
|
|
|
177
180
|
}),
|
|
178
181
|
)
|
|
179
182
|
} catch (cause) {
|
|
180
|
-
if (await duplicate()) return fail(409,
|
|
183
|
+
if (await duplicate()) return fail(409, held)
|
|
181
184
|
throw cause
|
|
182
185
|
}
|
|
183
186
|
if (updated === null) return fail(409, 'The access changed or is no longer allowed. Refresh and try again.')
|
package/src/admin/handlers.ts
CHANGED
|
@@ -17,6 +17,7 @@ import { getPasswordPolicyUseCase, setPasswordPolicyUseCase } from './password-p
|
|
|
17
17
|
import { disablePasswordUseCase, issuePasswordEnrollmentUseCase, issuePasswordResetUseCase } from './passwords'
|
|
18
18
|
import { createPolicyUseCase, deletePolicyUseCase, listPoliciesUseCase, updatePolicyUseCase } from './policies'
|
|
19
19
|
import { getPrincipalUseCase, invitePrincipalUseCase, listPrincipalsUseCase, me, promotePrincipalUseCase, updatePrincipalUseCase } from './principals'
|
|
20
|
+
import { getSecondFactorUseCase, resetSecondFactorUseCase } from './second-factor'
|
|
20
21
|
import { listSessionsUseCase, revokeSessionsForPrincipalUseCase, revokeSessionUseCase } from './sessions'
|
|
21
22
|
import { createShareLinkUseCase, listShareLinksUseCase, revokeShareLinkUseCase } from './share-links'
|
|
22
23
|
import { listTerminalsUseCase, revokeTerminalUseCase, setTerminalProfileUseCase } from './terminals'
|
|
@@ -93,6 +94,8 @@ export const adminUseCases = {
|
|
|
93
94
|
clearInstallationBrand: clearInstallationBrandUseCase,
|
|
94
95
|
getPasswordPolicy: getPasswordPolicyUseCase,
|
|
95
96
|
setPasswordPolicy: setPasswordPolicyUseCase,
|
|
97
|
+
getSecondFactor: getSecondFactorUseCase,
|
|
98
|
+
resetSecondFactor: resetSecondFactorUseCase,
|
|
96
99
|
listTerminals: listTerminalsUseCase,
|
|
97
100
|
setTerminalProfile: setTerminalProfileUseCase,
|
|
98
101
|
revokeTerminal: revokeTerminalUseCase,
|
package/src/admin/principals.ts
CHANGED
|
@@ -14,7 +14,7 @@ import { normalizeEmailIdentity } from '../email-identity'
|
|
|
14
14
|
import { resolvePermissionsAt } from '../resolve'
|
|
15
15
|
import { listRolesUseCase } from './app-schema'
|
|
16
16
|
import { type AdminContext, adminEvent, fail } from './context'
|
|
17
|
-
import { toGrantDtos } from './grant-support'
|
|
17
|
+
import { grantAuthorLabels, toGrantDtos } from './grant-support'
|
|
18
18
|
import { cursorOf, normalizeLimit } from './pagination'
|
|
19
19
|
import { canManagePrincipal, managesApp, requireActableTarget, requireInvitableMailbox } from './user-admin'
|
|
20
20
|
|
|
@@ -79,10 +79,7 @@ export async function getPrincipalUseCase(c: AdminContext, input: PrincipalIdInp
|
|
|
79
79
|
const roles = new Map(
|
|
80
80
|
await Promise.all([...new Set(grants.map((grant) => grant.app))].map(async (app) => [app, (await listRolesUseCase(c, { app })).items] as const)),
|
|
81
81
|
)
|
|
82
|
-
const authors =
|
|
83
|
-
await Promise.all([...new Set(grants.flatMap((grant) => grant.granted_by === null ? [] : [grant.granted_by]))]
|
|
84
|
-
.map(async (author) => [author, (await c.services.repositories.principals.getPrincipalById(author))?.label ?? author] as const)),
|
|
85
|
-
)
|
|
82
|
+
const authors = await grantAuthorLabels(grants, c.services)
|
|
86
83
|
const grantDetails: PrincipalGrantDto[] = (await toGrantDtos(grants, c.services)).map((grant) => {
|
|
87
84
|
const role = roles.get(grant.app)?.find((role) => role.key === grant.roleKey)
|
|
88
85
|
return {
|
package/src/admin/rpc.ts
CHANGED
|
@@ -253,6 +253,14 @@ export const adminRpcRouter: RpcRouterFor<IamAppContext, IamAdminRpcContract> =
|
|
|
253
253
|
.require(ADMIN_ACTION)
|
|
254
254
|
.mutation(({ ctx, input }) => adminUseCases.setPasswordPolicy(context(ctx), input)),
|
|
255
255
|
}),
|
|
256
|
+
// A person's authenticator: `iam.admin` only, to read and to reset. The reset is the operator's path for a lost phone.
|
|
257
|
+
secondFactor: t.router({
|
|
258
|
+
get: t.procedure.input(principalIdInput).require(ADMIN_ACTION).query(({ ctx, input }) => adminUseCases.getSecondFactor(context(ctx), input)),
|
|
259
|
+
reset: t.procedure
|
|
260
|
+
.input(principalIdInput)
|
|
261
|
+
.require(ADMIN_ACTION)
|
|
262
|
+
.mutation(({ ctx, input }) => adminUseCases.resetSecondFactor(context(ctx), input)),
|
|
263
|
+
}),
|
|
256
264
|
})
|
|
257
265
|
|
|
258
266
|
/** Resolve the admin behind an `/admin/rpc` request, then run `next` with it on `ctx`; anyone else is refused. */
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// A person's second factor (TOTP), as an installation administrator reads and resets it. The reset is the operator's
|
|
2
|
+
// path for a lost phone: it removes the authenticator and every recovery code, so the next sign-in asks for no code
|
|
3
|
+
// and the person enrols again at IAM's `/auth/second-factor/enrol`.
|
|
4
|
+
|
|
5
|
+
import type { PrincipalIdInput, SecondFactorDto } from '@fabrika/iam-contract'
|
|
6
|
+
import { type AdminContext, adminEvent, fail } from './context'
|
|
7
|
+
|
|
8
|
+
export async function getSecondFactorUseCase(c: AdminContext, input: PrincipalIdInput): Promise<SecondFactorDto> {
|
|
9
|
+
requireInstallationAdmin(c)
|
|
10
|
+
await requirePrincipal(c, input.principalId)
|
|
11
|
+
return secondFactorDto(c, input.principalId)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Remove the authenticator and recovery codes, recorded as `iam.second_factor.reset`; a principal without one records nothing. */
|
|
15
|
+
export async function resetSecondFactorUseCase(c: AdminContext, input: PrincipalIdInput): Promise<SecondFactorDto> {
|
|
16
|
+
requireInstallationAdmin(c)
|
|
17
|
+
await requirePrincipal(c, input.principalId)
|
|
18
|
+
await c.services.repositories.secondFactors.reset(
|
|
19
|
+
input.principalId,
|
|
20
|
+
adminEvent(c, { action: 'iam.second_factor.reset', resourceType: 'principal', resourceId: input.principalId }),
|
|
21
|
+
)
|
|
22
|
+
return secondFactorDto(c, input.principalId)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function secondFactorDto(c: AdminContext, principalId: string): Promise<SecondFactorDto> {
|
|
26
|
+
const status = await c.services.repositories.secondFactors.status(principalId)
|
|
27
|
+
return { enrolledAt: status.confirmedAt, recoveryCodesLeft: status.recoveryCodesLeft, available: c.services.dataKey !== null }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function requirePrincipal(c: AdminContext, principalId: string): Promise<void> {
|
|
31
|
+
if (await c.services.repositories.principals.getPrincipalById(principalId) === null) fail(404, 'principal not found')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** `.require(iam.admin)` gates these procedures already; a direct caller of a use case meets the same rule. */
|
|
35
|
+
function requireInstallationAdmin(c: AdminContext): void {
|
|
36
|
+
if (c.administration.kind !== 'installation') {
|
|
37
|
+
return fail(403, 'a second factor is read and reset only by an installation administrator')
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/admin/sessions.ts
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
type SessionIdInput,
|
|
7
7
|
type SessionList,
|
|
8
8
|
} from '@fabrika/iam-contract'
|
|
9
|
-
import { sessionUsable } from '../auth'
|
|
9
|
+
import { sessionEndsAt, sessionUsable } from '../auth'
|
|
10
10
|
import type { ListedSessionRow } from '../repositories/sessions'
|
|
11
11
|
|
|
12
12
|
import { type AdminContext, adminEvent, fail } from './context'
|
|
@@ -18,13 +18,13 @@ import { requireActableTarget } from './user-admin'
|
|
|
18
18
|
function toSessionDto(c: AdminContext, row: ListedSessionRow, now: number, disabled: boolean): SessionDto {
|
|
19
19
|
const unavailableReason = row.revoked_at !== null
|
|
20
20
|
? 'revoked'
|
|
21
|
-
: row.
|
|
21
|
+
: sessionEndsAt(row, c.services.config) <= now
|
|
22
22
|
? 'expired'
|
|
23
23
|
: row.parent_session_id !== null && (row.parent_expires_at === null || row.parent_expires_at <= now || row.parent_revoked_at !== null)
|
|
24
24
|
? 'parent_ended'
|
|
25
25
|
: disabled
|
|
26
26
|
? 'account_disabled'
|
|
27
|
-
: !sessionUsable(row, c.services.config)
|
|
27
|
+
: !sessionUsable(row, c.services.config, now)
|
|
28
28
|
? 'method_disabled'
|
|
29
29
|
: null
|
|
30
30
|
return {
|
|
@@ -35,7 +35,7 @@ function toSessionDto(c: AdminContext, row: ListedSessionRow, now: number, disab
|
|
|
35
35
|
parentSessionId: row.parent_session_id,
|
|
36
36
|
status: row.revoked_at !== null ? 'revoked' : row.expires_at <= now ? 'expired' : 'active',
|
|
37
37
|
createdAt: row.created_at,
|
|
38
|
-
expiresAt: row.
|
|
38
|
+
expiresAt: sessionEndsAt(row, c.services.config),
|
|
39
39
|
revokedAt: row.revoked_at,
|
|
40
40
|
unavailableReason,
|
|
41
41
|
}
|
package/src/auth/failure.ts
CHANGED
|
@@ -21,5 +21,10 @@ export type AuthFailure =
|
|
|
21
21
|
| { readonly kind: 'terminal_enrolment_unavailable' }
|
|
22
22
|
/** A terminal identification completed by another browser, twice, too late, or after its login ended. */
|
|
23
23
|
| { readonly kind: 'terminal_completion_refused' }
|
|
24
|
+
/** The challenge cookie of a sign-in waiting for its second factor is missing, forged or older than its five minutes. */
|
|
25
|
+
| { readonly kind: 'second_factor_expired' }
|
|
26
|
+
/** The browser holds no login of a principal that may enrol an authenticator. */
|
|
27
|
+
| { readonly kind: 'second_factor_not_allowed' }
|
|
28
|
+
| { readonly kind: 'second_factor_unavailable' }
|
|
24
29
|
/** A refusal of the principal resolution; `reason` is its fixed code, never what the caller sent. */
|
|
25
30
|
| { readonly kind: 'login_refused'; readonly reason: string }
|
package/src/auth/http.ts
CHANGED
|
@@ -75,7 +75,7 @@ export function methodNotAllowed(): Response {
|
|
|
75
75
|
|
|
76
76
|
/**
|
|
77
77
|
* Headers for a 302 out of this surface. `no-store` belongs on every one of them, not just the
|
|
78
|
-
* password pages: these are the responses that carry the
|
|
78
|
+
* password pages: these are the responses that carry the session cookie and, on the handoff
|
|
79
79
|
* path, the single-use code in the `Location` itself.
|
|
80
80
|
*/
|
|
81
81
|
export function redirectHeaders(location: string): Headers {
|
package/src/auth/invitations.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { validatePassword } from '../password-policy'
|
|
|
10
10
|
import { parseLocale, rememberLocaleCookie } from '../person-locale'
|
|
11
11
|
import type { Services } from '../services'
|
|
12
12
|
import { methodNotAllowed, readForm, redirectHeaders, sameOrigin, stringValue } from './http'
|
|
13
|
+
import type { AuthEnv } from './oidc-flight'
|
|
13
14
|
import { currentSession, issueSession } from './sessions'
|
|
14
15
|
|
|
15
16
|
const tokenSchema = z.string().max(512).regex(/^[A-Za-z0-9_-]{32,}$/)
|
|
@@ -29,7 +30,13 @@ const tokenSchema = z.string().max(512).regex(/^[A-Za-z0-9_-]{32,}$/)
|
|
|
29
30
|
* The link's `?app=` picks the page's language; an accepted invitation lands on its own application's
|
|
30
31
|
* registered origin, where the application's proxy signs the browser in through the normal handoff.
|
|
31
32
|
*/
|
|
32
|
-
export async function handleInvitation(
|
|
33
|
+
export async function handleInvitation(
|
|
34
|
+
request: Request,
|
|
35
|
+
services: Services,
|
|
36
|
+
env: AuthEnv,
|
|
37
|
+
ctx: RequestContext,
|
|
38
|
+
requestId: string,
|
|
39
|
+
): Promise<Response> {
|
|
33
40
|
const linked = await presentationFor(services, new URL(request.url).searchParams.get('app'), { request })
|
|
34
41
|
if (request.method === 'GET') {
|
|
35
42
|
return invitationPage(linked)
|
|
@@ -66,7 +73,7 @@ export async function handleInvitation(request: Request, services: Services, ctx
|
|
|
66
73
|
}
|
|
67
74
|
const password = stringValue(form?.get('password') ?? null)
|
|
68
75
|
if (password !== null) {
|
|
69
|
-
return createAndAccept(request, services, ctx, { invitation: offer.invitation, token: token.data, password, requestId, brand: linked.brand })
|
|
76
|
+
return createAndAccept(request, services, env, ctx, { invitation: offer.invitation, token: token.data, password, requestId, brand: linked.brand })
|
|
70
77
|
}
|
|
71
78
|
const presentation = await presentationFor(services, offer.invitation.app, { request, brand: linked.brand, locale: offer.invitation.locale })
|
|
72
79
|
return invitationPasswordPage({
|
|
@@ -131,6 +138,7 @@ export async function handleInvitation(request: Request, services: Services, ctx
|
|
|
131
138
|
async function createAndAccept(
|
|
132
139
|
request: Request,
|
|
133
140
|
services: Services,
|
|
141
|
+
env: AuthEnv,
|
|
134
142
|
ctx: RequestContext,
|
|
135
143
|
input: {
|
|
136
144
|
readonly invitation: InvitationRow
|
|
@@ -159,7 +167,7 @@ async function createAndAccept(
|
|
|
159
167
|
if (!outcome.ok) {
|
|
160
168
|
return creationRefused(services, presentation, outcome.reason)
|
|
161
169
|
}
|
|
162
|
-
return issueSession(request, services, ctx, {
|
|
170
|
+
return issueSession(request, services, env, ctx, {
|
|
163
171
|
principalId: outcome.principal.id,
|
|
164
172
|
email: outcome.principal.email,
|
|
165
173
|
authenticationMethod: 'password',
|
package/src/auth/login.ts
CHANGED
|
@@ -66,7 +66,7 @@ export async function handleLogin(
|
|
|
66
66
|
}
|
|
67
67
|
|
|
68
68
|
if (services.config.localDevLogin) {
|
|
69
|
-
return handleLocalLogin(request, services, ctx, requestId, redirect, handoff, presentation)
|
|
69
|
+
return handleLocalLogin(request, services, env, ctx, requestId, redirect, handoff, presentation)
|
|
70
70
|
}
|
|
71
71
|
if (services.config.authentication.password.enabled) {
|
|
72
72
|
return loginPage({
|
|
@@ -133,6 +133,7 @@ export async function handleAccountChoice(request: Request, services: Services,
|
|
|
133
133
|
async function handleLocalLogin(
|
|
134
134
|
request: Request,
|
|
135
135
|
services: Services,
|
|
136
|
+
env: AuthEnv,
|
|
136
137
|
ctx: RequestContext,
|
|
137
138
|
requestId: string,
|
|
138
139
|
redirect: string | null,
|
|
@@ -148,7 +149,7 @@ async function handleLocalLogin(
|
|
|
148
149
|
() => authFailurePage(presentation, { kind: 'login_refused', reason: `local ${resolved.reason}` }, 403),
|
|
149
150
|
)
|
|
150
151
|
}
|
|
151
|
-
return issueSession(request, services, ctx, {
|
|
152
|
+
return issueSession(request, services, env, ctx, {
|
|
152
153
|
principalId: resolved.principal.id,
|
|
153
154
|
idpSub: LOCAL_DEV_ADMIN_ID,
|
|
154
155
|
email: LOCAL_DEV_ADMIN_EMAIL,
|
package/src/auth/oidc.ts
CHANGED
|
@@ -135,7 +135,7 @@ export async function handleCallback(
|
|
|
135
135
|
return refuse('handoff_refused', reading.failure, 400)
|
|
136
136
|
}
|
|
137
137
|
|
|
138
|
-
return issueSession(request, services, ctx, {
|
|
138
|
+
return issueSession(request, services, env, ctx, {
|
|
139
139
|
principalId: resolved.principal.id,
|
|
140
140
|
idpSub: identity.sub,
|
|
141
141
|
email: identity.email,
|
package/src/auth/password.ts
CHANGED
|
@@ -15,7 +15,7 @@ import { type Config, type Services } from '../services'
|
|
|
15
15
|
import type { AuthFailure } from './failure'
|
|
16
16
|
import { handoffOf, handoffRedirectOr, loginDestinationFields, readHandoff } from './handoff'
|
|
17
17
|
import { methodNotAllowed, readForm, sameOrigin, stringValue } from './http'
|
|
18
|
-
import {
|
|
18
|
+
import { readKnownDevice } from './known-device'
|
|
19
19
|
import type { AuthEnv } from './oidc-flight'
|
|
20
20
|
import { issueSession, type LoginRefusal, refuseLogin } from './sessions'
|
|
21
21
|
|
|
@@ -202,7 +202,8 @@ export async function handlePasswordLogin(
|
|
|
202
202
|
services.repositories.passwords.clearLoginFailures(accountKey),
|
|
203
203
|
deviceKey === null ? Promise.resolve() : services.repositories.passwords.clearLoginFailures(deviceKey),
|
|
204
204
|
])
|
|
205
|
-
|
|
205
|
+
// Only a recorded login earns a device cookie: `issueSession` sets it on its 302, after the second factor if any.
|
|
206
|
+
return issueSession(request, services, env, ctx, {
|
|
206
207
|
principalId: lookup.principal.id,
|
|
207
208
|
email: lookup.principal.email,
|
|
208
209
|
authenticationMethod: 'password',
|
|
@@ -210,10 +211,8 @@ export async function handlePasswordLogin(
|
|
|
210
211
|
reason: 'password_login',
|
|
211
212
|
requestId,
|
|
212
213
|
handoff,
|
|
214
|
+
rememberDevice: true,
|
|
213
215
|
})
|
|
214
|
-
// Only a recorded login (the 302) earns a device cookie; a 503 issued no session.
|
|
215
|
-
if (session.status === 302) session.headers.append('Set-Cookie', await knownDeviceCookie(env, lookup.principal.id))
|
|
216
|
-
return session
|
|
217
216
|
}
|
|
218
217
|
|
|
219
218
|
// A known device's attempt is already counted in its own bucket.
|
|
@@ -335,6 +334,7 @@ async function safelyCreateBootstrapPrincipal(services: Services, email: string,
|
|
|
335
334
|
export async function handlePasswordAction(
|
|
336
335
|
request: Request,
|
|
337
336
|
services: Services,
|
|
337
|
+
env: AuthEnv,
|
|
338
338
|
ctx: RequestContext,
|
|
339
339
|
purpose: PasswordActionPurpose,
|
|
340
340
|
requestId: string,
|
|
@@ -381,7 +381,7 @@ export async function handlePasswordAction(
|
|
|
381
381
|
// An action that keeps an application lands on its registered origin, any other on the installation's landing
|
|
382
382
|
// (`issueSession`); that application's proxy then signs the browser in through the normal handoff, which the
|
|
383
383
|
// session issued here makes silent.
|
|
384
|
-
return issueSession(request, services, ctx, {
|
|
384
|
+
return issueSession(request, services, env, ctx, {
|
|
385
385
|
principalId: completedPrincipal.id,
|
|
386
386
|
email: completedPrincipal.email,
|
|
387
387
|
authenticationMethod: 'password',
|
package/src/auth/routes.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { INVITATION_ACCEPT_PATH } from '../membership'
|
|
|
10
10
|
import { ACCOUNT_CHOICE_PATH, logoutPage, TERMINAL_ENROL_PATH } from '../password-pages'
|
|
11
11
|
import { readerLocale } from '../person-locale'
|
|
12
12
|
import { generateRequestId } from '../request-id'
|
|
13
|
+
import { SECOND_FACTOR_ENROL_PATH, SECOND_FACTOR_PATH } from '../second-factor-pages'
|
|
13
14
|
import type { Services } from '../services'
|
|
14
15
|
import { getSigner } from '../signing'
|
|
15
16
|
import { methodNotAllowed, safeRedirect } from './http'
|
|
@@ -18,6 +19,7 @@ import { handleAccountChoice, handleLogin } from './login'
|
|
|
18
19
|
import { handleCallback, handleOidcStart } from './oidc'
|
|
19
20
|
import type { AuthEnv } from './oidc-flight'
|
|
20
21
|
import { handleForgotPassword, handlePasswordAction, handlePasswordLogin } from './password'
|
|
22
|
+
import { handleSecondFactor, handleSecondFactorEnrolment } from './second-factor'
|
|
21
23
|
import { handleLogout } from './sessions'
|
|
22
24
|
import { handleTerminalCompletion, handleTerminalEnrolment, handleTerminalRelease, TERMINAL_RELEASE_PATH } from './terminals'
|
|
23
25
|
|
|
@@ -62,13 +64,13 @@ export async function handleAuth(
|
|
|
62
64
|
return handleForgotPassword(request, services, ctx, clientAddress, requestId)
|
|
63
65
|
}
|
|
64
66
|
if (url.pathname === '/auth/password/enroll') {
|
|
65
|
-
return handlePasswordAction(request, services, ctx, 'enrollment', requestId)
|
|
67
|
+
return handlePasswordAction(request, services, env, ctx, 'enrollment', requestId)
|
|
66
68
|
}
|
|
67
69
|
if (url.pathname === '/auth/password/reset') {
|
|
68
|
-
return handlePasswordAction(request, services, ctx, 'reset', requestId)
|
|
70
|
+
return handlePasswordAction(request, services, env, ctx, 'reset', requestId)
|
|
69
71
|
}
|
|
70
72
|
if (url.pathname === INVITATION_ACCEPT_PATH) {
|
|
71
|
-
return handleInvitation(request, services, ctx, requestId)
|
|
73
|
+
return handleInvitation(request, services, env, ctx, requestId)
|
|
72
74
|
}
|
|
73
75
|
if (url.pathname === TERMINAL_ENROL_PATH) {
|
|
74
76
|
return request.method === 'GET' || request.method === 'POST' ? handleTerminalEnrolment(request, services, requestId) : methodNotAllowed()
|
|
@@ -79,6 +81,12 @@ export async function handleAuth(
|
|
|
79
81
|
if (url.pathname === TERMINAL_RELEASE_PATH) {
|
|
80
82
|
return request.method === 'GET' ? handleTerminalRelease(request, services, requestId) : methodNotAllowed()
|
|
81
83
|
}
|
|
84
|
+
if (url.pathname === SECOND_FACTOR_PATH) {
|
|
85
|
+
return request.method === 'POST' ? handleSecondFactor(request, services, env, ctx, requestId) : methodNotAllowed()
|
|
86
|
+
}
|
|
87
|
+
if (url.pathname === SECOND_FACTOR_ENROL_PATH) {
|
|
88
|
+
return request.method === 'GET' || request.method === 'POST' ? handleSecondFactorEnrolment(request, services, requestId) : methodNotAllowed()
|
|
89
|
+
}
|
|
82
90
|
if (url.pathname === '/auth/logout') {
|
|
83
91
|
// Logging out is a state change, so it needs a method that can carry an origin check. A GET
|
|
84
92
|
// stays usable — it renders the same-origin form that posts — because a cross-site
|