@fabrika/iam 0.9.0-dev.33 → 0.9.0-dev.35

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.
@@ -2,6 +2,9 @@ import type { Env } from './env';
2
2
  import type { Services } from './services';
3
3
  export declare const OAUTH_METADATA_PATH = "/.well-known/oauth-authorization-server";
4
4
  type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>;
5
- /** The OAuth authorization server's public surface. With `OAUTH_CONFIG` unset every path is 404. */
6
- export declare function handleOAuth(request: Request, services: Services, env: SigningEnv, requestId: string): Promise<Response>;
5
+ /**
6
+ * The OAuth authorization server's public surface. With `OAUTH_CONFIG` unset every path is 404. `clientAddress` is the
7
+ * composition's client coordinate (`client-address.ts`), null where it names none.
8
+ */
9
+ export declare function handleOAuth(request: Request, services: Services, env: SigningEnv, requestId: string, clientAddress: string | null): Promise<Response>;
7
10
  export {};
@@ -1,46 +1,72 @@
1
1
  import { type KeyGrant, type PermissionEntry } from '@fabrika/auth-core';
2
- import type { OAuthAuthorizationRequest, OAuthClientMetadataDocument, OAuthResourceDto, OAuthRevocationRequest, OAuthTokenRequest, OAuthTokenResponse } from '@fabrika/iam-contract';
3
- import { type OAuthGrantRow, type PrincipalRow, type SessionRow } from './db';
2
+ import { OAUTH_DEVICE_CODE_GRANT_TYPE, type OAuthAuthorizationRequest, type OAuthClientMetadataDocument, type OAuthResourceDto, type OAuthRevocationRequest, type OAuthTokenRequest, type OAuthTokenResponse } from '@fabrika/iam-contract';
3
+ import { type AuditEventInput, type OAuthGrantRow, type PrincipalRow, type SessionRow } from './db';
4
4
  import type { Env } from './env';
5
5
  import type { ManagedOAuthClient, OAuthConfig } from './oauth-config';
6
6
  import type { Services } from './services';
7
7
  /** An authorization code is redeemed by the client's back end within seconds of the redirect. */
8
8
  export declare const OAUTH_CODE_TTL_SECONDS = 60;
9
9
  type SigningEnv = Pick<Env, 'FABRIKA_IAM_SIGNING_KEYS' | 'ENVIRONMENT'>;
10
- export interface EstablishedClient {
10
+ /**
11
+ * A client an authorization or token request comes from: an operator-registered CIMD client, or the installation's own
12
+ * command-line client, a public client IAM knows without a document. The CLI client has no redirect URI, so it never
13
+ * completes an authorization request; it redeems the grants IAM gives it otherwise and refreshes them.
14
+ */
15
+ export type EstablishedClient = {
16
+ kind: 'managed';
11
17
  registration: ManagedOAuthClient;
12
18
  metadata: OAuthClientMetadataDocument;
13
- }
19
+ } | {
20
+ kind: 'cli';
21
+ clientId: string;
22
+ };
23
+ export type ManagedClient = Extract<EstablishedClient, {
24
+ kind: 'managed';
25
+ }>;
26
+ /** Whether `resource` is served to the command-line client (`cli`) or to the managed clients; never to both. */
27
+ export declare function servesClient(resource: OAuthResourceDto, cli: boolean): boolean;
28
+ /** The resources a grant was given for: every token it mints names one of them. */
29
+ export declare function grantResources(grant: Pick<OAuthGrantRow, 'resource' | 'resources'>): string[];
30
+ /** A stored JSON list of resources, or null when it is not one. */
31
+ export declare function storedResourceList(text: string): string[] | null;
14
32
  /**
15
33
  * Resolve a client and its redirect URI. Until this succeeds nothing may be redirected to
16
34
  * `redirect_uri`. An unregistered client id is refused before any metadata fetch.
17
35
  */
18
- export declare function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<EstablishedClient | null>;
36
+ export declare function establishClient(config: OAuthConfig, clientId: string, redirectUri: string): Promise<ManagedClient | null>;
37
+ /** What a consent grants: a registered resource, or an identity-only client's own resource. */
38
+ export type AuthorizationTarget = Pick<OAuthResourceDto, 'app' | 'resource'>;
19
39
  /** Record the consent and return the plaintext authorization code — the only time it exists. */
