@fabrika/auth-core 0.9.0-dev.5 → 0.9.0-dev.50

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 (55) hide show
  1. package/package.json +3 -2
  2. package/src/agent.ts +89 -0
  3. package/src/canonical-path.ts +18 -0
  4. package/src/client-address.ts +74 -0
  5. package/src/contract-canonical.ts +168 -2
  6. package/src/contract-encoding.ts +181 -0
  7. package/src/contract.ts +220 -17
  8. package/src/egress.ts +97 -0
  9. package/src/endpoint-digest.ts +22 -2
  10. package/src/framework-release.ts +70 -0
  11. package/src/framework-variables.ts +14 -0
  12. package/src/iam-mail.ts +354 -0
  13. package/src/index.ts +7 -0
  14. package/src/installation-endpoint.ts +3 -2
  15. package/src/locale.ts +13 -1
  16. package/src/managed-environment.ts +11 -0
  17. package/src/membership.ts +12 -4
  18. package/src/oauth.ts +19 -0
  19. package/src/ops.ts +487 -16
  20. package/src/permissions.ts +42 -0
  21. package/src/public-egress.ts +168 -0
  22. package/src/requirement.ts +12 -4
  23. package/src/rpc.ts +137 -9
  24. package/src/scope-values.ts +123 -0
  25. package/src/sha256.ts +52 -14
  26. package/src/token.ts +195 -14
  27. package/src/types.ts +72 -1
  28. package/src/wire.ts +2 -1
  29. package/types/src/agent.d.ts +37 -0
  30. package/types/src/canonical-path.d.ts +6 -0
  31. package/types/src/client-address.d.ts +7 -0
  32. package/types/src/contract-canonical.d.ts +11 -1
  33. package/types/src/contract-encoding.d.ts +18 -0
  34. package/types/src/contract.d.ts +205 -16
  35. package/types/src/egress.d.ts +27 -0
  36. package/types/src/endpoint-digest.d.ts +5 -0
  37. package/types/src/framework-release.d.ts +23 -0
  38. package/types/src/framework-variables.d.ts +6 -1
  39. package/types/src/iam-mail.d.ts +92 -0
  40. package/types/src/index.d.ts +7 -0
  41. package/types/src/installation-endpoint.d.ts +3 -2
  42. package/types/src/locale.d.ts +11 -1
  43. package/types/src/managed-environment.d.ts +1 -1
  44. package/types/src/membership.d.ts +8 -3
  45. package/types/src/oauth.d.ts +11 -0
  46. package/types/src/ops.d.ts +133 -8
  47. package/types/src/permissions.d.ts +12 -0
  48. package/types/src/public-egress.d.ts +31 -0
  49. package/types/src/requirement.d.ts +5 -4
  50. package/types/src/rpc.d.ts +113 -6
  51. package/types/src/scope-values.d.ts +61 -0
  52. package/types/src/sha256.d.ts +10 -0
  53. package/types/src/token.d.ts +70 -8
  54. package/types/src/types.d.ts +48 -1
  55. package/types/src/wire.d.ts +2 -1
@@ -1,3 +1,4 @@
1
+ import type { KeyGrant } from './rpc'
1
2
  import type { PermissionEntry, Scope } from './types'
2
3
 
