@fabrika/auth-core 0.8.2 → 0.9.0-cloudflare.1

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 (42) hide show
  1. package/package.json +4 -3
  2. package/src/contract-canonical.ts +1 -0
  3. package/src/contract.ts +6 -0
  4. package/src/dev-environment.ts +45 -0
  5. package/src/framework-release.ts +2 -0
  6. package/src/framework-variables.ts +14 -2
  7. package/src/index.ts +5 -0
  8. package/src/managed-environment.ts +136 -0
  9. package/src/ops.ts +497 -0
  10. package/src/terminal.ts +105 -0
  11. package/src/token.ts +65 -5
  12. package/src/types.ts +4 -1
  13. package/types/src/app-environment.d.ts +24 -0
  14. package/types/src/canonical-path.d.ts +20 -0
  15. package/types/src/contract-canonical.d.ts +19 -0
  16. package/types/src/contract.d.ts +800 -0
  17. package/types/src/dev-environment.d.ts +37 -0
  18. package/types/src/device.d.ts +144 -0
  19. package/types/src/endpoint-digest.d.ts +58 -0
  20. package/types/src/endpoints.d.ts +65 -0
  21. package/types/src/environment.d.ts +58 -0
  22. package/types/src/framework-release.d.ts +2 -0
  23. package/types/src/framework-variables.d.ts +86 -0
  24. package/types/src/index.d.ts +28 -0
  25. package/types/src/installation-endpoint.d.ts +46 -0
  26. package/types/src/json.d.ts +13 -0
  27. package/types/src/locale.d.ts +14 -0
  28. package/types/src/mail.d.ts +67 -0
  29. package/types/src/managed-environment.d.ts +32 -0
  30. package/types/src/membership.d.ts +318 -0
  31. package/types/src/oauth.d.ts +7 -0
  32. package/types/src/ops.d.ts +181 -0
  33. package/types/src/path-segment.d.ts +5 -0
  34. package/types/src/permissions.d.ts +50 -0
  35. package/types/src/requirement.d.ts +24 -0
  36. package/types/src/rpc.d.ts +283 -0
  37. package/types/src/sha256.d.ts +2 -0
  38. package/types/src/terminal.d.ts +72 -0
  39. package/types/src/token.d.ts +240 -0
  40. package/types/src/types.d.ts +196 -0
  41. package/types/src/wire.d.ts +65 -0
  42. package/types/src/workloads.d.ts +25 -0
