@intellectual-frontiers/integrations 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +8 -2
  3. package/dist/governance/exchange.d.ts +224 -0
  4. package/dist/governance/exchange.js +86 -0
  5. package/dist/governance/ids.d.ts +61 -0
  6. package/dist/governance/ids.js +53 -0
  7. package/dist/governance/mod.d.ts +11 -0
  8. package/dist/governance/mod.js +12 -0
  9. package/dist/governance/observe.d.ts +172 -0
  10. package/dist/governance/observe.js +139 -0
  11. package/dist/logical/conformance.d.ts +44 -0
  12. package/dist/logical/conformance.js +108 -0
  13. package/dist/logical/constraints.d.ts +86 -0
  14. package/dist/logical/constraints.js +112 -0
  15. package/dist/logical/exchange.d.ts +98 -0
  16. package/dist/logical/exchange.js +135 -0
  17. package/dist/logical/ledger.d.ts +94 -0
  18. package/dist/logical/ledger.js +90 -0
  19. package/dist/logical/mapping.d.ts +64 -0
  20. package/dist/logical/mapping.js +99 -0
  21. package/dist/logical/mod.d.ts +18 -0
  22. package/dist/logical/mod.js +19 -0
  23. package/dist/logical/observe.d.ts +222 -0
  24. package/dist/logical/observe.js +156 -0
  25. package/dist/logical/plugin.d.ts +91 -0
  26. package/dist/logical/plugin.js +53 -0
  27. package/dist/logical/ports.d.ts +102 -0
  28. package/dist/logical/ports.js +31 -0
  29. package/dist/logical/registry.d.ts +72 -0
  30. package/dist/logical/registry.js +81 -0
  31. package/dist/logical/tree.d.ts +91 -0
  32. package/dist/logical/tree.js +114 -0
  33. package/dist/mod.d.ts +15 -0
  34. package/dist/mod.js +16 -0
  35. package/dist/physical/http/mod.d.ts +54 -0
  36. package/dist/physical/http/mod.js +114 -0
  37. package/dist/physical/transport/mod.d.ts +79 -0
  38. package/dist/physical/transport/mod.js +61 -0
  39. package/dist/surfaces/headless/mod.d.ts +46 -0
  40. package/dist/surfaces/headless/mod.js +258 -0
  41. package/package.json +67 -4
  42. package/src/governance/exchange.ts +220 -0
  43. package/src/governance/ids.ts +92 -0
  44. package/src/governance/mod.ts +12 -0
  45. package/src/governance/observe.ts +226 -0
  46. package/src/logical/conformance.ts +113 -0
  47. package/src/logical/constraints.ts +154 -0
  48. package/src/logical/exchange.ts +184 -0
  49. package/src/logical/ledger.ts +123 -0
  50. package/src/logical/mapping.ts +114 -0
  51. package/src/logical/mod.ts +19 -0
  52. package/src/logical/observe.ts +314 -0
  53. package/src/logical/plugin.ts +102 -0
  54. package/src/logical/ports.ts +89 -0
  55. package/src/logical/registry.ts +93 -0
  56. package/src/logical/tree.ts +153 -0
  57. package/src/mod.ts +16 -0
  58. package/src/physical/http/mod.ts +134 -0
  59. package/src/physical/transport/mod.ts +85 -0
  60. package/src/surfaces/headless/mod.ts +293 -0