3
4
  /**
@@ -29,6 +30,22 @@ export function matchAction(pattern: string, action: string): boolean {
29
30
  return pattern === action
30
31
  }
31
32
 
33
+ /**
34
+ * `entries` with each identical action, scope and source once, the first kept in order: how IAM resolves a principal's
35
+ * permissions, so two roles granting one action at one scope put one entry into the token.
36
+ */
37
+ export function uniquePermissions(entries: readonly PermissionEntry[]): PermissionEntry[] {
38
+ const seen = new Set<string>()
39
+ return entries.filter((entry) => {
40
+ const key = JSON.stringify([entry.action, entry.scope?.type ?? null, entry.scope?.value ?? null, entry.source])
41
+ if (seen.has(key)) {
42
+ return false
43
+ }
44
+ seen.add(key)
45
+ return true
46
+ })
47
+ }
48
+
32
49
  /**
33
50
  * Does `entries` grant `action` at the given scope? Mirrors `can()` semantics exactly:
34
51
  * - scope === undefined → scope-less: ONLY entries with scope === null satisfy (global perms only).
@@ -106,3 +123,28 @@ export function isActionAllowed(pattern: string, catalog: readonly string[]): bo
106
123
  }
107
124
  return false
108
125
  }
126
+
127
+ /**
128
+ * Intersect live permissions with a ceiling: an OAuth scope's grants, or a terminal's patterns for an application. The
129
+ * ceiling never adds anything: each result is the narrower action and the narrower scope of one held entry and one
130
+ * ceiling entry that overlap, so a held `*` under a ceiling `a.read` yields `a.read`.
131
+ */
132
+ export function narrowPermissions(live: readonly PermissionEntry[], ceiling: readonly KeyGrant[]): PermissionEntry[] {
133
+ const result: PermissionEntry[] = []
134
+ for (const held of live) {
135
+ for (const limit of ceiling) {
136
+ const action = matchAction(limit.action, held.action) ? held.action : matchAction(held.action, limit.action) ? limit.action : null
137
+ const scope = narrowerScope(held.scope, limit.scope ?? null)
138
+ if (action === null || scope === undefined) continue
139
+ result.push({ action, scope, source: held.source })
140
+ }
141
+ }
142
+ return uniquePermissions(result)
143
+ }
144
+
145
+ /** `null` is global; `undefined` means the two scopes do not overlap. */
146
+ function narrowerScope(held: Scope | null, limit: Scope | null): Scope | null | undefined {
147
+ if (held === null) return limit
148
+ if (limit === null) return held
149
+ return held.type === limit.type && held.value === limit.value ? held : undefined
150
+ }
@@ -0,0 +1,168 @@
1
+ // `egress: 'public'`: a cron job that calls the websites its operators name (a crawler, an auditor, a link checker)
2
+ // reaches any public host over HTTPS or HTTP, and never the installation or a private network (ADR-0075). These are the
3
+ // rules a URL alone decides, which the runtime guard and the checker share. The guard adds the installation's own hosts
4
+ // and, where the runtime exposes name resolution, the addresses a name resolves to.
5
+
6
+ /** The declared form of public egress: every public host, over HTTPS or HTTP, on its default port. */
7
+ export const PUBLIC_EGRESS = 'public'
8
+
9
+ export type PublicEgress = typeof PUBLIC_EGRESS
10
+
11
+ /** What a site declares in `egress`: its exact HTTPS origins, sorted, or every public host (a cron job only). */
12
+ export type DeclaredEgress = readonly string[] | PublicEgress
13
+
14
+ /**
15
+ * The name suffixes public egress refuses, each with every name under it: local and special-use names (RFC 6761,
16
+ * RFC 6762, RFC 8375, RFC 9476), the names private networks conventionally use (`.internal` holds Google's metadata
17
+ * host and Control's own `operations.internal`), and the platform subdomains an installation is served on beside its
18
+ * own domains: Cloudflare's `workers.dev`, where its Workers have their default routes, and Zerops' `zerops.app`, where
19
+ * its proxies, Control and IAM have their subdomains (a namespace proxy's `proxy-…-8080.<region>.zerops.app`), with the
20
+ * `zerops` suffix of a Zerops project's private network. Control knows no list of those subdomains, so every one is
21
+ * refused, another installation's too.
22
+ */
23
+ export const PUBLIC_EGRESS_REFUSED_SUFFIXES = [
24
+ 'localhost',
25
+ 'local',
26
+ 'internal',
27
+ 'intranet',
28
+ 'lan',
29
+ 'home',
30
+ 'corp',
31
+ 'private',
32
+ 'arpa',
33
+ 'test',
34
+ 'invalid',
35
+ 'example',
36
+ 'onion',
37
+ 'alt',
38
+ 'zerops',
39
+ 'zerops.app',
40
+ 'workers.dev',
41
+ ] as const
42
+
43
+ /** A host name without its trailing dots, lowercased: the form every comparison here uses. */
44
+ export function normalizedHost(hostname: string): string {
45
+ return hostname.toLowerCase().replace(/\.+$/, '')
46
+ }
47
+
48
+ const IPV4 = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
49
+
50
+ /**
51
+ * Why public egress refuses `url`, or `null` when the URL alone admits it: a scheme other than `https:` and `http:`, a
52
+ * port other than the scheme's default, credentials in the URL, an IP literal, a name of one label, a name under a
53
+ * refused suffix, or one of `refusedHosts` (normalized names). A host it admits may still resolve to a private address,
54
+ * which only a runtime that resolves names refuses.
55
+ */
56
+ export function publicEgressRefusal(url: URL, refusedHosts: ReadonlySet<string> = new Set()): string | null {
57
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return `${url.protocol} is not https: or http:`
58
+ if (url.port !== '') return `port ${url.port} is not the default port of ${url.protocol}`
59
+ if (url.username !== '' || url.password !== '') return 'the URL carries credentials, which a public request never sends'
60
+ const host = normalizedHost(url.hostname)
61
+ if (host.startsWith('[') || IPV4.test(host)) return `${host} is an IP address, not a public host name`
62
+ if (!host.includes('.')) return `${host} is a name of one label, as an internal service or a local machine has`
63
+ if (host.split('.').some((label) => label === '')) return `${host} has an empty label`
64
+ const suffix = PUBLIC_EGRESS_REFUSED_SUFFIXES.find((refused) => host === refused || host.endsWith(`.${refused}`))
65
+ if (suffix !== undefined) return `${host} is under .${suffix}, which names no public website`
66
+ if (refusedHosts.has(host)) return `${host} is a host of this installation`
67
+ return null
68
+ }
69
+
70
+ /**
71
+ * Whether `address` (an IPv4 or IPv6 address, as a resolver answers it) is a public unicast address: not private,
72
+ * loopback, link-local (which holds the cloud metadata address 169.254.169.254), shared, multicast, reserved,
73
+ * documentation, or an IPv6 form that embeds or tunnels an IPv4 address it cannot vouch for. A text that is no address
74
+ * is not public.
75
+ */
76
+ export function isPublicAddress(address: string): boolean {
77
+ const v4 = ipv4Octets(address)
78
+ if (v4 !== null) return isPublicIpv4(v4)
79
+ const words = ipv6Words(address)
80
+ if (words === null) return false
81
+ const [w0 = 0, w1 = 0, w2 = 0, w3 = 0, w4 = 0, w5 = 0, w6 = 0, w7 = 0] = words
82
+ // ::ffff:a.b.c.d, an IPv4 address in IPv6 form, is that IPv4 address.
83
+ if (w0 === 0 && w1 === 0 && w2 === 0 && w3 === 0 && w4 === 0 && w5 === 0xffff) {
84
+ return isPublicIpv4([w6 >> 8, w6 & 0xff, w7 >> 8, w7 & 0xff])
85
+ }
86
+ // Only global unicast (2000::/3) is public; every other block is local, multicast, reserved or a translation prefix.
87
+ if ((w0 & 0xe000) !== 0x2000) return false
88
+ // 2001::/32 Teredo, 2001:10::/28 ORCHID, 2001:20::/28 ORCHIDv2, 2001:db8::/32 documentation, 2002::/16 6to4.
89
+ if (w0 === 0x2001 && (w1 === 0 || (w1 & 0xfff0) === 0x10 || (w1 & 0xfff0) === 0x20 || w1 === 0x0db8)) return false
90
+ if (w0 === 0x2002) return false
91
+ // 3fff::/20 documentation (RFC 9637).
92
+ if (w0 === 0x3fff && (w1 & 0xf000) === 0) return false
93
+ return true
94
+ }
95
+
96
+ /** The non-public IPv4 blocks, each as its network (a 32-bit number) and its prefix length. */
97
+ const IPV4_REFUSED: readonly (readonly [number, number])[] = [
98
+ [0x00000000, 8], // 0.0.0.0/8 this network
99
+ [0x0a000000, 8], // 10.0.0.0/8 private
100
+ [0x64400000, 10], // 100.64.0.0/10 shared address space
101
+ [0x7f000000, 8], // 127.0.0.0/8 loopback
102
+ [0xa9fe0000, 16], // 169.254.0.0/16 link-local, the cloud metadata address
103
+ [0xa83f8110, 32], // 168.63.129.16 Azure's host endpoint (metadata, DNS), a public address answered inside the VM
104
+ [0xac100000, 12], // 172.16.0.0/12 private
105
+ [0xc0000000, 24], // 192.0.0.0/24 IETF protocol assignments
106
+ [0xc0000200, 24], // 192.0.2.0/24 documentation
107
+ [0xc0586300, 24], // 192.88.99.0/24 6to4 relay anycast
108
+ [0xc0a80000, 16], // 192.168.0.0/16 private
109
+ [0xc6120000, 15], // 198.18.0.0/15 benchmarking
110
+ [0xc6336400, 24], // 198.51.100.0/24 documentation
111
+ [0xcb007100, 24], // 203.0.113.0/24 documentation
112
+ [0xe0000000, 4], // 224.0.0.0/4 multicast
113
+ [0xf0000000, 4], // 240.0.0.0/4 reserved, broadcast
114
+ ]
115
+
116
+ function isPublicIpv4(octets: readonly number[]): boolean {
117
+ const [a = 0, b = 0, c = 0, d = 0] = octets
118
+ const value = ((a << 24) >>> 0) + (b << 16) + (c << 8) + d
119
+ return !IPV4_REFUSED.some(([network, prefix]) => {
120
+ const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0
121
+ return ((value & mask) >>> 0) === network
122
+ })
123
+ }
124
+
125
+ function ipv4Octets(text: string): number[] | null {
126
+ if (!IPV4.test(text)) return null
127
+ const octets = text.split('.').map((part) => Number.parseInt(part, 10))
128
+ return octets.every((octet) => octet >= 0 && octet <= 255) ? octets : null
129
+ }
130
+
131
+ const HEX_WORD = /^[0-9a-f]{1,4}$/i
132
+
133
+ /** The eight 16-bit words of an IPv6 address (brackets and a zone allowed, an embedded IPv4 tail too), or `null`. */
134
+ function ipv6Words(text: string): number[] | null {
135
+ let rest = text.startsWith('[') && text.endsWith(']') ? text.slice(1, -1) : text
136
+ const zone = rest.indexOf('%')
137
+ if (zone !== -1) rest = rest.slice(0, zone)
138
+ if (!rest.includes(':')) return null
139
+ const tailAt = rest.lastIndexOf(':')
140
+ const tail = ipv4Octets(rest.slice(tailAt + 1))
141
+ const embedded: number[] = []
142
+ if (tail !== null) {
143
+ const [a = 0, b = 0, c = 0, d = 0] = tail
144
+ embedded.push((a << 8) | b, (c << 8) | d)
145
+ rest = rest.slice(0, tailAt + 1) + '0'
146
+ }
147
+ const halves = rest.split('::')
148
+ if (halves.length > 2) return null
149
+ const parse = (half: string | undefined): number[] | null => {
150
+ if (half === undefined || half === '') return []
151
+ const parts = half.split(':')
152
+ if (!parts.every((part) => HEX_WORD.test(part))) return null
153
+ return parts.map((part) => Number.parseInt(part, 16))
154
+ }
155
+ const head = parse(halves[0])
156
+ const back = parse(halves[1])
157
+ if (head === null || back === null) return null
158
+ if (tail !== null) {
159
+ // The placeholder word stands for the two words of the IPv4 tail.
160
+ const last = halves.length === 2 ? back : head
161
+ last.pop()
162
+ last.push(...embedded)
163
+ }
164
+ const missing = 8 - head.length - back.length
165
+ if (halves.length === 1) return missing === 0 ? head : null
166
+ if (missing < 1) return null
167
+ return [...head, ...Array.from({ length: missing }, () => 0), ...back]
168
+ }
@@ -1,3 +1,4 @@
1
+ import { AGENT_CALLER } from './agent'
1
2
  import { type ActionRequirement, APP_CALLER_PREFIX, type CapabilityRequirement, CONNECT_PREFIX, type EndpointRequirement } from './contract'
