@rentnerproxy/app-contracts 0.0.0-stage → 1.0.0

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 (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +32 -2
  3. package/contracts.schema.json +4007 -0
  4. package/dist/Types/contract.types.d.ts +15 -0
  5. package/dist/Types/contract.types.js +1 -0
  6. package/dist/catalog.d.ts +352 -0
  7. package/dist/catalog.js +54 -0
  8. package/dist/client.d.ts +31 -0
  9. package/dist/client.js +66 -0
  10. package/dist/http-operations.d.ts +333 -0
  11. package/dist/http-operations.generated.d.ts +299 -0
  12. package/dist/http-operations.generated.js +300 -0
  13. package/dist/http-operations.js +17 -0
  14. package/dist/http.d.ts +127 -0
  15. package/dist/http.js +142 -0
  16. package/dist/index.d.ts +5 -0
  17. package/dist/index.js +4 -0
  18. package/dist/manifest.d.ts +90 -0
  19. package/dist/manifest.js +106 -0
  20. package/dist/platform-api.d.ts +282 -0
  21. package/dist/platform-api.js +287 -0
  22. package/dist/primitives.d.ts +33 -0
  23. package/dist/primitives.js +87 -0
  24. package/dist/provider-api.d.ts +221 -0
  25. package/dist/provider-api.js +227 -0
  26. package/dist/publication.d.ts +410 -0
  27. package/dist/publication.js +50 -0
  28. package/dist/runtime.d.ts +75 -0
  29. package/dist/runtime.js +88 -0
  30. package/dist/schemas.d.ts +926 -0
  31. package/dist/schemas.js +114 -0
  32. package/dist/ui-bridge.d.ts +81 -0
  33. package/dist/ui-bridge.js +92 -0
  34. package/dist/validation.d.ts +784 -0
  35. package/dist/validation.js +245 -0
  36. package/dist/wire.d.ts +31 -0
  37. package/dist/wire.js +54 -0
  38. package/fixtures.json +1094 -0
  39. package/http-fixtures.json +829 -0
  40. package/openapi.json +2557 -0
  41. package/package.json +56 -5
  42. package/protocol-fixtures.json +1804 -0
  43. package/upstream-probe-fixtures.json +852 -0
@@ -0,0 +1,245 @@
1
+ import { z } from 'zod';
2
+ import { catalog, catalogIcon, packageArtifact, releaseDistribution, } from './catalog.js';
3
+ import { appManifest } from './manifest.js';
4
+ import { v1ProtocolVersion } from './primitives.js';
5
+ import { approval, candidate, publication } from './publication.js';
6
+ import { protocolSchemas } from './schemas.js';
7
+ import { isWireJson } from './wire.js';
8
+ export class ContractError extends Error {
9
+ code;
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ this.name = 'ContractError';
14
+ }
15
+ }
16
+ function parseStructure(schema, input) {
17
+ const result = z.safeParse(schema, input);
18
+ if (!result.success) {
19
+ throw new ContractError('invalidShape', 'Invalid v1 contract structure.');
20
+ }
21
+ return result.data;
22
+ }
23
+ const protocolValidators = protocolSchemas;
24
+ function matchesProtocolSchema(schema, input) {
25
+ return isWireJson(input) && z.safeParse(schema, input).success;
26
+ }
27
+ /** Validate already-decoded wire JSON and retain its application payload and open response fields. */
28
+ export function parseProtocolDocument(name, input) {
29
+ if (!Object.hasOwn(protocolValidators, name)) {
30
+ throw new ContractError('invalidShape', 'Unknown v1 protocol document.');
31
+ }
32
+ if (!matchesProtocolSchema(protocolValidators[name], input)) {
33
+ throw new ContractError('invalidShape', 'Invalid v1 protocol document.');
34
+ }
35
+ return input;
36
+ }
37
+ function unique(values) {
38
+ return new Set(values).size === values.length;
39
+ }
40
+ function versionNumber(version) {
41
+ return version
42
+ .split('.')
43
+ .reduce((value, part) => value * 1_000_000 + Number(part), 0);
44
+ }
45
+ function rangeBounds(range) {
46
+ const separator = range.indexOf(' <');
47
+ return [
48
+ versionNumber(range.slice(2, separator)),
49
+ versionNumber(range.slice(separator + 2)),
50
+ ];
51
+ }
52
+ function orderedRange(range) {
53
+ const [minimum, maximum] = rangeBounds(range);
54
+ return minimum < maximum;
55
+ }
56
+ function supportsProtocol(range, available) {
57
+ const parsed = v1ProtocolVersion.safeParse(available);
58
+ if (!parsed.success)
59
+ return false;
60
+ const version = versionNumber(parsed.data);
61
+ const [minimum, maximum] = rangeBounds(range);
62
+ return minimum <= version && version < maximum;
63
+ }
64
+ function validMigrations(data) {
65
+ const { migrations, targetVersion } = data;
66
+ const starts = new Set(migrations.map(({ fromVersion }) => fromVersion));
67
+ let previous = -1;
68
+ for (const { fromVersion, toVersion } of migrations) {
69
+ if (fromVersion <= previous ||
70
+ toVersion <= fromVersion ||
71
+ toVersion > targetVersion ||
72
+ (toVersion !== targetVersion && !starts.has(toVersion)))
73
+ return false;
74
+ previous = fromVersion;
75
+ }
76
+ return true;
77
+ }
78
+ function validateManifest(manifest) {
79
+ const { capabilities, data, permissions, providers, requires, ui } = manifest;
80
+ if (!orderedRange(requires.platformApi) ||
81
+ !orderedRange(requires.appProtocol) ||
82
+ Boolean(ui) !== Boolean(requires.uiBridge) ||
83
+ (requires.uiBridge !== undefined && !orderedRange(requires.uiBridge))) {
84
+ throw new ContractError('invalidManifest', 'Invalid protocol range or UI requirements.');
85
+ }
86
+ if (!unique(capabilities.map(({ id }) => id)) ||
87
+ !unique(permissions) ||
88
+ !unique(providers) ||
89
+ !unique(requires.engineCapabilities) ||
90
+ (ui !== undefined && !unique(ui.slots))) {
91
+ throw new ContractError('invalidManifest', 'Duplicate manifest declarations.');
92
+ }
93
+ if (data &&
94
+ (!unique(data.readVersions) ||
95
+ !unique(data.writeVersions) ||
96
+ !data.writeVersions.includes(data.targetVersion) ||
97
+ !data.writeVersions.every((version) => data.readVersions.includes(version)) ||
98
+ !validMigrations(data))) {
99
+ throw new ContractError('invalidManifest', 'Inconsistent data versions or migrations.');
100
+ }
101
+ const { incidentCategories } = manifest;
102
+ const managesIncidents = capabilities.some(({ id }) => id === 'notifications.incidents.manage.v1');
103
+ if (managesIncidents !== (incidentCategories !== undefined) ||
104
+ (incidentCategories !== undefined &&
105
+ !unique(incidentCategories.map(({ id }) => id)))) {
106
+ throw new ContractError('invalidManifest', 'Incident categories and their capability must be declared together, with unique IDs.');
107
+ }
108
+ }
109
+ function orderedRecord(record) {
110
+ return JSON.stringify(record, (_key, value) => {
111
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
112
+ return value;
113
+ const entries = Object.entries(value);
114
+ return Object.fromEntries(entries.toSorted(([a], [b]) => a.localeCompare(b, 'en')));
115
+ });
116
+ }
117
+ function sameRecord(left, right) {
118
+ // Compare record members independently of key order and preserve array order.
119
+ return orderedRecord(left) === orderedRecord(right);
120
+ }
121
+ function validateRelease(release) {
122
+ const { appId, packages, publisher, source, version } = release;
123
+ if (!appId.startsWith(publisher.namespace + '.') ||
124
+ !unique(packages.map(({ manifest }) => manifest.target)) ||
125
+ (publisher.namespace === 'rentnerproxy' && packages.length !== 2)) {
126
+ throw new ContractError('invalidRelease', 'Invalid publisher namespace or package targets.');
127
+ }
128
+ const display = packages[0].manifest.display;
129
+ for (const { manifest } of packages) {
130
+ validateManifest(manifest);
131
+ if (manifest.id !== appId ||
132
+ manifest.version !== version ||
133
+ !sameRecord(manifest.source, source) ||
134
+ !sameRecord(manifest.display, display)) {
135
+ throw new ContractError('invalidRelease', 'Package manifest does not match the release.');
136
+ }
137
+ }
138
+ }
139
+ function validateCandidate(record) {
140
+ validateRelease(record.release);
141
+ if (!sameRecord(record.source, record.release.source)) {
142
+ throw new ContractError('invalidCandidate', 'Candidate and release source must agree.');
143
+ }
144
+ }
145
+ export function parseAppManifest(input) {
146
+ const manifest = parseStructure(appManifest, input);
147
+ validateManifest(manifest);
148
+ return manifest;
149
+ }
150
+ /** Compare requirements with the capabilities of the trusted local runtime. */
151
+ export function checkManifestCompatibility(input, environment) {
152
+ const manifest = parseAppManifest(input);
153
+ const { requires } = manifest;
154
+ if (manifest.target !== environment.target ||
155
+ requires.runtimeProfile !== environment.runtimeProfile ||
156
+ !supportsProtocol(requires.platformApi, environment.platformApi) ||
157
+ !supportsProtocol(requires.appProtocol, environment.appProtocol) ||
158
+ (requires.uiBridge !== undefined &&
159
+ !supportsProtocol(requires.uiBridge, environment.uiBridge)) ||
160
+ !requires.engineCapabilities.every((capability) => environment.engineCapabilities.includes(capability))) {
161
+ throw new ContractError('incompatibleManifest', 'The local runtime does not satisfy the manifest requirements.');
162
+ }
163
+ return manifest;
164
+ }
165
+ export function parseCatalog(input) {
166
+ const snapshot = parseStructure(catalog, input);
167
+ const identities = new Set();
168
+ for (const entry of [...snapshot.releases, ...snapshot.revocations]) {
169
+ const identity = entry.appId + '@' + entry.version;
170
+ if (identities.has(identity)) {
171
+ throw new ContractError('invalidCatalog', 'Duplicate or revoked catalog release.');
172
+ }
173
+ identities.add(identity);
174
+ }
175
+ for (const release of snapshot.releases)
176
+ validateRelease(release);
177
+ return snapshot;
178
+ }
179
+ export function parseCandidate(input) {
180
+ const record = parseStructure(candidate, input);
181
+ validateCandidate(record);
182
+ return record;
183
+ }
184
+ export function parseApproval(input) {
185
+ const record = parseStructure(approval, input);
186
+ validateCandidate(record.candidate);
187
+ return record;
188
+ }
189
+ export function parsePublication(input) {
190
+ const receipt = parseStructure(publication, input);
191
+ validateRelease(receipt.release);
192
+ return receipt;
193
+ }
194
+ // Pass the current candidate and approval from the trusted store. Shape and
195
+ // equality checks do not establish authorization, freshness or provenance.
196
+ export function checkApprovalBinding(candidateInput, approvalInput) {
197
+ const current = parseCandidate(candidateInput);
198
+ const approved = parseApproval(approvalInput);
199
+ if (!sameRecord(current, approved.candidate)) {
200
+ throw new ContractError('approvalMismatch', 'Candidate differs from the approved snapshot.');
201
+ }
202
+ return current.release;
203
+ }
204
+ export function checkPublicationBinding(approvalInput, publicationInput, catalogInput) {
205
+ const approved = parseApproval(approvalInput);
206
+ const receipt = parsePublication(publicationInput);
207
+ const snapshot = parseCatalog(catalogInput);
208
+ const published = snapshot.releases.find(({ appId, version }) => appId === receipt.release.appId &&
209
+ version === receipt.release.version);
210
+ if (receipt.approvalId !== approved.id ||
211
+ receipt.approvalRevision !== approved.revision ||
212
+ receipt.catalogRevision !== snapshot.revision ||
213
+ !published ||
214
+ !sameRecord(receipt.release, approved.candidate.release) ||
215
+ !sameRecord(receipt.release, published)) {
216
+ throw new ContractError('publicationMismatch', 'Publication does not match approval and catalog.');
217
+ }
218
+ return receipt;
219
+ }
220
+ /** Resolve download locations and byte identities from a trusted catalog. */
221
+ export function packageReleaseAssets(input) {
222
+ const { manifest, archive, manifestSha256, sbom, provenance } = parseStructure(packageArtifact, input);
223
+ validateManifest(manifest);
224
+ const { id, version, target } = manifest;
225
+ const tag = id + '-v' + version;
226
+ const filename = id + '-' + version + '-' + target + '.tar.zst';
227
+ const url = releaseDistribution + tag + '/' + filename;
228
+ return {
229
+ archive: { ...archive, url },
230
+ manifestSha256,
231
+ sbom: { ...sbom, url: url + '.sbom.json' },
232
+ provenance: { ...provenance, url: url + '.provenance.json' },
233
+ };
234
+ }
235
+ export function packageDownloadUrl(input) {
236
+ return packageReleaseAssets(input).archive.url;
237
+ }
238
+ /** Resolve the icon target and byte identity from a trusted catalog. */
239
+ export function catalogIconTarget(input) {
240
+ const { sha256, sizeBytes, format } = parseStructure(catalogIcon, input);
241
+ return { path: 'assets/' + sha256 + '.' + format, sha256, sizeBytes };
242
+ }
243
+ export function catalogIconPath(input) {
244
+ return catalogIconTarget(input).path;
245
+ }
package/dist/wire.d.ts ADDED
@@ -0,0 +1,31 @@
1
+ import { z } from 'zod';
2
+ /** Admit decoded wire JSON, including own members that a shape validator may skip. */
3
+ export declare function isWireJson(value: unknown, depth?: number): boolean;
4
+ export declare const problem: z.ZodObject<{
5
+ type: z.ZodString;
6
+ title: z.ZodString;
7
+ status: z.ZodNumber;
8
+ code: z.ZodString;
9
+ requestId: z.ZodString;
10
+ }, z.core.$strict>;
11
+ export declare const operation: z.ZodDiscriminatedUnion<[z.ZodObject<{
12
+ id: z.ZodString;
13
+ status: z.ZodEnum<{
14
+ accepted: "accepted";
15
+ cancelled: "cancelled";
16
+ cancelling: "cancelling";
17
+ running: "running";
18
+ succeeded: "succeeded";
19
+ }>;
20
+ problem: z.ZodOptional<z.ZodNever>;
21
+ }, z.core.$loose>, z.ZodObject<{
22
+ id: z.ZodString;
23
+ status: z.ZodLiteral<"failed">;
24
+ problem: z.ZodObject<{
25
+ type: z.ZodString;
26
+ title: z.ZodString;
27
+ status: z.ZodNumber;
28
+ code: z.ZodString;
29
+ requestId: z.ZodString;
30
+ }, z.core.$strict>;
31
+ }, z.core.$loose>], "status">;
package/dist/wire.js ADDED
@@ -0,0 +1,54 @@
1
+ import { z } from 'zod';
2
+ import { rpcLimits } from './http-operations.js';
3
+ import { recordId } from './primitives.js';
4
+ const loneSurrogate = /\p{Cs}/u;
5
+ /** Admit decoded wire JSON, including own members that a shape validator may skip. */
6
+ export function isWireJson(value, depth = 0) {
7
+ if (value === null || typeof value === 'boolean')
8
+ return true;
9
+ if (typeof value === 'number')
10
+ return Math.abs(value) <= Number.MAX_SAFE_INTEGER;
11
+ if (typeof value === 'string')
12
+ return !loneSurrogate.test(value);
13
+ if (typeof value !== 'object' || depth >= rpcLimits.maxJsonDepth)
14
+ return false;
15
+ if (Array.isArray(value)) {
16
+ for (const item of value) {
17
+ if (!isWireJson(item, depth + 1))
18
+ return false;
19
+ }
20
+ return true;
21
+ }
22
+ const prototype = Object.getPrototypeOf(value);
23
+ if (prototype !== Object.prototype && prototype !== null)
24
+ return false;
25
+ return Object.entries(value).every(([key, member]) => !loneSurrogate.test(key) && isWireJson(member, depth + 1));
26
+ }
27
+ export const problem = z
28
+ .strictObject({
29
+ type: z
30
+ .string()
31
+ .regex(/^urn:rentnerproxy:problem:[a-z][a-zA-Z0-9]{0,63}$/),
32
+ title: z.string().min(1).max(120),
33
+ status: z.number().int().min(400).max(599),
34
+ code: z.string().regex(/^[a-z][a-zA-Z0-9]{0,63}$/),
35
+ requestId: recordId,
36
+ })
37
+ .refine(({ type, code }) => type === 'urn:rentnerproxy:problem:' + code)
38
+ .describe('RFC 9457 problem with a stable machine code and no private error details. The type URN suffix equals code; on HTTP the status also equals the status line.');
39
+ export const operation = z
40
+ .discriminatedUnion('status', [
41
+ z.looseObject({
42
+ id: recordId,
43
+ status: z.enum([
44
+ 'accepted',
45
+ 'running',
46
+ 'cancelling',
47
+ 'cancelled',
48
+ 'succeeded',
49
+ ]),
50
+ problem: z.never().optional(),
51
+ }),
52
+ z.looseObject({ id: recordId, status: z.literal('failed'), problem }),
53
+ ])
54
+ .describe('Accepted work has a durable operation ID. Cancellation is an operation request. A disconnect or timeout does not confirm cancellation or rollback.');