@@ -0,0 +1,220 @@
1
+ // Spec: 0002-integrations-governance FR-010, FR-011, FR-012, FR-013, FR-014, FR-015
2
+ /**
3
+ * The governance of exchange (commons integrations 0002-integrations-governance): standards as registry entries with identity, version and licence, the four levels
4
+ * a standard is at (syntax, schema, profile, terminology), the agreement with a trading partner, the protection of what is exchanged and the obligations that follow.
5
+ * It names no syntax and no transport: X12, HL7 v2 and FHIR are entries of the registry, not words of this module.
6
+ *
7
+ * @remarks
8
+ * A standard's licence is data with the rule that follows from it (`Embedding`): what may be committed to this public repository and what must be read from a
9
+ * copy the user supplies. Payloads are classified (`Classification`) and a classification says whether the payload may appear in a log, a hint or a trace; for
10
+ * every classification above `public` it may not.
11
+ *
12
+ * @module
13
+ */
14
+ import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
15
+ import type { AgreementId, CredentialRef, Duration, PartnerId, Sha256, StandardUrn } from "./ids.ts";
16
+
17
+ /** The four levels a standard is at. */
18
+ export type Level = "syntax" | "schema" | "profile" | "terminology";
19
+ export const LEVELS: readonly Level[] = ["syntax", "schema", "profile", "terminology"];
20
+
21
+ /** A reference to a standard at one level; the level is in the type so that a schema cannot stand where a terminology is wanted. */
22
+ export type Ref<L extends Level> = { readonly level: L; readonly urn: StandardUrn };
23
+
24
+ /** A reference at a level. */
25
+ export const ref = <L extends Level>(level: L, urn: StandardUrn): Ref<L> => ({ level, urn });
26
+
27
+ /** What kind of thing a standard defines. */
28
+ export type Family = "message" | "document" | "resource-api" | "vocabulary" | "file-format";
29
+
30
+ /** How a standard relates to the standard it comes from (commons 0018-standards-first). */
31
+ export type Basis =
32
+ | { readonly kind: "adopts"; readonly of: StandardUrn }
33
+ | { readonly kind: "specializes"; readonly of: StandardUrn }
34
+ | { readonly kind: "maps"; readonly to: StandardUrn }
35
+ | { readonly kind: "unaligned"; readonly reason: string };
36
+
37
+ /** What the licence of a standard allows this repository to hold. */
38
+ export type Embedding =
39
+ | "allowed" // the text and its machine-readable definitions may be committed, with the licence cited
40
+ | "user-supplied" // only a copy the user holds under a licence is read; nothing of it is committed
41
+ | "refused"; // not even read from a copy by this library
42
+
43
+ /** A licence as data: its SPDX identifier (or a `LicenseRef-` of the holder's terms), what it allows, and the text that cites the terms. */
44
+ export type License = { readonly spdx: string; readonly embedding: Embedding; readonly terms: string };
45
+
46
+ /** A standard: a registry entry with a stable identity (commons 0018-standards-first FR-006). */
47
+ export type Standard = {
48
+ readonly urn: StandardUrn;
49
+ readonly level: Level;
50
+ readonly family: Family;
51
+ readonly title: string;
52
+ readonly issuer: string;
53
+ readonly version: string;
54
+ readonly basis: Basis;
55
+ readonly location: string;
56
+ readonly license: License;
57
+ /** The digest of what was imported; absent where nothing was (a standard that is read from the user's copy). */
58
+ readonly sha256: Sha256 | undefined;
59
+ };
60
+
61
+ /** What a binding of a terminology demands of a code. */
62
+ export type BindingStrength = "required" | "extensible" | "preferred" | "example";
63
+
64
+ /** A binding of an element to a terminology. */
65
+ export type TerminologyBinding = { readonly path: string; readonly terminology: Ref<"terminology">; readonly strength: BindingStrength };
66
+
67
+ /** A profile bound to the schema it constrains. */
68
+ export type ProfileBinding = { readonly profile: Ref<"profile">; readonly schema: Ref<"schema"> };
69
+
70
+ /** Whether a standard may be loaded from a source of the given kind. */
71
+ export type Source = "embedded-in-package" | "user-supplied" | "published-by-issuer";
72
+
73
+ /** Whether the licence of a standard lets this source be used: a pure decision. */
74
+ export function sourceAllowed(license: License, source: Source): boolean {
75
+ switch (license.embedding) {
76
+ case "allowed":
77
+ return true;
78
+ case "user-supplied":
79
+ return source !== "embedded-in-package";
80
+ case "refused":
81
+ return false;
82
+ default:
83
+ return absurd(license.embedding);
84
+ }
85
+ }
86
+
87
+ /** How sensitive what is exchanged is. */
88
+ export type Classification = "public" | "internal" | "confidential" | "protected-health-information";
89
+ export const CLASSIFICATIONS: readonly Classification[] = ["public", "internal", "confidential", "protected-health-information"];
90
+
91
+ /** Where a payload of a classification may appear: only a `public` one in a log, a hint or a trace; no other, ever. */
92
+ export function mayAppearInLogs(c: Classification): boolean {
93
+ switch (c) {
94
+ case "public":
95
+ return true;
96
+ case "internal":
97
+ case "confidential":
98
+ case "protected-health-information":
99
+ return false;
100
+ default:
101
+ return absurd(c);
102
+ }
103
+ }
104
+
105
+ /** How much of a record a recipient may be given. */
106
+ export type MinimumNecessary =
107
+ | { readonly kind: "whole-record" }
108
+ | { readonly kind: "listed-elements"; readonly paths: readonly string[] }
109
+ | { readonly kind: "treatment-exempt" };
110
+
111
+ /** What is done with a payload at rest and in flight. */
112
+ export type Handling = { readonly encryptedInTransit: true; readonly encryptedAtRest: boolean; readonly retention: Duration };
113
+
114
+ /** The data protection of an exchange. */
115
+ export type DataProtection = { readonly classification: Classification; readonly handling: Handling; readonly minimumNecessary: MinimumNecessary };
116
+
117
+ /** The acknowledgement a partner requires, by standard. */
118
+ export type AckRequirement =
119
+ | { readonly kind: "x12-ta1"; readonly within: Duration }
120
+ | { readonly kind: "x12-999"; readonly within: Duration }
121
+ | { readonly kind: "hl7-ack"; readonly mode: "original" | "enhanced"; readonly within: Duration }
122
+ | { readonly kind: "fhir-operation-outcome"; readonly within: Duration };
123
+
124
+ /** Which direction messages flow with a partner. */
125
+ export type Direction = "inbound" | "outbound" | "both";
126
+
127
+ /** What an exchange must do. */
128
+ export type Obligation =
129
+ | { readonly kind: "validate"; readonly levels: readonly Level[] }
130
+ | { readonly kind: "acknowledge" }
131
+ | { readonly kind: "log"; readonly what: "metadata-only" }
132
+ | { readonly kind: "keep"; readonly for: Duration };
133
+
134
+ /** The service levels agreed: how long until an acknowledgement is overdue and how many times a send is tried. */
135
+ export type ServiceLevels = { readonly ackWithin: Duration; readonly maxAttempts: number };
136
+
137
+ /** How a partner is reached; the credential is a reference. */
138
+ export type ExchangeTransportPolicy =
139
+ | { readonly kind: "https"; readonly endpoint: string; readonly auth: "oauth2-backend-services" | "mutual-tls" | "api-key" }
140
+ | { readonly kind: "sftp"; readonly host: string }
141
+ | { readonly kind: "as2"; readonly endpoint: string }
142
+ | { readonly kind: "mllp"; readonly host: string; readonly port: number };
143
+
144
+ /** An exchange agreement with a trading partner. */
145
+ export type ExchangeAgreement = {
146
+ readonly id: AgreementId;
147
+ readonly partner: PartnerId;
148
+ readonly direction: Direction;
149
+ readonly syntax: Ref<"syntax">;
150
+ readonly schemas: readonly Ref<"schema">[];
151
+ readonly profiles: readonly ProfileBinding[];
152
+ readonly bindings: readonly TerminologyBinding[];
153
+ readonly acknowledgements: readonly AckRequirement[];
154
+ readonly serviceLevels: ServiceLevels;
155
+ readonly protection: DataProtection;
156
+ readonly obligations: readonly Obligation[];
157
+ readonly transport: ExchangeTransportPolicy;
158
+ readonly credential: CredentialRef;
159
+ };
160
+
161
+ /** What is wrong with an agreement. */
162
+ export type AgreementProblem =
163
+ | { readonly kind: "no-schema" }
164
+ | { readonly kind: "unacknowledged"; readonly needs: "acknowledgement-requirement" }
165
+ | { readonly kind: "validates-no-level" }
166
+ | { readonly kind: "log-would-carry-payload"; readonly classification: Classification }
167
+ | { readonly kind: "attempts-not-positive" }
168
+ | { readonly kind: "retention-shorter-than-keep" };
169
+
170
+ /** Every problem of an agreement against the standards registry; none where it may be used. */
171
+ export function agreementProblems(a: ExchangeAgreement): readonly AgreementProblem[] {
172
+ const out: AgreementProblem[] = [];
173
+ if (a.schemas.length === 0) out.push({ kind: "no-schema" });
174
+ const acks = a.obligations.some((o) => o.kind === "acknowledge");
175
+ if (acks && a.acknowledgements.length === 0) out.push({ kind: "unacknowledged", needs: "acknowledgement-requirement" });
176
+ const validates = a.obligations.filter((o) => o.kind === "validate");
177
+ if (validates.length > 0 && validates.every((o) => o.kind === "validate" && o.levels.length === 0)) out.push({ kind: "validates-no-level" });
178
+ if (a.serviceLevels.maxAttempts < 1) out.push({ kind: "attempts-not-positive" });
179
+ for (const o of a.obligations) {
180
+ if (o.kind === "keep" && o.for > a.protection.handling.retention) out.push({ kind: "retention-shorter-than-keep" });
181
+ }
182
+ return out;
183
+ }
184
+
185
+ /** A standard registry: typed entries by urn. */
186
+ export type StandardsRegistry = ReadonlyMap<StandardUrn, Standard>;
187
+
188
+ /** Why an entry is refused by a registry. */
189
+ export type RegistryError =
190
+ | { readonly kind: "duplicate"; readonly urn: StandardUrn }
191
+ | { readonly kind: "urn-mismatch"; readonly urn: StandardUrn; readonly want: string }
192
+ | { readonly kind: "no-terms"; readonly urn: StandardUrn };
193
+
194
+ /** The registry with one more entry, or why not. */
195
+ export function register(reg: StandardsRegistry, s: Standard): Result<StandardsRegistry, RegistryError> {
196
+ if (reg.has(s.urn)) return err({ kind: "duplicate", urn: s.urn });
197
+ const want = `urn:standard:${s.issuer}:${s.urn.split(":")[3] ?? ""}:${s.version}`;
198
+ if (s.urn !== want) return err({ kind: "urn-mismatch", urn: s.urn, want });
199
+ if (s.license.terms.trim() === "") return err({ kind: "no-terms", urn: s.urn });
200
+ return ok(new Map([...reg, [s.urn, s]]));
201
+ }
202
+
203
+ /** A file a package holds, with the standard whose content it embeds. */
204
+ export type EmbeddedContent = { readonly path: string; readonly standard: StandardUrn };
205
+
206
+ /** A finding of the publication gate. */
207
+ export type EmbeddingFinding =
208
+ | { readonly kind: "embedded-not-allowed"; readonly path: string; readonly standard: StandardUrn; readonly embedding: Embedding }
209
+ | { readonly kind: "embedded-unknown-standard"; readonly path: string; readonly standard: StandardUrn };
210
+
211
+ /** The refusal to publish embedded content a licence does not allow: a finding for each embedded file whose standard's licence is not `allowed` or is not in the registry. */
212
+ export function embeddingFindings(reg: StandardsRegistry, embedded: readonly EmbeddedContent[]): readonly EmbeddingFinding[] {
213
+ const out: EmbeddingFinding[] = [];
214
+ for (const e of embedded) {
215
+ const s = reg.get(e.standard);
216
+ if (s === undefined) out.push({ kind: "embedded-unknown-standard", path: e.path, standard: e.standard });
217
+ else if (!sourceAllowed(s.license, "embedded-in-package")) out.push({ kind: "embedded-not-allowed", path: e.path, standard: e.standard, embedding: s.license.embedding });
218
+ }
219
+ return out;
220
+ }
@@ -0,0 +1,92 @@
1
+ // Spec: 0002-integrations-governance FR-001, FR-002, FR-003
2
+ /**
3
+ * The identities of Integrations (commons integrations 0002-integrations-governance): each an opaque (branded) string that only a smart constructor makes, so that a
4
+ * value that is not a connector id, a standard urn, a credential reference, a digest or an instant cannot reach a function that wants one (parse, do not validate).
5
+ *
6
+ * @remarks
7
+ * `brand` is the one cast of the library. A refusal says what was expected and never repeats the input of a credential reference, because a mistaken
8
+ * reference may be the value itself.
9
+ *
10
+ * @module
11
+ */
12
+ import { err, ok, type Brand, type Result } from "@intellectual-frontiers/core";
13
+
14
+ /** Why a text is not an identity: what it was to be, and the input where the input is an identity and not a secret. */
15
+ export type IdError = { readonly kind: "id"; readonly what: string; readonly expected: string; readonly input?: string };
16
+
17
+ /** The one cast of the library: a text that a smart constructor has checked. */
18
+ export function brand<B extends string, T extends string | number = string>(value: T): Brand<T, B> {
19
+ return value as Brand<T, B>;
20
+ }
21
+
22
+ function parseWith<B extends string>(what: B, pattern: RegExp, expected: string, text: string, echo = true): Result<Brand<string, B>, IdError> {
23
+ return pattern.test(text) ? ok(brand<B>(text)) : err(echo ? { kind: "id", what, expected, input: text } : { kind: "id", what, expected });
24
+ }
25
+
26
+ /** The id of a connector: `^[a-z][a-z0-9-]{1,39}$`. */
27
+ export type ConnectorId = Brand<string, "ConnectorId">;
28
+ export const parseConnectorId = (text: string): Result<ConnectorId, IdError> => parseWith("ConnectorId", /^[a-z][a-z0-9-]{1,39}$/, "a lower-case name of 2 to 40 letters, digits and dashes", text);
29
+
30
+ /** The id of a trading partner. */
31
+ export type PartnerId = Brand<string, "PartnerId">;
32
+ export const parsePartnerId = (text: string): Result<PartnerId, IdError> => parseWith("PartnerId", /^[a-z][a-z0-9-]{1,63}$/, "a lower-case name of 2 to 64 letters, digits and dashes", text);
33
+
34
+ /** The id of an exchange agreement. */
35
+ export type AgreementId = Brand<string, "AgreementId">;
36
+ export const parseAgreementId = (text: string): Result<AgreementId, IdError> => parseWith("AgreementId", /^[a-z][a-z0-9-]{1,79}$/, "a lower-case name of 2 to 80 letters, digits and dashes", text);
37
+
38
+ /** The urn of a standard: `urn:standard:<issuer>:<name>:<version>` (commons 0018-standards-first FR-006). */
39
+ export type StandardUrn = Brand<string, "StandardUrn">;
40
+ export const parseStandardUrn = (text: string): Result<StandardUrn, IdError> =>
41
+ parseWith("StandardUrn", /^urn:standard:[a-z0-9][a-z0-9.-]*:[a-z0-9][a-z0-9._-]*:[A-Za-z0-9][A-Za-z0-9._-]*$/, "urn:standard:<issuer>:<name>:<version>", text);
42
+
43
+ /** The parts of a standard's urn. */
44
+ export type StandardParts = { readonly issuer: string; readonly name: string; readonly version: string };
45
+
46
+ /** The issuer, name and version a urn names. */
47
+ export function partsOfUrn(urn: StandardUrn): StandardParts {
48
+ const [, , issuer = "", name = "", version = ""] = urn.split(":");
49
+ return { issuer, name, version };
50
+ }
51
+
52
+ /** A urn built from its parts. */
53
+ export const standardUrn = (p: StandardParts): Result<StandardUrn, IdError> => parseStandardUrn(`urn:standard:${p.issuer}:${p.name}:${p.version}`);
54
+
55
+ /** A reference to a secret in a vault: `vault://<store>/<name>`. Never the secret; a refusal never repeats its input. */
56
+ export type CredentialRef = Brand<string, "CredentialRef">;
57
+ export const parseCredentialRef = (text: string): Result<CredentialRef, IdError> =>
58
+ parseWith("CredentialRef", /^vault:\/\/[a-z][a-z0-9-]{0,31}\/[a-z][a-z0-9._/-]{0,95}$/, "vault://<store>/<name>", text, false);
59
+
60
+ /** A SHA-256 digest as 64 lower-case hexadecimal digits. */
61
+ export type Sha256 = Brand<string, "Sha256">;
62
+ export const parseSha256 = (text: string): Result<Sha256, IdError> => parseWith("Sha256", /^[0-9a-f]{64}$/, "64 lower-case hexadecimal digits", text);
63
+
64
+ /** A moment in UTC as an ISO 8601 text with a `Z`: `2026-11-20T10:00:00.000Z`. */
65
+ export type Instant = Brand<string, "Instant">;
66
+ export function parseInstant(text: string): Result<Instant, IdError> {
67
+ const t = Date.parse(text);
68
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/.test(text) || Number.isNaN(t)) return err({ kind: "id", what: "Instant", expected: "an ISO 8601 moment in UTC, such as 2026-11-20T10:00:00Z", input: text });
69
+ return ok(brand<"Instant">(text));
70
+ }
71
+
72
+ /** The instant of a number of milliseconds since the epoch. */
73
+ export const instantOf = (ms: number): Instant => brand<"Instant">(new Date(ms).toISOString());
74
+
75
+ /** The milliseconds since the epoch of an instant. */
76
+ export const msOf = (at: Instant): number => Date.parse(at);
77
+
78
+ /** A length of time in whole milliseconds, positive. */
79
+ export type Duration = Brand<number, "Duration">;
80
+
81
+ const UNITS: Readonly<Record<string, number>> = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
82
+
83
+ /** A duration from `15m`, `6h`, `1d` or `30s`: a whole number and one unit. */
84
+ export function parseDuration(text: string): Result<Duration, IdError> {
85
+ const m = /^([1-9][0-9]{0,5})([smhd])$/.exec(text);
86
+ const unit = m?.[2] === undefined ? undefined : UNITS[m[2]];
87
+ if (m?.[1] === undefined || unit === undefined) return err({ kind: "id", what: "Duration", expected: "a whole number and one of s, m, h, d, such as 15m", input: text });
88
+ return ok(brand<"Duration", number>(Number(m[1]) * unit));
89
+ }
90
+
91
+ /** The milliseconds of a duration, as a duration (for arithmetic that stays positive). */
92
+ export const durationMs = (d: Duration): number => d;
@@ -0,0 +1,12 @@
1
+ // Spec: 0002-integrations-governance FR-001
2
+ /**
3
+ * Layer 1 of Integrations, governance (commons integrations 0002-integrations-governance): identities made by smart constructors, the governance of observation
4
+ * (connector class, read-only contract, credential reference and least-privilege scope, cadence, entity kinds, the denylist of fields, labels, trust policy) and the
5
+ * governance of exchange (standards with licences, the four levels, bindings, agreements, data protection, obligations). It knows no vendor, no syntax, no transport
6
+ * and no file; it imports Core and nothing else.
7
+ *
8
+ * @module
9
+ */
10
+ export * from "./exchange.ts";
11
+ export * from "./ids.ts";
12
+ export * from "./observe.ts";
@@ -0,0 +1,226 @@
1
+ // Spec: 0002-integrations-governance FR-004, FR-005, FR-006, FR-007, FR-008, FR-009
2
+ /**
3
+ * The governance of observation (commons integrations 0002-integrations-governance): what a connector is allowed to be and to read, as data that names no
4
+ * vendor, no HTTP and no file path. A connector has a class, one read-only contract, a credential reference with its least-privilege scope, a cadence, the
5
+ * kinds of entity it may produce and the fields that are never kept, labels in the world's terms, and a policy for the trust it places in the system it reads.
6
+ *
7
+ * @remarks
8
+ * Every list is a closed union with an exhaustive `switch` where it is read; the policy data of a consumer (a fleet's paths, an estate's labels, a catalogue of
9
+ * controls) is attached by the consumer and is not in this module.
10
+ *
11
+ * @module
12
+ */
13
+ import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
14
+ import { brand, durationMs, parseDuration, type ConnectorId, type CredentialRef, type Duration, type IdError, type Instant, msOf, type Sha256 } from "./ids.ts";
15
+
16
+ /** What a connector connects to. */
17
+ export type ConnectorClass = "cloud" | "identity" | "code-host" | "hr" | "endpoint" | "ticketing" | "network-device" | "vulnerability";
18
+ export const CONNECTOR_CLASSES: readonly ConnectorClass[] = ["cloud", "identity", "code-host", "hr", "endpoint", "ticketing", "network-device", "vulnerability"];
19
+
20
+ /** The service models of NIST SP 800-145. */
21
+ export type ServiceModel = "IaaS" | "PaaS" | "SaaS";
22
+
23
+ /** The labels of a connector in the world's terms: its service models and the categories a consumer's own vocabulary (an analyst's, a catalogue's) names. */
24
+ export type Labels = { readonly serviceModels: readonly ServiceModel[]; readonly categories: readonly string[] };
25
+
26
+ /** The only thing a connector may do to a system it observes. */
27
+ export type Access = "read";
28
+
29
+ /** One grant of the least-privilege scope: a resource the credential must reach, named in the system's own words, and read access. */
30
+ export type Grant = { readonly resource: string; readonly access: Access };
31
+
32
+ /** The least privilege a connector needs: its grants, all read. */
33
+ export type Scope = { readonly grants: readonly Grant[] };
34
+
35
+ /** The read-only contract: a connector never changes what it observes, and this is a value so that a conformance check can hold it. */
36
+ export type ReadOnlyContract = { readonly writes: "never"; readonly tokenEndpoints: readonly string[] };
37
+
38
+ /** The kinds of entity an observation may carry. */
39
+ export type EntityKind = "person" | "account" | "device" | "repository";
40
+ export const ENTITY_KINDS: readonly EntityKind[] = ["person", "account", "device", "repository"];
41
+
42
+ /** What the denylist matches: a field name exactly, or a field name containing the text, ignoring case. */
43
+ export type FieldPattern =
44
+ | { readonly kind: "exact"; readonly text: string; readonly why: string }
45
+ | { readonly kind: "contains"; readonly text: string; readonly why: string };
46
+
47
+ /** The fields that are never kept, whichever connector reads them. */
48
+ export type Denylist = { readonly patterns: readonly FieldPattern[] };
49
+
50
+ /** The generic denylist: personal, compensation and secret fields. A connector may add to it and never remove from it. */
51
+ export const GENERIC_DENYLIST: Denylist = {
52
+ patterns: [
53
+ { kind: "contains", text: "salary", why: "compensation" },
54
+ { kind: "contains", text: "compensation", why: "compensation" },
55
+ { kind: "contains", text: "bonus", why: "compensation" },
56
+ { kind: "contains", text: "ssn", why: "government identifier" },
57
+ { kind: "contains", text: "social_security", why: "government identifier" },
58
+ { kind: "contains", text: "passport", why: "government identifier" },
59
+ { kind: "contains", text: "national_id", why: "government identifier" },
60
+ { kind: "contains", text: "birth", why: "birth date" },
61
+ { kind: "contains", text: "dob", why: "birth date" },
62
+ { kind: "contains", text: "address", why: "home address" },
63
+ { kind: "contains", text: "phone", why: "personal contact" },
64
+ { kind: "contains", text: "password", why: "secret" },
65
+ { kind: "contains", text: "secret", why: "secret" },
66
+ { kind: "contains", text: "token", why: "secret" },
67
+ { kind: "contains", text: "private_key", why: "secret" },
68
+ { kind: "contains", text: "api_key", why: "secret" },
69
+ ],
70
+ };
71
+
72
+ /** Whether a field name is denied by a denylist. */
73
+ export function isDenied(list: Denylist, field: string): boolean {
74
+ const f = field.toLowerCase();
75
+ return list.patterns.some((p) => {
76
+ switch (p.kind) {
77
+ case "exact":
78
+ return f === p.text.toLowerCase();
79
+ case "contains":
80
+ return f.includes(p.text.toLowerCase());
81
+ default:
82
+ return absurd(p);
83
+ }
84
+ });
85
+ }
86
+
87
+ /** The denylist of a connector: the generic one and what the connector adds. */
88
+ export const denylistWith = (extra: readonly FieldPattern[]): Denylist => ({ patterns: [...GENERIC_DENYLIST.patterns, ...extra] });
89
+
90
+ /** A cadence: how often the system is observed, and after how long an observation is stale. */
91
+ export type Cadence = { readonly every: Duration; readonly staleAfter: Duration };
92
+
93
+ /** An observation is never held fresh for longer than seven days. */
94
+ export const MAX_STALE_MS = 7 * 86_400_000;
95
+
96
+ /** Why a cadence is refused. */
97
+ export type CadenceError =
98
+ | { readonly kind: "cadence-text"; readonly error: IdError }
99
+ | { readonly kind: "stale-before-every"; readonly every: Duration; readonly staleAfter: Duration }
100
+ | { readonly kind: "stale-beyond-cap"; readonly staleAfter: Duration };
101
+
102
+ /** A cadence from `every` (`15m`, `6h`, `1d`) and, where given, `staleAfter`: by default twice `every`, never more than seven days, never less than `every`. */
103
+ export function cadence(every: string, staleAfter?: string): Result<Cadence, CadenceError> {
104
+ const e = parseDuration(every);
105
+ if (e.kind === "err") return err({ kind: "cadence-text", error: e.error });
106
+ let s: Duration;
107
+ if (staleAfter === undefined) {
108
+ s = brand<"Duration", number>(Math.min(durationMs(e.value) * 2, MAX_STALE_MS));
109
+ } else {
110
+ const parsed = parseDuration(staleAfter);
111
+ if (parsed.kind === "err") return err({ kind: "cadence-text", error: parsed.error });
112
+ s = parsed.value;
113
+ }
114
+ if (durationMs(s) > MAX_STALE_MS) return err({ kind: "stale-beyond-cap", staleAfter: s });
115
+ if (durationMs(s) < durationMs(e.value)) return err({ kind: "stale-before-every", every: e.value, staleAfter: s });
116
+ return ok({ every: e.value, staleAfter: s });
117
+ }
118
+
119
+ /** Whether an observation made at `at` is stale at `now`. */
120
+ export const isStale = (c: Cadence, at: Instant, now: Instant): boolean => msOf(now) - msOf(at) > durationMs(c.staleAfter);
121
+
122
+ /** A field of the credential a person gives the vault: its name, whether it is secret and a hint. A secret field is never optional. */
123
+ export type CredentialField = { readonly name: string; readonly secret: boolean; readonly hint: string };
124
+
125
+ /** The credential a connector needs: where the vault keeps it (a reference, never a value) and its fields. */
126
+ export type CredentialSpec = { readonly ref: CredentialRef; readonly fields: readonly CredentialField[] };
127
+
128
+ /** Why a credential spec is refused. */
129
+ export type CredentialSpecError = { readonly kind: "no-secret-field" } | { readonly kind: "field-without-hint"; readonly name: string } | { readonly kind: "duplicate-field"; readonly name: string };
130
+
131
+ /** A credential spec that has at least one secret field, a hint on each field and no field twice. */
132
+ export function credentialSpec(ref: CredentialRef, fields: readonly CredentialField[]): Result<CredentialSpec, CredentialSpecError> {
133
+ if (!fields.some((f) => f.secret)) return err({ kind: "no-secret-field" });
134
+ const seen = new Set<string>();
135
+ for (const f of fields) {
136
+ if (f.hint.trim() === "") return err({ kind: "field-without-hint", name: f.name });
137
+ if (seen.has(f.name)) return err({ kind: "duplicate-field", name: f.name });
138
+ seen.add(f.name);
139
+ }
140
+ return ok({ ref, fields });
141
+ }
142
+
143
+ /** How a pinned certificate came to be trusted: the first one seen (trust on first use), or one that was set beforehand. */
144
+ export type PinOrigin = "trust-on-first-use" | "preconfigured";
145
+
146
+ /** How the TLS of a system is trusted. */
147
+ export type TlsPolicy =
148
+ | { readonly kind: "system-roots" }
149
+ | { readonly kind: "pinned"; readonly origin: PinOrigin; readonly sha256: Sha256 | undefined };
150
+
151
+ /** How the system is reached: over HTTPS to listed hosts, or over SNMPv3. */
152
+ export type TransportPolicy =
153
+ | { readonly kind: "https"; readonly hosts: readonly string[]; readonly tls: TlsPolicy }
154
+ | { readonly kind: "snmp-v3"; readonly level: "authPriv" };
155
+
156
+ /** The governance of one connector. */
157
+ export type ConnectorGovernance = {
158
+ readonly id: ConnectorId;
159
+ readonly title: string;
160
+ readonly class: ConnectorClass;
161
+ readonly labels: Labels;
162
+ readonly contract: ReadOnlyContract;
163
+ readonly credential: CredentialSpec;
164
+ readonly scope: Scope;
165
+ readonly cadence: Cadence;
166
+ readonly entities: readonly EntityKind[];
167
+ readonly denylist: Denylist;
168
+ readonly transport: TransportPolicy;
169
+ };
170
+
171
+ /** What is wrong with the governance of a connector. */
172
+ export type GovernanceProblem =
173
+ | { readonly kind: "no-scope" }
174
+ | { readonly kind: "no-host" }
175
+ | { readonly kind: "pin-without-digest"; readonly origin: "preconfigured" }
176
+ | { readonly kind: "denylist-weaker"; readonly missing: string }
177
+ | { readonly kind: "no-service-model" }
178
+ | { readonly kind: "entity-twice"; readonly entity: EntityKind };
179
+
180
+ /** Every problem of a connector's governance; none where it may be used. */
181
+ export function governanceProblems(g: ConnectorGovernance): readonly GovernanceProblem[] {
182
+ const out: GovernanceProblem[] = [];
183
+ if (g.scope.grants.length === 0) out.push({ kind: "no-scope" });
184
+ if (g.transport.kind === "https") {
185
+ if (g.transport.hosts.length === 0) out.push({ kind: "no-host" });
186
+ if (g.transport.tls.kind === "pinned" && g.transport.tls.origin === "preconfigured" && g.transport.tls.sha256 === undefined) out.push({ kind: "pin-without-digest", origin: "preconfigured" });
187
+ }
188
+ for (const p of GENERIC_DENYLIST.patterns) {
189
+ if (!g.denylist.patterns.some((q) => q.kind === p.kind && q.text === p.text)) out.push({ kind: "denylist-weaker", missing: p.text });
190
+ }
191
+ if (g.labels.serviceModels.length === 0 && g.class === "cloud") out.push({ kind: "no-service-model" });
192
+ const seen = new Set<EntityKind>();
193
+ for (const e of g.entities) {
194
+ if (seen.has(e)) out.push({ kind: "entity-twice", entity: e });
195
+ seen.add(e);
196
+ }
197
+ return out;
198
+ }
199
+
200
+ /** What the next contact with a system does about its pinned certificate. */
201
+ export type PinDecision =
202
+ | { readonly kind: "accept" }
203
+ | { readonly kind: "remember"; readonly sha256: Sha256 }
204
+ | { readonly kind: "refuse"; readonly why: "mismatch" | "no-pin-and-not-first-use" | "not-pinned-policy" };
205
+
206
+ /** What a pinned policy does with the digest the system shows and the one remembered (or none): a total function of the policy, the shown digest and what is remembered. */
207
+ export function decidePin(policy: TlsPolicy, shown: Sha256, remembered: Sha256 | undefined): PinDecision {
208
+ switch (policy.kind) {
209
+ case "system-roots":
210
+ return { kind: "refuse", why: "not-pinned-policy" };
211
+ case "pinned": {
212
+ const expected = policy.sha256 ?? remembered;
213
+ if (expected !== undefined) return expected === shown ? { kind: "accept" } : { kind: "refuse", why: "mismatch" };
214
+ switch (policy.origin) {
215
+ case "trust-on-first-use":
216
+ return { kind: "remember", sha256: shown };
217
+ case "preconfigured":
218
+ return { kind: "refuse", why: "no-pin-and-not-first-use" };
219
+ default:
220
+ return absurd(policy.origin);
221
+ }
222
+ }
223
+ default:
224
+ return absurd(policy);
225
+ }
226
+ }