@runeditrun/rer 0.2.85 → 0.2.86

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 (144) hide show
  1. package/README.md +138 -29
  2. package/cli/README.md +61 -1
  3. package/cli/agent-door.mjs +149 -0
  4. package/cli/agent-fixtures.mjs +16 -0
  5. package/cli/agent-mail.mjs +54 -0
  6. package/cli/agent-network.mjs +64 -0
  7. package/cli/agent-reviewers.mjs +110 -0
  8. package/cli/agent-secrets.mjs +23 -0
  9. package/cli/agent-sponsors.mjs +43 -0
  10. package/cli/agent-surface.mjs +34 -0
  11. package/cli/agent-webhooks.mjs +19 -0
  12. package/cli/authoring.mjs +2 -1
  13. package/cli/business/archive-task.mjs +32 -0
  14. package/cli/business/carry.mjs +3 -1
  15. package/cli/business/catchup-task.mjs +42 -0
  16. package/cli/business/choices.mjs +97 -0
  17. package/cli/business/command.mjs +23 -5
  18. package/cli/business/connect.mjs +19 -7
  19. package/cli/business/detector.mjs +4 -1
  20. package/cli/business/device.mjs +13 -0
  21. package/cli/business/export-inputs.mjs +69 -0
  22. package/cli/business/export-task.mjs +17 -0
  23. package/cli/business/invocation.mjs +8 -1
  24. package/cli/business/keychain.mjs +8 -1
  25. package/cli/business/lease.mjs +11 -1
  26. package/cli/business/local-commands.mjs +79 -31
  27. package/cli/business/outbound.mjs +9 -4
  28. package/cli/business/parsers-config.mjs +8 -7
  29. package/cli/business/parsers-syntax.mjs +7 -3
  30. package/cli/business/permissions.mjs +2 -0
  31. package/cli/business/questions.mjs +89 -9
  32. package/cli/business/setup-command.mjs +49 -0
  33. package/cli/business/setup-company.json +15 -0
  34. package/cli/business/setup-demo.mjs +95 -0
  35. package/cli/business/state.mjs +44 -10
  36. package/cli/business/supervisor.mjs +94 -35
  37. package/cli/business/vendor-door.mjs +230 -0
  38. package/cli/business/vendors/README.md +29 -3
  39. package/cli/business/vendors/common.mjs +8 -6
  40. package/cli/business/vendors/index.mjs +22 -11
  41. package/cli/business/vendors/sorry.mjs +106 -0
  42. package/cli/contract.mjs +2 -2
  43. package/cli/demo-deploy-error.mjs +14 -0
  44. package/cli/demo-native.mjs +4 -1
  45. package/cli/deploy-config.mjs +1 -1
  46. package/cli/deploy-owner-input.mjs +3 -1
  47. package/cli/deploy-variables.mjs +58 -0
  48. package/cli/door-clauses.mjs +157 -0
  49. package/cli/export.mjs +16 -4
  50. package/cli/hosted-output.mjs +17 -7
  51. package/cli/inspect.mjs +4 -0
  52. package/cli/jsonc.mjs +8 -4
  53. package/cli/lifecycle.mjs +3 -1
  54. package/cli/main.mjs +1 -0
  55. package/cli/managed-data-schema.mjs +14 -1
  56. package/cli/portability-empty.mjs +6 -0
  57. package/cli/portability-migrations.mjs +26 -4
  58. package/cli/production-auth.mjs +1 -1
  59. package/cli/production-mail.mjs +8 -2
  60. package/edition-authoring/archive-source.mjs +59 -0
  61. package/edition-authoring/base-copies.mjs +92 -18
  62. package/edition-authoring/cli.mjs +1 -1
  63. package/edition-authoring/edition-migrations.mjs +7 -3
  64. package/edition-authoring/module-closure.mjs +2 -16
  65. package/edition-authoring/workflow-copies.mjs +1 -1
  66. package/edition-authoring/workflow-scripts.mjs +12 -3
  67. package/foundation/runtime/contract-docs.mjs +215 -32
  68. package/foundation/runtime/contract-prose-patterns.mjs +14 -0
  69. package/foundation/runtime/contract-prose.mjs +88 -0
  70. package/global/CHANGELOG.md +93 -0
  71. package/global/README.md +138 -29
  72. package/global/door/command.mjs +3 -1
  73. package/global/main.mjs +1 -1
  74. package/modules/agent-door/CLAUSES.md +215 -0
  75. package/modules/agent-door/conformance/audit.mjs +66 -0
  76. package/modules/agent-door/conformance/authority.d.mts +2 -0
  77. package/modules/agent-door/conformance/authority.mjs +17 -0
  78. package/modules/agent-door/conformance/crypto.mjs +36 -0
  79. package/modules/agent-door/conformance/discovery.mjs +61 -0
  80. package/modules/agent-door/conformance/index.mjs +41 -0
  81. package/modules/agent-door/conformance/invocation.mjs +32 -0
  82. package/modules/agent-door/conformance/journey.mjs +112 -0
  83. package/modules/agent-door/conformance/narrowing.d.mts +1 -0
  84. package/modules/agent-door/conformance/narrowing.mjs +21 -0
  85. package/modules/agent-door/conformance/negative.mjs +47 -0
  86. package/modules/agent-door/conformance/network-modules.mjs +86 -0
  87. package/modules/agent-door/conformance/network-runtime.mjs +46 -0
  88. package/modules/agent-door/conformance/policy-phases.mjs +75 -0
  89. package/modules/agent-door/conformance/protocol.mjs +145 -0
  90. package/modules/agent-door/conformance/replay.mjs +38 -0
  91. package/modules/agent-door/conformance/schema.mjs +71 -0
  92. package/modules/agent-door/conformance/security.mjs +33 -0
  93. package/modules/agent-door/conformance/sponsors.mjs +68 -0
  94. package/modules/agent-door/conformance/surface.mjs +89 -0
  95. package/modules/agent-door/conformance/target.mjs +18 -0
  96. package/modules/agent-door/conformance/tool-name.d.mts +1 -0
  97. package/modules/agent-door/conformance/tool-name.mjs +7 -0
  98. package/modules/agent-door/conformance/webhooks.mjs +30 -0
  99. package/modules/container/image-variables.mjs +8 -2
  100. package/modules/demo-host/README.md +6 -0
  101. package/modules/demo-host/ownership.mjs +39 -0
  102. package/modules/demo-host/plan.mjs +2 -1
  103. package/modules/demo-host/remove.mjs +6 -1
  104. package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
  105. package/modules/import-kit/schema/importers.schema.json +107 -0
  106. package/modules/import-kit/src/door/ADOPTING.md +20 -0
  107. package/modules/import-kit/src/door/README.md +2 -1
  108. package/modules/import-kit/src/door/admission.ts +5 -3
  109. package/modules/import-kit/src/door/archive.ts +5 -2
  110. package/modules/import-kit/src/door/authority.ts +1 -0
  111. package/modules/import-kit/src/door/grants.ts +1 -1
  112. package/modules/import-kit/src/door/handler.ts +14 -8
  113. package/modules/import-kit/src/door/index.ts +1 -1
  114. package/modules/import-kit/src/door/jobs.ts +40 -0
  115. package/modules/import-kit/src/door/operator.ts +3 -3
  116. package/modules/import-kit/src/door/planning.ts +10 -6
  117. package/modules/import-kit/src/door/protocol.ts +2 -2
  118. package/modules/import-kit/src/door/raw.ts +25 -0
  119. package/modules/import-kit/src/door/refusals.ts +1 -0
  120. package/modules/import-kit/src/door/types.ts +26 -6
  121. package/modules/import-kit/src/receipt/encoding.ts +37 -0
  122. package/modules/import-kit/src/receipt/index.ts +69 -0
  123. package/modules/import-kit/src/receipt/policy.ts +24 -0
  124. package/modules/import-kit/src/receipt/types.ts +64 -0
  125. package/modules/import-kit/src/receipt/uri.ts +45 -0
  126. package/modules/import-kit/src/receipt/validation.ts +87 -0
  127. package/modules/import-kit/src/status/encoding.ts +13 -0
  128. package/modules/import-kit/src/status/evidence.ts +218 -0
  129. package/modules/import-kit/src/status/index.ts +56 -0
  130. package/modules/import-kit/src/status/schema.ts +208 -0
  131. package/modules/import-kit/src/status/types.ts +86 -0
  132. package/modules/operator-auth/accounts/delegated.mjs +48 -0
  133. package/modules/operator-auth/index.d.mts +7 -0
  134. package/modules/operator-auth/service.mjs +2 -0
  135. package/modules/portability/README.md +32 -11
  136. package/modules/portability/bridge.mjs +22 -2
  137. package/modules/portability/copies.mjs +8 -1
  138. package/modules/portability/derived.mjs +33 -0
  139. package/modules/portability/http-errors.mjs +1 -1
  140. package/modules/portability/import.mjs +14 -7
  141. package/package.json +4 -2
  142. package/scripts/publish-check/copy_identities.py +3 -1
  143. package/scripts/publish-check/github_refs.py +32 -13
  144. package/cli/business/opt-ins.mjs +0 -37
