@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.
Files changed (61) hide show
  1. package/fabrika.config.ts +11 -3
  2. package/migrations/0032_second_factor.sql +29 -0
  3. package/migrations-postgres/0032_second_factor.sql +29 -0
  4. package/package.json +11 -10
  5. package/src/admin/api-keys.ts +15 -5
  6. package/src/admin/grant-support.ts +10 -0
  7. package/src/admin/grants.ts +5 -2
  8. package/src/admin/handlers.ts +3 -0
  9. package/src/admin/principals.ts +2 -5
  10. package/src/admin/rpc.ts +8 -0
  11. package/src/admin/second-factor.ts +39 -0
  12. package/src/admin/sessions.ts +4 -4
  13. package/src/auth/failure.ts +5 -0
  14. package/src/auth/http.ts +1 -1
  15. package/src/auth/invitations.ts +11 -3
  16. package/src/auth/login.ts +3 -2
  17. package/src/auth/oidc.ts +1 -1
  18. package/src/auth/password.ts +6 -6
  19. package/src/auth/routes.ts +11 -3
  20. package/src/auth/second-factor-challenge.ts +114 -0
  21. package/src/auth/second-factor.ts +276 -0
  22. package/src/auth/sessions.ts +72 -21
  23. package/src/auth.ts +19 -4
  24. package/src/catalog/cs.ts +32 -0
  25. package/src/catalog/en.ts +33 -0
  26. package/src/catalog/index.ts +28 -0
  27. package/src/catalog/uk.ts +33 -0
  28. package/src/data-key.ts +92 -0
  29. package/src/db.ts +12 -1
  30. package/src/env.ts +12 -0
  31. package/src/node/runtime.ts +7 -0
  32. package/src/oauth.ts +7 -3
  33. package/src/oidc-session.ts +25 -0
  34. package/src/repositories/second-factors.ts +165 -0
  35. package/src/repositories/sessions.ts +17 -9
  36. package/src/second-factor-pages.ts +129 -0
  37. package/src/services.ts +11 -2
  38. package/src/tokens.ts +3 -3
  39. package/src/totp.ts +132 -0
  40. package/types/src/admin/api-keys.d.ts +3 -3
  41. package/types/src/admin/grant-support.d.ts +2 -0
  42. package/types/src/admin/handlers.d.ts +3 -0
  43. package/types/src/admin/second-factor.d.ts +5 -0
  44. package/types/src/auth/failure.d.ts +10 -0
  45. package/types/src/auth/http.d.ts +1 -1
  46. package/types/src/auth/invitations.d.ts +2 -1
  47. package/types/src/auth/password.d.ts +1 -1
  48. package/types/src/auth/second-factor-challenge.d.ts +34 -0
  49. package/types/src/auth/second-factor.d.ts +19 -0
  50. package/types/src/auth/sessions.d.ts +22 -9
  51. package/types/src/auth.d.ts +9 -3
  52. package/types/src/catalog/index.d.ts +28 -0
  53. package/types/src/data-key.d.ts +19 -0
  54. package/types/src/db.d.ts +4 -1
  55. package/types/src/env.d.ts +12 -0
  56. package/types/src/oidc-session.d.ts +12 -0
  57. package/types/src/repositories/second-factors.d.ts +68 -0
  58. package/types/src/repositories/sessions.d.ts +7 -3
  59. package/types/src/second-factor-pages.d.ts +42 -0
  60. package/types/src/services.d.ts +4 -0
  61. package/types/src/totp.d.ts +32 -0