20
40
  export declare function grantAuthorization(services: Services, input: {
21
41
  request: OAuthAuthorizationRequest;
22
- resource: OAuthResourceDto;
42
+ resource: AuthorizationTarget;
23
43
  scopes: string[];
24
44
  session: SessionRow;
25
45
  requestId: string;
26
46
  }): Promise<string>;
47
+ /** RFC 6749 §5.2 and RFC 8628 §3.5: what a refused token request answers. */
48
+ export type OAuthTokenError = 'invalid_grant' | 'invalid_target' | 'unauthorized_client' | 'authorization_pending' | 'slow_down' | 'access_denied' | 'expired_token';
27
49
  export type OAuthTokenOutcome = {
28
50
  ok: true;
29
51
  body: OAuthTokenResponse;
30
52
  } | {
31
53
  ok: false;
32
- error: 'invalid_grant';
54
+ error: OAuthTokenError;
33
55
  };
34
56
  /** Redeem a code or rotate a refresh token for a client `authenticateOAuthClient` established. */
35
- export declare function exchangeOAuthToken(services: Services, env: SigningEnv, client: EstablishedClient, input: OAuthTokenRequest, requestId: string): Promise<OAuthTokenOutcome>;
57
+ export declare function exchangeOAuthToken(services: Services, env: SigningEnv, client: EstablishedClient, input: Exclude<OAuthTokenRequest, {
58
+ grant_type: typeof OAUTH_DEVICE_CODE_GRANT_TYPE;
59
+ }>, requestId: string): Promise<OAuthTokenOutcome>;
36
60
  /** RFC 7009: revoking either token kind revokes its grant. An unknown or foreign token is a silent no-op. */
37
61
  export declare function revokeOAuthToken(services: Services, env: SigningEnv, input: OAuthRevocationRequest, requestId: string): Promise<void>;
62
+ /** An access token for `resource`, one of the grant's resources, carrying the grant's live authority there. */
63
+ export declare function mintForGrant(services: Services, env: SigningEnv, grant: OAuthGrantRow, resource: string, now: number): Promise<OAuthTokenResponse | null>;
38
64
  /**
39
65
  * Everything a grant needs to still mean something, checked at every code exchange and refresh: the
40
66
  * grant live, its client and resource still configured, the IAM session it was given under live and
41
67
  * usable, the principal an active user. The permissions are resolved live, never from the consent.
42
68
  */