2
3
  import { type AuthenticatedRequirement, OAUTH_CALLER, type TokenCaller } from './installation-endpoint'
3
4
  import { permits } from './permissions'
@@ -8,8 +9,8 @@ import type { PermissionEntry } from './types'
8
9
  * Whether a token's permissions meet an endpoint's requirement. This is authorization, not a gate: it reads only the
9
10
  * token. `member` is any permission of this application; an action is that action in some scope, global included.
10
11
  * The access form narrows it to one scope afterwards, against the application's own data. The `app` form is the
11
- * action held as a global grant, so an entry scoped to any value does not meet it. Several capabilities need every
12
- * one of their actions. `authenticated`, which only an installation row carries, needs no permission.
12
+ * action held as a global grant, so an entry scoped to any value does not meet it; `anyOf` is one of its actions held so.
13
+ * Several capabilities need every one of their actions. `authenticated`, which only an installation row carries, needs no permission.
13
14
  */
14
15
  export function satisfies(requirement: EndpointRequirement | AuthenticatedRequirement, perms: readonly PermissionEntry[]): boolean {
15
16
  if (requirement.kind === 'authenticated') {
@@ -18,6 +19,9 @@ export function satisfies(requirement: EndpointRequirement | AuthenticatedRequir
18
19
  if (requirement.kind === 'member') {
19
20
  return perms.length > 0
20
21
  }
22
+ if (requirement.kind === 'anyOf') {
23
+ return requirement.actions.some((action) => perms.some((entry) => permits([entry], action)))
24
+ }
21
25
  if (requirement.kind === 'capabilities') {
22
26
  return Object.values(requirement.capabilities).every((capability) => holdsAction(capability, perms))
23
27
  }
@@ -34,13 +38,17 @@ function holdsAction(requirement: ActionRequirement | CapabilityRequirement, per
34
38
  /**
35
39
  * The caller kind a verified token presents: a `user` principal is `human`, a `service` principal is `machine`, a
36
40
  * connector key of application `<id>` is `app:<id>`, and a token bound to no principal is a share link. An OAuth
37
- * resource token is `oauth`, which only an installation row admits. A job, webhook or public procedure token is no
38
- * caller: `null` is refused by every endpoint.
41
+ * resource token is `oauth`, which only an installation row admits. A person's token that acts for an agent (`act`,
42
+ * ADR-0090) is `agent`, admitted only where a row lists it. A job, webhook or public procedure token is no caller:
43
+ * `null` is refused by every endpoint.
39
44
  */
40
45
  export function callerOf(claims: AccessTokenClaims): TokenCaller | null {
41
46
  if (claims.oauth !== undefined) {
42
47
  return OAUTH_CALLER
43
48
  }
49
+ if (claims.act !== undefined) {
50
+ return AGENT_CALLER
51
+ }
44
52
  switch (claims.ptype) {
45
53
  case 'user':
46
54
  return 'human'
package/src/rpc.ts CHANGED
@@ -7,10 +7,10 @@ import type {
7
7
  ListOwnDeviceAuthorizationsInput,
8
8
  ListOwnDeviceAuthorizationsResult,
9
9
  } from './device'
10
- import type { Jwks } from './token'
10
+ import { DEFAULT_TOKEN_TTL_SECONDS, type Jwks } from './token'
11
11
  import type { PermissionEntry, PrincipalType, Scope } from './types'
12
12
 
13
- // ── propustka-native session auth (mint a per-app permission token from an SSO session) ──
13
+ // ── IAM-native session auth (mint a per-app permission token from an SSO session) ──
14
14
  //
15
15
  // The SDK middleware presents the browser's opaque SSO session cookie; the Worker validates it,
16
16
  // resolves the principal's permissions FOR THE CALLING APP, and signs a short-lived per-app
@@ -33,7 +33,7 @@ export type MintTokenResult =
33
33
  /** `token_too_large`: the principal holds more than fits in one header; a decided refusal, never a login bounce. */
34
34
  | { ok: false; reason: 'no_session' | 'invalid_session' | 'unknown_principal' | 'disabled' | 'token_too_large' }
35
35
 
36
- // ── propustka-native key auth (mint an access token from an opaque `px_` credential) ──
36
+ // ── IAM-native key auth (mint an access token from an opaque `px_` credential) ──
37
37
  //
38
38
  // The other front over the same resolve→sign core as `mintToken`: the SDK presents an opaque
39
39
  // credential (an API key as a bearer, or a share-link path token) and the Worker resolves its
@@ -99,6 +99,134 @@ export interface IamHandoffRpc {
99
99
  exchangeAuthCode(input: ExchangeAuthCodeInput): Promise<ExchangeAuthCodeResult>
100
100
  }
101
101
 
102
+ // ── An agent's device grant at an application (ADR-0090) ──────────────────────
103
+ //
104
+ // The proxy verifies an agent's resource token for its own host first, then asks IAM for the approving person's
105
+ // application token: the person's live permissions, narrowed when the grant names one scope value, with `act`. Like the
106
+ // handoff it is on the proxy's surface only, never on `IamRpc`, which every application holds.
107
+
108
+ export interface MintFromGrantInput {
109
+ /** The application environment `<app>@<env>` the proxy fronts. */
110
+ app: string
111
+ /** The resource the proxy serves the request on: the host's origin. */
112
+ resource: string
113
+ /** The agent's resource access token, as it arrived as the bearer. */
114
+ token: string
115
+ requestId: string
116
+ }
117
+
118
+ export type MintFromGrantResult =
119
+ | { ok: true; token: string; expiresAt: number }
120
+ /**
121
+ * `invalid_grant`: the token, its grant, the approving login or the person no longer holds. `write_refused`: the
122
+ * environment's `agent-write` gate serves no `write` grant. `token_too_large`: a decided refusal, as for a key.
123
+ */
124
+ | { ok: false; reason: 'invalid_grant' | 'write_refused' | 'token_too_large' }
125
+
126
+ /** The exchange of an agent's grant, as a contract of its own: only the proxy calls it. */
127
+ export interface IamGrantRpc {
128
+ mintFromGrant(input: MintFromGrantInput): Promise<MintFromGrantResult>
129
+ }
130
+
131
+ // ── The revocation feed (ADR-0022, "Revocation reaches a cached token") ─────────
132
+ //
133
+ // The proxy verifies a cached token locally until it expires. To end it sooner, it asks IAM which subjects lost
134
+ // something since its last read: a principal disabled, a session, key or OAuth grant revoked. A cached token of such a
135
+ // subject minted no later than the revocation is dropped and minted again, and IAM decides. Like the mint operations it
136
+ // is the proxy's alone, never a member of `IamRpc`.
137
+
138
+ /** How far back the feed reaches: no token outlives `DEFAULT_TOKEN_TTL_SECONDS`, so an older revocation ends nothing. */
139
+ export const REVOCATION_FEED_WINDOW_SECONDS = DEFAULT_TOKEN_TTL_SECONDS
140
+
141
+ /** The most subjects one answer lists; past it the answer is `complete: false` and the proxy drops every cached token. */
142
+ export const REVOCATION_FEED_MAX_SUBJECTS = 5000
143
+
144
+ export interface RevocationsInput {
145
+ /** IAM's clock, unix seconds: the feed answers revocations at or after it, within the window. `null`: the whole window. */
146
+ since: number | null
147
+ }
148
+
149
+ /** A subject (a token's `sub`: a principal, or an anonymous credential) and the latest revocation of it, IAM's clock. */
150
+ export interface RevokedSubject {
151
+ subject: string
152
+ at: number
153
+ }
154
+
155
+ export type RevocationsResult =
156
+ /** `now` is IAM's clock at the read; `complete: false` when more subjects were revoked than one answer lists. */
157
+ | { ok: true; now: number; complete: boolean; subjects: RevokedSubject[] }
158
+ /** The caller is not the proxy (an application's binding on Cloudflare). */
159
+ | { ok: false; reason: 'not_allowed' }
160
+
161
+ /** The revocation feed, as a contract of its own: only the proxy calls it. */
162
+ export interface IamRevocationRpc {
163
+ revocations(input: RevocationsInput): Promise<RevocationsResult>
164
+ }
165
+
166
+ // ── Sign-in signals for Operations' security alerts ───────────────────────────
167
+ //
168
+ // Operations' maintenance pass asks IAM for a bounded summary of its `auth_log` over a time window. Only IAM's full
169
+ // entrypoint serves it (the Cloudflare default export and the management `/rpc/*`), never the entrypoint every
170
+ // application binds, so it is a contract of its own and not a member of `IamRpc`.
171
+
172
+ /** The longest window `signInSignals` answers: a reader that fell further behind reads the last day only. */
173
+ export const SIGN_IN_SIGNALS_MAX_WINDOW_SECONDS = 24 * 60 * 60
174
+
175
+ /** The most accounts and privileged sign-ins one answer lists; `accountsTruncated`/`privilegedTruncated` say a list was cut. */
176
+ export const SIGN_IN_SIGNALS_LIMIT = 500
177
+
178
+ export interface SignInSignalsInput {
179
+ /**
180
+ * Unix seconds, inclusive, by `auth_log.created_at`: where privileged sign-ins are listed from. The reader overlaps
181
+ * windows, never resumes from an id.
182
+ */
183
+ since: number
184
+ /** Unix seconds, inclusive, by `auth_log.created_at`: where refusals are counted from, so a threshold has one window. */
185
+ refusalsSince: number
186
+ /** Unix seconds, inclusive. */
187
+ until: number
188
+ }
189
+
190
+ export interface SignInAccountRefusals {
191
+ principalId: string
192
+ /** Refused password sign-ins of this known account from `refusalsSince`. */
193
+ refusals: number
194
+ }
195
+
196
+ export interface SignInRefusalReason {
197
+ reason: string
198
+ refusals: number
199
+ }
200
+
201
+ export interface PrivilegedSignIn {
202
+ /** The `auth_log` row id, as a string on both engines: the reader's deduplication key. */
203
+ id: string
204
+ principalId: string
205
+ reason: string | null
206
+ /** Unix seconds. */
207
+ at: number
208
+ }
209
+
210
+ export type SignInSignalsResult =
211
+ | {
212
+ ok: true
213
+ /** Per known account, the most first. */
214
+ accounts: SignInAccountRefusals[]
215
+ /** Every counted refusal from `refusalsSince`, unknown accounts and refused `px_` keys included. */
216
+ refusals: number
217
+ reasons: SignInRefusalReason[]
218
+ /** Allowed sign-ins of a principal that administers at IAM from `since`, oldest first. */
219
+ privileged: PrivilegedSignIn[]
220
+ accountsTruncated: boolean
221
+ /** The list stops at its oldest `SIGN_IN_SIGNALS_LIMIT`; a reader resumes after the last one it got. */
222
+ privilegedTruncated: boolean
223
+ }
224
+ | { ok: false; reason: 'invalid_window' }
225
+
226
+ export interface IamSignInSignalsRpc {
227
+ signInSignals(input: SignInSignalsInput): Promise<SignInSignalsResult>
228
+ }
229
+
102
230
  /**
103
231
  * Where the proxy answers the handoff, on every app host it fronts. Reserved: an app route at this
104
232
  * path is shadowed by the proxy and never reaches the upstream, so it is deliberately namespaced.
@@ -154,8 +282,8 @@ export interface IssueKeyServiceSpec {
154
282
  export interface IssueKeyInput {
155
283
  app: string
156
284
  /**
157
- * The propustka-native credential the ISSUER is resolved from server-side (never self-asserted):
158
- * a `px_token` access JWT (verified against propustka's signing keys) or a `px_` key. Null = absent.
285
+ * The IAM-native credential the ISSUER is resolved from server-side (never self-asserted):
286
+ * a `px_token` access JWT (verified against IAM's signing keys) or a `px_` key. Null = absent.
159
287
  */
160
288
  credential: string | null
161
289
  requestId: string
@@ -227,7 +355,7 @@ export interface AuditInput {
227
355
 
228
356
  export interface RevokeKeyInput {
229
357
  app: string
230
- /** The propustka-native credential the CALLER (authorizer) is resolved from; null = absent. */
358
+ /** The IAM-native credential the CALLER (authorizer) is resolved from; null = absent. */
231
359
  credential: string | null
232
360
  requestId: string
233
361
  /** The credential id (the `id` returned by `issueKey`), NOT the plaintext `px_` token. */
@@ -242,7 +370,7 @@ export type RevokeKeyResult =
242
370
  // ── List principals (the app's people directory) ───────────────────────────────
243
371
  //
244
372
  // A read-only enumeration of the USER principals who can access an app — its people
245
- // directory. Apps consume it for things propustka isn't the authority on but needs the
373
+ // directory. Apps consume it for things IAM isn't the authority on but needs the
246
374
  // roster for: an assignee picker, an actor/owner label list. The caller is resolved from
247
375
  // the forwarded Access credentials and the listed app is the aud-VERIFIED app — an operator
248
376
  // can only enumerate the roster of an app it itself authenticates to (never a self-asserted
@@ -252,7 +380,7 @@ export type RevokeKeyResult =
252
380
  export interface ListPrincipalsInput {
253
381
  /** Self-asserted caller app id; superseded by the credential's aud on a valid `px_token`. */
254
382
  app: string
255
- /** The propustka-native credential the CALLER is resolved from (px_token / px_ key); null = absent. */
383
+ /** The IAM-native credential the CALLER is resolved from (px_token / px_ key); null = absent. */
256
384
  credential: string | null
257
385
  requestId: string
258
386
  }
@@ -286,7 +414,7 @@ export interface IamRpc {
286
414
  listOwnDeviceAuthorizations(input: ListOwnDeviceAuthorizationsInput): Promise<ListOwnDeviceAuthorizationsResult>
287
415
  /**
288
416
  * Mint a short-lived, per-app permission token from the browser's SSO session — the
289
- * propustka-native auth path. The SDK middleware calls this only when its cached permission
417
+ * IAM-native auth path. The SDK middleware calls this only when its cached permission
290
418
  * token is missing/near-expiry (≈ once per TTL), NOT per request: every other request verifies
291
419
  * the cached token locally against `getJwks`.
292
420
  */
@@ -0,0 +1,123 @@
1
+ // The values a dimension lists for the person who grants (ADR-0085): information for the console, never authorization.
2
+
3
+ import type { OutputShape, SchemaShape } from './contract'
4
+ import { MAX_MEMBERSHIP_SCOPE_PART_LENGTH } from './membership'
5
+
6
+ /** One value a dimension lists, with the text the console shows beside it. */
7
+ export interface DimensionValue {
8
+ readonly value: string
9
+ readonly label?: string
10
+ }
11
+
12
+ /** The most values a dimension lists. */
13
+ export const MAX_DIMENSION_VALUES = 500
14
+
15
+ /** The longest label of a listed value. */
16
+ export const MAX_DIMENSION_VALUE_LABEL_LENGTH = 120
17
+
18
+ /**
19
+ * Why `values` is not a dimension's list, or `null`: at least one and at most `MAX_DIMENSION_VALUES` values, each a
20
+ * non-empty value no longer than a scope value IAM takes, listed once, with a non-empty label when it has one.
21
+ */
22
+ export function dimensionValuesProblem(values: readonly DimensionValue[]): string | null {
23
+ if (values.length === 0) return 'lists no value (allowed: at least one, or no values field)'
24
+ if (values.length > MAX_DIMENSION_VALUES) return `lists ${values.length} values (allowed: at most ${MAX_DIMENSION_VALUES})`
25
+ const seen = new Set<string>()
26
+ for (const { value, label } of values) {
27
+ if (value === '' || value.length > MAX_MEMBERSHIP_SCOPE_PART_LENGTH) {
28
+ return `lists the value '${value}' (allowed: 1 to ${MAX_MEMBERSHIP_SCOPE_PART_LENGTH} characters)`
29
+ }
30
+ if (seen.has(value)) return `lists the value '${value}' twice`
31
+ seen.add(value)
32
+ if (label !== undefined && (label.trim() === '' || label.length > MAX_DIMENSION_VALUE_LABEL_LENGTH)) {
33
+ return `labels the value '${value}' with '${label}' (allowed: 1 to ${MAX_DIMENSION_VALUE_LABEL_LENGTH} characters)`
34
+ }
35
+ }
36
+ return null
37
+ }
38
+
39
+ /**
40
+ * Where IAM asks the application for a dimension's values (ADR-0085 §4): the procedure's endpoint id, its path on the
41
+ * application's origin and the action its requirement names. IAM calls it as the administrator, through the proxy.
42
+ */
43
+ export interface DimensionValueSource {
44
+ readonly endpoint: string
45
+ readonly path: string
46
+ readonly action: string
47
+ }
48
+
49
+ /** How long IAM waits for a value source's whole answer before the console falls back. */
50
+ export const SCOPE_VALUE_SOURCE_TIMEOUT_MS = 3000
51
+
52
+ /** The largest answer IAM reads from a value source. */
53
+ export const MAX_SCOPE_VALUE_SOURCE_BYTES = 256 * 1024
54
+
55
+ /** The row of a value-source procedure, as far as its rule reads it. */
56
+ interface ValueSourceRow {
57
+ readonly id: string
58
+ readonly kind: string
59
+ readonly method: string
60
+ readonly callers: readonly string[]
61
+ readonly requirement:
62
+ | { readonly kind: string; readonly action?: string; readonly access?: { readonly form: string; readonly dimension?: string } }
63
+ | null
64
+ readonly input: SchemaShape | null
65
+ readonly output: OutputShape | null
66
+ }
67
+
68
+ /**
69
+ * Why `row` cannot be `dimension`'s value source, or null: a person's `POST` query without input, requiring an action
70
+ * `over` that dimension other than its `members.manage` (`managedBy`), whose output is
71
+ * `{ values: [{ value: string, label?: string }] }`. The proxy decides the call from the row like any other; the
72
+ * requirement's action is what IAM's key for the call carries, and a row of `members.manage` would carry a membership
73
+ * delegation into a call the administrator only reads with.
74
+ */
75
+ export function valueSourceProblem(row: ValueSourceRow, dimension: string, managedBy: string | null): string | null {
76
+ if (row.kind !== 'query' || row.method !== 'POST') return `'${row.id}' is not a query procedure (allowed: r.query(…) of an rpc mount)`
77
+ if (!row.callers.includes('human')) return `'${row.id}' admits no person (allowed: callers including 'human')`
78
+ const requirement = row.requirement
79
+ if (requirement?.kind !== 'action' || requirement.access?.form !== 'over' || requirement.access.dimension !== dimension) {
80
+ return `'${row.id}' does not require an action over '${dimension}' (allowed: access: { action: '<action>', over: '${dimension}' })`
81
+ }
82
+ if (managedBy !== null && requirement.action === managedBy) {
83
+ return `'${row.id}' requires '${managedBy}', which manages the members of '${dimension}' (allowed: an action that reads, not members.manage)`
84
+ }
85
+ if (row.input !== null) return `'${row.id}' takes an input (allowed: no input)`
86
+ if (row.output === null || !isDimensionValuesShape(row.output)) {
87
+ return `'${row.id}' does not answer { values: [{ value: string, label?: string }] }`
88
+ }
89
+ return null
90
+ }
91
+
92
+ /** The output shape `{ values: [{ value: string, label?: string }] }`, strings with any checks. */
93
+ export function isDimensionValuesShape(shape: OutputShape): boolean {
94
+ if (shape.type !== 'object' || Object.keys(shape.fields).length !== 1) return false
95
+ const values = shape.fields['values']
96
+ if (values?.type !== 'array') return false
97
+ const item = values.items
98
+ if (item.type !== 'object') return false
99
+ const keys = Object.keys(item.fields)
100
+ if (!keys.includes('value') || keys.some((key) => key !== 'value' && key !== 'label')) return false
101
+ const label = item.fields['label']
102
+ return item.fields['value']?.type === 'string' && (label === undefined || (label.type === 'optional' && label.inner.type === 'string'))
103
+ }
104
+
105
+ /**
106
+ * The values a source answered, or null when the answer is not `{ values }` of at most `MAX_DIMENSION_VALUES` values
107
+ * `dimensionValuesProblem` admits. An answer is the application's word: the console shows it, IAM decides nothing by it.
108
+ */
109
+ export function parseDimensionValues(result: unknown): DimensionValue[] | null {
110
+ if (typeof result !== 'object' || result === null || Array.isArray(result)) return null
111
+ const list: unknown = Reflect.get(result, 'values')
112
+ if (!Array.isArray(list)) return null
113
+ const values: DimensionValue[] = []
114
+ for (const entry of list) {
115
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return null
116
+ const value: unknown = Reflect.get(entry, 'value')
117
+ const label: unknown = Reflect.get(entry, 'label')
118
+ if (typeof value !== 'string' || (label !== undefined && typeof label !== 'string')) return null
119
+ values.push(label === undefined ? { value } : { value, label })
120
+ }
121
+ if (values.length === 0) return values
122
+ return dimensionValuesProblem(values) === null ? values : null
123
+ }