@@ -0,0 +1,19 @@
1
+ /** AES-256: the installation's key and each data key. */
2
+ export declare const DATA_KEY_BYTES = 32;
3
+ /** The sealed pieces as stored: all base64, never a plaintext value or data key. */
4
+ export interface SealedValue {
5
+ readonly ciphertext: string;
6
+ readonly valueIv: string;
7
+ readonly wrappedDek: string;
8
+ readonly dekIv: string;
9
+ }
10
+ /**
11
+ * Parse `FABRIKA_IAM_DATA_KEY` (base64 of 32 random bytes) once at boot. Unset or empty is null: nothing can be sealed,
12
+ * so TOTP enrolment is unavailable. Anything else that is not 32 bytes fails the boot; a short key would be a weak key
13
+ * nobody notices.
14
+ */
15
+ export declare function parseDataKey(raw: string | undefined): Uint8Array<ArrayBuffer> | null;
16
+ /** Seal `value` for `owner` (the associated data of both layers). */
17
+ export declare function sealValue(dataKey: Uint8Array<ArrayBuffer>, owner: string, value: Uint8Array<ArrayBuffer>): Promise<SealedValue>;
18
+ /** Open a value `sealValue` sealed for `owner`. A wrong key, another owner or any tampered piece throws. */
19
+ export declare function openValue(dataKey: Uint8Array<ArrayBuffer>, owner: string, sealed: SealedValue): Promise<Uint8Array<ArrayBuffer>>;
package/types/src/db.d.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';
@@ -27,7 +28,8 @@ export { MembershipTransportKeyRepository, type MembershipTransportKeyRow } from
27
28
  export { type OAuthCodeRow, type OAuthGrantRow, type OAuthRefreshTokenRow, OAuthRepository } from './repositories/oauth';
28
29
  export { PasswordPolicyRepository, type PasswordPolicyRow } from './repositories/password-policy';
29
30
  export { PrincipalRepository, type PrincipalRow, type PrincipalStatus, principalStatus } from './repositories/principals';
30
- export { type AuthenticationMethod, SessionRepository, type SessionRow, type SessionTerminal, sessionTerminal } from './repositories/sessions';
31
+ export { SecondFactorRepository, type SecondFactorRow, type SecondFactorStatus } from './repositories/second-factors';
32
+ export { type AuthenticationMethod, SessionRepository, type SessionRow, type SessionTerminal, sessionTerminal, type SignedInSessionRow, } from './repositories/sessions';
31
33
  export { DEFAULT_TERMINAL_SESSION_TTL_SECONDS, MAX_TERMINAL_SESSION_TTL_SECONDS, type TerminalAsserter, type TerminalIdentificationRow, type TerminalProfile, TerminalRepository, type TerminalRow, } from './repositories/terminals';
32
34
  export { type AppWorkloadRow, type WorkloadPrincipalRow, WorkloadRepository } from './repositories/workloads';
33
35
  /** IAM persistence capabilities selected together by a runtime composition root. */
@@ -48,6 +50,7 @@ export interface IamRepositories {
48
50
  membershipTransport: MembershipTransportKeyRepository;
49
51
  brand: InstallationBrandRepository;
50
52
  passwordPolicy: PasswordPolicyRepository;
53
+ secondFactors: SecondFactorRepository;
51
54
  }
52
55
  /**
53
56
  * The portable repository bundle. A composition root may replace one complete capability. `dialect` picks how a
@@ -51,6 +51,11 @@ export interface Env {
51
51
  * `FABRIKA_IAM_AUDIT_RETENTION_DAYS`. A value that is not a whole number of days fails the boot.
52
52
  */
53
53
  AUDIT_RETENTION_DAYS?: string;
54
+ /**
55
+ * Hours an OIDC login stays usable after its sign-in; unset means 12. Deploy var `FABRIKA_IAM_OIDC_SESSION_HOURS`.
56
+ * Anything but a whole number of hours from 1 to 720 fails the boot.
57
+ */
58
+ OIDC_SESSION_HOURS?: string;
54
59
  /** `local` / `stage` / `prod`. */
55
60
  ENVIRONMENT: string;
56
61
  /** Explicit local-only human login bypass. Ignored unless `ENVIRONMENT=local`. */
