@fabrika/app 0.9.0-dev.11 → 0.9.0-dev.13
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 +10 -10
- package/skill/SKILL.md +7 -5
- package/skill/references/app-setup.md +8 -8
- package/skill/references/endpoint.md +12 -4
- package/skill/references/files.md +11 -1
- package/skill/references/relations.md +558 -0
- package/skill/references/table-and-migration.md +30 -0
- package/src/contract/artifact-schema.ts +94 -5
- package/src/contract/build.ts +127 -34
- package/src/contract/compile.ts +1 -0
- package/src/contract/declaration.ts +8 -2
- package/src/contract/define.ts +18 -1
- package/src/contract/group.ts +12 -10
- package/src/contract/index.ts +2 -0
- package/src/contract/kit.ts +1 -0
- package/src/contract/platform.ts +1 -0
- package/src/contract/vocabulary.ts +3 -0
- package/src/dev/launcher.ts +14 -15
- package/src/dev/output.ts +8 -11
- package/src/files/kinds.ts +1 -1
- package/src/files/sniff.ts +18 -1
- package/src/files/treatment.ts +12 -10
- package/src/implement/boot.ts +33 -2
- package/src/implement/capability.ts +19 -4
- package/src/implement/client-address.ts +5 -71
- package/src/implement/dispatch.ts +117 -14
- package/src/implement/egress.ts +30 -12
- package/src/implement/implement.ts +7 -0
- package/src/implement/public.ts +3 -3
- package/src/jobs/report.ts +32 -5
- package/src/jobs/scrub.ts +1 -1
- package/src/testing/caller.ts +9 -2
- package/src/testing/endpoint-access.ts +2 -1
- package/src/testing/sample-file.ts +4 -1
- package/types/src/contract/declaration.d.ts +9 -1
- package/types/src/contract/define.d.ts +20 -1
- package/types/src/contract/group.d.ts +5 -3
- package/types/src/contract/index.d.ts +1 -0
- package/types/src/contract/vocabulary.d.ts +4 -1
- package/types/src/dev/output.d.ts +7 -6
- package/types/src/files/treatment.d.ts +4 -3
- package/types/src/implement/capability.d.ts +4 -4
- package/types/src/implement/client-address.d.ts +0 -5
- package/types/src/implement/dispatch.d.ts +11 -0
- package/types/src/implement/implement.d.ts +7 -0
- package/types/src/testing/caller.d.ts +1 -1
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
isFileShape,
|
|
22
22
|
isRedirectShape,
|
|
23
23
|
type LinkTokenClaims,
|
|
24
|
+
matchAction,
|
|
24
25
|
parseEndpointHeader,
|
|
25
26
|
type PermissionEntry,
|
|
26
27
|
permits,
|
|
@@ -29,6 +30,8 @@ import {
|
|
|
29
30
|
PROXY_TOKEN_HEADER,
|
|
30
31
|
rawRequestTarget,
|
|
31
32
|
type RedirectShape,
|
|
33
|
+
RELATION_SCOPE_TYPE,
|
|
34
|
+
sameOriginTarget,
|
|
32
35
|
satisfies,
|
|
33
36
|
type SchemaShape,
|
|
34
37
|
type ScopeBinding,
|
|
@@ -41,7 +44,7 @@ import { type CapabilityAuthority, type ContainerGrant, MAX_WITHIN_VALUES } from
|
|
|
41
44
|
import type { DataAccess, FileBinding, FrameworkTables } from '@fabrika/db/framework'
|
|
42
45
|
import type { DataKind } from '@fabrika/db/tables'
|
|
43
46
|
import type { TokenVerifier } from '@fabrika/jwks'
|
|
44
|
-
import { applyAnswerCache, withResponseHeaders } from '@fabrika/proxy-core/headers'
|
|
47
|
+
import { applyAnswerCache, INLINE_FILE_TYPES, inlineFileTypes, withResponseHeaders } from '@fabrika/proxy-core/headers'
|
|
45
48
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
46
49
|
import { createHash, timingSafeEqual } from 'node:crypto'
|
|
47
50
|
import { z } from 'zod/v4'
|
|
@@ -307,6 +310,12 @@ export interface ProcedureQuery {
|
|
|
307
310
|
readonly shape: SchemaShape
|
|
308
311
|
}
|
|
309
312
|
|
|
313
|
+
/** A relation's reveal: a row it reaches reveals its node in `dimension` for `actions`. */
|
|
314
|
+
export interface RevealedNode {
|
|
315
|
+
readonly dimension: string
|
|
316
|
+
readonly actions: readonly string[]
|
|
317
|
+
}
|
|
318
|
+
|
|
310
319
|
export interface RuntimeParts {
|
|
311
320
|
readonly table: CompiledEndpointTable
|
|
312
321
|
readonly endpoints: ReadonlyMap<string, ServedEndpoint>
|
|
@@ -323,6 +332,12 @@ export interface RuntimeParts {
|
|
|
323
332
|
readonly ownedDimensions: ReadonlySet<string>
|
|
324
333
|
/** Each dimension's containers, nearest first; a grant on one reaches every value inside it. */
|
|
325
334
|
readonly containers: ReadonlyMap<string, readonly string[]>
|
|
335
|
+
/** Each relation of the contract with its dimension: a `~rel` entry holds its action at that dimension's nodes. */
|
|
336
|
+
readonly relations: ReadonlyMap<string, string>
|
|
337
|
+
/** Each relation's reveals: a `~rel` entry of one of their actions also holds it at the ancestor nodes they reveal. */
|
|
338
|
+
readonly reveals: ReadonlyMap<string, readonly RevealedNode[]>
|
|
339
|
+
/** Each dimension's member reveals: a grant of one of their actions at its node also reads under the ancestor they reveal. */
|
|
340
|
+
readonly memberReveals: ReadonlyMap<string, readonly RevealedNode[]>
|
|
326
341
|
readonly assets: SpaAssets | null
|
|
327
342
|
/** IAM's membership operations; `boot` refuses a contract that needs them when the adapter supplies none. */
|
|
328
343
|
readonly membership: IamMembership | null
|
|
@@ -412,10 +427,11 @@ export class ContractRuntime {
|
|
|
412
427
|
async fetch(request: Request, exec?: RequestExecutionContext): Promise<Response> {
|
|
413
428
|
const plan = planEndpoint(this.#parts.table, request.method, rawRequestTarget(request.url).pathname)
|
|
414
429
|
const answer = await this.#answer(request, plan, exec)
|
|
430
|
+
const inline = plan.outcome === 'endpoint' ? inlineFileTypes(plan.endpoint.response) : INLINE_FILE_TYPES
|
|
415
431
|
const answered = answer instanceof FileDownload
|
|
416
|
-
? fileResponse(answer)
|
|
432
|
+
? fileResponse(answer, inline)
|
|
417
433
|
: plan.outcome === 'endpoint' && answersFile(plan.endpoint)
|
|
418
|
-
? withFileTreatment(answer)
|
|
434
|
+
? withFileTreatment(answer, inline)
|
|
419
435
|
: withHeaderPolicy(answer, this.#parts.policy)
|
|
420
436
|
if (plan.outcome !== 'endpoint' || plan.endpoint.cache === undefined) {
|
|
421
437
|
return answered
|
|
@@ -929,35 +945,110 @@ export class ContractRuntime {
|
|
|
929
945
|
}
|
|
930
946
|
const held = this.#heldContainers(caller.perms, action, dimension)
|
|
931
947
|
const inside = this.#heldContained(caller.perms, action, dimension)
|
|
932
|
-
|
|
948
|
+
const related = this.#heldRelations(caller.perms, action, [dimension, ...(this.#parts.containers.get(dimension) ?? [])])
|
|
949
|
+
const revealing = this.#heldRevealing(caller.perms, action, [dimension, ...(this.#parts.containers.get(dimension) ?? [])])
|
|
950
|
+
if (direct.length === 0 && held.length === 0 && inside.length === 0 && related.length === 0 && revealing.length === 0) {
|
|
933
951
|
throw new ForbiddenError(`The caller holds '${action}' in no ${dimension}`)
|
|
934
952
|
}
|
|
935
|
-
return this.#parts.mint.within(frame, dimension, action, caller.subject, direct, held, inside)
|
|
953
|
+
return this.#parts.mint.within(frame, dimension, action, caller.subject, direct, held, inside, related, revealing)
|
|
936
954
|
}
|
|
937
955
|
|
|
938
956
|
/** A scope value the caller acts in: without a grant on it or on a container of it, 403 whether it exists or not. */
|
|
939
957
|
async #inRef(caller: Caller, action: string, dimension: string, value: string, frame: RequestFrame): Promise<Ref<string, string>> {
|
|
940
958
|
const direct = permits(caller.perms, action, { type: dimension, value })
|
|
941
|
-
|
|
959
|
+
const candidates = this.#heldRelations(caller.perms, action, [dimension, ...(this.#parts.containers.get(dimension) ?? [])])
|
|
960
|
+
if (!direct && this.#heldContainers(caller.perms, action, dimension).length === 0 && candidates.length === 0) {
|
|
942
961
|
throw new ForbiddenError(`The caller does not hold '${action}' in this ${dimension}`)
|
|
943
962
|
}
|
|
944
963
|
const chain = await this.#chain(dimension, value)
|
|
945
|
-
if (
|
|
946
|
-
|
|
964
|
+
if (holdsOnChain(caller.perms, action, dimension, value, chain ?? new Map())) {
|
|
965
|
+
if (chain === null) {
|
|
966
|
+
throw new NotFoundError('Not found')
|
|
967
|
+
}
|
|
968
|
+
return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain)
|
|
947
969
|
}
|
|
948
|
-
|
|
949
|
-
|
|
970
|
+
const related = chain === null ? [] : await this.#relatedOn(caller.subject, candidates, action, dimension, value, chain)
|
|
971
|
+
if (chain === null || related.length === 0) {
|
|
972
|
+
throw new ForbiddenError(`The caller does not hold '${action}' in this ${dimension}`)
|
|
950
973
|
}
|
|
951
|
-
return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain)
|
|
974
|
+
return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain, related)
|
|
952
975
|
}
|
|
953
976
|
|
|
954
977
|
/** An object the caller acts on; one it may not act on is indistinguishable from a missing one. */
|
|
955
978
|
async #onRef(caller: Caller, action: string, dimension: string, value: string, frame: RequestFrame): Promise<Ref<string, string>> {
|
|
956
979
|
const chain = await this.#chain(dimension, value)
|
|
957
|
-
if (chain === null
|
|
980
|
+
if (chain === null) {
|
|
958
981
|
throw new NotFoundError('Not found')
|
|
959
982
|
}
|
|
960
|
-
|
|
983
|
+
if (holdsOnChain(caller.perms, action, dimension, value, chain)) {
|
|
984
|
+
return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain)
|
|
985
|
+
}
|
|
986
|
+
const candidates = this.#heldRelations(caller.perms, action, [dimension, ...chain.keys()])
|
|
987
|
+
const related = await this.#relatedOn(caller.subject, candidates, action, dimension, value, chain)
|
|
988
|
+
if (related.length === 0) {
|
|
989
|
+
throw new NotFoundError('Not found')
|
|
990
|
+
}
|
|
991
|
+
return this.#parts.mint.ref(frame, dimension, action, caller.subject, value, chain, related)
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
/**
|
|
995
|
+
* The relations through which the caller holds `action` at a node of one of `dimensions` (a `~rel` entry, which IAM
|
|
996
|
+
* gives a global grant of a role with `via`), at the relation's own dimension or at an ancestor a reveal of `action`
|
|
997
|
+
* names. An entry of a relation the contract does not declare counts for none.
|
|
998
|
+
*/
|
|
999
|
+
#heldRelations(perms: PermissionEntry[], action: string, dimensions: readonly string[]): string[] {
|
|
1000
|
+
const held: string[] = []
|
|
1001
|
+
for (const entry of perms) {
|
|
1002
|
+
const scope = entry.scope
|
|
1003
|
+
if (scope === null || scope.type !== RELATION_SCOPE_TYPE || !matchAction(entry.action, action)) continue
|
|
1004
|
+
const relation = scope.value
|
|
1005
|
+
const at = this.#parts.relations.get(relation)
|
|
1006
|
+
const revealed = this.#revealed(relation, action).some((dimension) => dimensions.includes(dimension))
|
|
1007
|
+
if (at !== undefined && (dimensions.includes(at) || revealed) && !held.includes(relation)) held.push(relation)
|
|
1008
|
+
}
|
|
1009
|
+
return held
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
/** The ancestor dimensions a reveal of `relation` holds `action` at. */
|
|
1013
|
+
#revealed(relation: string, action: string): string[] {
|
|
1014
|
+
return (this.#parts.reveals.get(relation) ?? []).filter((reveal) => reveal.actions.includes(action)).map((reveal) => reveal.dimension)
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/**
|
|
1018
|
+
* Of `candidates`, the relations a row of which names the caller at the object or at a container on its chain, or
|
|
1019
|
+
* reaches a row that reveals one of them for `action`, now.
|
|
1020
|
+
*/
|
|
1021
|
+
async #relatedOn(
|
|
1022
|
+
principal: string,
|
|
1023
|
+
candidates: readonly string[],
|
|
1024
|
+
action: string,
|
|
1025
|
+
dimension: string,
|
|
1026
|
+
value: string,
|
|
1027
|
+
chain: ReadonlyMap<string, string>,
|
|
1028
|
+
): Promise<string[]> {
|
|
1029
|
+
const relates = this.#parts.database?.relates
|
|
1030
|
+
const reveals = this.#parts.database?.reveals
|
|
1031
|
+
if (relates === undefined) {
|
|
1032
|
+
return []
|
|
1033
|
+
}
|
|
1034
|
+
const nodeOf = (at: string | undefined) => (at === dimension ? value : at === undefined ? undefined : chain.get(at))
|
|
1035
|
+
const related: string[] = []
|
|
1036
|
+
for (const relation of candidates) {
|
|
1037
|
+
const node = nodeOf(this.#parts.relations.get(relation))
|
|
1038
|
+
if (node !== undefined && (await relates(relation, node, principal))) {
|
|
1039
|
+
related.push(relation)
|
|
1040
|
+
continue
|
|
1041
|
+
}
|
|
1042
|
+
if (reveals === undefined) continue
|
|
1043
|
+
for (const revealed of this.#revealed(relation, action)) {
|
|
1044
|
+
const at = nodeOf(revealed)
|
|
1045
|
+
if (at !== undefined && (await reveals(relation, revealed, at, principal))) {
|
|
1046
|
+
related.push(relation)
|
|
1047
|
+
break
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
return related
|
|
961
1052
|
}
|
|
962
1053
|
|
|
963
1054
|
/**
|
|
@@ -1464,6 +1555,18 @@ export class ContractRuntime {
|
|
|
1464
1555
|
})
|
|
1465
1556
|
}
|
|
1466
1557
|
|
|
1558
|
+
/**
|
|
1559
|
+
* The caller's grants of `action` at nodes of a dimension whose rows reveal one of `dimensions` for it to their
|
|
1560
|
+
* members; a grant at a container of such a node is not one at the node.
|
|
1561
|
+
*/
|
|
1562
|
+
#heldRevealing(perms: PermissionEntry[], action: string, dimensions: readonly string[]): ContainerGrant[] {
|
|
1563
|
+
return [...this.#parts.memberReveals].flatMap(([source, revealed]) => {
|
|
1564
|
+
const reveals = revealed.some((reveal) => reveal.actions.includes(action) && dimensions.includes(reveal.dimension))
|
|
1565
|
+
const values = reveals ? scopedValues(perms, action, source) ?? [] : []
|
|
1566
|
+
return values.length === 0 ? [] : [{ dimension: source, values }]
|
|
1567
|
+
})
|
|
1568
|
+
}
|
|
1569
|
+
|
|
1467
1570
|
/** The caller's grants of `action` on every dimension that lies inside `dimension`. */
|
|
1468
1571
|
#heldContained(perms: PermissionEntry[], action: string, dimension: string): ContainerGrant[] {
|
|
1469
1572
|
return [...this.#parts.containers].flatMap(([inner, containers]) => {
|
|
@@ -1894,7 +1997,7 @@ function readQuery(
|
|
|
1894
1997
|
*/
|
|
1895
1998
|
function redirectResponse(row: EndpointRow, shape: RedirectShape, output: unknown, request: Request, carried: ReadonlySet<string>): Response {
|
|
1896
1999
|
const to = isRecord(output) && typeof output['to'] === 'string' ? output['to'] : ''
|
|
1897
|
-
const own =
|
|
2000
|
+
const own = sameOriginTarget(new URL(request.url).origin, to) !== null
|
|
1898
2001
|
let listed = false
|
|
1899
2002
|
if (!own) {
|
|
1900
2003
|
try {
|
package/src/implement/egress.ts
CHANGED
|
@@ -1,23 +1,41 @@
|
|
|
1
|
-
// `egress`: while a site's handler runs, the global `fetch` reaches only the HTTPS origins the site declares
|
|
2
|
-
//
|
|
3
|
-
// boot, or opens its own sockets, escapes it.
|
|
4
|
-
// run outside the site's scope, under their own
|
|
1
|
+
// `egress`: while a site's handler runs, the global `fetch` reaches only the HTTPS origins the site declares, exactly or
|
|
2
|
+
// by a one-label pattern (`egressAdmits` of `@fabrika/auth-core`). It stops a mistake and makes a bypass conspicuous; it
|
|
3
|
+
// is not a sandbox (ADR-0012 §8): code that kept the `fetch` it found before boot, or opens its own sockets, escapes it.
|
|
4
|
+
// The framework's own facilities (mail, connectors, IAM, the object store) run outside the site's scope, under their own
|
|
5
|
+
// declarations.
|
|
5
6
|
|
|
7
|
+
import { egressAdmits, type EgressEntry, parseEgressEntry } from '@fabrika/auth-core'
|
|
6
8
|
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
7
9
|
import { CapabilityRefusedError } from './capability'
|
|
8
10
|
|
|
9
11
|
interface EgressScope {
|
|
10
12
|
/** The site, as a refusal names it. */
|
|
11
13
|
readonly site: string
|
|
12
|
-
readonly
|
|
14
|
+
readonly entries: readonly EgressEntry[]
|
|
13
15
|
}
|
|
14
16
|
|
|
15
17
|
const scope = new AsyncLocalStorage<EgressScope>()
|
|
16
18
|
const guards = new WeakSet<object>()
|
|
19
|
+
const parsed = new WeakMap<readonly string[], readonly EgressEntry[]>()
|
|
17
20
|
|
|
18
21
|
/** Runs a site's handler: every `fetch` it starts reaches only `egress`. */
|
|
19
22
|
export function runAsSite<T>(site: string, egress: readonly string[], work: () => Promise<T>): Promise<T> {
|
|
20
|
-
return scope.run({ site,
|
|
23
|
+
return scope.run({ site, entries: entriesOf(egress) }, work)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The approved declaration's entries, parsed once per list. The build and the artifact parser refused every other
|
|
28
|
+
* value, so one that does not parse here admits nothing.
|
|
29
|
+
*/
|
|
30
|
+
function entriesOf(egress: readonly string[]): readonly EgressEntry[] {
|
|
31
|
+
const known = parsed.get(egress)
|
|
32
|
+
if (known !== undefined) return known
|
|
33
|
+
const entries = egress.flatMap((value) => {
|
|
34
|
+
const entry = parseEgressEntry(value)
|
|
35
|
+
return entry.ok ? [entry.entry] : []
|
|
36
|
+
})
|
|
37
|
+
parsed.set(egress, entries)
|
|
38
|
+
return entries
|
|
21
39
|
}
|
|
22
40
|
|
|
23
41
|
/**
|
|
@@ -56,16 +74,16 @@ export function installEgressGuard(): void {
|
|
|
56
74
|
if (running === undefined) {
|
|
57
75
|
return current(input, init)
|
|
58
76
|
}
|
|
59
|
-
const
|
|
60
|
-
if (
|
|
77
|
+
const url = urlOf(input)
|
|
78
|
+
if (url !== null && egressAdmits(running.entries, url)) {
|
|
61
79
|
return current(input, init)
|
|
62
80
|
}
|
|
63
81
|
return Promise.reject(
|
|
64
82
|
new CapabilityRefusedError(
|
|
65
83
|
'undeclared_egress',
|
|
66
|
-
|
|
84
|
+
url === null
|
|
67
85
|
? `${running.site} called fetch with a URL that is not absolute`
|
|
68
|
-
: `${running.site} calls ${origin}, which it does not declare (egress: ['${origin}'])`,
|
|
86
|
+
: `${running.site} calls ${url.origin}, which it does not declare (egress: ['${url.origin}'])`,
|
|
69
87
|
),
|
|
70
88
|
)
|
|
71
89
|
},
|
|
@@ -75,9 +93,9 @@ export function installEgressGuard(): void {
|
|
|
75
93
|
globalThis.fetch = guarded
|
|
76
94
|
}
|
|
77
95
|
|
|
78
|
-
function
|
|
96
|
+
function urlOf(input: string | URL | Request): URL | null {
|
|
79
97
|
try {
|
|
80
|
-
return new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url)
|
|
98
|
+
return new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url)
|
|
81
99
|
} catch {
|
|
82
100
|
return null
|
|
83
101
|
}
|
|
@@ -22,6 +22,13 @@ export interface ContractDatabase {
|
|
|
22
22
|
* `using` is a job's transaction, which also sees the object it wrote; a layer of the application's own ignores it.
|
|
23
23
|
*/
|
|
24
24
|
locate(dimension: string, id: string, using?: Session): Promise<ReadonlyMap<string, string> | null>
|
|
25
|
+
/**
|
|
26
|
+
* Whether a row of `relation`'s source names `principal` at `node` and confers it now. A layer of the application's
|
|
27
|
+
* own has none, so no Ref is ever held through a relation there.
|
|
28
|
+
*/
|
|
29
|
+
relates?(relation: string, node: string, principal: string): Promise<boolean>
|
|
30
|
+
/** Whether a row `relation` reaches for `principal` reveals `node` of `dimension` now; none in a layer of the application's own. */
|
|
31
|
+
reveals?(relation: string, dimension: string, node: string, principal: string): Promise<boolean>
|
|
25
32
|
}
|
|
26
33
|
|
|
27
34
|
/** `scoped(tables)` of `@fabrika/db`, which `boot` binds, or a `ContractDatabase` of the application's own. */
|
package/src/implement/public.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// public procedure's challenge, and its time limit. The buckets live in the application's database
|
|
3
3
|
// (`@fabrika/db`'s `Admissions`, keyed by the endpoint id), so every instance shares them. Admission is not authorization: it bounds how much one client, one caller and everyone together send.
|
|
4
4
|
|
|
5
|
-
import { type AdmissionRate, CLIENT_ADDRESS_HEADER, type ContractArtifact, type ProcedureArtifact } from '@fabrika/auth-core'
|
|
5
|
+
import { type AdmissionRate, CLIENT_ADDRESS_HEADER, clientAddressKey, type ContractArtifact, type ProcedureArtifact } from '@fabrika/auth-core'
|
|
6
6
|
import { createHash } from 'node:crypto'
|
|
7
7
|
import { ALTCHA_LIMITS } from '../contract/defaults'
|
|
8
8
|
import { REQUEST_BUDGET_MS } from './bounded'
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
type ChallengeWork,
|
|
15
15
|
turnstileVerifier,
|
|
16
16
|
} from './challenge'
|
|
17
|
-
import { clientBucket
|
|
17
|
+
import { clientBucket } from './client-address'
|
|
18
18
|
import type { RequestClient } from './types'
|
|
19
19
|
|
|
20
20
|
/** The bucket every call of an endpoint takes from; a client's is `client:<digest>`, a caller's `caller:<digest>`. */
|
|
@@ -128,7 +128,7 @@ export function requestClient(request: Request, vouched: boolean): RequestClient
|
|
|
128
128
|
const address = vouched ? request.headers.get(CLIENT_ADDRESS_HEADER)?.trim() ?? '' : ''
|
|
129
129
|
const agent = request.headers.get('User-Agent')
|
|
130
130
|
return Object.freeze({
|
|
131
|
-
ip: address === '' ||
|
|
131
|
+
ip: address === '' || clientAddressKey(address) === null ? null : address,
|
|
132
132
|
userAgent: agent === null || agent === '' ? null : agent.slice(0, MAX_USER_AGENT_LENGTH),
|
|
133
133
|
})
|
|
134
134
|
}
|
package/src/jobs/report.ts
CHANGED
|
@@ -32,6 +32,8 @@ export interface OperationsTarget {
|
|
|
32
32
|
const PUBLIC_KEY = /^[0-9a-f]{32}$/
|
|
33
33
|
const PROJECT_ID = /^[1-9][0-9]{0,18}$/
|
|
34
34
|
const DELIVERY_TIMEOUT_MS = 5_000
|
|
35
|
+
const RETRY_DELAY_MIN_MS = 200
|
|
36
|
+
const RETRY_DELAY_JITTER_MS = 300
|
|
35
37
|
|
|
36
38
|
/** The envelope endpoint and key of a DSN `https://<key>@<host>/<project>`, or `null` when it is not one. */
|
|
37
39
|
export function operationsTarget(dsn: string): OperationsTarget | null {
|
|
@@ -135,7 +137,16 @@ export function crashEnvelope(kind: CrashKind, error: unknown, options: Envelope
|
|
|
135
137
|
return eventEnvelope({ tags: { crash: kind }, values: exceptionChain(error, options.scrubber) }, options, now)
|
|
136
138
|
}
|
|
137
139
|
|
|
138
|
-
|
|
140
|
+
/**
|
|
141
|
+
* One delivery attempt. `retry` is a network failure, a timeout or a 5xx: the retry resends the same body, so the same
|
|
142
|
+
* `event_id`, which the ingest ignores when it already stored it.
|
|
143
|
+
*/
|
|
144
|
+
type Attempt = { readonly kind: 'delivered' } | { readonly kind: 'refused'; readonly status: number } | {
|
|
145
|
+
readonly kind: 'retry'
|
|
146
|
+
readonly status: number | null
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
async function attempt(options: OperationsReporterOptions, body: string): Promise<Attempt> {
|
|
139
150
|
const send = options.fetch ?? ((request: Request) => fetch(request))
|
|
140
151
|
const timer = deadline(DELIVERY_TIMEOUT_MS)
|
|
141
152
|
const request = new Request(options.target.envelopeUrl, {
|
|
@@ -150,17 +161,33 @@ async function deliver(options: OperationsReporterOptions, body: string): Promis
|
|
|
150
161
|
try {
|
|
151
162
|
const response = await send(request)
|
|
152
163
|
await response.body?.cancel()
|
|
153
|
-
if (
|
|
154
|
-
|
|
164
|
+
if (response.ok) {
|
|
165
|
+
return { kind: 'delivered' }
|
|
155
166
|
}
|
|
167
|
+
return response.status >= 500 ? { kind: 'retry', status: response.status } : { kind: 'refused', status: response.status }
|
|
156
168
|
} catch {
|
|
157
|
-
// The error may quote the ingest URL with its key.
|
|
158
|
-
|
|
169
|
+
// The error may quote the ingest URL with its key, so it is not kept.
|
|
170
|
+
return { kind: 'retry', status: null }
|
|
159
171
|
} finally {
|
|
160
172
|
timer.clear()
|
|
161
173
|
}
|
|
162
174
|
}
|
|
163
175
|
|
|
176
|
+
/** One retry after a short jittered pause, so a transient ingress fault (a reset, a timeout, a 5xx) loses no report. */
|
|
177
|
+
async function deliver(options: OperationsReporterOptions, body: string): Promise<void> {
|
|
178
|
+
let outcome = await attempt(options, body)
|
|
179
|
+
if (outcome.kind === 'retry') {
|
|
180
|
+
await new Promise<void>((resolve) => setTimeout(resolve, RETRY_DELAY_MIN_MS + Math.random() * RETRY_DELAY_JITTER_MS))
|
|
181
|
+
outcome = await attempt(options, body)
|
|
182
|
+
}
|
|
183
|
+
if (outcome.kind === 'delivered') {
|
|
184
|
+
return
|
|
185
|
+
}
|
|
186
|
+
console.error(
|
|
187
|
+
outcome.status === null ? 'fabrika: a report to Operations could not be delivered' : `fabrika: a report to Operations answered ${outcome.status}`,
|
|
188
|
+
)
|
|
189
|
+
}
|
|
190
|
+
|
|
164
191
|
export function operationsReporter(options: OperationsReporterOptions): OperationsReporter {
|
|
165
192
|
return {
|
|
166
193
|
report: (report) => deliver(options, reportEnvelope(report, options, new Date())),
|
package/src/jobs/scrub.ts
CHANGED
|
@@ -41,7 +41,7 @@ const PUBLIC_FRAMEWORK_VARIABLES: ReadonlySet<string> = new Set([
|
|
|
41
41
|
* An application variable whose name says it holds a secret. The runtime does not know which names the application
|
|
42
42
|
* declared as secrets, so the name decides (backlog 176).
|
|
43
43
|
*/
|
|
44
|
-
const SECRET_NAME = /secret|token|
|
|
44
|
+
const SECRET_NAME = /secret|token|pass|private|credential|key|auth|dsn|salt|connection|cookie|session|signature|cert|database_?ur[il]|db_?ur[il]/i
|
|
45
45
|
|
|
46
46
|
const JWT = /\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]*/g
|
|
47
47
|
const AUTHORIZATION_SCHEME = /\b(Bearer|Basic|Token)\s+[A-Za-z0-9._~+/=-]{8,}/gi
|
package/src/testing/caller.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Test callers: a principal of the test IAM with the permissions its grants resolve to, as IAM resolves them, and
|
|
2
2
|
// the credential it presents.
|
|
3
3
|
|
|
4
|
-
import type
|
|
4
|
+
import { type PermissionEntry, type PrincipalAffiliation, RELATION_SCOPE_TYPE } from '@fabrika/auth-core'
|
|
5
5
|
import type { ActionOf, AnyContract, DimensionOf, RoleOf } from '../contract/define'
|
|
6
6
|
|
|
7
7
|
/** `app` is the connector of another application: its key reaches only the exports that application consumes. */
|
|
@@ -118,6 +118,13 @@ export function resolveGrants<C extends AnyContract>(contract: C, grants: readon
|
|
|
118
118
|
if (role.member !== undefined && grant.scope?.type !== role.member.scope) {
|
|
119
119
|
throw new Error(`'${grant.role}' is a membership role: grant it in one ${role.member.scope} (scope: { type: '${role.member.scope}', value })`)
|
|
120
120
|
}
|
|
121
|
-
|
|
121
|
+
const entries: PermissionEntry[] = role.grants.map((action) => ({ action, scope: scopeOf(grant.scope), source: 'grant' }))
|
|
122
|
+
// As IAM resolves it: a global grant of a role with `via` also holds each action through its relation.
|
|
123
|
+
if (grant.scope === undefined && role.member === undefined) {
|
|
124
|
+
for (const [relation, held] of Object.entries(role.via ?? {})) {
|
|
125
|
+
for (const action of held) entries.push({ action, scope: { type: RELATION_SCOPE_TYPE, value: relation }, source: 'grant' })
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return entries
|
|
122
129
|
})
|
|
123
130
|
}
|
|
@@ -415,7 +415,8 @@ export function endpointAccessKit<DB, P>(
|
|
|
415
415
|
challengeFetch: () => Promise.resolve(Response.json({ success: false, 'error-codes': ['invalid-input-response'] })),
|
|
416
416
|
})
|
|
417
417
|
const policies = tablePolicies(tables)
|
|
418
|
-
|
|
418
|
+
// A view's rows come from the tables it reads, which the kit seeds instead.
|
|
419
|
+
const tableNames = Object.keys(policies).filter((name) => policies[name]?.view !== true).sort()
|
|
419
420
|
|
|
420
421
|
const ownerOf = (dimension: string): string | undefined =>
|
|
421
422
|
tableNames.find((name) => {
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
// A small file the testing kits write: the leading bytes `files/sniff.ts` accepts for its type, then a text marker.
|
|
2
2
|
|
|
3
|
+
import { INLINE_DOCUMENT_TYPES } from '@fabrika/proxy-core/headers'
|
|
4
|
+
|
|
3
5
|
const randomHex = (): string => crypto.randomUUID().replaceAll('-', '').slice(0, 8)
|
|
4
6
|
|
|
5
7
|
const ascii = (text: string): number[] => [...text].map((char) => char.charCodeAt(0))
|
|
6
8
|
const ZIP_HEAD = [0x50, 0x4b, 0x03, 0x04]
|
|
7
9
|
|
|
8
|
-
/** The leading bytes `files/sniff.ts` accepts for each binary type it verifies;
|
|
10
|
+
/** The leading bytes `files/sniff.ts` accepts for each binary or XML type it verifies; another text type needs none. */
|
|
9
11
|
const SAMPLE_HEADS: Readonly<Record<string, readonly number[]>> = {
|
|
10
12
|
'image/png': [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
|
|
11
13
|
'image/jpeg': [0xff, 0xd8, 0xff, 0xe0],
|
|
@@ -17,6 +19,7 @@ const SAMPLE_HEADS: Readonly<Record<string, readonly number[]>> = {
|
|
|
17
19
|
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': ZIP_HEAD,
|
|
18
20
|
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': ZIP_HEAD,
|
|
19
21
|
'application/vnd.openxmlformats-officedocument.presentationml.presentation': ZIP_HEAD,
|
|
22
|
+
...Object.fromEntries(INLINE_DOCUMENT_TYPES.map((type) => [type, ascii('<?xml version="1.0"?>\n')])),
|
|
20
23
|
}
|
|
21
24
|
const TEXT_TYPES: ReadonlySet<string> = new Set(['text/plain', 'text/csv', 'text/markdown', 'application/json', 'image/svg+xml'])
|
|
22
25
|
|
|
@@ -4,6 +4,10 @@ export interface ContractDeclaration<S> {
|
|
|
4
4
|
readonly dimensions: Readonly<Record<string, DimensionDeclaration>>;
|
|
5
5
|
readonly actions: Readonly<Record<string, string>>;
|
|
6
6
|
readonly roles: Readonly<Record<string, RoleDeclaration>>;
|
|
7
|
+
/** The vocabulary's relations, by name; absent without any. */
|
|
8
|
+
readonly relations?: Readonly<Record<string, {
|
|
9
|
+
readonly dimension: string;
|
|
10
|
+
}>>;
|
|
7
11
|
readonly mounts: Readonly<Record<string, MountDeclaration<S>>>;
|
|
8
12
|
readonly files: Readonly<Record<string, FileKindDeclaration>>;
|
|
9
13
|
readonly jobs: Readonly<Record<string, CronDeclaration>>;
|
|
@@ -99,6 +103,8 @@ export interface RoleDeclaration {
|
|
|
99
103
|
};
|
|
100
104
|
/** `true` only; `buildArtifact` refuses another value, and refuses it on a role without `member`. */
|
|
101
105
|
readonly external?: boolean;
|
|
106
|
+
/** Relation → the actions a global holder of the role holds where a row of the relation names them. */
|
|
107
|
+
readonly via?: Readonly<Record<string, readonly string[]>>;
|
|
102
108
|
}
|
|
103
109
|
export type AccessDeclaration = {
|
|
104
110
|
readonly member: true;
|
|
@@ -258,7 +264,7 @@ export interface WebhookMountDeclaration<S> extends OptionsRecord {
|
|
|
258
264
|
readonly declared?: unknown;
|
|
259
265
|
}
|
|
260
266
|
/**
|
|
261
|
-
* A file kind (`c.files({ types, maxBytes, scan? })`, no `owner`): a class of stored files a table's file column holds.
|
|
267
|
+
* A file kind (`c.files({ types, maxBytes, scan?, inline? })`, no `owner`): a class of stored files a table's file column holds.
|
|
262
268
|
* It has no owner, no actions and no endpoint.
|
|
263
269
|
*/
|
|
264
270
|
export interface FileKindDeclaration extends OptionsRecord {
|
|
@@ -267,6 +273,8 @@ export interface FileKindDeclaration extends OptionsRecord {
|
|
|
267
273
|
readonly maxBytes: number;
|
|
268
274
|
/** Every file waits `quarantined` until the scan gives it a clean verdict; a byte consumer answers 409 until then. */
|
|
269
275
|
readonly scan?: boolean;
|
|
276
|
+
/** Its files are shown, not downloaded: only inert images and the XML documents a machine reads. */
|
|
277
|
+
readonly inline?: boolean;
|
|
270
278
|
}
|
|
271
279
|
export interface CronDeclaration extends OptionsRecord {
|
|
272
280
|
readonly kind: 'cron';
|
|
@@ -64,6 +64,17 @@ export interface RoleDef<A extends string, D extends string, R extends string> {
|
|
|
64
64
|
* only internal people hold it. Only a role with `member` may declare it; an internal person may hold it too.
|
|
65
65
|
*/
|
|
66
66
|
readonly external?: true;
|
|
67
|
+
/**
|
|
68
|
+
* Relation → actions: a holder of this role, granted globally, holds them at each node a row of the relation's
|
|
69
|
+
* source names them at (`via: { owner: ['projects.edit'] }`). A scoped grant of the role carries none of them.
|
|
70
|
+
*/
|
|
71
|
+
readonly via?: {
|
|
72
|
+
readonly [relation: string]: readonly A[];
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/** A relation of the vocabulary: a table's rows name a principal at a node of `dimension` (`confers` on that table). */
|
|
76
|
+
export interface RelationDef<D extends string> {
|
|
77
|
+
readonly dimension: D;
|
|
67
78
|
}
|
|
68
79
|
export interface Vocabulary<A extends string, D extends string, R extends string> extends Presentation, AppPeople<A>, AppTerminal {
|
|
69
80
|
readonly app: string;
|
|
@@ -76,6 +87,9 @@ export interface Vocabulary<A extends string, D extends string, R extends string
|
|
|
76
87
|
readonly roles: {
|
|
77
88
|
readonly [K in R]: RoleDef<A, D, R>;
|
|
78
89
|
};
|
|
90
|
+
readonly relations?: {
|
|
91
|
+
readonly [name: string]: RelationDef<D>;
|
|
92
|
+
};
|
|
79
93
|
}
|
|
80
94
|
/** The actions that manage and list the application's own people. */
|
|
81
95
|
export interface AppMembers<A extends string> {
|
|
@@ -224,7 +238,7 @@ export interface WebhookMount<B extends string, Acts extends string, I extends S
|
|
|
224
238
|
readonly actions: readonly Acts[];
|
|
225
239
|
readonly input: I;
|
|
226
240
|
}
|
|
227
|
-
/** A file kind `c.files({ types, maxBytes, scan? })` declares: what a file column of that kind holds. */
|
|
241
|
+
/** A file kind `c.files({ types, maxBytes, scan?, inline? })` declares: what a file column of that kind holds. */
|
|
228
242
|
export interface FileKind extends FileKindDeclaration {
|
|
229
243
|
}
|
|
230
244
|
export interface CronJob<Acts extends string> extends CronDeclaration {
|
|
@@ -331,6 +345,11 @@ export interface Kit<A extends string, D extends string, CD extends string> {
|
|
|
331
345
|
readonly maxBytes: number;
|
|
332
346
|
/** Each file is scanned for malware and served only after a clean verdict; until then it answers 409. */
|
|
333
347
|
readonly scan?: boolean;
|
|
348
|
+
/**
|
|
349
|
+
* Each file is shown, not downloaded (`Content-Disposition: inline`): a feed or a sitemap a machine reads. Every
|
|
350
|
+
* type is an inert image or `application/xml`, `text/xml`, `application/rss+xml`, `application/atom+xml`.
|
|
351
|
+
*/
|
|
352
|
+
readonly inline?: boolean;
|
|
334
353
|
} & Owned<'kind'>): FileKind;
|
|
335
354
|
/** A job of the whole application, holding `actions`; it runs on its schedule (UTC, five fields) and when kicked. */
|
|
336
355
|
cron<const Acts extends readonly [A, ...A[]]>(schedule: string, options: {
|
|
@@ -70,8 +70,8 @@ export type SignsField<Sg, Purposes extends string> = {
|
|
|
70
70
|
readonly signs: Sg & NoInfer<KnownPurposes<Sg, Purposes>>;
|
|
71
71
|
});
|
|
72
72
|
/**
|
|
73
|
-
* The HTTPS origins a site's code calls (`fetch`): each an exact origin, no path
|
|
74
|
-
* `fetch` refuses any other while the site runs; a public procedure declares none.
|
|
73
|
+
* The HTTPS origins a site's code calls (`fetch`): each an exact origin or `https://*.<domain>`, one label, no path. A
|
|
74
|
+
* guard on the global `fetch` refuses any other while the site runs; a public procedure declares none.
|
|
75
75
|
*/
|
|
76
76
|
export interface EgressField {
|
|
77
77
|
readonly egress?: readonly `https://${string}`[];
|
|
@@ -208,8 +208,10 @@ export interface Endpoint<T extends ProcedureType, I extends InputSchema | null,
|
|
|
208
208
|
/**
|
|
209
209
|
* An endpoint before `.handle`: a group refuses it. `Tk` are the kit's token purposes: a signed token field of the input
|
|
210
210
|
* reaches the handler as the claims of its purpose.
|
|
211
|
+
* The parameters are declared invariant, stricter than their structure: measuring that variance through `ExactReturn`
|
|
212
|
+
* exceeds TypeScript 7's instantiation limit (TS2589), and the compiler does not check an `in out` annotation.
|
|
211
213
|
*/
|
|
212
|
-
export interface EndpointBuilder<T extends ProcedureType, I extends InputSchema | null, O extends Schema, Acc, D, Ctx, X = unknown, Tk = Record<never, never>> extends PendingEndpoint {
|
|
214
|
+
export interface EndpointBuilder<in out T extends ProcedureType, in out I extends InputSchema | null, in out O extends Schema, in out Acc, in out D, in out Ctx, in out X = unknown, in out Tk = Record<never, never>> extends PendingEndpoint {
|
|
213
215
|
/** The endpoint's handler, typed by its access form and declaration; it may return only the output's fields. */
|
|
214
216
|
handle<const F extends KitHandler<WithClaims<HandlerInput<I, Acc>, Tk>, Ctx, HandlerReturn<F, O>, X>>(handler: F): ExactReturn<F, O, Endpoint<T, I, O, Acc, D>>;
|
|
215
217
|
}
|
|
@@ -3,6 +3,7 @@ export { type Attachment, attachment, type AttachmentBrand, type AttachmentMark,
|
|
|
3
3
|
export { buildArtifact } from './build';
|
|
4
4
|
export { deniedCaseRuledOutBy } from './capability-cases';
|
|
5
5
|
export { compileContract, describeContract } from './compile';
|
|
6
|
+
export type { ContractArtifact } from '@fabrika/auth-core';
|
|
6
7
|
export { type ConnectSnapshot, describeSnapshot, exportDescription, exportDescriptionSchema, incompatibleChanges, incompatibleMountChanges, parseExportDescription, type SnapshotProcedure, } from './connect';
|
|
7
8
|
export type * from './context';
|
|
8
9
|
export * from './declaration';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type AppMembers, type DimensionDef, type Presentation, type RoleDefs, type TerminalDeclaration, type Vocabulary, type WildcardMessage } from './define';
|
|
1
|
+
import { type AppMembers, type DimensionDef, type Presentation, type RelationDef, type RoleDefs, type TerminalDeclaration, type Vocabulary, type WildcardMessage } from './define';
|
|
2
2
|
/**
|
|
3
3
|
* The vocabulary as `defineVocabulary` returned it, with its literal names, dimension definitions, the actions of its
|
|
4
4
|
* people (`M`, `never` when it declares none) and its terminal (`T`, `never` when it declares none).
|
|
@@ -26,6 +26,9 @@ export declare function defineVocabulary<const A extends string, const D extends
|
|
|
26
26
|
readonly [K in A]: K extends `${string}*${string}` ? WildcardMessage : string;
|
|
27
27
|
};
|
|
28
28
|
readonly roles: RoleDefs<NoInfer<A>, NoInfer<D>, R>;
|
|
29
|
+
readonly relations?: {
|
|
30
|
+
readonly [name: string]: RelationDef<NoInfer<D>>;
|
|
31
|
+
};
|
|
29
32
|
readonly members?: M;
|
|
30
33
|
readonly directory?: 'labels';
|
|
31
34
|
readonly terminal?: T;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Scrubber } from '../jobs/scrub.js';
|
|
1
2
|
import { type DevLogLine } from './wire.js';
|
|
2
3
|
export type OutputStream = DevLogLine['stream'];
|
|
3
4
|
export interface OutputSink {
|
|
@@ -6,23 +7,23 @@ export interface OutputSink {
|
|
|
6
7
|
/** The launcher process's own stdout and stderr. */
|
|
7
8
|
export declare const processOutput: OutputSink;
|
|
8
9
|
/**
|
|
9
|
-
* The newest `capacity` lines, numbered from 0 since the launcher started,
|
|
10
|
-
* mark starts the lines a report carries: those of the newest sync or reset, and the output after it.
|
|
10
|
+
* The newest `capacity` lines, numbered from 0 since the launcher started, each scrubbed of secrets once, as it arrives.
|
|
11
|
+
* A mark starts the lines a report carries: those of the newest sync or reset, and the output after it.
|
|
11
12
|
*/
|
|
12
13
|
export declare class OutputRing {
|
|
13
14
|
private readonly capacity;
|
|
14
|
-
private readonly
|
|
15
|
+
private readonly scrubber;
|
|
15
16
|
private readonly sink;
|
|
16
17
|
private readonly lines;
|
|
17
18
|
private next;
|
|
18
19
|
private marked;
|
|
19
|
-
constructor(capacity: number,
|
|
20
|
-
|
|
20
|
+
constructor(capacity: number, scrubber: Scrubber, sink: OutputSink);
|
|
21
|
+
/** Log and keep `text` scrubbed, and return the scrubbed line: a caller keeps that copy and never the raw one. */
|
|
22
|
+
push(stream: OutputStream, text: string): string;
|
|
21
23
|
/** Report from the next line on: the lines before it belong to an older head. */
|
|
22
24
|
mark(): void;
|
|
23
25
|
/** The newest `count` lines since the mark, oldest first. */
|
|
24
26
|
tail(count: number): DevLogLine[];
|
|
25
|
-
private redact;
|
|
26
27
|
}
|
|
27
28
|
/** Feed `stream` to `onLine` one line at a time; a last line without a newline is fed when the stream ends. */
|
|
28
29
|
export declare function readLines(stream: ReadableStream<Uint8Array>, onLine: (line: string) => void): Promise<void>;
|