@fabrika/auth-core 0.9.0-dev.2 → 0.9.0-dev.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/canonical-path.ts +18 -0
- package/src/client-address.ts +74 -0
- package/src/contract-canonical.ts +152 -1
- package/src/contract-encoding.ts +181 -0
- package/src/contract.ts +201 -9
- package/src/dev-environment.ts +6 -0
- package/src/egress.ts +97 -0
- package/src/endpoint-digest.ts +22 -2
- package/src/framework-release.ts +2 -0
- package/src/framework-variables.ts +15 -0
- package/src/iam-mail.ts +354 -0
- package/src/index.ts +9 -0
- package/src/locale.ts +13 -1
- package/src/managed-environment.ts +140 -0
- package/src/membership.ts +12 -4
- package/src/ops.ts +1933 -0
- package/src/public-egress.ts +168 -0
- package/src/requirement.ts +5 -2
- package/src/rpc.ts +8 -8
- package/src/sha256.ts +52 -14
- package/src/terminal.ts +105 -0
- package/src/token.ts +73 -13
- package/src/types.ts +63 -2
- package/src/wire.ts +7 -0
- package/types/src/canonical-path.d.ts +6 -0
- package/types/src/client-address.d.ts +7 -0
- package/types/src/contract-canonical.d.ts +11 -1
- package/types/src/contract-encoding.d.ts +18 -0
- package/types/src/contract.d.ts +186 -8
- package/types/src/dev-environment.d.ts +5 -0
- package/types/src/egress.d.ts +27 -0
- package/types/src/endpoint-digest.d.ts +5 -0
- package/types/src/framework-release.d.ts +2 -0
- package/types/src/framework-variables.d.ts +12 -1
- package/types/src/iam-mail.d.ts +92 -0
- package/types/src/index.d.ts +9 -0
- package/types/src/locale.d.ts +11 -1
- package/types/src/managed-environment.d.ts +32 -0
- package/types/src/membership.d.ts +8 -3
- package/types/src/ops.d.ts +657 -0
- package/types/src/public-egress.d.ts +31 -0
- package/types/src/requirement.d.ts +2 -2
- package/types/src/rpc.d.ts +5 -5
- package/types/src/sha256.d.ts +10 -0
- package/types/src/terminal.d.ts +72 -0
- package/types/src/token.d.ts +36 -11
- package/types/src/types.d.ts +42 -2
- package/types/src/wire.d.ts +6 -0
|
@@ -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
|
+
}
|
package/src/requirement.ts
CHANGED
|
@@ -8,8 +8,8 @@ import type { PermissionEntry } from './types'
|
|
|
8
8
|
* Whether a token's permissions meet an endpoint's requirement. This is authorization, not a gate: it reads only the
|
|
9
9
|
* token. `member` is any permission of this application; an action is that action in some scope, global included.
|
|
10
10
|
* 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
|
|
12
|
-
* one of their actions. `authenticated`, which only an installation row carries, needs no permission.
|
|
11
|
+
* 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.
|
|
12
|
+
* Several capabilities need every one of their actions. `authenticated`, which only an installation row carries, needs no permission.
|
|
13
13
|
*/
|
|
14
14
|
export function satisfies(requirement: EndpointRequirement | AuthenticatedRequirement, perms: readonly PermissionEntry[]): boolean {
|
|
15
15
|
if (requirement.kind === 'authenticated') {
|
|
@@ -18,6 +18,9 @@ export function satisfies(requirement: EndpointRequirement | AuthenticatedRequir
|
|
|
18
18
|
if (requirement.kind === 'member') {
|
|
19
19
|
return perms.length > 0
|
|
20
20
|
}
|
|
21
|
+
if (requirement.kind === 'anyOf') {
|
|
22
|
+
return requirement.actions.some((action) => perms.some((entry) => permits([entry], action)))
|
|
23
|
+
}
|
|
21
24
|
if (requirement.kind === 'capabilities') {
|
|
22
25
|
return Object.values(requirement.capabilities).every((capability) => holdsAction(capability, perms))
|
|
23
26
|
}
|
package/src/rpc.ts
CHANGED
|
@@ -10,7 +10,7 @@ import type {
|
|
|
10
10
|
import type { Jwks } from './token'
|
|
11
11
|
import type { PermissionEntry, PrincipalType, Scope } from './types'
|
|
12
12
|
|
|
13
|
-
// ──
|
|
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
|
-
// ──
|
|
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
|
|
@@ -154,8 +154,8 @@ export interface IssueKeyServiceSpec {
|
|
|
154
154
|
export interface IssueKeyInput {
|
|
155
155
|
app: string
|
|
156
156
|
/**
|
|
157
|
-
* The
|
|
158
|
-
* a `px_token` access JWT (verified against
|
|
157
|
+
* The IAM-native credential the ISSUER is resolved from server-side (never self-asserted):
|
|
158
|
+
* a `px_token` access JWT (verified against IAM's signing keys) or a `px_` key. Null = absent.
|
|
159
159
|
*/
|
|
160
160
|
credential: string | null
|
|
161
161
|
requestId: string
|
|
@@ -227,7 +227,7 @@ export interface AuditInput {
|
|
|
227
227
|
|
|
228
228
|
export interface RevokeKeyInput {
|
|
229
229
|
app: string
|
|
230
|
-
/** The
|
|
230
|
+
/** The IAM-native credential the CALLER (authorizer) is resolved from; null = absent. */
|
|
231
231
|
credential: string | null
|
|
232
232
|
requestId: string
|
|
233
233
|
/** The credential id (the `id` returned by `issueKey`), NOT the plaintext `px_` token. */
|
|
@@ -242,7 +242,7 @@ export type RevokeKeyResult =
|
|
|
242
242
|
// ── List principals (the app's people directory) ───────────────────────────────
|
|
243
243
|
//
|
|
244
244
|
// A read-only enumeration of the USER principals who can access an app — its people
|
|
245
|
-
// directory. Apps consume it for things
|
|
245
|
+
// directory. Apps consume it for things IAM isn't the authority on but needs the
|
|
246
246
|
// roster for: an assignee picker, an actor/owner label list. The caller is resolved from
|
|
247
247
|
// the forwarded Access credentials and the listed app is the aud-VERIFIED app — an operator
|
|
248
248
|
// can only enumerate the roster of an app it itself authenticates to (never a self-asserted
|
|
@@ -252,7 +252,7 @@ export type RevokeKeyResult =
|
|
|
252
252
|
export interface ListPrincipalsInput {
|
|
253
253
|
/** Self-asserted caller app id; superseded by the credential's aud on a valid `px_token`. */
|
|
254
254
|
app: string
|
|
255
|
-
/** The
|
|
255
|
+
/** The IAM-native credential the CALLER is resolved from (px_token / px_ key); null = absent. */
|
|
256
256
|
credential: string | null
|
|
257
257
|
requestId: string
|
|
258
258
|
}
|
|
@@ -286,7 +286,7 @@ export interface IamRpc {
|
|
|
286
286
|
listOwnDeviceAuthorizations(input: ListOwnDeviceAuthorizationsInput): Promise<ListOwnDeviceAuthorizationsResult>
|
|
287
287
|
/**
|
|
288
288
|
* Mint a short-lived, per-app permission token from the browser's SSO session — the
|
|
289
|
-
*
|
|
289
|
+
* IAM-native auth path. The SDK middleware calls this only when its cached permission
|
|
290
290
|
* token is missing/near-expiry (≈ once per TTL), NOT per request: every other request verifies
|
|
291
291
|
* the cached token locally against `getJwks`.
|
|
292
292
|
*/
|
package/src/sha256.ts
CHANGED
|
@@ -76,21 +76,60 @@ function rotateRight(value: number, bits: number): number {
|
|
|
76
76
|
|
|
77
77
|
/** The SHA-256 of `text`'s UTF-8 bytes, as 64 lower-case hex digits. */
|
|
78
78
|
export function sha256Hex(text: string): string {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
79
|
+
return new Sha256().update(text).hex()
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* SHA-256 over text fed in pieces, so a digest of a large serialization never needs the whole text in memory. Each
|
|
84
|
+
* piece is whole text: a surrogate pair split across two pieces encodes as two replacement characters.
|
|
85
|
+
*/
|
|
86
|
+
export class Sha256 {
|
|
87
|
+
readonly #hash = new Uint32Array(INITIAL_HASH)
|
|
88
|
+
readonly #schedule = new Uint32Array(64)
|
|
89
|
+
readonly #block = new Uint8Array(64)
|
|
90
|
+
readonly #blockView = new DataView(this.#block.buffer)
|
|
91
|
+
readonly #encoder = new TextEncoder()
|
|
92
|
+
#filled = 0
|
|
93
|
+
#length = 0
|
|
94
|
+
|
|
95
|
+
update(text: string): this {
|
|
96
|
+
const bytes = this.#encoder.encode(text)
|
|
97
|
+
this.#length += bytes.length
|
|
98
|
+
let offset = 0
|
|
99
|
+
while (offset < bytes.length) {
|
|
100
|
+
const taken = Math.min(64 - this.#filled, bytes.length - offset)
|
|
101
|
+
this.#block.set(bytes.subarray(offset, offset + taken), this.#filled)
|
|
102
|
+
this.#filled += taken
|
|
103
|
+
offset += taken
|
|
104
|
+
if (this.#filled === 64) {
|
|
105
|
+
this.#compress()
|
|
106
|
+
this.#filled = 0
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return this
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The digest of everything fed so far; the hash takes no piece after it. */
|
|
113
|
+
hex(): string {
|
|
114
|
+
const bitLength = this.#length * 8
|
|
115
|
+
// The message, a 0x80 byte, zero padding and the 64-bit bit length fill whole 64-byte blocks.
|
|
116
|
+
this.#block[this.#filled] = 0x80
|
|
117
|
+
this.#block.fill(0, this.#filled + 1)
|
|
118
|
+
if (this.#filled + 1 > 56) {
|
|
119
|
+
this.#compress()
|
|
120
|
+
this.#block.fill(0)
|
|
121
|
+
}
|
|
122
|
+
this.#blockView.setUint32(56, Math.floor(bitLength / 0x1_0000_0000))
|
|
123
|
+
this.#blockView.setUint32(60, bitLength >>> 0)
|
|
124
|
+
this.#compress()
|
|
125
|
+
return Array.from(this.#hash, (word) => word.toString(16).padStart(8, '0')).join('')
|
|
126
|
+
}
|
|
88
127
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
128
|
+
#compress(): void {
|
|
129
|
+
const hash = this.#hash
|
|
130
|
+
const schedule = this.#schedule
|
|
92
131
|
for (let index = 0; index < 16; index++) {
|
|
93
|
-
schedule[index] =
|
|
132
|
+
schedule[index] = this.#blockView.getUint32(index * 4)
|
|
94
133
|
}
|
|
95
134
|
for (let index = 16; index < 64; index++) {
|
|
96
135
|
const early = schedule[index - 15] ?? 0
|
|
@@ -121,5 +160,4 @@ export function sha256Hex(text: string): string {
|
|
|
121
160
|
hash[index] = (hash[index] ?? 0) + value
|
|
122
161
|
}
|
|
123
162
|
}
|
|
124
|
-
return Array.from(hash, (word) => word.toString(16).padStart(8, '0')).join('')
|
|
125
163
|
}
|
package/src/terminal.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// What an application declares and calls to sign a person in on an enrolled terminal (ADR-0067): its identification
|
|
2
|
+
// page, and the identification operations a handler asks IAM for. IAM takes the asserting application from the
|
|
3
|
+
// verified transport, never from the input: over `/membership/*` the application's membership transport key pins it, and
|
|
4
|
+
// over a Workers binding the `props` the deployer wrote on the application's `IAM` binding pin it. The credential must
|
|
5
|
+
// also verify for that application, but its audience alone proves nothing.
|
|
6
|
+
|
|
7
|
+
import { isCanonicalPath } from './canonical-path'
|
|
8
|
+
import type { MembershipCaller } from './membership'
|
|
9
|
+
|
|
10
|
+
/** The terminal declaration of a contract: the page on the application's own origin that identifies a person. */
|
|
11
|
+
export interface TerminalArtifact {
|
|
12
|
+
readonly identify: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** The longest identification path a contract declares. */
|
|
16
|
+
export const MAX_TERMINAL_IDENTIFY_PATH_LENGTH = 200
|
|
17
|
+
|
|
18
|
+
/** The query parameter IAM appends to the identification page: the identification's id. */
|
|
19
|
+
export const IDENTIFICATION_QUERY_PARAMETER = 'identification'
|
|
20
|
+
|
|
21
|
+
/** The path prefix the platform owns on every application host. */
|
|
22
|
+
const PLATFORM_PATH = '/__fabrika'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Why `path` is not an identification page, or `null`: an absolute, canonical path on the application's own origin,
|
|
26
|
+
* with no query or fragment (IAM appends its own) and outside the platform's `/__fabrika`.
|
|
27
|
+
*/
|
|
28
|
+
export function terminalIdentifyProblem(path: string): string | null {
|
|
29
|
+
if (path.length === 0 || path.length > MAX_TERMINAL_IDENTIFY_PATH_LENGTH) {
|
|
30
|
+
return `is 1 to ${MAX_TERMINAL_IDENTIFY_PATH_LENGTH} characters`
|
|
31
|
+
}
|
|
32
|
+
if (!path.startsWith('/') || path.startsWith('//')) {
|
|
33
|
+
return "is not an absolute path on the application's own origin (write it as '/identify')"
|
|
34
|
+
}
|
|
35
|
+
if (/[?#\s\p{Cc}]/u.test(path)) {
|
|
36
|
+
return 'carries a query, a fragment, whitespace or a control character; IAM appends the query itself'
|
|
37
|
+
}
|
|
38
|
+
if (!isCanonicalPath(path)) {
|
|
39
|
+
return 'is not a canonical path: no empty, `.` or `..` segment, no `\\` and no encoded separator'
|
|
40
|
+
}
|
|
41
|
+
if (path === PLATFORM_PATH || path.startsWith(`${PLATFORM_PATH}/`)) {
|
|
42
|
+
return `lies under ${PLATFORM_PATH}, which the platform owns`
|
|
43
|
+
}
|
|
44
|
+
return null
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Every identification operation carries the caller's verified credential: a public procedure's workload token. */
|
|
48
|
+
export type TerminalCaller = MembershipCaller
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Why IAM refused. `not_found` is an identification that is unknown, expired, consumed, cancelled, of another
|
|
52
|
+
* application, or whose terminal no longer lists the application: alike, so an id reveals nothing. `invalid_principal`
|
|
53
|
+
* is a principal that cannot sign in on a terminal: unknown, disabled, not a person, or external (ADR-0051).
|
|
54
|
+
*/
|
|
55
|
+
export type TerminalFailure = {
|
|
56
|
+
ok: false
|
|
57
|
+
reason: 'missing_token' | 'invalid_token' | 'not_allowed' | 'not_found' | 'invalid_principal'
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export type TerminalFailureReason = TerminalFailure['reason']
|
|
61
|
+
|
|
62
|
+
/** The terminal an identification was opened on, as the token's `terminal` claim names it. */
|
|
63
|
+
export interface IdentificationTerminal {
|
|
64
|
+
id: string
|
|
65
|
+
label: string
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Read an open identification: the id is the `identification` query parameter of the identification page. */
|
|
69
|
+
export interface InspectIdentificationInput extends TerminalCaller {
|
|
70
|
+
id: string
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `expiresAt` is unix seconds. The application keys its throttle of guesses on `terminal.id`. */
|
|
74
|
+
export type InspectIdentificationResult = { ok: true; terminal: IdentificationTerminal; expiresAt: number } | TerminalFailure
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The application's word that `principalId` stands at the identification's terminal. IAM consumes the identification
|
|
78
|
+
* (single use), signs the person in under the terminal's ceiling, and answers the URL the browser goes to next: IAM's
|
|
79
|
+
* completion of the identification, which issues the handoff code only to the terminal's own browser. The application
|
|
80
|
+
* never holds a code.
|
|
81
|
+
*/
|
|
82
|
+
export interface AssertIdentityInput extends TerminalCaller {
|
|
83
|
+
id: string
|
|
84
|
+
principalId: string
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export type AssertIdentityResult = { ok: true; completionUrl: string } | TerminalFailure
|
|
88
|
+
|
|
89
|
+
/** End an identification the person abandoned. Repeating it, or cancelling a consumed one, answers `not_found`. */
|
|
90
|
+
export interface CancelIdentificationInput extends TerminalCaller {
|
|
91
|
+
id: string
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export type CancelIdentificationResult = { ok: true } | TerminalFailure
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The identification operations IAM serves an application: on the membership transport (`/membership/<method>`) and
|
|
98
|
+
* on its application entrypoint. A SEPARATE interface from `IamMembershipRpc`, so a transport that predates terminals
|
|
99
|
+
* still satisfies that one.
|
|
100
|
+
*/
|
|
101
|
+
export interface IamTerminalRpc {
|
|
102
|
+
inspectIdentification(input: InspectIdentificationInput): Promise<InspectIdentificationResult>
|
|
103
|
+
assertIdentity(input: AssertIdentityInput): Promise<AssertIdentityResult>
|
|
104
|
+
cancelIdentification(input: CancelIdentificationInput): Promise<CancelIdentificationResult>
|
|
105
|
+
}
|
package/src/token.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The
|
|
2
|
+
* The IAM-issued token contract — the SECOND thing (after `IamRpc`) that must not drift
|
|
3
3
|
* between the Worker and the SDK.
|
|
4
4
|
*
|
|
5
5
|
* Background: today a request is authorized by the Worker resolving a Cloudflare Access JWT on
|
|
6
6
|
* every call over RPC (the CF token carries only identity, so authz needs a round-trip). When
|
|
7
|
-
*
|
|
7
|
+
* IAM issues its OWN token it can embed the already-resolved permission set, and the SDK
|
|
8
8
|
* authorizes LOCALLY — no per-request round-trip. This module is the wire shape of that token:
|
|
9
9
|
*
|
|
10
10
|
* - the Worker BUILDS claims here and signs them (`buildAccessClaims`);
|
|
@@ -47,7 +47,7 @@ export const FABRIKA_COOKIE_PREFIX = '__Host-px_'
|
|
|
47
47
|
* because those origins are potentially trustworthy.
|
|
48
48
|
*/
|
|
49
49
|
export const SESSION_COOKIE = `${FABRIKA_COOKIE_PREFIX}session`
|
|
50
|
-
/** Prefix marking
|
|
50
|
+
/** Prefix marking an IAM opaque credential (API key / share link), e.g. `Bearer px_<random>`. */
|
|
51
51
|
export const API_KEY_PREFIX = 'px_'
|
|
52
52
|
|
|
53
53
|
/**
|
|
@@ -56,7 +56,7 @@ export const API_KEY_PREFIX = 'px_'
|
|
|
56
56
|
*/
|
|
57
57
|
export const WORKLOAD_TOKEN_PATH = '/auth/workload/token'
|
|
58
58
|
|
|
59
|
-
/** Signing algorithm
|
|
59
|
+
/** Signing algorithm IAM issues with and the SDK verifies (ECDSA P-256 — compact, ubiquitous). */
|
|
60
60
|
export const TOKEN_ALG = 'ES256'
|
|
61
61
|
/** JWT `typ` of an OAuth resource access token (RFC 9068). Native app tokens carry no `typ`. */
|
|
62
62
|
export const RESOURCE_ACCESS_TOKEN_TYP = 'at+jwt'
|
|
@@ -70,22 +70,32 @@ export const DEFAULT_TOKEN_TTL_SECONDS = 300
|
|
|
70
70
|
export const TOKEN_REFRESH_SKEW_SECONDS = 30
|
|
71
71
|
|
|
72
72
|
/**
|
|
73
|
-
* The largest access token IAM signs, in bytes (a JWT is ASCII)
|
|
74
|
-
*
|
|
75
|
-
*
|
|
76
|
-
*
|
|
73
|
+
* The largest access token IAM signs, in bytes (a JWT is ASCII), except an application token below. A client sends
|
|
74
|
+
* such a token itself (an OAuth access token, a console bearer), so it crosses Caddy's `forward_auth` into the proxy's
|
|
75
|
+
* auth service and reaches installation services, which run on Bun with its default: a request's headers at most
|
|
76
|
+
* 16 KiB in total. 8 KiB leaves the rest for the request's own headers and cookies.
|
|
77
77
|
*/
|
|
78
78
|
export const MAX_ACCESS_TOKEN_BYTES = 8192
|
|
79
79
|
|
|
80
|
+
/**
|
|
81
|
+
* The largest token IAM mints for the proxy to inject toward a contract application, in bytes. No client sends it; on
|
|
82
|
+
* that hop it travels twice (`X-Fabrika-Token`, and `Authorization` on a bearer request), so two copies and 16 KiB of
|
|
83
|
+
* the request's own headers fit the header limit the platform starts the application's Bun with.
|
|
84
|
+
*/
|
|
85
|
+
export const MAX_APPLICATION_TOKEN_BYTES = 24576
|
|
86
|
+
|
|
87
|
+
/** The request-header limit the platform starts an application's Bun server with (`--max-http-header-size`). */
|
|
88
|
+
export const APPLICATION_SERVER_MAX_HEADER_BYTES = 65536
|
|
89
|
+
|
|
80
90
|
// ── Claim shape (one, no discriminator) ────────────────────────────────────────
|
|
81
91
|
|
|
82
92
|
/**
|
|
83
|
-
* The
|
|
93
|
+
* The IAM access token. `perms` is always present (matched via `permits`); `ptype` is present
|
|
84
94
|
* only when `sub` is a principal. `label` is the audit actor — the principal's label when bound, the
|
|
85
95
|
* credential label otherwise (or null).
|
|
86
96
|
*/
|
|
87
97
|
export interface AccessTokenClaims {
|
|
88
|
-
/** Issuer —
|
|
98
|
+
/** Issuer — IAM's own origin (e.g. `https://iam.example.com`). */
|
|
89
99
|
iss: string
|
|
90
100
|
/** The app id this token is scoped to. The SDK REJECTS a token whose `aud` is not its app. */
|
|
91
101
|
aud: string
|
|
@@ -117,12 +127,29 @@ export interface AccessTokenClaims {
|
|
|
117
127
|
* key carries what the key's own grants narrow, so a check that resolves the person's permissions requires this.
|
|
118
128
|
*/
|
|
119
129
|
session?: true
|
|
130
|
+
/**
|
|
131
|
+
* Present only on a session token of a person an application asserted at an enrolled terminal (ADR-0067), and
|
|
132
|
+
* always together with `terminal`.
|
|
133
|
+
*/
|
|
134
|
+
amr?: TerminalAuthenticationMethod
|
|
135
|
+
/** The terminal the person is signed in on; present exactly when `amr` is. */
|
|
136
|
+
terminal?: TerminalTokenClaims
|
|
120
137
|
/** Present only on an OAuth resource token (`aud` is then a resource URI, not an app id). */
|
|
121
138
|
oauth?: OAuthTokenClaims
|
|
122
139
|
/** Present only on a share-link token, which has no `ptype`: `sub` is then the link key's id. */
|
|
123
140
|
link?: LinkTokenClaims
|
|
124
141
|
}
|
|
125
142
|
|
|
143
|
+
/** The `amr` value of a session an application asserted at a terminal. */
|
|
144
|
+
export const TERMINAL_AUTHENTICATION_METHOD = 'terminal_assertion'
|
|
145
|
+
export type TerminalAuthenticationMethod = typeof TERMINAL_AUTHENTICATION_METHOD
|
|
146
|
+
|
|
147
|
+
/** The terminal a person's session was asserted on: its principal id and the label an administrator gave it. */
|
|
148
|
+
export interface TerminalTokenClaims {
|
|
149
|
+
id: string
|
|
150
|
+
label: string
|
|
151
|
+
}
|
|
152
|
+
|
|
126
153
|
/** What a share-link token adds: the link mount that issued the key and the chain the key is bound to. */
|
|
127
154
|
export interface LinkTokenClaims {
|
|
128
155
|
mount: string
|
|
@@ -162,7 +189,7 @@ export type TokenAudienceProfile = { kind: 'app'; app: string } | { kind: 'resou
|
|
|
162
189
|
//
|
|
163
190
|
// Transport is the IAM service binding (`getJwks()` RPC), NOT a public HTTPS URL: app↔IAM is
|
|
164
191
|
// RPC over the binding, which never traverses the Access edge — so the SDK reaches the key set
|
|
165
|
-
// even while
|
|
192
|
+
// even while IAM's own hostname is still gated by Cloudflare Access. The Worker also
|
|
166
193
|
// serves the standard `/.well-known/jwks.json`, for when Access is gone. Both emit this shape.
|
|
167
194
|
|
|
168
195
|
/** A published public signing key (EC P-256 / ES256). A jose-compatible JWK subset. */
|
|
@@ -184,7 +211,7 @@ export interface Jwks {
|
|
|
184
211
|
// ── Build (Worker side, pre-sign) ──────────────────────────────────────────────
|
|
185
212
|
|
|
186
213
|
export interface AccessTokenParams {
|
|
187
|
-
/** Issuer (
|
|
214
|
+
/** Issuer (IAM origin). */
|
|
188
215
|
iss: string
|
|
189
216
|
/** App id this token is for (becomes `aud`). */
|
|
190
217
|
app: string
|
|
@@ -200,6 +227,8 @@ export interface AccessTokenParams {
|
|
|
200
227
|
email?: string
|
|
201
228
|
/** Minted from a signed-in session; refused on a token without `type` or of a workload. */
|
|
202
229
|
session?: true
|
|
230
|
+
/** The terminal of a person's session asserted on one; sets `amr` too, and requires a user `type` and `session`. */
|
|
231
|
+
terminal?: TerminalTokenClaims
|
|
203
232
|
permissions: PermissionEntry[]
|
|
204
233
|
issuedAt: number
|
|
205
234
|
expiresAt: number
|
|
@@ -284,6 +313,13 @@ export function buildAccessClaims(params: AccessTokenParams): AccessTokenClaims
|
|
|
284
313
|
if (params.type === undefined || isWorkloadKind(params.type)) throw new Error("Only a person's or a service's token is minted from a session")
|
|
285
314
|
claims.session = params.session
|
|
286
315
|
}
|
|
316
|
+
if (params.terminal !== undefined) {
|
|
317
|
+
if (params.type !== 'user' || params.session !== true || !isTerminalClaims(params.terminal)) {
|
|
318
|
+
throw new Error("Only a person's session token names a terminal, and only by a non-empty id and label")
|
|
319
|
+
}
|
|
320
|
+
claims.amr = TERMINAL_AUTHENTICATION_METHOD
|
|
321
|
+
claims.terminal = { id: params.terminal.id, label: params.terminal.label }
|
|
322
|
+
}
|
|
287
323
|
if (params.link !== undefined) {
|
|
288
324
|
if (params.type !== undefined) throw new Error('A share-link token has no principal type')
|
|
289
325
|
claims.link = { mount: params.link.mount, chain: params.link.chain.map((scope) => ({ type: scope.type, value: scope.value })) }
|
|
@@ -333,6 +369,10 @@ export function parseAccessClaims(payload: unknown): AccessTokenClaims | null {
|
|
|
333
369
|
if (session !== undefined && (session !== true || ptype === null || isWorkloadKind(ptype) || oauth !== null)) {
|
|
334
370
|
return null
|
|
335
371
|
}
|
|
372
|
+
const terminal = parseTerminalClaims(prop(payload, 'amr'), prop(payload, 'terminal'))
|
|
373
|
+
if (terminal === undefined || (terminal !== null && (ptype !== 'user' || session !== true || oauth !== null))) {
|
|
374
|
+
return null
|
|
375
|
+
}
|
|
336
376
|
const claims: AccessTokenClaims = { iss, aud, sub, iat, exp, perms, label }
|
|
337
377
|
if (ptype !== null) {
|
|
338
378
|
claims.ptype = ptype
|
|
@@ -346,6 +386,10 @@ export function parseAccessClaims(payload: unknown): AccessTokenClaims | null {
|
|
|
346
386
|
if (session === true) {
|
|
347
387
|
claims.session = true
|
|
348
388
|
}
|
|
389
|
+
if (terminal !== null) {
|
|
390
|
+
claims.amr = TERMINAL_AUTHENTICATION_METHOD
|
|
391
|
+
claims.terminal = terminal
|
|
392
|
+
}
|
|
349
393
|
if (oauth !== null) {
|
|
350
394
|
claims.oauth = oauth
|
|
351
395
|
}
|
|
@@ -379,6 +423,22 @@ function parseEmail(value: unknown, ptype: TokenPrincipalType | null): string |
|
|
|
379
423
|
return ptype === 'user' && typeof value === 'string' && isNormalizedMailbox(value) ? value : undefined
|
|
380
424
|
}
|
|
381
425
|
|
|
426
|
+
/** Both absent → null; `amr` naming the terminal method beside a well-formed `terminal` → it; anything else → undefined. */
|
|
427
|
+
function parseTerminalClaims(amr: unknown, value: unknown): TerminalTokenClaims | null | undefined {
|
|
428
|
+
if (amr === undefined && value === undefined) {
|
|
429
|
+
return null
|
|
430
|
+
}
|
|
431
|
+
if (amr !== TERMINAL_AUTHENTICATION_METHOD) {
|
|
432
|
+
return undefined
|
|
433
|
+
}
|
|
434
|
+
const terminal = { id: stringField(value, 'id'), label: stringField(value, 'label') }
|
|
435
|
+
return isTerminalClaims(terminal) ? { id: terminal.id, label: terminal.label } : undefined
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function isTerminalClaims(value: { id: string | undefined; label: string | undefined }): value is TerminalTokenClaims {
|
|
439
|
+
return value.id !== undefined && value.id !== '' && value.label !== undefined && value.label !== ''
|
|
440
|
+
}
|
|
441
|
+
|
|
382
442
|
/** Absent → null; a mount and a non-empty chain → the claims; anything else → undefined. */
|
|
383
443
|
function parseLinkClaims(value: unknown): LinkTokenClaims | null | undefined {
|
|
384
444
|
if (value === undefined) {
|
|
@@ -470,7 +530,7 @@ function parseScope(value: unknown): Scope | null | undefined {
|
|
|
470
530
|
|
|
471
531
|
/** Validate `source` against the union — our own token, but read without `as`. */
|
|
472
532
|
function parseSource(value: unknown): PermissionSource | null {
|
|
473
|
-
if (value === 'grant' || value === 'bootstrap') {
|
|
533
|
+
if (value === 'grant' || value === 'bootstrap' || value === 'terminal') {
|
|
474
534
|
return value
|
|
475
535
|
}
|
|
476
536
|
if (typeof value === 'string' && value.startsWith('group:')) {
|