@@ -0,0 +1,283 @@
1
+ import type { ApproveDeviceAuthorizationInput, ApproveDeviceAuthorizationResult, DenyDeviceAuthorizationResult, InspectDeviceAuthorizationInput, InspectDeviceAuthorizationResult, ListOwnDeviceAuthorizationsInput, ListOwnDeviceAuthorizationsResult } from './device';
2
+ import type { Jwks } from './token';
3
+ import type { PermissionEntry, PrincipalType, Scope } from './types';
4
+ export interface MintTokenInput {
5
+ /** The app requesting a permission token (the SDK bakes this into its constructor). */
6
+ app: string;
7
+ /** The opaque session cookie value (`__Host-px_session`); null when the browser has no session. */
8
+ session: string | null;
9
+ requestId: string;
10
+ }
11
+ export type MintTokenResult =
12
+ /** `expiresAt` (unix seconds) lets the SDK refresh ahead of expiry. */
13
+ {
14
+ ok: true;
15
+ token: string;
16
+ expiresAt: number;
17
+ }
18
+ /** `token_too_large`: the principal holds more than fits in one header; a decided refusal, never a login bounce. */
19
+ | {
20
+ ok: false;
21
+ reason: 'no_session' | 'invalid_session' | 'unknown_principal' | 'disabled' | 'token_too_large';
22
+ };
23
+ export interface MintFromKeyInput {
24
+ /** The app requesting the token (the SDK bakes this into its constructor). */
25
+ app: string;
26
+ /** The opaque `px_` credential (bearer / path token). */
27
+ key: string;
28
+ requestId: string;
29
+ }
30
+ export type MintFromKeyResult = {
31
+ ok: true;
32
+ token: string;
33
+ expiresAt: number;
34
+ } | {
35
+ ok: false;
36
+ reason: 'invalid_key' | 'unknown_principal' | 'disabled' | 'token_too_large';
37
+ };
38
+ export interface ExchangeAuthCodeInput {
39
+ /** The app redeeming the code. A code issued for another app is refused. */
40
+ app: string;
41
+ /** The single-use code, as it arrived in the callback query. */
42
+ code: string;
43
+ /** Browser-held proof for the S256 challenge integrity-bound into the code. */
44
+ verifier: string;
45
+ requestId: string;
46
+ }
47
+ export type ExchangeAuthCodeResult =
48
+ /**
49
+ * `session` is the opaque APP session the proxy sets as a host-only cookie; `returnUrl` is where
50
+ * the browser goes next and is carried server-side so a caller cannot redirect it elsewhere.
51
+ * `expiresAt` is the session's absolute expiry, for the cookie's `Max-Age`.
52
+ */
53
+ {
54
+ ok: true;
55
+ session: string;
56
+ returnUrl: string;
57
+ expiresAt: number;
58
+ }
59
+ /** Every failure is terminal — a code is single-use, so there is nothing to retry. */
60
+ | {
61
+ ok: false;
62
+ reason: 'invalid_code' | 'expired_code' | 'wrong_app' | 'invalid_verifier' | 'unknown_principal' | 'disabled';
63
+ };
64
+ /**
65
+ * Redemption, as a contract of its own rather than a method on `IamRpc`. Only the proxy calls it, and
66
+ * `IamRpc` is held by every SDK consumer — folding it in would hand the ability to convert a code
67
+ * into a session to everything that holds the management key.
68
+ */
69
+ export interface IamHandoffRpc {
70
+ exchangeAuthCode(input: ExchangeAuthCodeInput): Promise<ExchangeAuthCodeResult>;
71
+ }
72
+ /**
73
+ * Where the proxy answers the handoff, on every app host it fronts. Reserved: an app route at this
74
+ * path is shadowed by the proxy and never reaches the upstream, so it is deliberately namespaced.
75
+ */
76
+ export declare const AUTH_CALLBACK_PATH = "/__fabrika/auth/callback";
77
+ /** Query parameter carrying the single-use code on the callback. */
78
+ export declare const AUTH_CODE_PARAM = "code";
79
+ /** Public nonce that selects the app-host handoff cookie on the callback. */
80
+ export declare const AUTH_HANDOFF_STATE_PARAM = "state";
81
+ /** S256 challenge sent to IAM when the proxy starts a handoff. */
82
+ export declare const AUTH_HANDOFF_CHALLENGE_PARAM = "code_challenge";
83
+ /** Dynamic app-host cookie prefix; the public state suffix permits concurrent login tabs. */
84
+ export declare const HANDOFF_COOKIE_PREFIX = "__Host-px_handoff_";
85
+ /** A login attempt may wait at IAM or an upstream IdP before the code itself is issued. */
86
+ export declare const HANDOFF_COOKIE_TTL_SECONDS: number;
87
+ /**
88
+ * How long a code may be held before redemption. Seconds, not minutes: it travels in one redirect
89
+ * and is redeemed by the next request, so anything longer is only a larger replay window.
90
+ */
91
+ export declare const AUTH_CODE_TTL_SECONDS = 120;
92
+ /** One grant on a `px_` credential — an action pattern + optional scope. */
93
+ export interface KeyGrant {
94
+ action: string;
95
+ /** Omitted/null = global (the issuer must hold the action globally). */
96
+ scope?: Scope | null;
97
+ }
98
+ /**
99
+ * Create a NEW service (machine) principal and bind the key to it — the folded `issueServiceToken`.
100
+ * The issuer must hold every `permissions` action on `scope` (the same delegation rule as a grant).
101
+ */
102
+ export interface IssueKeyServiceSpec {
103
+ /** Display label for the new service principal + the credential. */
104
+ label: string;
105
+ /** Inline action patterns granted to the new service principal; delegation-checked on `scope`. */
106
+ permissions: string[];
107
+ /** Scope the grant + the delegation check apply to; omitted/null → global. */
108
+ scope?: Scope | null;
109
+ }
110
+ export interface IssueKeyInput {
111
+ app: string;
112
+ /**
113
+ * The propustka-native credential the ISSUER is resolved from server-side (never self-asserted):
114
+ * a `px_token` access JWT (verified against propustka's signing keys) or a `px_` key. Null = absent.
115
+ */
116
+ credential: string | null;
117
+ requestId: string;
118
+ /**
119
+ * Create a NEW machine principal and bind the key to it (the folded `issueServiceToken`). When set,
120
+ * `principalId` / `permissions` (the bind / standalone modes) are ignored.
121
+ */
122
+ service?: IssueKeyServiceSpec;
123
+ /**
124
+ * Bind to a principal (the credential then carries that principal's LIVE perms; inline
125
+ * `permissions` downscope it). v1: only the issuer's OWN id. Omit for a standalone credential.
126
+ */
127
+ principalId?: string;
128
+ /** Inline grants — the frozen set (standalone) and/or a downscope restriction (bound). */
129
+ permissions?: KeyGrant[];
130
+ label?: string;
131
+ /** Absolute credential expiry (unix seconds), after now and at most `MAX_KEY_LIFETIME_SECONDS` ahead. */
132
+ expiresAt: number;
133
+ }
134
+ /**
135
+ * The longest a `px_` credential `issueKey` writes may live, in every mode. A key is a standing copy
136
+ * of authority that outlives any token it was issued from, so it must end; 30 days is also the
137
+ * builder's device-authorized key lifetime.
138
+ */
139
+ export declare const MAX_KEY_LIFETIME_SECONDS: number;
140
+ export type IssueKeyResult =
141
+ /**
142
+ * Plaintext `px_` token returned ONCE; `id` is the credential's stable handle (revoke). `principalId`
143
+ * is present when the key is bound to a principal (a `service` create or a self-bind), absent for a
144
+ * standalone (anonymous) credential.
145
+ */
146
+ {
147
+ ok: true;
148
+ token: string;
149
+ id: string;
150
+ principalId?: string;
151
+ } | {
152
+ ok: false;
153
+ reason: 'missing_token' | 'invalid_token' | 'unknown_principal' | 'disabled' | 'not_allowed';
154
+ };
155
+ /**
156
+ * A resolved caller identity + its frozen permission snapshot. Produced by `accessClaimsToResolved`
157
+ * from a verified access token (`token.ts`); consumed where a principal's resolved perms are needed
158
+ * as a plain serializable value.
159
+ */
160
+ export interface ResolvedPrincipal {
161
+ id: string;
162
+ type: PrincipalType;
163
+ label: string;
164
+ permissions: PermissionEntry[];
165
+ requestId: string;
166
+ }
167
+ export interface AuditInput {
168
+ /**
169
+ * The caller's verified access token — the one the proxy injected. IAM verifies it and records
170
+ * the app it was minted for; there is no `app` field, so a caller cannot name another app.
171
+ */
172
+ credential: string;
173
+ requestId: string;
174
+ /** NULL for an anonymous-credential event (a share link has no principal). */
175
+ principalId: string | null;
176
+ /** Snapshot — survives principal deletion (the credential/token label for anonymous events). */
177
+ principalLabel: string;
178
+ /** Set for an anonymous-credential event — the issuing credential id. */
179
+ credentialId?: string;
180
+ action: string;
181
+ resourceType: string;
182
+ resourceId?: string;
183
+ diff?: unknown;
184
+ metadata?: unknown;
185
+ }
186
+ export interface RevokeKeyInput {
187
+ app: string;
188
+ /** The propustka-native credential the CALLER (authorizer) is resolved from; null = absent. */
189
+ credential: string | null;
190
+ requestId: string;
191
+ /** The credential id (the `id` returned by `issueKey`), NOT the plaintext `px_` token. */
192
+ id: string;
193
+ }
194
+ export type RevokeKeyResult =
195
+ /** `revoked` is false when the credential was already revoked (idempotent). */
196
+ {
197
+ ok: true;
198
+ revoked: boolean;
199
+ } | {
200
+ ok: false;
201
+ reason: 'missing_token' | 'invalid_token' | 'unknown_principal' | 'disabled' | 'not_allowed' | 'not_found';
202
+ };
203
+ export interface ListPrincipalsInput {
204
+ /** Self-asserted caller app id; superseded by the credential's aud on a valid `px_token`. */
205
+ app: string;
206
+ /** The propustka-native credential the CALLER is resolved from (px_token / px_ key); null = absent. */
207
+ credential: string | null;
208
+ requestId: string;
209
+ }
210
+ export interface PrincipalListItem {
211
+ /** IAM principal id (UUIDv7) — stable, safe to store on domain rows (assignee/actor). */
212
+ id: string;
213
+ type: PrincipalType;
214
+ /** Human-readable: the user's email. */
215
+ label: string;
216
+ /** The user's email (users always have one; null only defensively). */
217
+ email: string | null;
218
+ /** True when the principal is soft-disabled (kept listable so labels still resolve). */
219
+ disabled: boolean;
220
+ }
221
+ export type ListPrincipalsResult = {
222
+ ok: true;
223
+ principals: PrincipalListItem[];
224
+ }
225
+ /** `not_allowed` when the caller has no verified app / no permission on it (a zero-grant user). */
226
+ | {
227
+ ok: false;
228
+ reason: 'missing_token' | 'invalid_token' | 'unknown_principal' | 'disabled' | 'not_allowed';
229
+ };
230
+ /**
231
+ * The RPC contract. The Worker's `WorkerEntrypoint` `implements IamRpc`; the SDK types its
232
+ * binding as `Service<IamRpc>` (so the SDK never imports the Worker). Methods return plain
233
+ * serializable objects (RPC-friendly).
234
+ */
235
+ export interface IamRpc {
236
+ inspectDeviceAuthorization(input: InspectDeviceAuthorizationInput): Promise<InspectDeviceAuthorizationResult>;
237
+ approveDeviceAuthorization(input: ApproveDeviceAuthorizationInput): Promise<ApproveDeviceAuthorizationResult>;
238
+ denyDeviceAuthorization(input: InspectDeviceAuthorizationInput): Promise<DenyDeviceAuthorizationResult>;
239
+ listOwnDeviceAuthorizations(input: ListOwnDeviceAuthorizationsInput): Promise<ListOwnDeviceAuthorizationsResult>;
240
+ /**
241
+ * Mint a short-lived, per-app permission token from the browser's SSO session — the
242
+ * propustka-native auth path. The SDK middleware calls this only when its cached permission
243
+ * token is missing/near-expiry (≈ once per TTL), NOT per request: every other request verifies
244
+ * the cached token locally against `getJwks`.
245
+ */
246
+ mintToken(input: MintTokenInput): Promise<MintTokenResult>;
247
+ /**
248
+ * Mint a per-app access token from an opaque `px_` credential (API key / share link) — the other
249
+ * front over the same resolve→sign core as `mintToken`. Called by the SDK middleware once per TTL
250
+ * when a request carries a `px_` bearer/path credential; every other request verifies the cached
251
+ * token locally. Fails closed (`invalid_key`/`unknown_principal`/`disabled`).
252
+ */
253
+ mintFromKey(input: MintFromKeyInput): Promise<MintFromKeyResult>;
254
+ /**
255
+ * Mint an opaque, stored, revocable `px_` credential (API key / share link). Delegated: the issuer
256
+ * is resolved from the forwarded credentials and may only grant what it holds, only exact actions of the
257
+ * app's catalog, and only with an expiry inside `MAX_KEY_LIFETIME_SECONDS`. Returns the
258
+ * plaintext token ONCE; `id` is the durable handle for revoke.
259
+ */
260
+ issueKey(input: IssueKeyInput): Promise<IssueKeyResult>;
261
+ /**
262
+ * The public signing key set. The SDK fetches it ONCE per isolate (cached) over the binding —
263
+ * which never traverses the Access edge — then verifies every permission token locally.
264
+ */
265
+ getJwks(): Promise<Jwks>;
266
+ audit(event: AuditInput): Promise<void>;
267
+ /**
268
+ * List the USER principals who can access the caller's app (its people directory). The caller
269
+ * is resolved from the forwarded Access credentials and the app is the aud-VERIFIED app — so an
270
+ * operator only ever sees its own app's roster. Authorized for any member that holds at least
271
+ * one permission on the app; a zero-grant authenticated user gets `not_allowed`. Read-only.
272
+ */
273
+ listPrincipals(input: ListPrincipalsInput): Promise<ListPrincipalsResult>;
274
+ /**
275
+ * Revoke a previously-issued opaque `px_` credential (an API key / share link) by id. The caller
276
+ * is resolved from the forwarded Access credentials and authorized: the credential must be bound to
277
+ * the caller's verified app (any other is `not_found`); then the original issuer may always revoke,
278
+ * and otherwise, for an anonymous credential, the caller must hold every granted action (an
279
+ * admin / app-wide operator). Idempotent — revoking an already-revoked credential returns
280
+ * `{ ok: true, revoked: false }`. An unknown id returns `{ ok: false, reason: 'not_found' }`.
281
+ */
282
+ revokeKey(input: RevokeKeyInput): Promise<RevokeKeyResult>;
283
+ }
@@ -0,0 +1,2 @@
1
+ /** The SHA-256 of `text`'s UTF-8 bytes, as 64 lower-case hex digits. */
2
+ export declare function sha256Hex(text: string): string;
@@ -0,0 +1,72 @@
1
+ import type { MembershipCaller } from './membership';
2
+ /** The terminal declaration of a contract: the page on the application's own origin that identifies a person. */
3
+ export interface TerminalArtifact {
4
+ readonly identify: string;
5
+ }
6
+ /** The longest identification path a contract declares. */
7
+ export declare const MAX_TERMINAL_IDENTIFY_PATH_LENGTH = 200;
8
+ /** The query parameter IAM appends to the identification page: the identification's id. */
9
+ export declare const IDENTIFICATION_QUERY_PARAMETER = "identification";
10
+ /**
11
+ * Why `path` is not an identification page, or `null`: an absolute, canonical path on the application's own origin,
12
+ * with no query or fragment (IAM appends its own) and outside the platform's `/__fabrika`.
13
+ */
14
+ export declare function terminalIdentifyProblem(path: string): string | null;
15
+ /** Every identification operation carries the caller's verified credential: a public procedure's workload token. */
16
+ export type TerminalCaller = MembershipCaller;
17
+ /**
18
+ * Why IAM refused. `not_found` is an identification that is unknown, expired, consumed, cancelled, of another
19
+ * application, or whose terminal no longer lists the application: alike, so an id reveals nothing. `invalid_principal`
20
+ * is a principal that cannot sign in on a terminal: unknown, disabled, not a person, or external (ADR-0051).
21
+ */
22
+ export type TerminalFailure = {
23
+ ok: false;
24
+ reason: 'missing_token' | 'invalid_token' | 'not_allowed' | 'not_found' | 'invalid_principal';
25
+ };
26
+ export type TerminalFailureReason = TerminalFailure['reason'];
27
+ /** The terminal an identification was opened on, as the token's `terminal` claim names it. */
28
+ export interface IdentificationTerminal {
29
+ id: string;
30
+ label: string;
31
+ }
32
+ /** Read an open identification: the id is the `identification` query parameter of the identification page. */
33
+ export interface InspectIdentificationInput extends TerminalCaller {
34
+ id: string;
35
+ }
36
+ /** `expiresAt` is unix seconds. The application keys its throttle of guesses on `terminal.id`. */
37
+ export type InspectIdentificationResult = {
38
+ ok: true;
39
+ terminal: IdentificationTerminal;
40
+ expiresAt: number;
41
+ } | TerminalFailure;
42
+ /**
43
+ * The application's word that `principalId` stands at the identification's terminal. IAM consumes the identification
44
+ * (single use), signs the person in under the terminal's ceiling, and answers the URL the browser goes to next: IAM's
45
+ * completion of the identification, which issues the handoff code only to the terminal's own browser. The application
46
+ * never holds a code.
47
+ */
48
+ export interface AssertIdentityInput extends TerminalCaller {
49
+ id: string;
50
+ principalId: string;
51
+ }
52
+ export type AssertIdentityResult = {
53
+ ok: true;
54
+ completionUrl: string;
55
+ } | TerminalFailure;
56
+ /** End an identification the person abandoned. Repeating it, or cancelling a consumed one, answers `not_found`. */
57
+ export interface CancelIdentificationInput extends TerminalCaller {
58
+ id: string;
59
+ }
60
+ export type CancelIdentificationResult = {
61
+ ok: true;
62
+ } | TerminalFailure;
63
+ /**
64
+ * The identification operations IAM serves an application: on the membership transport (`/membership/<method>`) and
65
+ * on its application entrypoint. A SEPARATE interface from `IamMembershipRpc`, so a transport that predates terminals
66
+ * still satisfies that one.
67
+ */
68
+ export interface IamTerminalRpc {
69
+ inspectIdentification(input: InspectIdentificationInput): Promise<InspectIdentificationResult>;
70
+ assertIdentity(input: AssertIdentityInput): Promise<AssertIdentityResult>;
71
+ cancelIdentification(input: CancelIdentificationInput): Promise<CancelIdentificationResult>;
72
+ }
@@ -0,0 +1,240 @@
1
+ /**
2
+ * The propustka-issued token contract — the SECOND thing (after `IamRpc`) that must not drift
3
+ * between the Worker and the SDK.
4
+ *
5
+ * Background: today a request is authorized by the Worker resolving a Cloudflare Access JWT on
6
+ * every call over RPC (the CF token carries only identity, so authz needs a round-trip). When
7
+ * propustka issues its OWN token it can embed the already-resolved permission set, and the SDK
8
+ * authorizes LOCALLY — no per-request round-trip. This module is the wire shape of that token:
9
+ *
10
+ * - the Worker BUILDS claims here and signs them (`buildAccessClaims`);
11
+ * - the SDK verifies the signature with jose, then PARSES the payload back into typed claims
12
+ * here (`parseAccessClaims`) — structurally, so it reads them without an `as` cast — and maps a
13
+ * principal-bound token into the `ResolvedPrincipal` the existing `AuthContext` consumes.
14
+ *
15
+ * ONE shape, no `kind` discriminator — the optional `ptype` carries the distinction. Every token carries
16
+ * `perms: PermissionEntry[]` (authorized via `permits` — scopes + wildcards) and an OPTIONAL
17
+ * principal (`ptype`): present means the token is bound to a user/service principal; absent means an
18
+ * anonymous credential (a share link), whose `perms` are narrow scoped entries and
19
+ * whose audit actor is `label`. `sub` is the subject id either way — a principal id when bound, else
20
+ * the issuing credential id.
21
+ *
22
+ * Pure: no jose, no I/O. Signing/verifying (key material) stays in the packages that own it.
23
+ */
24
+ import type { ResolvedPrincipal } from './rpc';
25
+ import { type PermissionEntry, type Scope, type TokenPrincipalType } from './types';
26
+ /** Namespace reserved for browser credentials owned by IAM and the Fabrika proxy. */
27
+ export declare const FABRIKA_COOKIE_PREFIX = "__Host-px_";
28
+ /**
29
+ * Long-lived opaque session id, HOST-ONLY on whichever host wrote it — IAM's own at login, an app's
30
+ * own after the proxy redeems a handoff code
31
+ * ([ADR-0023](../../../docs/decisions/0023-one-session-per-host.md)). Same name, different host,
32
+ * different `sessions` row.
33
+ *
34
+ * `__Host-` is a browser-enforced restatement of that: the prefix makes the browser refuse the cookie
35
+ * unless it carries `Secure`, omits `Domain` and uses `Path=/`, so a sibling host under a shared
36
+ * registrable domain cannot plant a second cookie of this name that the real host would then send
37
+ * alongside its own. Measured, not assumed: Chromium accepts it over plain HTTP on `*.localhost`,
38
+ * because those origins are potentially trustworthy.
39
+ */
40
+ export declare const SESSION_COOKIE = "__Host-px_session";
41
+ /** Prefix marking a propustka opaque credential (API key / share link), e.g. `Bearer px_<random>`. */
42
+ export declare const API_KEY_PREFIX = "px_";
43
+ /**
44
+ * Where a job or a webhook exchanges its own `px_` key for an access token at IAM's public origin: `POST` with the key
45
+ * as the bearer and `{ app }` as the body. IAM answers `MintFromKeyResult`, and only for a workload key of that app.
46
+ */
47
+ export declare const WORKLOAD_TOKEN_PATH = "/auth/workload/token";
48
+ /** Signing algorithm propustka issues with and the SDK verifies (ECDSA P-256 — compact, ubiquitous). */
49
+ export declare const TOKEN_ALG = "ES256";
50
+ /** JWT `typ` of an OAuth resource access token (RFC 9068). Native app tokens carry no `typ`. */
51
+ export declare const RESOURCE_ACCESS_TOKEN_TYP = "at+jwt";
52
+ /** Default per-app access-token lifetime. Revocation/role changes take effect within this. */
53
+ export declare const DEFAULT_TOKEN_TTL_SECONDS = 300;
54
+ /**
55
+ * The SDK refreshes an access token this many seconds BEFORE it expires, so a request never rides a
56
+ * token that expires mid-flight. Must be < the token TTL.
57
+ */
58
+ export declare const TOKEN_REFRESH_SKEW_SECONDS = 30;
59
+ /**
60
+ * The largest access token IAM signs, in bytes (a JWT is ASCII), except an application token below. A client sends
61
+ * such a token itself (an OAuth access token, a console bearer), so it crosses Caddy's `forward_auth` into the proxy's
62
+ * auth service and reaches installation services, which run on Bun with its default: a request's headers at most
63
+ * 16 KiB in total. 8 KiB leaves the rest for the request's own headers and cookies.
64
+ */
65
+ export declare const MAX_ACCESS_TOKEN_BYTES = 8192;
66
+ /**
67
+ * The largest token IAM mints for the proxy to inject toward a contract application, in bytes. No client sends it; on
68
+ * that hop it travels twice (`X-Fabrika-Token`, and `Authorization` on a bearer request), so two copies and 16 KiB of
69
+ * the request's own headers fit the header limit the platform starts the application's Bun with.
70
+ */
71
+ export declare const MAX_APPLICATION_TOKEN_BYTES = 24576;
72
+ /** The request-header limit the platform starts an application's Bun server with (`--max-http-header-size`). */
73
+ export declare const APPLICATION_SERVER_MAX_HEADER_BYTES = 65536;
74
+ /**
75
+ * The propustka access token. `perms` is always present (matched via `permits`); `ptype` is present
76
+ * only when `sub` is a principal. `label` is the audit actor — the principal's label when bound, the
77
+ * credential label otherwise (or null).
78
+ */
79
+ export interface AccessTokenClaims {
80
+ /** Issuer — propustka's own origin (e.g. `https://propustka.example.com`). */
81
+ iss: string;
82
+ /** The app id this token is scoped to. The SDK REJECTS a token whose `aud` is not its app. */
83
+ aud: string;
84
+ /** Subject id: a principal id when `ptype` is set, else the issuing credential id. */
85
+ sub: string;
86
+ /** Issued-at (unix seconds). */
87
+ iat: number;
88
+ /** Expiry (unix seconds). */
89
+ exp: number;
90
+ /** Resolved/effective permissions; `can(action, scope?)` = `permits(perms, action, scope)`. */
91
+ perms: PermissionEntry[];
92
+ /** Present only when the token is bound to a principal (`sub` is that principal). */
93
+ ptype?: TokenPrincipalType;
94
+ /**
95
+ * Present exactly when `ptype` is a workload kind: the job's or the webhook's name, a public procedure's endpoint id,
96
+ * or for `app` the id of the consuming application, which the proxy admits as the caller `app:<id>`.
97
+ */
98
+ workload?: string;
99
+ /** Audit actor label — the principal's label, or the credential label, or null (anonymous). */
100
+ label: string | null;
101
+ /**
102
+ * Only on a user token: the mailbox IAM recorded for the principal (`principals.email`, `normalizeEmailIdentity`).
103
+ * The signature authenticates that IAM recorded it, not that the person controls it. A user's `label` is that
104
+ * address as it was spelled, never a substitute for it.
105
+ */
106
+ email?: string;
107
+ /**
108
+ * Present only on a principal token IAM minted from a signed-in session (`mintToken`). A token minted from a `px_`
109
+ * key carries what the key's own grants narrow, so a check that resolves the person's permissions requires this.
110
+ */
111
+ session?: true;
112
+ /**
113
+ * Present only on a session token of a person an application asserted at an enrolled terminal (ADR-0067), and
114
+ * always together with `terminal`.
115
+ */
116
+ amr?: TerminalAuthenticationMethod;
117
+ /** The terminal the person is signed in on; present exactly when `amr` is. */
118
+ terminal?: TerminalTokenClaims;
119
+ /** Present only on an OAuth resource token (`aud` is then a resource URI, not an app id). */
120
+ oauth?: OAuthTokenClaims;
121
+ /** Present only on a share-link token, which has no `ptype`: `sub` is then the link key's id. */
122
+ link?: LinkTokenClaims;
123
+ }
124
+ /** The `amr` value of a session an application asserted at a terminal. */
125
+ export declare const TERMINAL_AUTHENTICATION_METHOD = "terminal_assertion";
126
+ export type TerminalAuthenticationMethod = typeof TERMINAL_AUTHENTICATION_METHOD;
127
+ /** The terminal a person's session was asserted on: its principal id and the label an administrator gave it. */
128
+ export interface TerminalTokenClaims {
129
+ id: string;
130
+ label: string;
131
+ }
132
+ /** What a share-link token adds: the link mount that issued the key and the chain the key is bound to. */
133
+ export interface LinkTokenClaims {
134
+ mount: string;
135
+ /** The bound object first, then each value containing it, outward. */
136
+ chain: Scope[];
137
+ }
138
+ /**
139
+ * The principal kind of a token (ADR-0022 rule 3): a user or a service principal, a workload, or a share link. Null
140
+ * for an anonymous credential that is not a link, which no contract mount admits.
141
+ */
142
+ export type PrincipalKind = TokenPrincipalType | 'link';
143
+ export declare function principalKind(claims: AccessTokenClaims): PrincipalKind | null;
144
+ /** What an OAuth resource token adds: the signed app coordinate and the grant it was minted from. */
145
+ export interface OAuthTokenClaims {
146
+ /** The app whose permissions `perms` are; `aud` names the resource URI instead. */
147
+ app: string;
148
+ /** CIMD URL of the MCP client the user consented to. */
149
+ clientId: string;
150
+ /** Consented scopes; `perms` is already narrowed by them. */
151
+ scopes: string[];
152
+ /** IAM's OAuth grant id — revoking it stops refresh. */
153
+ grantId: string;
154
+ /** Unique token id, fresh on every mint. */
155
+ tokenId: string;
156
+ }
157
+ /** Which tokens a verifier accepts: native app tokens, or OAuth tokens minted for one resource of one app. */
158
+ export type TokenAudienceProfile = {
159
+ kind: 'app';
160
+ app: string;
161
+ } | {
162
+ kind: 'resource';
163
+ app: string;
164
+ resource: string;
165
+ };
166
+ /** A published public signing key (EC P-256 / ES256). A jose-compatible JWK subset. */
167
+ export interface PublicJwk {
168
+ kty: string;
169
+ crv?: string;
170
+ x?: string;
171
+ y?: string;
172
+ kid?: string;
173
+ alg?: string;
174
+ use?: string;
175
+ }
176
+ /** The public key set the SDK feeds to a local JWKS verifier. */
177
+ export interface Jwks {
178
+ keys: PublicJwk[];
179
+ }
180
+ export interface AccessTokenParams {
181
+ /** Issuer (propustka origin). */
182
+ iss: string;
183
+ /** App id this token is for (becomes `aud`). */
184
+ app: string;
185
+ /** Subject id (becomes `sub`) — a principal id when `type` is given, else a credential id. */
186
+ subject: string;
187
+ /** Principal type — omit for an anonymous credential (share link). */
188
+ type?: TokenPrincipalType;
189
+ /** The workload's name; required with a workload `type`, refused with any other. */
190
+ workload?: string;
191
+ /** Audit actor label, or null for an unlabeled anonymous token. */
192
+ label: string | null;
193
+ /** A user principal's normalized mailbox; refused with any other `type`. */
194
+ email?: string;
195
+ /** Minted from a signed-in session; refused on a token without `type` or of a workload. */
196
+ session?: true;
197
+ /** The terminal of a person's session asserted on one; sets `amr` too, and requires a user `type` and `session`. */
198
+ terminal?: TerminalTokenClaims;
199
+ permissions: PermissionEntry[];
200
+ issuedAt: number;
201
+ expiresAt: number;
202
+ /** A share-link key's mount and chain; only on a token without `type`. */
203
+ link?: LinkTokenClaims;
204
+ }
205
+ export interface ResourceAccessTokenParams {
206
+ iss: string;
207
+ app: string;
208
+ resource: string;
209
+ subject: string;
210
+ label: string | null;
211
+ permissions: PermissionEntry[];
212
+ issuedAt: number;
213
+ expiresAt: number;
214
+ clientId: string;
215
+ scopes: string[];
216
+ grantId: string;
217
+ tokenId: string;
218
+ }
219
+ /**
220
+ * Assemble an OAuth resource access token. Always a user principal. The wire carries the standard
221
+ * `client_id`/`scope`/`jti` claims plus Fabrika's `app` and `grant`; the caller signs with
222
+ * `typ: RESOURCE_ACCESS_TOKEN_TYP`.
223
+ */
224
+ export declare function buildResourceAccessClaims(params: ResourceAccessTokenParams): Record<string, unknown>;
225
+ /** A token is accepted only by the profile it was minted for: an app token never passes as a resource token, and vice versa. */
226
+ export declare function matchesTokenAudience(claims: AccessTokenClaims, profile: TokenAudienceProfile): boolean;
227
+ /** Assemble the claim object for an access token. Pure — the caller signs the result. */
228
+ export declare function buildAccessClaims(params: AccessTokenParams): AccessTokenClaims;
229
+ /**
230
+ * Narrow a verified JWT payload into typed access-token claims WITHOUT trusting its shape. jose has
231
+ * already checked the signature, `exp`, and `aud`; this validates the custom claims structurally so
232
+ * the SDK reads them without an `as` cast. Returns null on any malformed claim shape.
233
+ */
234
+ export declare function parseAccessClaims(payload: unknown): AccessTokenClaims | null;
235
+ /**
236
+ * Map a verified PRINCIPAL-bound access token into the `ResolvedPrincipal` the existing
237
+ * `AuthContext` consumes. Returns null for an anonymous token (no `ptype`) and for a workload token,
238
+ * which no `AuthContext` represents — the caller handles both separately.
239
+ */
240
+ export declare function accessClaimsToResolved(claims: AccessTokenClaims, requestId: string): ResolvedPrincipal | null;