43
- export declare function grantAuthority(services: Services, grant: OAuthGrantRow, now: number): Promise<{
69
+ export declare function grantAuthority(services: Services, grant: OAuthGrantRow, now: number, resourceUri?: string): Promise<{
44
70
  principal: PrincipalRow;
45
71
  scopes: string[];
46
72
  permissions: PermissionEntry[];
@@ -48,4 +74,6 @@ export declare function grantAuthority(services: Services, grant: OAuthGrantRow,
48
74
  } | null>;
49
75
  /** The union of the scopes' grants, or null when a scope is no longer configured. */
50
76
  export declare function scopeCeiling(resource: OAuthResourceDto, scopes: readonly string[]): KeyGrant[] | null;
77
+ /** The record of a grant's revocation: by its client, or by IAM on a replayed code or refresh token. */
78
+ export declare function grantRevocation(requestId: string, grantId: string, clientId: string, reason: 'code_replay' | 'refresh_replay' | 'device_code_replay' | 'client_revocation'): AuditEventInput;
51
79
  export {};
@@ -92,7 +92,8 @@ export type SqlDialect = 'sqlite' | 'postgres';
92
92
  * The INSERT of one audit row, for the batch of an unconditional change it records: the row and the change commit
93
93
  * together, and a failed insert rolls the change back. Diff and metadata are stored JSON-encoded.
94
94
  */
95
- export declare function auditEventStatement(db: SqlDatabase, event: AuditEventInput): SqlStatement;
95
+ /** The INSERT of one audit row; with `guard`, written only when the guard finds its row (see `SqlGuard`). */
96
+ export declare function auditEventStatement(db: SqlDatabase, event: AuditEventInput, guard?: SqlGuard): SqlStatement;
96
97
  /**
97
98
  * `auditEventStatement` whose `resource_id` is read in the batch by `resourceId`, a one-row SELECT of one column: for
98
99
  * a resource whose id the batch itself settles, such as a principal another writer may have created first.
@@ -6,7 +6,10 @@ export interface OAuthGrantRow {
6
6
  session_id: string;
7
7
  client_id: string;
8
8
  app: string;
9
+ /** The grant's first resource; `resources` lists them all when it was given for several. */
9
10
  resource: string;
11
+ /** JSON array of every resource of the grant, all of `app`; null when `resource` is the only one. */
12
+ resources: string | null;
10
13
  /** JSON array of the consented scope names. */
11
14
  scopes: string;
12
15
  created_at: number;
@@ -27,6 +30,27 @@ export interface OAuthRefreshTokenRow {
27
30
  expires_at: number;
28
31
  used_at: number | null;
29
32
  }
33
+ /** An RFC 8628 attempt. `principal_id`, `session_id` and `grant_expires_at` are set by its approval, `grant_id` by its redemption. */
34
+ export interface OAuthDeviceAuthorizationRow {
35
+ device_code_hash: string;
36
+ user_code_hash: string;
37
+ client_id: string;
38
+ app: string;
39
+ /** JSON array of the resources the grant will cover, all of `app`. */
40
+ resources: string;
41
+ /** JSON array of the requested scope tokens. */
42
+ scopes: string;
43
+ interval_seconds: number;
44
+ next_poll_at: number;
45
+ created_at: number;
46
+ expires_at: number;
47
+ status: 'pending' | 'approved' | 'denied' | 'redeemed';
48
+ principal_id: string | null;
49
+ session_id: string | null;
50
+ grant_expires_at: number | null;
51
+ grant_id: string | null;
52
+ }
53
+ export type NewOAuthDeviceAuthorization = Pick<OAuthDeviceAuthorizationRow, 'device_code_hash' | 'user_code_hash' | 'client_id' | 'app' | 'resources' | 'scopes' | 'interval_seconds' | 'created_at' | 'expires_at'>;
30
54
  /** Codes and refresh tokens are addressed by hash only; the plaintext never reaches this layer. */
31
55
  export declare class OAuthRepository {
32
56
  private readonly db;
@@ -45,10 +69,33 @@ export declare class OAuthRepository {
45
69
  /** Spend a refresh token for rotation. A second presentation gets null and finds the spent row via `refreshToken`. */
46
70
  consumeRefreshToken(tokenHash: string, now: number): Promise<OAuthRefreshTokenRow | null>;
47
71
  refreshToken(tokenHash: string): Promise<OAuthRefreshTokenRow | null>;
72
+ /** Record a device attempt. False when either code's hash is taken already, so the caller draws new codes. */
73
+ startDeviceAuthorization(row: NewOAuthDeviceAuthorization): Promise<boolean>;
74
+ deviceAuthorization(deviceCodeHash: string): Promise<OAuthDeviceAuthorizationRow | null>;
75
+ /** The attempt a person may still decide: pending and unexpired. */
76
+ pendingDeviceAuthorization(userCodeHash: string, now: number): Promise<OAuthDeviceAuthorizationRow | null>;
77
+ /** Approve a pending attempt under the approver's IAM session. False when it was decided, or expired, meanwhile. */
78
+ approveDeviceAuthorization(userCodeHash: string, approval: {
79
+ principalId: string;
80
+ sessionId: string;
81
+ grantExpiresAt: number;
82
+ }, now: number): Promise<boolean>;
83
+ denyDeviceAuthorization(userCodeHash: string, now: number): Promise<boolean>;
84
+ /**
85
+ * Admit one poll of an attempt (RFC 8628 §3.5). A poll before the interval has passed is refused and lengthens the
86
+ * interval by five seconds, which the client is told to add with `slow_down`.
87
+ */
88
+ admitDevicePoll(deviceCodeHash: string, now: number): Promise<boolean>;
89
+ /**
90
+ * Spend an approved attempt for `grant`: the claim, the grant, its record and its first refresh token in one batch.
91
+ * Every write after the claim requires the claim this batch made (`grant_id` names this grant), so exactly one poll
92
+ * gives a grant, and a refused or failed claim writes nothing. Answers the claimed row, or null.
93
+ */
94
+ redeemDeviceAuthorization(deviceCodeHash: string, grant: OAuthGrantRow, refreshTokenHash: string, audit: AuditEventInput, now: number): Promise<OAuthDeviceAuthorizationRow | null>;
48
95
  /** Record an accepted client assertion's `jti`. False when the client already presented it: a replay. */
49
96
  recordClientAssertion(clientId: string, jti: string, expiresAt: number): Promise<boolean>;
50
97
  /**
51
- * Delete codes, refresh tokens and client assertion ids past expiry. Spent rows stay until then because they are what
98
+ * Delete codes, refresh tokens, client assertion ids and device attempts past expiry. Spent rows stay until then because they are what
52
99
  * detects a replay. Grants go with their session row (`ON DELETE CASCADE`), which shares their expiry.
53
100
  */
54
101
  prune(now: number): Promise<void>;
@@ -31,14 +31,14 @@ export declare const exchangeAuthCodeSchema: z.ZodCatch<z.ZodObject<{
31
31
  verifier: z.ZodString;
32
32
  requestId: z.ZodString;
33
33
  }, "strip", z.ZodTypeAny, {
34
- code: string;
35
34
  app: string;
36
35
  requestId: string;
36
+ code: string;
37
37
  verifier: string;
38
38
  }, {
39
- code: string;
40
39
  app: string;
41
40
  requestId: string;
41
+ code: string;
42
42
  verifier: string;
43
43
  }>>;
44
44
  export declare const issueKeySchema: z.ZodCatch<z.ZodEffects<z.ZodObject<{
@@ -154,8 +154,8 @@ export declare const issueKeySchema: z.ZodCatch<z.ZodEffects<z.ZodObject<{
154
154
  label: z.ZodEffects<z.ZodOptional<z.ZodNullable<z.ZodString>>, string | undefined, string | null | undefined>;
155
155
  expiresAt: z.ZodNumber;
156
156
  }, "strip", z.ZodTypeAny, {
157
- expiresAt: number;
158
157
  app: string;
158
+ expiresAt: number;
159
159
  credential: string | null;
160
160
  requestId: string;
161
161
  service?: {
@@ -176,8 +176,8 @@ export declare const issueKeySchema: z.ZodCatch<z.ZodEffects<z.ZodObject<{
176
176
  }[] | undefined;
177
177
  principalId?: string | undefined;
178
178
  }, {
179
- expiresAt: number;
180
179
  app: string;
180
+ expiresAt: number;
181
181
  credential: string | null;
182
182
  requestId: string;
183
183
  service?: {
@@ -220,8 +220,8 @@ export declare const issueKeySchema: z.ZodCatch<z.ZodEffects<z.ZodObject<{
220
220
  credential: string | null;
221
221
  requestId: string;
222
222
  }, {
223
- expiresAt: number;
224
223
  app: string;
224
+ expiresAt: number;
225
225
  credential: string | null;
226
226
  requestId: string;
227
227
  service?: {
@@ -248,13 +248,13 @@ export declare const revokeKeySchema: z.ZodCatch<z.ZodObject<{
248
248
  credential: z.ZodNullable<z.ZodString>;
249
249
  requestId: z.ZodString;
250
250
  }, "strip", z.ZodTypeAny, {
251
- id: string;
252
251
  app: string;
252
+ id: string;
253
253
  credential: string | null;
254
254
  requestId: string;
255
255
  }, {
256
- id: string;
257
256
  app: string;
257
+ id: string;
258
258
  credential: string | null;
259
259
  requestId: string;
260
260
  }>>;
@@ -394,15 +394,15 @@ export declare const assignMemberSchema: z.ZodCatch<z.ZodObject<{
394
394
  resend: z.ZodOptional<z.ZodBoolean>;
395
395
  locale: z.ZodOptional<z.ZodEnum<["en", "cs", "uk"]>>;
396
396
  }, "strict", z.ZodTypeAny, {
397
- message?: string | undefined;
398
- resend?: boolean | undefined;
399
397
  locale?: "en" | "cs" | "uk" | undefined;
400
- label?: string | undefined;
401
- }, {
402
398
  message?: string | undefined;
399
+ label?: string | undefined;
403
400
  resend?: boolean | undefined;
401
+ }, {
404
402
  locale?: "en" | "cs" | "uk" | undefined;
403
+ message?: string | undefined;
405
404
  label?: string | undefined;
405
+ resend?: boolean | undefined;
406
406
  }>>;
407
407
  app: z.ZodString;
408
408
  credential: z.ZodNullable<z.ZodString>;
@@ -423,10 +423,10 @@ export declare const assignMemberSchema: z.ZodCatch<z.ZodObject<{
423
423
  delegation: string;
424
424
  role: string;
425
425
  invitation?: {
426
- message?: string | undefined;
427
- resend?: boolean | undefined;
428
426
  locale?: "en" | "cs" | "uk" | undefined;
427
+ message?: string | undefined;
429
428
  label?: string | undefined;
429
+ resend?: boolean | undefined;
430
430
  } | undefined;
431
431
  }, {
432
432
  app: string;
@@ -444,10 +444,10 @@ export declare const assignMemberSchema: z.ZodCatch<z.ZodObject<{
444
444
  delegation: string;
445
445
  role: string;
446
446
  invitation?: {
447
- message?: string | undefined;
448
- resend?: boolean | undefined;
449
447
  locale?: "en" | "cs" | "uk" | undefined;
448
+ message?: string | undefined;
450
449
  label?: string | undefined;
450
+ resend?: boolean | undefined;
451
451
  } | undefined;
452
452
  }>>;
453
453
  export declare const revokeMemberSchema: z.ZodCatch<z.ZodObject<{
@@ -642,13 +642,13 @@ export declare const revokeLinkSchema: z.ZodCatch<z.ZodObject<{
642
642
  credential: z.ZodNullable<z.ZodString>;
643
643
  requestId: z.ZodString;
644
644
  }, "strip", z.ZodTypeAny, {
645
- id: string;
646
645
  app: string;
646
+ id: string;
647
647
  credential: string | null;
648
648
  requestId: string;
649
649
  }, {
650
- id: string;
651
650
  app: string;
651
+ id: string;
652
652
  credential: string | null;
653
653
  requestId: string;
654
654
  }>>;
@@ -658,13 +658,13 @@ export declare const inspectIdentificationSchema: z.ZodCatch<z.ZodObject<{
658
658
  credential: z.ZodNullable<z.ZodString>;
659
659
  requestId: z.ZodString;
660
660
  }, "strip", z.ZodTypeAny, {
661
- id: string;
662
661
  app: string;
662
+ id: string;
663
663
  credential: string | null;
664
664
  requestId: string;
665
665
  }, {
666
- id: string;
667
666
  app: string;
667
+ id: string;
668
668
  credential: string | null;
669
669
  requestId: string;
670
670
  }>>;
@@ -675,14 +675,14 @@ export declare const assertIdentitySchema: z.ZodCatch<z.ZodObject<{
675
675
  credential: z.ZodNullable<z.ZodString>;
676
676
  requestId: z.ZodString;
677
677
  }, "strip", z.ZodTypeAny, {
678
- id: string;
679
678
  app: string;
679
+ id: string;
680
680
  principalId: string;
681
681
  credential: string | null;
682
682
  requestId: string;
683
683
  }, {
684
- id: string;
685
684
  app: string;
685
+ id: string;
686
686
  principalId: string;
687
687
  credential: string | null;
688
688
  requestId: string;
@@ -693,13 +693,13 @@ export declare const cancelIdentificationSchema: z.ZodCatch<z.ZodObject<{
693
693
  credential: z.ZodNullable<z.ZodString>;
694
694
  requestId: z.ZodString;
695
695
  }, "strip", z.ZodTypeAny, {
696
- id: string;
697
696
  app: string;
697
+ id: string;
698
698
  credential: string | null;
699
699
  requestId: string;
700
700
  }, {
701
- id: string;
702
701
  app: string;
702
+ id: string;
703
703
  credential: string | null;
704
704
  requestId: string;
705
705
  }>>;
@@ -73,4 +73,10 @@ export declare const DEFAULT_ADMIN_AUDIENCES: ReadonlySet<string>;
73
73
  export declare const DEFAULT_PLATFORM_AUDIENCES: ReadonlySet<string>;
74
74
  /** An admin audience is a console gateway, so it is a platform service too, whatever it is named. */
75
75
  export declare function platformAudiencesFor(adminAudiences: ReadonlySet<string>): ReadonlySet<string>;
76
+ /**
77
+ * Parse `ADMIN_AUDIENCES` (comma-separated app ids). Unset = `DEFAULT_ADMIN_AUDIENCES`; explicitly
78
+ * empty = no JWT may administer. A malformed entry is REFUSED rather than skipped: an entry no `aud`
79
+ * can ever equal would otherwise read as a registry while admitting nobody.
80
+ */
81
+ export declare function parseAdminAudiences(raw: string | undefined): ReadonlySet<string>;
76
82
  export declare function buildServices(env: Env): Services;