@@ -0,0 +1,218 @@
1
+ import { receiptSha256 as sha256 } from '../receipt/encoding.ts';
2
+ import { verifyImporterVerificationReceipt } from '../receipt/index.ts';
3
+ import type { ImporterVerificationReceipt } from '../receipt/types.ts';
4
+ import { isAsciiHostname, splitAuthority, splitUri } from '../receipt/uri.ts';
5
+ import type {
6
+ ImporterEvidenceArtifact,
7
+ ImporterEvidencePort,
8
+ ImporterRecord,
9
+ ImporterValidationIssue,
10
+ ImporterValidationResult,
11
+ VerifiedImporter,
12
+ } from './types.ts';
13
+
14
+ interface ImporterEvidenceReference extends ImporterEvidenceArtifact {
15
+ research?: ImporterEvidenceArtifact;
16
+ }
17
+
18
+ const maximumEvidenceBytes = 8 * 1024 * 1024;
19
+ // One class with `%` and a stray-`%` check, as for the export origin's path (receipt/validation.ts), so no host length
20
+ // overflows V8's regexp backtrack stack.
21
+ const registeredName = /^[A-Za-z0-9._~!$&'()*+,;=%-]*$/;
22
+ const strayPercent = /%(?![0-9A-Fa-f]{2})/;
23
+ const nonAscii = /[^\x00-\x7f]/;
24
+
25
+ export async function validateImporterEvidence(
26
+ records: ImporterRecord[],
27
+ evidence: ImporterEvidencePort | undefined,
28
+ issues: ImporterValidationIssue[],
29
+ ): Promise<ImporterValidationResult['evidence']> {
30
+ const counters: ImporterValidationResult['evidence'] = { required: 0, resolved: 0, verifiedReceipts: 0 };
31
+ if (!evidence || typeof evidence.resolve !== 'function' || !Array.isArray(evidence.trustedHosts)
32
+ || !evidence.trustedHosts.every((host) => typeof host === 'string' && host.length > 0 && host.trim() === host)) {
33
+ issues.push({ code: 'EVIDENCE_PORT_REQUIRED', path: '$', message: 'Supply a resolver for linked artifact bytes and trusted publisher hosts.' });
34
+ return counters;
35
+ }
36
+
37
+ for (let index = 0; index < records.length; index += 1) {
38
+ const record = records[index]!;
39
+ const path = `$.importers[${index}]`;
40
+ const reference = record.evidence as ImporterEvidenceReference;
41
+ const receipt = await resolveAndCheckArtifact(reference, evidence, `${path}.evidence`, issues, counters);
42
+ if (!receipt) continue;
43
+
44
+ if (record.status === 'verified') {
45
+ const research = await resolveAndCheckArtifact(reference.research!, evidence, `${path}.evidence.research`, issues, counters);
46
+ if (!research) continue;
47
+ if (await verifyReceipt(receipt.bytes, research.bytes, record, evidence, path, issues)) counters.verifiedReceipts += 1;
48
+ }
49
+ }
50
+
51
+ return counters;
52
+ }
53
+
54
+ async function resolveAndCheckArtifact(
55
+ reference: ImporterEvidenceArtifact,
56
+ evidence: ImporterEvidencePort,
57
+ path: string,
58
+ issues: ImporterValidationIssue[],
59
+ counters: ImporterValidationResult['evidence'],
60
+ ): Promise<{ url: string; bytes: Uint8Array } | undefined> {
61
+ counters.required += 1;
62
+ if (reference.link.trim() !== reference.link || reference.link.length === 0) {
63
+ issues.push({ code: 'EVIDENCE_LINK_INVALID', path: `${path}.link`, message: 'Evidence links must be non-empty and trimmed.' });
64
+ return undefined;
65
+ }
66
+
67
+ const link = readLink(reference.link);
68
+ if (!link) {
69
+ issues.push({ code: 'EVIDENCE_LINK_INVALID', path: `${path}.link`, message: 'Evidence link must be an absolute HTTPS (ASCII host; IDN as xn-- labels) or evidence URL without spaces or controls.' });
70
+ return undefined;
71
+ }
72
+ if (link.scheme !== 'https' && link.scheme !== 'evidence') {
73
+ issues.push({ code: 'EVIDENCE_LINK_SCHEME', path: `${path}.link`, message: 'Evidence links must use HTTPS or the consumer evidence scheme.' });
74
+ return undefined;
75
+ }
76
+ if (link.userinfo !== undefined || queryKeys(link.query ?? '').some((key) => /token|password|secret|api[_-]?key|authorization/i.test(key))) {
77
+ issues.push({ code: 'EVIDENCE_LINK_CREDENTIALS', path: `${path}.link`, message: 'Evidence links cannot embed credentials.' });
78
+ return undefined;
79
+ }
80
+ if (link.scheme === 'https' && !isTrustedHost(link.host!, evidence.trustedHosts)) {
81
+ issues.push({ code: 'EVIDENCE_PUBLISHER_UNTRUSTED', path: `${path}.link`, message: 'The evidence host is not pinned by the consumer.' });
82
+ return undefined;
83
+ }
84
+
85
+ let resolved: { url: string; bytes: Uint8Array } | undefined;
86
+ try {
87
+ resolved = await evidence.resolve(reference.link);
88
+ } catch {
89
+ issues.push({ code: 'EVIDENCE_RESOLUTION_FAILED', path: `${path}.link`, message: 'The evidence resolver could not resolve this link.' });
90
+ return undefined;
91
+ }
92
+ if (!resolved) {
93
+ issues.push({ code: 'EVIDENCE_NOT_FOUND', path: `${path}.link`, message: 'The linked evidence artifact was not found.' });
94
+ return undefined;
95
+ }
96
+ if (resolved.url !== reference.link) {
97
+ issues.push({ code: 'EVIDENCE_URL_MISMATCH', path: `${path}.link`, message: 'Resolved evidence URL differs from the requested link.' });
98
+ return undefined;
99
+ }
100
+ if (!(resolved.bytes instanceof Uint8Array) || resolved.bytes.byteLength < 1 || resolved.bytes.byteLength > maximumEvidenceBytes) {
101
+ issues.push({ code: 'EVIDENCE_BYTES_INVALID', path: `${path}.link`, message: `Evidence bytes must be between 1 and ${maximumEvidenceBytes} bytes.` });
102
+ return undefined;
103
+ }
104
+
105
+ const snapshot = new Uint8Array(resolved.bytes);
106
+ counters.resolved += 1;
107
+ if (snapshot.byteLength !== reference.size) {
108
+ issues.push({ code: 'EVIDENCE_SIZE_MISMATCH', path: `${path}.size`, message: 'Resolved bytes do not match the declared evidence size.' });
109
+ return undefined;
110
+ }
111
+ if (await sha256(snapshot) !== reference.sha256) {
112
+ issues.push({ code: 'EVIDENCE_HASH_MISMATCH', path: `${path}.sha256`, message: 'Resolved bytes do not match the declared SHA-256.' });
113
+ return undefined;
114
+ }
115
+ return { url: resolved.url, bytes: snapshot };
116
+ }
117
+
118
+ /**
119
+ * Scheme, userinfo, host and port by the module's ASCII grammar: an https host must be an ASCII hostname, another
120
+ * scheme's host an RFC 3986 registered name. Path, query and fragment reach the resolver as written.
121
+ */
122
+ function readLink(text: string): { scheme: string; userinfo?: string; host?: string; query?: string } | undefined {
123
+ const link = splitUri(text);
124
+ if (!link || /[\u0000-\u0020\u007f-\u009f]/.test(text)) return undefined;
125
+ if (link.authority === undefined) return link.scheme === 'https' ? undefined : link;
126
+ const address = splitAuthority(link.authority);
127
+ if (!address || !(link.scheme === 'https' ? isAsciiHostname(address.host) : registeredName.test(address.host) && !strayPercent.test(address.host))) return undefined;
128
+ return { ...link, ...address };
129
+ }
130
+
131
+ /** Names as URL searchParams decodes them (application/x-www-form-urlencoded): `+` is a space, then UTF-8 `%XX` bytes. */
132
+ function queryKeys(query: string): string[] {
133
+ const decoder = new TextDecoder('utf-8', { ignoreBOM: true });
134
+ return query.split('&').filter(Boolean).map((pair) => {
135
+ const name = pair.split('=', 1)[0]!;
136
+ return name.includes('%') || name.includes('+') ? decodeUtf8(decoder, formDecode(name)) : name;
137
+ });
138
+ }
139
+
140
+ /** One TextDecoder call per 16 MiB with streaming state: workerd's decoder refuses one input above about 170 MB. */
141
+ function decodeUtf8(decoder: TextDecoder, bytes: Uint8Array): string {
142
+ const chunk = 16 * 1024 * 1024;
143
+ let text = '';
144
+ for (let start = 0; start < bytes.length; start += chunk) {
145
+ text += decoder.decode(bytes.subarray(start, start + chunk), { stream: start + chunk < bytes.length });
146
+ }
147
+ return text;
148
+ }
149
+
150
+ /**
151
+ * The URL Standard's form decoding of the text's UTF-8 bytes in one pass: `+` becomes a space, `%` and two hex digits
152
+ * that byte. String replaces build their result from one piece per match: a global replace with a callback first lists
153
+ * every match, and V8 aborts the process once that list outgrows 2^26 entries (it did at 25,000,000 matches);
154
+ * replaceAll('+', ' ') ended the workerd process at 75,000,000 characters.
155
+ */
156
+ function formDecode(text: string): Uint8Array {
157
+ const bytes = new TextEncoder().encode(text);
158
+ let length = 0;
159
+ for (let index = 0; index < bytes.length; index += 1) {
160
+ const high = bytes[index] === 0x25 ? hexValue(bytes[index + 1]) : -1;
161
+ const low = high < 0 ? -1 : hexValue(bytes[index + 2]);
162
+ if (low >= 0) { bytes[length++] = high * 16 + low; index += 2; }
163
+ else bytes[length++] = bytes[index] === 0x2b ? 0x20 : bytes[index]!;
164
+ }
165
+ return bytes.subarray(0, length);
166
+ }
167
+
168
+ /** 0-15 for the byte of an ASCII hex digit, otherwise -1. */
169
+ function hexValue(byte: number | undefined): number {
170
+ if (byte === undefined) return -1;
171
+ if (byte >= 0x30 && byte <= 0x39) return byte - 0x30;
172
+ const lower = byte | 0x20;
173
+ return lower >= 0x61 && lower <= 0x66 ? lower - 0x57 : -1;
174
+ }
175
+
176
+ /** `host` is an ASCII hostname, where toLowerCase folds only A-Z; a pin with a non-ASCII character never equals it. */
177
+ function isTrustedHost(host: string, trustedHosts: readonly string[]): boolean {
178
+ const normalized = host.toLowerCase();
179
+ // Checked before toLowerCase, which would fold a pin's U+212A KELVIN SIGN to "k".
180
+ return trustedHosts.some((trusted) => !nonAscii.test(trusted) && trusted.toLowerCase() === normalized);
181
+ }
182
+
183
+ async function verifyReceipt(
184
+ receiptBytes: Uint8Array,
185
+ researchBytes: Uint8Array,
186
+ importer: VerifiedImporter,
187
+ evidence: ImporterEvidencePort,
188
+ path: string,
189
+ issues: ImporterValidationIssue[],
190
+ ): Promise<boolean> {
191
+ const firstIssue = issues.length;
192
+ let parsed: unknown;
193
+ try {
194
+ parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(receiptBytes));
195
+ } catch {
196
+ issues.push({ code: 'RECEIPT_NOT_JSON', path: `${path}.evidence.link`, message: 'The linked verification receipt is not valid UTF-8 JSON.' });
197
+ return false;
198
+ }
199
+
200
+ const policy = evidence.receiptTrustPolicy ?? {
201
+ environment: 'unrestricted',
202
+ keys: Object.fromEntries(Object.entries(evidence.receiptPublicKeys ?? {}).map(([keyId, publicKey]) => [keyId, { publicKey }])),
203
+ };
204
+ const verified = await verifyImporterVerificationReceipt(parsed, policy, path);
205
+ issues.push(...verified.issues);
206
+ if (!verified.valid) return false;
207
+ const receipt = parsed as ImporterVerificationReceipt;
208
+
209
+ const payload = receipt.payload;
210
+ if (payload.incumbent !== importer.incumbent || payload.product !== importer.product) {
211
+ issues.push({ code: 'RECEIPT_PAIR_MISMATCH', path: `${path}.receipt.payload`, message: 'Receipt incumbent and product do not match the catalog row.' });
212
+ }
213
+ if (await sha256(researchBytes) !== payload.research.sha256 || payload.research.sha256 !== importer.evidence.research.sha256) {
214
+ issues.push({ code: 'RESEARCH_HASH_MISMATCH', path: `${path}.receipt.payload.research.sha256`, message: 'The finished research artifact does not match the signed receipt.' });
215
+ }
216
+
217
+ return issues.length === firstIssue;
218
+ }
@@ -0,0 +1,56 @@
1
+ import { validateImporterEvidence } from './evidence.ts';
2
+ import { validateStatusDocumentSchema } from './schema.ts';
3
+ import type {
4
+ ImporterEvidencePort,
5
+ ImporterRecord,
6
+ ImporterValidationIssue,
7
+ ImporterValidationResult,
8
+ ImportersDocument,
9
+ } from './types.ts';
10
+
11
+ export type * from './types.ts';
12
+
13
+ /**
14
+ * Validate the published status document and resolve its evidence through the
15
+ * consumer's trust policy. A verified status also needs a trusted signed receipt.
16
+ */
17
+ export async function validateImporters(
18
+ document: unknown,
19
+ evidence?: ImporterEvidencePort,
20
+ ): Promise<ImporterValidationResult> {
21
+ const issues = validateStatusDocumentSchema(document);
22
+ const counters: ImporterValidationResult['evidence'] = { required: 0, resolved: 0, verifiedReceipts: 0 };
23
+ if (issues.length > 0) return result(issues, counters);
24
+
25
+ const records = (document as ImportersDocument).importers;
26
+ const seen = new Map<string, number>();
27
+ for (let index = 0; index < records.length; index += 1) {
28
+ const record = records[index]!;
29
+ const path = `$.importers[${index}]`;
30
+ const incumbent = normalizeLabel(record.incumbent);
31
+ const product = normalizeLabel(record.product);
32
+ if (record.incumbent.trim() !== record.incumbent || record.product.trim() !== record.product || !incumbent || !product) {
33
+ issues.push({ code: 'LABEL_NOT_NORMALIZED', path, message: 'Incumbent and product must be trimmed, non-empty labels.' });
34
+ continue;
35
+ }
36
+ const key = JSON.stringify([incumbent, product]);
37
+ const previous = seen.get(key);
38
+ if (previous !== undefined) {
39
+ issues.push({ code: 'DUPLICATE_PAIR', path, message: `Importer pair duplicates $.importers[${previous}].` });
40
+ } else {
41
+ seen.set(key, index);
42
+ }
43
+ }
44
+ if (issues.length > 0) return result(issues, counters);
45
+
46
+ const evidenceCounters = await validateImporterEvidence(records as ImporterRecord[], evidence, issues);
47
+ return result(issues, evidenceCounters);
48
+ }
49
+
50
+ function result(issues: ImporterValidationIssue[], evidence: ImporterValidationResult['evidence']): ImporterValidationResult {
51
+ return { valid: issues.length === 0, issues, evidence: { ...evidence } };
52
+ }
53
+
54
+ function normalizeLabel(value: string): string {
55
+ return value.normalize('NFKC').trim().toLowerCase();
56
+ }
@@ -0,0 +1,208 @@
1
+ import importersSchemaJson from '../../schema/importers.schema.json' with { type: 'json' };
2
+ import receiptSchemaJson from '../../schema/importer-verification-receipt.schema.json' with { type: 'json' };
3
+ import { canonicalReceiptJson as canonicalJson } from '../receipt/encoding.ts';
4
+ import type { ImporterValidationIssue } from './types.ts';
5
+
6
+ interface JsonSchema {
7
+ $ref?: string;
8
+ type?: string;
9
+ const?: unknown;
10
+ enum?: unknown[];
11
+ minLength?: number;
12
+ maxLength?: number;
13
+ pattern?: string;
14
+ minimum?: number;
15
+ minItems?: number;
16
+ minProperties?: number;
17
+ required?: string[];
18
+ properties?: Record<string, JsonSchema>;
19
+ additionalProperties?: boolean | JsonSchema;
20
+ items?: JsonSchema;
21
+ oneOf?: JsonSchema[];
22
+ format?: string;
23
+ [key: string]: unknown;
24
+ }
25
+
26
+ const importersSchema = importersSchemaJson as unknown as JsonSchema;
27
+ const receiptSchema = receiptSchemaJson as unknown as JsonSchema;
28
+
29
+ export function validateStatusDocumentSchema(document: unknown): ImporterValidationIssue[] {
30
+ if (!isJsonValue(document)) {
31
+ return [{ code: 'DOCUMENT_NOT_JSON', path: '$', message: 'Importer status must be JSON data.' }];
32
+ }
33
+ return schemaIssues(document, importersSchema, importersSchema, '$');
34
+ }
35
+
36
+ export function validateReceiptDocumentSchema(document: unknown, path: string): ImporterValidationIssue[] {
37
+ if (!isJsonValue(document)) {
38
+ return [{ code: 'RECEIPT_NOT_JSON', path, message: 'Verification receipt must be JSON data.' }];
39
+ }
40
+ return schemaIssues(document, receiptSchema, receiptSchema, path);
41
+ }
42
+
43
+ function schemaIssues(value: unknown, schema: JsonSchema, root: JsonSchema, path: string): ImporterValidationIssue[] {
44
+ if (typeof schema.$ref === 'string') {
45
+ const target = resolveSchemaReference(root, schema.$ref);
46
+ if (!target) return [{ code: 'INVALID_SCHEMA_REFERENCE', path, message: `Schema reference ${schema.$ref} does not resolve.` }];
47
+ return schemaIssues(value, target, root, path);
48
+ }
49
+
50
+ if (schema.oneOf) {
51
+ const matching = schema.oneOf.filter((branch) => schemaIssues(value, branch, root, path).length === 0).length;
52
+ return matching === 1
53
+ ? []
54
+ : [{ code: 'SCHEMA_ONE_OF', path, message: matching === 0 ? 'Value does not match any allowed schema branch.' : 'Value matches more than one schema branch.' }];
55
+ }
56
+
57
+ const issues: ImporterValidationIssue[] = [];
58
+ if (schema.type && !matchesType(value, schema.type)) {
59
+ return [{ code: 'SCHEMA_TYPE', path, message: `Expected ${schema.type}.` }];
60
+ }
61
+ if (Object.hasOwn(schema, 'const') && !sameJsonValue(value, schema.const)) {
62
+ issues.push({ code: 'SCHEMA_CONST', path, message: `Expected the constant ${JSON.stringify(schema.const)}.` });
63
+ }
64
+ if (schema.enum && !schema.enum.some((allowed) => sameJsonValue(value, allowed))) {
65
+ issues.push({ code: 'SCHEMA_ENUM', path, message: 'Value is not one of the allowed values.' });
66
+ }
67
+
68
+ if (typeof value === 'string') {
69
+ const length = codePointLength(value);
70
+ if (schema.minLength !== undefined && value.trim().length === 0) {
71
+ issues.push({ code: 'SCHEMA_BLANK_STRING', path, message: 'A non-empty string cannot contain only whitespace.' });
72
+ }
73
+ if (schema.minLength !== undefined && length < schema.minLength) {
74
+ issues.push({ code: 'SCHEMA_MIN_LENGTH', path, message: `String must contain at least ${schema.minLength} character(s).` });
75
+ }
76
+ if (schema.maxLength !== undefined && length > schema.maxLength) {
77
+ issues.push({ code: 'SCHEMA_MAX_LENGTH', path, message: `String must contain no more than ${schema.maxLength} character(s).` });
78
+ }
79
+ if (schema.pattern && !new RegExp(schema.pattern).test(value)) {
80
+ issues.push({ code: 'SCHEMA_PATTERN', path, message: 'String does not match the required pattern.' });
81
+ }
82
+ if (schema.format === 'date-time' && !isDateTime(value)) {
83
+ issues.push({ code: 'SCHEMA_FORMAT', path, message: 'Expected an ISO 8601 date-time with a timezone.' });
84
+ }
85
+ }
86
+ if (typeof value === 'number' && schema.minimum !== undefined && value < schema.minimum) {
87
+ issues.push({ code: 'SCHEMA_MINIMUM', path, message: `Number must be at least ${schema.minimum}.` });
88
+ }
89
+
90
+ if (Array.isArray(value)) {
91
+ if (schema.minItems !== undefined && value.length < schema.minItems) {
92
+ issues.push({ code: 'SCHEMA_MIN_ITEMS', path, message: `Array must contain at least ${schema.minItems} item(s).` });
93
+ }
94
+ if (schema.items) {
95
+ for (let index = 0; index < value.length; index += 1) {
96
+ issues.push(...schemaIssues(value[index], schema.items, root, `${path}[${index}]`));
97
+ }
98
+ }
99
+ }
100
+
101
+ if (isPlainObject(value)) {
102
+ for (const required of schema.required ?? []) {
103
+ if (!Object.hasOwn(value, required)) {
104
+ issues.push({ code: 'SCHEMA_REQUIRED', path: `${path}.${required}`, message: 'Required property is missing.' });
105
+ }
106
+ }
107
+ if (schema.minProperties !== undefined && Object.keys(value).length < schema.minProperties) {
108
+ issues.push({ code: 'SCHEMA_MIN_PROPERTIES', path, message: `Object must contain at least ${schema.minProperties} property/properties.` });
109
+ }
110
+ for (const [key, propertyValue] of Object.entries(value)) {
111
+ // Own members only: `constructor` or `__proto__` must not resolve to Object.prototype.
112
+ const propertySchema = schema.properties && Object.hasOwn(schema.properties, key) ? schema.properties[key] : undefined;
113
+ if (propertySchema) {
114
+ issues.push(...schemaIssues(propertyValue, propertySchema, root, `${path}.${key}`));
115
+ } else if (schema.additionalProperties === false) {
116
+ issues.push({ code: 'SCHEMA_ADDITIONAL_PROPERTY', path: `${path}.${key}`, message: 'Unknown property is not allowed.' });
117
+ } else if (schema.additionalProperties && typeof schema.additionalProperties === 'object') {
118
+ issues.push(...schemaIssues(propertyValue, schema.additionalProperties, root, `${path}.${key}`));
119
+ }
120
+ }
121
+ }
122
+
123
+ return issues;
124
+ }
125
+
126
+ /** Array.from(value).length without building the array: a surrogate pair counts once, a lone surrogate once. */
127
+ function codePointLength(value: string): number {
128
+ let length = value.length;
129
+ for (let index = 0; index + 1 < value.length; index += 1) {
130
+ const unit = value.charCodeAt(index);
131
+ if (unit >= 0xd800 && unit <= 0xdbff) {
132
+ const next = value.charCodeAt(index + 1);
133
+ if (next >= 0xdc00 && next <= 0xdfff) { length -= 1; index += 1; }
134
+ }
135
+ }
136
+ return length;
137
+ }
138
+
139
+ function resolveSchemaReference(root: JsonSchema, reference: string): JsonSchema | undefined {
140
+ if (!reference.startsWith('#/')) return undefined;
141
+ let value: unknown = root;
142
+ for (const token of reference.slice(2).split('/').map((part) => part.replaceAll('~1', '/').replaceAll('~0', '~'))) {
143
+ if (!isPlainObject(value) || !Object.hasOwn(value, token)) return undefined;
144
+ value = value[token];
145
+ }
146
+ return isPlainObject(value) ? value as JsonSchema : undefined;
147
+ }
148
+
149
+ function matchesType(value: unknown, type: string): boolean {
150
+ switch (type) {
151
+ case 'object': return isPlainObject(value);
152
+ case 'array': return Array.isArray(value);
153
+ case 'string': return typeof value === 'string';
154
+ case 'integer': return typeof value === 'number' && Number.isInteger(value);
155
+ case 'number': return typeof value === 'number' && Number.isFinite(value);
156
+ case 'boolean': return typeof value === 'boolean';
157
+ case 'null': return value === null;
158
+ default: return false;
159
+ }
160
+ }
161
+
162
+ function isJsonValue(value: unknown, active = new WeakSet<object>()): boolean {
163
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;
164
+ if (typeof value === 'number') return Number.isFinite(value);
165
+ if (Array.isArray(value)) {
166
+ if (active.has(value)) return false;
167
+ active.add(value);
168
+ const valid = value.every((item) => isJsonValue(item, active));
169
+ active.delete(value);
170
+ return valid;
171
+ }
172
+ if (isPlainObject(value)) {
173
+ if (active.has(value)) return false;
174
+ active.add(value);
175
+ const valid = Object.values(value).every((item) => isJsonValue(item, active));
176
+ active.delete(value);
177
+ return valid;
178
+ }
179
+ return false;
180
+ }
181
+
182
+ function isPlainObject(value: unknown): value is Record<string, any> {
183
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;
184
+ const prototype = Object.getPrototypeOf(value);
185
+ return prototype === Object.prototype || prototype === null;
186
+ }
187
+
188
+ function sameJsonValue(left: unknown, right: unknown): boolean {
189
+ return canonicalJson(left) === canonicalJson(right);
190
+ }
191
+
192
+ function isDateTime(value: string): boolean {
193
+ const match = value.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(Z|([+-])(\d{2}):(\d{2}))$/);
194
+ if (!match || !Number.isFinite(Date.parse(value))) return false;
195
+ const year = Number(match[1]);
196
+ const month = Number(match[2]);
197
+ const day = Number(match[3]);
198
+ const hour = Number(match[4]);
199
+ const minute = Number(match[5]);
200
+ const second = Number(match[6]);
201
+ const offsetHour = Number(match[9] ?? 0);
202
+ const offsetMinute = Number(match[10] ?? 0);
203
+ const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
204
+ const daysInMonth = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
205
+ const offsetWithinRange = offsetHour < 14 || (offsetHour === 14 && offsetMinute === 0);
206
+ return month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth[month - 1]!
207
+ && hour <= 23 && minute <= 59 && second <= 59 && offsetMinute <= 59 && offsetWithinRange;
208
+ }
@@ -0,0 +1,86 @@
1
+ import type { ImporterReceiptTrustPolicy } from '../receipt/types.ts';
2
+
3
+ export type ImporterStatus = 'verified' | 'documented format' | 'none';
4
+
5
+ export interface ImporterEvidenceArtifact {
6
+ link: string;
7
+ sha256: string;
8
+ size: number;
9
+ }
10
+
11
+ export interface DocumentedFormatEvidence extends ImporterEvidenceArtifact {
12
+ sourceRepository: string;
13
+ sourceRevision: string;
14
+ sourcePath: string;
15
+ sourceSha256: string;
16
+ validation: 'synthetic-only';
17
+ realExport: 'not-supplied';
18
+ }
19
+
20
+ export interface VerifiedEvidence extends ImporterEvidenceArtifact {
21
+ research: ImporterEvidenceArtifact;
22
+ }
23
+
24
+ export interface NoneEvidence extends ImporterEvidenceArtifact {
25
+ reason: string;
26
+ checkedAt: string;
27
+ }
28
+
29
+ export interface VerifiedImporter {
30
+ incumbent: string;
31
+ product: string;
32
+ status: 'verified';
33
+ evidence: VerifiedEvidence;
34
+ }
35
+
36
+ export interface DocumentedImporter {
37
+ incumbent: string;
38
+ product: string;
39
+ status: 'documented format';
40
+ evidence: DocumentedFormatEvidence;
41
+ }
42
+
43
+ export interface NoImporter {
44
+ incumbent: string;
45
+ product: string;
46
+ status: 'none';
47
+ evidence: NoneEvidence;
48
+ }
49
+
50
+ export type ImporterRecord = VerifiedImporter | DocumentedImporter | NoImporter;
51
+
52
+ export interface ImportersDocument {
53
+ $schema: './schema/importers.schema.json';
54
+ schemaVersion: 1;
55
+ importers: ImporterRecord[];
56
+ }
57
+
58
+ /** A resolver must return the bytes it actually resolved and the final URL. */
59
+ export interface ResolvedEvidenceArtifact {
60
+ url: string;
61
+ bytes: Uint8Array;
62
+ }
63
+
64
+ /** Trust anchors belong to the consumer, never to the status document. */
65
+ export interface ImporterEvidencePort {
66
+ resolve: (link: string) => ResolvedEvidenceArtifact | undefined | Promise<ResolvedEvidenceArtifact | undefined>;
67
+ trustedHosts: readonly string[];
68
+ receiptPublicKeys?: Readonly<Record<string, string>>;
69
+ receiptTrustPolicy?: ImporterReceiptTrustPolicy;
70
+ }
71
+
72
+ export interface ImporterValidationIssue {
73
+ code: string;
74
+ path: string;
75
+ message: string;
76
+ }
77
+
78
+ export interface ImporterValidationResult {
79
+ valid: boolean;
80
+ issues: ImporterValidationIssue[];
81
+ evidence: {
82
+ required: number;
83
+ resolved: number;
84
+ verifiedReceipts: number;
85
+ };
86
+ }
@@ -0,0 +1,48 @@
1
+ // Trusted server callers have already admitted a delegated principal. These
2
+ // commands reuse native administration, without minting or inventing a session.
3
+ import { administration } from './admin.mjs';
4
+ import { bindPolicyActor } from '../scheduled/fence.mjs';
5
+ import { emailAllowed } from './roles.mjs';
6
+ import { deny } from '../errors.mjs';
7
+ import { normalizeEmail } from '../policy.mjs';
8
+
9
+ export function delegatedAdministration(context, { personId, auditLabel, agentId }) {
10
+ const { store, config } = context;
11
+ if (typeof agentId !== 'string' || !agentId || typeof personId !== 'string' || !personId || typeof auditLabel !== 'string' || !auditLabel.trim()) deny('invalid_delegation', 400);
12
+ const request = new Request(new URL('/auth/delegated-administration', config.origin), {
13
+ method: 'POST', headers: { origin: config.origin, host: new URL(config.origin).host },
14
+ });
15
+ async function commands() {
16
+ const operator = await store.operator(personId);
17
+ if (!operator || operator.status !== 'active' || !emailAllowed(operator.email, config.allowList)) deny('unauthenticated', 401);
18
+ const actor = Object.freeze({ operator });
19
+ bindPolicyActor(actor, () => ({
20
+ sql: "EXISTS(SELECT 1 FROM oa_operators WHERE id=? AND version=? AND status='active' AND role=?)",
21
+ args: [operator.id, operator.version, operator.role],
22
+ }));
23
+ const audit = async event => {
24
+ const extra = context.audit ? await context.audit({ ...event, actorLabel: auditLabel, sponsorId: personId }) : [];
25
+ return [[`INSERT INTO oa_auth_audit(id,actor_id,action,value,created_at) VALUES(?,?,?,?,?)`,
26
+ [crypto.randomUUID(), `agent:${agentId}`, event.action, JSON.stringify({ operatorId: event.subjectId, detail: event.detail,
27
+ actor: auditLabel, for: personId }), event.now]], ...extra];
28
+ };
29
+ return administration({ ...context, authenticate: async () => actor, audit });
30
+ }
31
+ return Object.freeze({
32
+ async invite(input) {
33
+ if (input.role === 'owner') deny('delegated_owner_change', 403);
34
+ const admin = await commands();
35
+ const plan = await admin.prepareInvitation(request, input, { operator: await store.byEmail(normalizeEmail(input.email)) });
36
+ if (!await store.invite(plan.mutation, plan.actor, plan)) deny('invitation_conflict', 409);
37
+ await plan.afterCommit();
38
+ return { status: 'accepted' };
39
+ },
40
+ async setRole(operatorId, role) {
41
+ const target = await store.operator(operatorId);
42
+ // A delegation cannot widen its sponsor or transfer owner authority.
43
+ if (operatorId === personId || target?.role === 'owner' || role === 'owner') deny('delegated_owner_change', 403);
44
+ return (await commands()).setRole(request, operatorId, role);
45
+ },
46
+ async listOperators() { return (await commands()).listOperators(request); },
47
+ });
48
+ }
@@ -220,6 +220,13 @@ export interface OperatorAuth<R extends string = Role> {
220
220
  cancelInvitation(request: Request, operatorId: string): Promise<Operator<R>>;
221
221
  setOperatorStatus(request: Request, operatorId: string, status: 'active' | 'inactive'): Promise<Operator<R>>;
222
222
  setRole(request: Request, operatorId: string, role: Role): Promise<Operator<R>>;
223
+ /** Trusted server only: caller admits the delegated principal; native policy
224
+ * and sponsor authority are checked again in each mutation transaction. */
225
+ delegatedAdministration(input: { personId: string; auditLabel: string; agentId: string }): {
226
+ invite(input: { email: string; displayName: string; role?: 'admin' | 'member'; returnTo?: string }): Promise<{ status: 'accepted' }>;
227
+ setRole(operatorId: string, role: 'admin' | 'member'): Promise<Operator<R>>;
228
+ listOperators(): Promise<Operator<R>[]>;
229
+ };
223
230
  listSessions(request: Request, operatorId?: string): Promise<Array<{ id: string; kind: SessionKind; createdAt: number; expiresAt: number; active: boolean }>>;
224
231
  revokeSession(request: Request, sessionId: string): Promise<void>;
225
232
  issueReviewSession(request: Request, input?: { returnTo?: string }): Promise<CompletedSession<R>>;
@@ -25,6 +25,7 @@ import { displayNameChange } from './accounts/display-name.mjs';
25
25
  import { isLocalCli } from './local-cli.mjs';
26
26
  import { devAdmitted } from './dev-admission.mjs';
27
27
  import { oneClickAccounts } from './accounts/one-click.mjs';
28
+ import { delegatedAdministration } from './accounts/delegated.mjs';
28
29
 
29
30
  export { STEP_UP_ACTIONS, STEP_UP_SECONDS } from './identity/email-link/index.mjs';
30
31
  export function createOperatorAuth(options) {
@@ -80,6 +81,7 @@ export function createOperatorAuth(options) {
80
81
  const external = legacyAdmission({ admission, config });
81
82
  return Object.freeze({
82
83
  ...admin,
84
+ delegatedAdministration: input => delegatedAdministration(adminContext, input),
83
85
  businessTeam: businessTeam(adminContext),
84
86
  ...businessSettingsControls({ businessSettings: options.businessSettings, config, accounts, authenticate, requireFreshProof, store, clock }),
85
87
  ...(options.scheduledPolicies ? { scheduledPolicies: scheduledPolicies({ definitions: options.scheduledPolicies, store, config, clock, authenticate, requireFreshProof, rolePolicy }) } : {}),