@@ -100,6 +105,13 @@ export interface Env {
100
105
  * `vars`. Rotate by changing the env value.
101
106
  */
102
107
  FABRIKA_IAM_PROVISIONING_KEY: string;
108
+ /**
109
+ * **Secret.** Base64 of 32 random bytes: the key that seals the one value IAM must read back, a person's TOTP secret
110
+ * (`src/data-key.ts`). Unset makes TOTP enrolment unavailable; a value that is not 32 bytes fails the boot. Losing it
111
+ * makes every enrolled authenticator unreadable, so those people sign in with a recovery code or an administrator's
112
+ * reset. Never placed in `vars`.
113
+ */
114
+ FABRIKA_IAM_DATA_KEY?: string;
103
115
  /**
104
116
  * OIDC provider issuer URL (e.g. `https://accounts.google.com`, an Auth0/Okta/Keycloak/Entra
105
117
  * tenant). IAM discovers the endpoints from `${OIDC_ISSUER}/.well-known/openid-configuration`
@@ -0,0 +1,12 @@
1
+ /**
2
+ * How long an OIDC login lasts before IAM sends its holder back to the provider, in hours. The provider is where an
3
+ * organization blocks a person, so this bounds how long a person blocked there keeps fabrika access.
4
+ */
5
+ export declare const DEFAULT_OIDC_SESSION_HOURS = 12;
6
+ /** The longest cap: the lifetime of every IAM login (`SESSION_TTL_SECONDS`, 30 days). */
7
+ export declare const MAX_OIDC_SESSION_HOURS: number;
8
+ /**
9
+ * Parse the cap into seconds. Unset or empty means the default; anything but a whole number of hours from 1 to 720 is
10
+ * refused, so a typo fails the boot instead of capping at a value nobody chose.
11
+ */
12
+ export declare function parseOidcSessionSeconds(raw: string | undefined, name?: string): number;
@@ -0,0 +1,68 @@
1
+ import { type SqlDatabase } from '@fabrika/platform';
2
+ import type { SealedValue } from '../data-key';
3
+ import { type AuditEventInput, AuditWriter } from './audit';
4
+ /** A row of `second_factors` (migration 0032): one TOTP authenticator per principal, its secret sealed. */
5
+ export interface SecondFactorRow {
6
+ principal_id: string;
7
+ ciphertext: string;
8
+ value_iv: string;
9
+ wrapped_dek: string;
10
+ dek_iv: string;
11
+ created_at: number;
12
+ /** NULL while the enrolment waits for its first valid code. Only a confirmed factor is asked for at sign-in. */
13
+ confirmed_at: number | null;
14
+ /** The time step of the last accepted code; a code of that step or an earlier one is never accepted again. */
15
+ last_step: number | null;
16
+ /** The confirmation that wrote the recovery codes; NULL until one did. */
17
+ confirmation_id: string | null;
18
+ }
19
+ /** What an administrator sees of a principal's second factor. */
20
+ export interface SecondFactorStatus {
21
+ readonly confirmedAt: number | null;
22
+ readonly recoveryCodesLeft: number;
23
+ }
24
+ export declare function sealedValueOf(row: SecondFactorRow): SealedValue;
25
+ /**
26
+ * A person's TOTP authenticator and recovery codes. Every write that touches more than one of a principal's rows locks
27
+ * the principal row first on Postgres (`principalLockStatements`), the order every writer of a principal's rows keeps.
28
+ */
29
+ export declare class SecondFactorRepository {
30
+ protected readonly db: SqlDatabase;
31
+ private readonly writer;
32
+ constructor(db: SqlDatabase, writer?: AuditWriter);
33
+ get(principalId: string): Promise<SecondFactorRow | null>;
34
+ /** Whether a sign-in of the principal needs its second factor. */
35
+ isConfirmed(principalId: string): Promise<boolean>;
36
+ status(principalId: string): Promise<SecondFactorStatus>;
37
+ /**
38
+ * Store a new secret that waits for its first code, replacing one that still waits. A confirmed factor is never
39
+ * replaced here (false): only an administrator's reset removes it. Nothing is recorded: an unconfirmed secret asks
40
+ * nobody for anything; its confirmation is the enrolment, and that is recorded.
41
+ */
42
+ begin(principalId: string, sealed: SealedValue): Promise<boolean>;
43
+ /**
44
+ * Confirm the waiting secret whose ciphertext the caller checked the code against, with its record, and replace the
45
+ * principal's recovery codes with `recoveryCodeHashes`, in one transaction. The codes are written only when the
46
+ * confirmation changed the row, so a secret replaced in between confirms nothing (false) and issues no code. The guard
47
+ * reads this attempt's own `confirmation_id`, never the timestamp: a second confirmation in the same second must not
48
+ * replace the codes the first one showed.
49
+ */
50
+ confirm(input: {
51
+ principalId: string;
52
+ ciphertext: string;
53
+ step: number;
54
+ recoveryCodeHashes: readonly string[];
55
+ }, audit: AuditEventInput): Promise<boolean>;
56
+ /**
57
+ * Accept a code of `step` for a confirmed factor: true only when no code of this step or a later one was accepted
58
+ * before. The guard is the statement itself, so two submissions of one code accept it once.
59
+ */
60
+ acceptStep(principalId: string, step: number): Promise<boolean>;
61
+ /** Spend one unused recovery code of a confirmed factor, with its record; false when the code is not one. */
62
+ spendRecoveryCode(principalId: string, codeHash: string, audit: AuditEventInput): Promise<boolean>;
63
+ /**
64
+ * Remove the principal's authenticator and recovery codes, with one record, so its next sign-in asks for no second
65
+ * factor and it may enrol again. False when it had neither, and nothing is recorded.
66
+ */
67
+ reset(principalId: string, audit: AuditEventInput): Promise<boolean>;
68
+ }
@@ -30,7 +30,11 @@ export interface SessionRow {
30
30
  /** The terminal's generation the login was asserted in; the session is valid only while it is still the terminal's. */
31
31
  terminal_generation: number | null;
32
32
  }
33
- export interface ListedSessionRow extends SessionRow {
33
+ /** A session as a lookup returns it: with the time its login signed in, the parent's for a child session. */
34
+ export interface SignedInSessionRow extends SessionRow {
35
+ signed_in_at: number;
36
+ }
37
+ export interface ListedSessionRow extends SignedInSessionRow {
34
38
  parent_expires_at: number | null;
35
39
  parent_revoked_at: number | null;
36
40
  }
@@ -86,12 +90,12 @@ export declare class SessionRepository {
86
90
  * A session on a terminal is valid only while that terminal is enrolled, and so is a child whose parent is on one: a
87
91
  * revoked terminal ends them at once, with no sweep (ADR-0067).
88
92
  */
89
- getActiveSessionByHash(tokenHash: string): Promise<SessionRow | null>;
93
+ getActiveSessionByHash(tokenHash: string): Promise<SignedInSessionRow | null>;
90
94
  /**
91
95
  * The same validity rule as `getActiveSessionByHash`, addressed by id — how a handoff code reaches
92
96
  * the login it was issued against, which it holds by id rather than by a hash it must not store.
93
97
  */
94
- getActiveSessionById(id: string): Promise<SessionRow | null>;
98
+ getActiveSessionById(id: string): Promise<SignedInSessionRow | null>;
95
99
  /**
96
100
  * Whether the IAM login `parentSessionId` holds a live session bound to `app` — whether this login already chose that
97
101
  * application. The parent's own validity is the caller's: it reads the login it asks about first.
@@ -0,0 +1,42 @@
1
+ import type { Locale } from '@fabrika/auth-core';
2
+ import { SECOND_FACTOR_ENROL_PATH } from '@fabrika/iam-contract';
3
+ import type { InstallationBrand } from '@fabrika/proxy-core/brand';
4
+ import { type AppPresentation } from './app-presentation';
5
+ export { SECOND_FACTOR_ENROL_PATH };
6
+ /** Where a sign-in waiting for its second factor posts the code. */
7
+ export declare const SECOND_FACTOR_PATH = "/auth/second-factor";
8
+ /** Why the code form is shown again. */
9
+ export type ChallengeProblem = 'invalid' | 'throttled' | 'app_codes_unavailable';
10
+ /**
11
+ * The code a sign-in asks for after its first factor. The pending sign-in rides in the challenge cookie, never in the
12
+ * form. A verified code answers the login's own 302, to the handoff's registered origin, which `form-action` admits.
13
+ */
14
+ export declare function secondFactorChallengePage(input: {
15
+ readonly presentation: AppPresentation;
16
+ readonly redirectOrigin?: string;
17
+ readonly problem?: ChallengeProblem;
18
+ }): Response;
19
+ export interface EnrolPageBase {
20
+ readonly brand: InstallationBrand | null;
21
+ readonly locale: Locale;
22
+ }
23
+ /** The start of an enrolment: what two-step sign-in asks of the person, and the button that issues a key. */
24
+ export declare function secondFactorIntroPage(input: EnrolPageBase): Response;
25
+ /** The key to enrol, as a QR code and as text, and the form that confirms it with the first code. */
26
+ export declare function secondFactorEnrolPage(input: EnrolPageBase & {
27
+ readonly qrCode: string;
28
+ readonly key: string;
29
+ readonly invalidCode?: boolean;
30
+ }): Response;
31
+ /** The recovery codes, shown once, at the confirmed enrolment. `landing` is where the person continues. */
32
+ export declare function recoveryCodesPage(input: EnrolPageBase & {
33
+ readonly codes: readonly string[];
34
+ readonly landing: string;
35
+ }): Response;
36
+ /** An authenticator is already enrolled: since when, and how many recovery codes are left. */
37
+ export declare function secondFactorEnrolledPage(input: EnrolPageBase & {
38
+ readonly confirmedAt: number;
39
+ readonly recoveryCodesLeft: number;
40
+ }): Response;
41
+ /** The installation holds no data key, so no authenticator can be enrolled. */
42
+ export declare function secondFactorUnavailablePage(input: EnrolPageBase): Response;
@@ -16,6 +16,8 @@ export interface Services {
16
16
  readonly oidc: OidcClient | null;
17
17
  readonly passwordHasher: PasswordHasher;
18
18
  readonly email: EmailSender | null;
19
+ /** `FABRIKA_IAM_DATA_KEY`, which seals TOTP secrets (`src/data-key.ts`); null when unset, and TOTP enrolment is unavailable. */
20
+ readonly dataKey: Uint8Array<ArrayBuffer> | null;
19
21
  readonly config: Config;
20
22
  }
21
23
  export interface Config {
@@ -46,6 +48,8 @@ export interface Config {
46
48
  readonly authentication: {
47
49
  readonly oidc: {
48
50
  readonly enabled: boolean;
51
+ /** How long after its sign-in an OIDC login is usable (`OIDC_SESSION_HOURS`); then the provider is asked again. */
52
+ readonly sessionCapSeconds: number;
49
53
  };
50
54
  readonly password: {
51
55
  readonly enabled: boolean;
@@ -0,0 +1,32 @@
1
+ export declare const TOTP_PERIOD_SECONDS = 30;
2
+ export declare const TOTP_DIGITS = 6;
3
+ /** Recovery codes issued at enrolment; each signs in once in place of a code. */
4
+ export declare const RECOVERY_CODE_COUNT = 10;
5
+ export declare function generateTotpSecret(): Uint8Array<ArrayBuffer>;
6
+ /** RFC 4648 base32 without padding: what an authenticator app expects in `secret=` and what a person types. */
7
+ export declare function base32(bytes: Uint8Array): string;
8
+ /** The time step `unixSeconds` falls in. */
9
+ export declare function totpStep(unixSeconds: number): number;
10
+ /** The code of `step` (RFC 4226 dynamic truncation), zero-padded to six digits. */
11
+ export declare function totpCode(secret: Uint8Array<ArrayBuffer>, step: number): Promise<string>;
12
+ /** Six digits, as a person types them: spaces are dropped, anything else is not a code. */
13
+ export declare function parseTotpCode(input: string): string | null;
14
+ /**
15
+ * The step `code` belongs to, within the accepted drift of `now` and after `lastStep`, or null. A step at or before
16
+ * `lastStep` is refused, so an accepted code — and every earlier one — is never accepted again.
17
+ */
18
+ export declare function matchingStep(secret: Uint8Array<ArrayBuffer>, code: string, unixSeconds: number, lastStep: number | null): Promise<number | null>;
19
+ /** The URI an authenticator app enrols from, as a QR code or typed in. `issuer` names the installation, `account` the person. */
20
+ export declare function otpauthUri(input: {
21
+ readonly issuer: string;
22
+ readonly account: string;
23
+ readonly secret: Uint8Array;
24
+ }): string;
25
+ /** The URI as a QR code: an SVG `data:` URI, which the page CSP's `img-src data:` admits and which runs no script. */
26
+ export declare function qrCodeDataUri(text: string): string;
27
+ /** Fresh recovery codes, grouped by four for reading: `abcd-efgh-ijkl-mnop`. */
28
+ export declare function generateRecoveryCodes(): string[];
29
+ /** A recovery code as typed: case, spaces and dashes do not matter; anything else is not one. */
30
+ export declare function parseRecoveryCode(input: string): string | null;
31
+ /** The stored form of a recovery code: its hash, bound to its principal, so no code is stored and none spends elsewhere. */
32
+ export declare function recoveryCodeHash(principalId: string, code: string): Promise<string>;